code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
import React, { Component } from 'react'; import InputBar from "../containers/input_bar"; import PriceList from "../containers/price_list"; import StateTax from "../containers/state_tax"; import TipPercent from "../containers/tip_percent"; import FinalAmount from "../containers/final_amount"; export default class App extends Component { render() { return ( <div> <InputBar /> <div className="container middle-area"> <div className="row"> <PriceList /> <StateTax /> <TipPercent /> </div> </div> <FinalAmount /> </div> ); } }
saramorais/Tip-Calculator
src/components/app.js
JavaScript
mit
639
import { createVue, destroyVM } from '../util'; describe('Tabs', () => { let vm; afterEach(() => { destroyVM(vm); }); it('create', done => { vm = createVue({ template: ` <el-tabs ref="tabs"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理" ref="pane-click">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); let paneList = vm.$el.querySelector('.el-tabs__content').children; let spy = sinon.spy(); vm.$refs.tabs.$on('tab-click', spy); setTimeout(_ => { const tabList = vm.$refs.tabs.$refs.tabs; expect(tabList[0].classList.contains('is-active')).to.be.true; expect(paneList[0].style.display).to.not.ok; tabList[2].click(); vm.$nextTick(_ => { expect(spy.withArgs(vm.$refs['pane-click']).calledOnce).to.true; expect(tabList[2].classList.contains('is-active')).to.be.true; expect(paneList[2].style.display).to.not.ok; done(); }); }, 100); }); it('active-name', done => { vm = createVue({ template: ` <el-tabs ref="tabs" :active-name="activeName" @click="handleClick"> <el-tab-pane name="tab-A" label="用户管理">A</el-tab-pane> <el-tab-pane name="tab-B" label="配置管理">B</el-tab-pane> <el-tab-pane name="tab-C" label="角色管理">C</el-tab-pane> <el-tab-pane name="tab-D" label="定时任务补偿">D</el-tab-pane> </el-tabs> `, data() { return { activeName: 'tab-B' }; }, methods: { handleClick(tab) { this.activeName = tab.name; } } }, true); setTimeout(_ => { const paneList = vm.$el.querySelector('.el-tabs__content').children; const tabList = vm.$refs.tabs.$refs.tabs; expect(tabList[1].classList.contains('is-active')).to.be.true; expect(paneList[1].style.display).to.not.ok; tabList[3].click(); vm.$nextTick(_ => { expect(tabList[3].classList.contains('is-active')).to.be.true; expect(paneList[3].style.display).to.not.ok; expect(vm.activeName === 'tab-D'); done(); }); }, 100); }); it('card', () => { vm = createVue({ template: ` <el-tabs type="card"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); expect(vm.$el.classList.contains('el-tabs--card')).to.be.true; }); it('border card', () => { vm = createVue({ template: ` <el-tabs type="border-card"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); expect(vm.$el.classList.contains('el-tabs--border-card')).to.be.true; }); it('dynamic', (done) => { vm = createVue({ template: ` <el-tabs type="card" ref="tabs"> <el-tab-pane :label="tab.label" :name="tab.name" v-for="tab in tabs">Test Content</el-tab-pane> </el-tabs> `, data() { return { tabs: [{ label: 'tab1', name: 'tab1' }, { label: 'tab2', name: 'tab2' }, { label: 'tab3', name: 'tab3' }, { label: 'tab4', name: 'tab4' }] }; } }, true); setTimeout(() => { expect(vm.$el.querySelectorAll('.el-tab-pane').length).to.equal(4); vm.tabs.push({ label: 'tab5', name: 'tab5' }); setTimeout(() => { expect(vm.$el.querySelectorAll('.el-tab-pane').length).to.equal(5); done(); }); }, 100); }); it('closable', done => { vm = createVue({ template: ` <el-tabs type="card" :closable="true" ref="tabs"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); let spy = sinon.spy(); vm.$refs.tabs.$on('tab-remove', spy); setTimeout(_ => { const tabList = vm.$refs.tabs.$refs.tabs; const paneList = vm.$el.querySelector('.el-tabs__content').children; tabList[1].querySelector('.el-icon-close').click(); vm.$nextTick(_ => { expect(tabList.length).to.be.equal(3); expect(paneList.length).to.be.equal(3); expect(spy.calledOnce).to.true; expect(tabList[1].innerText.trim()).to.be.equal('角色管理'); expect(paneList[0].innerText.trim()).to.be.equal('A'); done(); }); }, 100); }); it('closable in tab-pane', (done) => { vm = createVue({ template: ` <el-tabs type="card" ref="tabs"> <el-tab-pane label="用户管理" closable>A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理" closable>C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); setTimeout(() => { expect(vm.$el.querySelectorAll('.el-icon-close').length).to.equal(2); done(); }, 100); }); it('closable edge', done => { vm = createVue({ template: ` <el-tabs type="card" :closable="true" ref="tabs"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane label="配置管理">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); vm.$nextTick(_ => { const paneList = vm.$el.querySelector('.el-tabs__content').children; const tabList = vm.$refs.tabs.$refs.tabs; tabList[0].querySelector('.el-icon-close').click(); vm.$nextTick(_ => { expect(tabList.length).to.be.equal(3); expect(paneList.length).to.be.equal(3); expect(tabList[0].innerText.trim()).to.be.equal('配置管理'); expect(paneList[0].innerText.trim()).to.be.equal('B'); tabList[2].click(); tabList[2].querySelector('.el-icon-close').click(); setTimeout(_ => { expect(tabList.length).to.be.equal(2); expect(paneList.length).to.be.equal(2); expect(tabList[1].classList.contains('is-active')).to.be.true; expect(tabList[1].innerText.trim()).to.be.equal('角色管理'); expect(paneList[1].innerText.trim()).to.be.equal('C'); done(); }, 100); }); }); }); it('disabled', done => { vm = createVue({ template: ` <el-tabs type="card" ref="tabs"> <el-tab-pane label="用户管理">A</el-tab-pane> <el-tab-pane disabled label="配置管理" ref="disabled">B</el-tab-pane> <el-tab-pane label="角色管理">C</el-tab-pane> <el-tab-pane label="定时任务补偿">D</el-tab-pane> </el-tabs> ` }, true); vm.$nextTick(_ => { const tabList = vm.$refs.tabs.$refs.tabs; tabList[1].click(); vm.$nextTick(_ => { expect(tabList[1].classList.contains('is-active')).to.not.true; done(); }); }); }); });
karol-f/element
test/unit/specs/tabs.spec.js
JavaScript
mit
7,799
/*jshint node:true */ "use strict"; var extend = require('util')._extend; module.exports = function (task, args, done) { var that = this, params, finish, cb, isDone = false, start, r, streamReturn = []; finish = function (err, results, runMethod) { var hrDuration = process.hrtime(start); if (isDone) { return; } isDone = true; var duration = hrDuration[0] + (hrDuration[1] / 1e9); // seconds done.call(that, err, results, { duration: duration, // seconds hrDuration: hrDuration, // [seconds,nanoseconds] runMethod: runMethod }); }; cb = function (err, results) { finish(err, results, 'callback'); }; params = extend([], args); params.push(cb); try { start = process.hrtime(); r = task.apply(this, params); } catch (err) { finish(err, null, 'catch'); } if (r && typeof r.done === 'function') { // wait for promise to resolve // FRAGILE: ASSUME: Promises/A+, see http://promises-aplus.github.io/promises-spec/ r.done(function (results) { finish(null, results, 'promise'); }, function(err) { finish(err, null, 'promise'); }); } else if (r && typeof r.on === 'function' && typeof r.once === 'function' && typeof r.end === 'function' && r.pipe) { // wait for stream to end r.on('data', function (results) { // return an array of results because we must listen to all the traffic through the stream if (typeof results !== 'undefined') { streamReturn.push(results); } }); r.once('error', function (err) { finish(err, null, 'stream'); }); r.once('end', function () { finish(null, streamReturn, 'stream'); }); // start stream if (typeof args !== 'undefined' && args !== null) { r.write.apply(that, args); } } else if (task.length < params.length) { // synchronous, function took in args.length parameters, and the callback was extra finish(null, r, 'sync'); //} else { // FRAGILE: ASSUME: callback } };
robrich/execify
lib/runTask.js
JavaScript
mit
1,923
import path from 'node:path'; import test from 'ava'; import slash from 'slash'; import { isIgnoredByIgnoreFiles, isIgnoredByIgnoreFilesSync, isGitIgnored, isGitIgnoredSync, } from '../ignore.js'; import { PROJECT_ROOT, getPathValues, } from './utilities.js'; const runIsIgnoredByIgnoreFiles = async (t, patterns, options, fn) => { const promisePredicate = await isIgnoredByIgnoreFiles(patterns, options); const syncPredicate = isIgnoredByIgnoreFilesSync(patterns, options); const promiseResult = fn(promisePredicate); const syncResult = fn(syncPredicate); t[Array.isArray(promiseResult) ? 'deepEqual' : 'is']( promiseResult, syncResult, 'isIgnoredByIgnoreFilesSync() result is different than isIgnoredByIgnoreFiles()', ); return promiseResult; }; const runIsGitIgnored = async (t, options, fn) => { const promisePredicate = await isGitIgnored(options); const syncPredicate = isGitIgnoredSync(options); const promiseResult = fn(promisePredicate); const syncResult = fn(syncPredicate); t[Array.isArray(promiseResult) ? 'deepEqual' : 'is']( promiseResult, syncResult, 'isGitIgnoredSync() result is different than isGitIgnored()', ); return promiseResult; }; test('ignore', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/gitignore'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => ['foo.js', 'bar.js'].filter(file => !isIgnored(file)), ); const expected = ['bar.js']; t.deepEqual(actual, expected); } }); test('ignore - mixed path styles', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const cwd of getPathValues(directory)) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd}, isIgnored => isIgnored(slash(path.resolve(directory, 'foo.js'))), ), ); } }); test('ignore - os paths', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const cwd of getPathValues(directory)) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd}, isIgnored => isIgnored(path.resolve(directory, 'foo.js')), ), ); } }); test('negative ignore', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/negative'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => ['foo.js', 'bar.js'].filter(file => !isIgnored(file)), ); const expected = ['foo.js']; t.deepEqual(actual, expected); } }); test('multiple negation', async t => { for (const cwd of getPathValues(path.join(PROJECT_ROOT, 'fixtures/multiple-negation'))) { // eslint-disable-next-line no-await-in-loop const actual = await runIsGitIgnored( t, {cwd}, isIgnored => [ '!!!unicorn.js', '!!unicorn.js', '!unicorn.js', 'unicorn.js', ].filter(file => !isIgnored(file)), ); const expected = ['!!unicorn.js', '!unicorn.js']; t.deepEqual(actual, expected); } }); test('check file', async t => { const directory = path.join(PROJECT_ROOT, 'fixtures/gitignore'); for (const ignoredFile of getPathValues(path.join(directory, 'foo.js'))) { t.true( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd: directory}, isIgnored => isIgnored(ignoredFile), ), ); } for (const notIgnoredFile of getPathValues(path.join(directory, 'bar.js'))) { t.false( // eslint-disable-next-line no-await-in-loop await runIsGitIgnored( t, {cwd: directory}, isIgnored => isIgnored(notIgnoredFile), ), ); } }); test('custom ignore files', async t => { const cwd = path.join(PROJECT_ROOT, 'fixtures/ignore-files'); const files = [ 'ignored-by-eslint.js', 'ignored-by-prettier.js', 'not-ignored.js', ]; t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.eslintignore', {cwd}, isEslintIgnored => files.filter(file => isEslintIgnored(file)), ), [ 'ignored-by-eslint.js', ], ); t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.prettierignore', {cwd}, isPrettierIgnored => files.filter(file => isPrettierIgnored(file)), ), [ 'ignored-by-prettier.js', ], ); t.deepEqual( await runIsIgnoredByIgnoreFiles( t, '.{prettier,eslint}ignore', {cwd}, isEslintOrPrettierIgnored => files.filter(file => isEslintOrPrettierIgnored(file)), ), [ 'ignored-by-eslint.js', 'ignored-by-prettier.js', ], ); });
sindresorhus/globby
tests/ignore.js
JavaScript
mit
4,547
/* jshint expr:true */ import Ember from 'ember'; const { run } = Ember; import { expect } from 'chai'; import { describeModel, it } from 'ember-mocha'; import { beforeEach } from 'mocha'; let store; let m; describeModel( 'parent', 'Unit | Model | foo', { // Specify the other units that are required for this test. needs: ['model:child', 'model:pet'], }, function() { beforeEach( function () { store = this.store(); return run(() => { store.pushPayload({ data: null, included: [ { id: '1', type: 'parents', relationships: { children: { data: [ {id: '1', type: 'children'} ] } } }, { id: '1', type: 'children' }, { id: '2', type: 'children' }, { id: '1', type: 'pets' }, { id: '2', type: 'pets' } ] }); }); }); // Replace this with your real tests. it('parent stains itself', function() { const parent = store.peekRecord('parent', '1'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { parent.set('name', 'asdf'); }); m = "Parent should be dirty after updating an attribute on itself"; expect(parent.get('hasDirtyAttributes'), m).true; }); // Replace this with your real tests. it('dirty child stains parent', function() { const child = store.peekRecord('child', '1'); const parent = store.peekRecord('parent', '1'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { child.set('name', 'foo'); }); m = "Parent should be dirty after updating an attribute on child"; expect(parent.get('hasDirtyAttributes'), m).true; }); // Replace this with your real tests. it('parent stains when children relationship is updated', function() { const parent = store.peekRecord('parent', '1'); const child2 = store.peekRecord('child', '2'); m = "Parent should not be initially dirty"; expect(parent.get('hasDirtyAttributes'), m).false; run(() => { parent.get('children').pushObject(child2); }); m = "Parent should be dirty after adding another child"; expect(parent.get('hasDirtyAttributes'), m).true; }); } );
lolmaus/ember-cli-stained-by-children
tests/unit/models/foo-test.js
JavaScript
mit
2,704
import { mediaPreview } from 'mtt-blog/helpers/media-preview'; import { module, test } from 'qunit'; module('Unit | Helper | media preview'); // Replace this with your real tests. test('it works', function(assert) { let result = mediaPreview([42]); assert.ok(result); });
morontt/zend-blog-3-backend
spa/tests/unit/helpers/media-preview-test.js
JavaScript
mit
278
/*============================= = Views = =============================*/ App.Views.UserInfo = Backbone.View.extend({ el: $('#user-info'), events: { "click #settings" : "clickSettings", "click #logout" : "clickLogout" }, clickLogout: function(event) { $.ajax({ url: 'auth/logout', type: 'get', dataType: 'json', success: function(data) { if (data.result == 'Success') { window.location = '/'; //Reload index page } else { alert('Logout failed'); //Alert on fail } }, error: function (xhr, ajaxOptions, thrownError) { console.log('Logout failed (hard)'); } }); }, clickSettings: function(event) { console.log('Settings clicked'); } });
tjoskar/odot
public/js/views/userInfo.js
JavaScript
mit
917
// Generated by CoffeeScript 1.10.0 var AppController, MainController, ModalNewDeckController, NavController; AppController = (function() { function AppController($scope) { this.scope = $scope; this.scope.$on('search', function(term) { return console.log(term); }); $scope.$on('deckHasBeenSelected', function(deck) { $scope.currentDeck = deck.targetScope.currentDeck; return $scope.$broadcast('currentDeckHasChanged'); }); } return AppController; })(); NavController = (function() { function NavController($scope, $uibModal, $localStorage) { if (!$localStorage.decks) { $localStorage.decks = []; } $scope.decks = $localStorage.decks; $scope.selectDeck = function(deck) { $scope.currentDeck = deck; return $scope.$emit('deckHasBeenSelected', $scope.currentDeck); }; $scope.selectDeck($scope.decks[0]); $scope.addDeck = function($scope) { var modal; modal = $uibModal.open({ templateUrl: "template/modalNewDeck.html", controller: "modalNewDeckController" }); return modal.result.then(function(deckName) { return $localStorage.decks.push(new Deck(deckName)); }); }; } return NavController; })(); ModalNewDeckController = (function() { function ModalNewDeckController($scope, $uibModalInstance) { $scope.cancel = function() { return $uibModalInstance.dismiss("cancel"); }; $scope.submit = function() { return $uibModalInstance.close($scope.name); }; } return ModalNewDeckController; })(); MainController = (function() { function MainController($scope, $localStorage, $http) { $scope.cards = []; $scope.$on("currentDeckHasChanged", function(e) { $scope.currentDeck = e.targetScope.currentDeck; return $scope.load(); }); $scope.load = function() { return $scope.cards = $scope.currentDeck.cards; }; $scope.addNewCard = function() { $scope.cards.push(new Card($scope.title, $scope.description)); $scope.title = ""; return $scope.description = ""; }; } return MainController; })(); myApp.controller('appController', AppController); myApp.controller('navController', NavController); myApp.controller('mainController', MainController); myApp.controller('modalNewDeckController', ModalNewDeckController);
marconvcm/sandbox
02-angularjs-protractor/lib/controller.js
JavaScript
mit
2,368
/* vim: set expandtab sw=4 ts=4 sts=4: */ /** * @fileoverview functions used for visualizing GIS data * * @requires jquery * @requires vendor/jquery/jquery.svg.js * @requires vendor/jquery/jquery.mousewheel.js * @requires vendor/jquery/jquery.event.drag-2.2.js */ /* global drawOpenLayers */ // templates/table/gis_visualization/gis_visualization.twig // Constants var zoomFactor = 1.5; var defaultX = 0; var defaultY = 0; // Variables var x = 0; var y = 0; var scale = 1; var svg; /** * Zooms and pans the visualization. */ function zoomAndPan () { var g = svg.getElementById('groupPanel'); if (!g) { return; } g.setAttribute('transform', 'translate(' + x + ', ' + y + ') scale(' + scale + ')'); var id; var circle; $('circle.vector').each(function () { id = $(this).attr('id'); circle = svg.getElementById(id); $(svg).on('change', circle, { r : (3 / scale), 'stroke-width' : (2 / scale) }); }); var line; $('polyline.vector').each(function () { id = $(this).attr('id'); line = svg.getElementById(id); $(svg).on('change', line, { 'stroke-width' : (2 / scale) }); }); var polygon; $('path.vector').each(function () { id = $(this).attr('id'); polygon = svg.getElementById(id); $(svg).on('change', polygon, { 'stroke-width' : (0.5 / scale) }); }); } /** * Initially loads either SVG or OSM visualization based on the choice. */ function selectVisualization () { if ($('#choice').prop('checked') !== true) { $('#openlayersmap').hide(); } else { $('#placeholder').hide(); } } /** * Adds necessary styles to the div that coontains the openStreetMap. */ function styleOSM () { var $placeholder = $('#placeholder'); var cssObj = { 'border' : '1px solid #aaa', 'width' : $placeholder.width(), 'height' : $placeholder.height(), 'float' : 'right' }; $('#openlayersmap').css(cssObj); } /** * Loads the SVG element and make a reference to it. */ function loadSVG () { var $placeholder = $('#placeholder'); $placeholder.svg({ onLoad: function (svgRef) { svg = svgRef; } }); // Removes the second SVG element unnecessarily added due to the above command $placeholder.find('svg:nth-child(2)').remove(); } /** * Adds controllers for zooming and panning. */ function addZoomPanControllers () { var $placeholder = $('#placeholder'); if ($('#placeholder').find('svg').length > 0) { var pmaThemeImage = $('#pmaThemeImage').val(); // add panning arrows $('<img class="button" id="left_arrow" src="' + pmaThemeImage + 'west-mini.png">').appendTo($placeholder); $('<img class="button" id="right_arrow" src="' + pmaThemeImage + 'east-mini.png">').appendTo($placeholder); $('<img class="button" id="up_arrow" src="' + pmaThemeImage + 'north-mini.png">').appendTo($placeholder); $('<img class="button" id="down_arrow" src="' + pmaThemeImage + 'south-mini.png">').appendTo($placeholder); // add zooming controls $('<img class="button" id="zoom_in" src="' + pmaThemeImage + 'zoom-plus-mini.png">').appendTo($placeholder); $('<img class="button" id="zoom_world" src="' + pmaThemeImage + 'zoom-world-mini.png">').appendTo($placeholder); $('<img class="button" id="zoom_out" src="' + pmaThemeImage + 'zoom-minus-mini.png">').appendTo($placeholder); } } /** * Resizes the GIS visualization to fit into the space available. */ function resizeGISVisualization () { var $placeholder = $('#placeholder'); var oldWidth = $placeholder.width(); var visWidth = $('#div_view_options').width() - 48; // Assign new value for width $placeholder.width(visWidth); $('svg').attr('width', visWidth); // Assign the offset created due to resizing to defaultX and center the svg. defaultX = (visWidth - oldWidth) / 2; x = defaultX; y = 0; scale = 1; } /** * Initialize the GIS visualization. */ function initGISVisualization () { // Loads either SVG or OSM visualization based on the choice selectVisualization(); // Resizes the GIS visualization to fit into the space available resizeGISVisualization(); if (typeof OpenLayers !== 'undefined') { // Configure OpenLayers // eslint-disable-next-line no-underscore-dangle OpenLayers._getScriptLocation = function () { return './js/vendor/openlayers/'; }; // Adds necessary styles to the div that coontains the openStreetMap styleOSM(); // Draws openStreetMap with openLayers drawOpenLayers(); } // Loads the SVG element and make a reference to it loadSVG(); // Adds controllers for zooming and panning addZoomPanControllers(); zoomAndPan(); } function getRelativeCoords (e) { var position = $('#placeholder').offset(); return { x : e.pageX - position.left, y : e.pageY - position.top }; } /** * Ajax handlers for GIS visualization page * * Actions Ajaxified here: * * Zooming in and zooming out on mousewheel movement. * Panning the visualization on dragging. * Zooming in on double clicking. * Zooming out on clicking the zoom out button. * Panning on clicking the arrow buttons. * Displaying tooltips for GIS objects. */ /** * Unbind all event handlers before tearing down a page */ AJAX.registerTeardown('table/gis_visualization.js', function () { $(document).off('click', '#choice'); $(document).off('mousewheel', '#placeholder'); $(document).off('dragstart', 'svg'); $(document).off('mouseup', 'svg'); $(document).off('drag', 'svg'); $(document).off('dblclick', '#placeholder'); $(document).off('click', '#zoom_in'); $(document).off('click', '#zoom_world'); $(document).off('click', '#zoom_out'); $(document).off('click', '#left_arrow'); $(document).off('click', '#right_arrow'); $(document).off('click', '#up_arrow'); $(document).off('click', '#down_arrow'); $('.vector').off('mousemove').off('mouseout'); }); AJAX.registerOnload('table/gis_visualization.js', function () { // If we are in GIS visualization, initialize it if ($('#gis_div').length > 0) { initGISVisualization(); } if (typeof OpenLayers === 'undefined') { $('#choice, #labelChoice').hide(); } $(document).on('click', '#choice', function () { if ($(this).prop('checked') === false) { $('#placeholder').show(); $('#openlayersmap').hide(); } else { $('#placeholder').hide(); $('#openlayersmap').show(); } }); $(document).on('mousewheel', '#placeholder', function (event, delta) { event.preventDefault(); var relCoords = getRelativeCoords(event); if (delta > 0) { // zoom in scale *= zoomFactor; // zooming in keeping the position under mouse pointer unmoved. x = relCoords.x - (relCoords.x - x) * zoomFactor; y = relCoords.y - (relCoords.y - y) * zoomFactor; zoomAndPan(); } else { // zoom out scale /= zoomFactor; // zooming out keeping the position under mouse pointer unmoved. x = relCoords.x - (relCoords.x - x) / zoomFactor; y = relCoords.y - (relCoords.y - y) / zoomFactor; zoomAndPan(); } return true; }); var dragX = 0; var dragY = 0; $(document).on('dragstart', 'svg', function (event, dd) { $('#placeholder').addClass('placeholderDrag'); dragX = Math.round(dd.offsetX); dragY = Math.round(dd.offsetY); }); $(document).on('mouseup', 'svg', function () { $('#placeholder').removeClass('placeholderDrag'); }); $(document).on('drag', 'svg', function (event, dd) { var newX = Math.round(dd.offsetX); x += newX - dragX; dragX = newX; var newY = Math.round(dd.offsetY); y += newY - dragY; dragY = newY; zoomAndPan(); }); $(document).on('dblclick', '#placeholder', function (event) { scale *= zoomFactor; // zooming in keeping the position under mouse pointer unmoved. var relCoords = getRelativeCoords(event); x = relCoords.x - (relCoords.x - x) * zoomFactor; y = relCoords.y - (relCoords.y - y) * zoomFactor; zoomAndPan(); }); $(document).on('click', '#zoom_in', function (e) { e.preventDefault(); // zoom in scale *= zoomFactor; var $placeholder = $('#placeholder').find('svg'); var width = $placeholder.attr('width'); var height = $placeholder.attr('height'); // zooming in keeping the center unmoved. x = width / 2 - (width / 2 - x) * zoomFactor; y = height / 2 - (height / 2 - y) * zoomFactor; zoomAndPan(); }); $(document).on('click', '#zoom_world', function (e) { e.preventDefault(); scale = 1; x = defaultX; y = defaultY; zoomAndPan(); }); $(document).on('click', '#zoom_out', function (e) { e.preventDefault(); // zoom out scale /= zoomFactor; var $placeholder = $('#placeholder').find('svg'); var width = $placeholder.attr('width'); var height = $placeholder.attr('height'); // zooming out keeping the center unmoved. x = width / 2 - (width / 2 - x) / zoomFactor; y = height / 2 - (height / 2 - y) / zoomFactor; zoomAndPan(); }); $(document).on('click', '#left_arrow', function (e) { e.preventDefault(); x += 100; zoomAndPan(); }); $(document).on('click', '#right_arrow', function (e) { e.preventDefault(); x -= 100; zoomAndPan(); }); $(document).on('click', '#up_arrow', function (e) { e.preventDefault(); y += 100; zoomAndPan(); }); $(document).on('click', '#down_arrow', function (e) { e.preventDefault(); y -= 100; zoomAndPan(); }); /** * Detect the mousemove event and show tooltips. */ $('.vector').on('mousemove', function (event) { var contents = $.trim(Functions.escapeHtml($(this).attr('name'))); $('#tooltip').remove(); if (contents !== '') { $('<div id="tooltip">' + contents + '</div>').css({ position : 'absolute', top : event.pageY + 10, left : event.pageX + 10, border : '1px solid #fdd', padding : '2px', 'background-color' : '#fee', opacity : 0.90 }).appendTo('body').fadeIn(200); } }); /** * Detect the mouseout event and hide tooltips. */ $('.vector').on('mouseout', function () { $('#tooltip').remove(); }); });
cytopia/devilbox
.devilbox/www/htdocs/vendor/phpmyadmin-5.0.4/js/table/gis_visualization.js
JavaScript
mit
11,138
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = Logger; var _lodash = require('lodash'); var _moment = require('moment'); var _moment2 = _interopRequireDefault(_moment); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var logLevels = { TRACE: 'TRACE', INFO: 'INFO', WARN: 'WARN', ERROR: 'ERROR' }; function _log(category, level) { var _console2; var now = (0, _moment2.default)().format(); for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (level === logLevels.ERROR) { var _console; return (_console = console).error.apply(_console, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } return (_console2 = console).log.apply(_console2, [now + ' ' + level + ' [' + category + ']'].concat(args)); // eslint-disable-line no-console } function Logger(category, requestId) { this.category = category; this.requestId = requestId; } function createLogLevel(level) { return function logWithLevel() { for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { args[_key2] = arguments[_key2]; } if (this.requestId) { _log.apply(undefined, [this.category, level, 'RequestId: ' + this.requestId].concat(args)); } _log.apply(undefined, [this.category, level].concat(args)); }; } Logger.prototype.trace = createLogLevel(logLevels.TRACE); Logger.prototype.info = createLogLevel(logLevels.INFO); Logger.prototype.warn = createLogLevel(logLevels.WARN); Logger.prototype.error = createLogLevel(logLevels.ERROR); Logger.prototype.log = function log(level) { for (var _len3 = arguments.length, args = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { args[_key3 - 1] = arguments[_key3]; } if ((0, _lodash.size)(args) === 1 && (0, _lodash.isObject)(args[0])) { _log(this.category, (0, _lodash.toUpper)(level), JSON.stringify(args[0])); return; } _log.apply(undefined, [this.category, (0, _lodash.toUpper)(level)].concat(args)); };
noahlvb/dotfiles
.atom/packages/git-blame/node_modules/@workpop/simple-logger/lib/index.js
JavaScript
mit
2,217
import { expect } from "chai"; import { createStore, applyMiddleware } from 'redux'; import Immutable from 'immutable'; import reducers from '../src/lib/reducers'; import * as Utils from '../src/lib/utils'; describe('utils', function () { beforeEach(function () { this.state = Immutable.fromJS([ {title: "alpha"}, {title: "beta", children: [ {title: "foo"}, {title: "bar", children: [ {title: "quux"}, {title: "xyzzy"} ]}, {title: "baz"} ]}, {title: "gamma"}, {title: "level1", children: [ {title: 'level2', children: [ {title: 'level3', children: [ {title: 'level4'} ]} ]} ]}, {title: 'thud'} ]); this.store = createStore(reducers, { nodes: this.state }); this.expectedSeries = [ '0', '1', '1.children.0', '1.children.1', '1.children.1.children.0', '1.children.1.children.1', '1.children.2', '2', '3', '3.children.0', '3.children.0.children.0', '3.children.0.children.0.children.0', '4' ]; this.expectedSiblings = [ ['0', '1', '2', '3', '4'], ['1.children.0', '1.children.1', '1.children.2'], ['1.children.1.children.0', '1.children.1.children.1'], ['3.children.0'] ['3.children.0.children.0'], ['3.children.0.children.0.children.0'], ]; }); describe('splitPath', function () { it('should split a dot-delimited path into a key array', function () { expect(Utils.splitPath('1.children.1.children.2')) .to.deep.equal(['1', 'children', '1', 'children', '2']); }) }) describe('getNodeContext', function () { it('should construct contextual information for a node path', function () { var path = '1.children.1.children.0'; var expected = { key: ['1', 'children', '1', 'children', '0'], parentKey: ['1', 'children', '1'], index: 0, value: this.state.getIn(['1', 'children', '1', 'children', '0']), siblings: this.state.getIn(['1', 'children', '1', 'children']) }; var result = Utils.getNodeContext(this.state, path); expect(result).to.deep.equal(expected); }) }); function commonSiblingPathTest (inReverse, state, expectedSiblings) { var traversal = inReverse ? Utils.getPreviousSiblingPath : Utils.getNextSiblingPath; var siblingList; while (siblingList = expectedSiblings.shift()) { if (inReverse) { siblingList.reverse(); } var current, expected, result; current = siblingList.shift(); while (siblingList.length) { expected = siblingList.shift(); result = traversal(state, current); expect(result).to.equal(expected); current = expected; } result = traversal(state, current); expect(result).to.equal(null); } } describe('getNextSiblingPath', function () { it('should find the path to the next sibling', function () { commonSiblingPathTest(false, this.state, this.expectedSiblings); }); }); describe('getPreviousSiblingPath', function () { it('should find the path to the previous sibling', function () { commonSiblingPathTest(true, this.state, this.expectedSiblings); }); }); function commonNodePathTest (inReverse, state, expectedSeries) { var current, expected, result; var traversal = (inReverse) ? Utils.getPreviousNodePath : Utils.getNextNodePath; if (inReverse) { expectedSeries.reverse(); } current = expectedSeries.shift(); while (expectedSeries.length) { expected = expectedSeries.shift(); result = traversal(state, current); expect(result).to.equal(expected); current = expected; } } describe('getNextNodePath', function () { it('should find the path to the next node', function () { commonNodePathTest(false, this.state, this.expectedSeries); }) it('should skip children of collapsed nodes', function () { let state = this.state; ['1', '3.children.0'].forEach(path => { state = state.updateIn( path.split('.'), n => n.set('collapsed', true)); }); commonNodePathTest(false, state, ['0', '1', '2', '3', '3.children.0', '4']); }); }); describe('getPreviousNodePath', function () { it('should find the path to the previous node', function () { commonNodePathTest(true, this.state, this.expectedSeries); }); it('should skip children of collapsed nodes', function () { let state = this.state; ['1', '3.children.0'].forEach(path => { state = state.updateIn( path.split('.'), n => n.set('collapsed', true)); }); commonNodePathTest(true, state, ['0', '1', '2', '3', '3.children.0', '4']); }); }); });
lmorchard/arboretum
test/test-utils.js
JavaScript
mit
4,905
function child() { alert('child'); } function parent() { alert('parent'); } function grandParent() { alert('grand parent'); }
mwagg/stylo
features/fixtures/grand_parent_with_parent_with_child.js
JavaScript
mit
139
/** * Created by ko on 2016-07-15. */ $(document).ready(function () { var pageNo= 1; // webtoon $("#recipe").on("click", function () { $("#travel_content").html(""); $("#youtube_content").html(""); $("#honbap_content").html(""); $("#game_content").html(""); $("#parcelArea").css("display","none"); $("#resultArea").html(""); $("#prodInfo_content").css("display", "none"); pageNo=1; $("#cvs_content").css("display", "none"); common_module.moveYoutubeMenu(); recipe_module.recipeTitle(); recipe_module.showRecipe(1); $(window).unbind('scroll'); $(window).scroll(function(){ if (Math.ceil($(window).scrollTop()) == $(document).height() - $(window).height()) { pageNo +=1; recipe_module.showRecipe(pageNo); $(".loadingArea").html('<img src = "https://cdn.rawgit.com/kokk9239/singleLife_web/master/src/img/preloader.gif" style="width: 60px; height: 60px">'); } }); $("#webtoon_content").css("display", "none"); }); });
kokk9239/singleLife_web
src/js/recipe/event-recipe.js
JavaScript
mit
1,136
/*! * inferno-component v1.2.2 * (c) 2017 Dominic Gannaway * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('inferno')) : typeof define === 'function' && define.amd ? define(['inferno'], factory) : (global.Inferno = global.Inferno || {}, global.Inferno.Component = factory(global.Inferno)); }(this, (function (inferno) { 'use strict'; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; var isBrowser = typeof window !== 'undefined' && window.document; // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though var isArray = Array.isArray; function isStringOrNumber(obj) { var type = typeof obj; return type === 'string' || type === 'number'; } function isNullOrUndef(obj) { return isUndefined(obj) || isNull(obj); } function isInvalid(obj) { return isNull(obj) || obj === false || isTrue(obj) || isUndefined(obj); } function isFunction(obj) { return typeof obj === 'function'; } function isNull(obj) { return obj === null; } function isTrue(obj) { return obj === true; } function isUndefined(obj) { return obj === undefined; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } var Lifecycle = function Lifecycle() { this.listeners = []; this.fastUnmount = true; }; Lifecycle.prototype.addListener = function addListener (callback) { this.listeners.push(callback); }; Lifecycle.prototype.trigger = function trigger () { var this$1 = this; for (var i = 0; i < this.listeners.length; i++) { this$1.listeners[i](); } }; var noOp = ERROR_MSG; if (process.env.NODE_ENV !== 'production') { noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.'; } var componentCallbackQueue = new Map(); // when a components root VNode is also a component, we can run into issues // this will recursively look for vNode.parentNode if the VNode is a component function updateParentComponentVNodes(vNode, dom) { if (vNode.flags & 28 /* Component */) { var parentVNode = vNode.parentVNode; if (parentVNode) { parentVNode.dom = dom; updateParentComponentVNodes(parentVNode, dom); } } } // this is in shapes too, but we don't want to import from shapes as it will pull in a duplicate of createVNode function createVoidVNode() { return inferno.createVNode(4096 /* Void */); } function createTextVNode(text) { return inferno.createVNode(1 /* Text */, null, null, text); } function addToQueue(component, force, callback) { // TODO this function needs to be revised and improved on var queue = componentCallbackQueue.get(component); if (!queue) { queue = []; componentCallbackQueue.set(component, queue); Promise.resolve().then(function () { componentCallbackQueue.delete(component); applyState(component, force, function () { for (var i = 0; i < queue.length; i++) { queue[i](); } }); }); } if (callback) { queue.push(callback); } } function queueStateChanges(component, newState, callback, sync) { if (isFunction(newState)) { newState = newState(component.state, component.props, component.context); } for (var stateKey in newState) { component._pendingState[stateKey] = newState[stateKey]; } if (!component._pendingSetState && isBrowser) { if (sync || component._blockRender) { component._pendingSetState = true; applyState(component, false, callback); } else { addToQueue(component, false, callback); } } else { component.state = Object.assign({}, component.state, component._pendingState); component._pendingState = {}; } } function applyState(component, force, callback) { if ((!component._deferSetState || force) && !component._blockRender && !component._unmounted) { component._pendingSetState = false; var pendingState = component._pendingState; var prevState = component.state; var nextState = Object.assign({}, prevState, pendingState); var props = component.props; var context = component.context; component._pendingState = {}; var nextInput = component._updateComponent(prevState, nextState, props, props, context, force, true); var didUpdate = true; if (isInvalid(nextInput)) { nextInput = createVoidVNode(); } else if (nextInput === inferno.NO_OP) { nextInput = component._lastInput; didUpdate = false; } else if (isStringOrNumber(nextInput)) { nextInput = createTextVNode(nextInput); } else if (isArray(nextInput)) { if (process.env.NODE_ENV !== 'production') { throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.'); } throwError(); } var lastInput = component._lastInput; var vNode = component._vNode; var parentDom = (lastInput.dom && lastInput.dom.parentNode) || (lastInput.dom = vNode.dom); component._lastInput = nextInput; if (didUpdate) { var subLifecycle = component._lifecycle; if (!subLifecycle) { subLifecycle = new Lifecycle(); } else { subLifecycle.listeners = []; } component._lifecycle = subLifecycle; var childContext = component.getChildContext(); if (!isNullOrUndef(childContext)) { childContext = Object.assign({}, context, component._childContext, childContext); } else { childContext = Object.assign({}, context, component._childContext); } component._patch(lastInput, nextInput, parentDom, subLifecycle, childContext, component._isSVG, false); subLifecycle.trigger(); component.componentDidUpdate(props, prevState); inferno.options.afterUpdate && inferno.options.afterUpdate(vNode); } var dom = vNode.dom = nextInput.dom; var componentToDOMNodeMap = component._componentToDOMNodeMap; componentToDOMNodeMap && componentToDOMNodeMap.set(component, nextInput.dom); updateParentComponentVNodes(vNode, dom); if (!isNullOrUndef(callback)) { callback(); } } else if (!isNullOrUndef(callback)) { callback(); } } var Component$1 = function Component(props, context) { this.state = {}; this.refs = {}; this._blockRender = false; this._ignoreSetState = false; this._blockSetState = false; this._deferSetState = false; this._pendingSetState = false; this._pendingState = {}; this._lastInput = null; this._vNode = null; this._unmounted = true; this._lifecycle = null; this._childContext = null; this._patch = null; this._isSVG = false; this._componentToDOMNodeMap = null; /** @type {object} */ this.props = props || inferno.EMPTY_OBJ; /** @type {object} */ this.context = context || {}; }; Component$1.prototype.render = function render (nextProps, nextState, nextContext) { }; Component$1.prototype.forceUpdate = function forceUpdate (callback) { if (this._unmounted) { return; } isBrowser && applyState(this, true, callback); }; Component$1.prototype.setState = function setState (newState, callback) { if (this._unmounted) { return; } if (!this._blockSetState) { if (!this._ignoreSetState) { queueStateChanges(this, newState, callback, false); } } else { if (process.env.NODE_ENV !== 'production') { throwError('cannot update state via setState() in componentWillUpdate().'); } throwError(); } }; Component$1.prototype.setStateSync = function setStateSync (newState) { if (this._unmounted) { return; } if (!this._blockSetState) { if (!this._ignoreSetState) { queueStateChanges(this, newState, null, true); } } else { if (process.env.NODE_ENV !== 'production') { throwError('cannot update state via setState() in componentWillUpdate().'); } throwError(); } }; Component$1.prototype.componentWillMount = function componentWillMount () { }; Component$1.prototype.componentDidUpdate = function componentDidUpdate (prevProps, prevState, prevContext) { }; Component$1.prototype.shouldComponentUpdate = function shouldComponentUpdate (nextProps, nextState, context) { return true; }; Component$1.prototype.componentWillReceiveProps = function componentWillReceiveProps (nextProps, context) { }; Component$1.prototype.componentWillUpdate = function componentWillUpdate (nextProps, nextState, nextContext) { }; Component$1.prototype.getChildContext = function getChildContext () { }; Component$1.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, context, force, fromSetState) { if (this._unmounted === true) { if (process.env.NODE_ENV !== 'production') { throwError(noOp); } throwError(); } if ((prevProps !== nextProps || nextProps === inferno.EMPTY_OBJ) || prevState !== nextState || force) { if (prevProps !== nextProps || nextProps === inferno.EMPTY_OBJ) { if (!fromSetState) { this._blockRender = true; this.componentWillReceiveProps(nextProps, context); this._blockRender = false; } if (this._pendingSetState) { nextState = Object.assign({}, nextState, this._pendingState); this._pendingSetState = false; this._pendingState = {}; } } var shouldUpdate = this.shouldComponentUpdate(nextProps, nextState, context); if (shouldUpdate !== false || force) { this._blockSetState = true; this.componentWillUpdate(nextProps, nextState, context); this._blockSetState = false; this.props = nextProps; var state = this.state = nextState; this.context = context; inferno.options.beforeRender && inferno.options.beforeRender(this); var render = this.render(nextProps, state, context); inferno.options.afterRender && inferno.options.afterRender(this); return render; } } return inferno.NO_OP; }; return Component$1; })));
ChadoNihi/fcc-voting-app
node_modules/inferno/dist/inferno-component.node.js
JavaScript
mit
11,107
/** * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @providesModule getDOMNodeID * @typechecks */ "use strict"; /** * Accessing "id" or calling getAttribute('id') on a form element can return its * control whose name or ID is "id". All DOM nodes support `getAttributeNode` * but this can also get called on other objects so just return '' if we're * given something other than a DOM node (such as window). * * @param {DOMElement|DOMWindow|DOMDocument} domNode DOM node. * @returns {string} ID of the supplied `domNode`. */ function getDOMNodeID(domNode) { if (domNode.getAttributeNode) { var attributeNode = domNode.getAttributeNode('id'); return attributeNode && attributeNode.value || ''; } else { return ''; } } module.exports = getDOMNodeID;
petehunt/rendr-react-template
app/vendor/react/getDOMNodeID.js
JavaScript
mit
1,322
/** * @jsx React.DOM * @copyright Prometheus Research, LLC 2014 */ "use strict"; var React = require('react/addons'); var PropTypes = React.PropTypes; var Header = require('./Header'); var Viewport = require('./Viewport'); var ColumnMetrics = require('./ColumnMetrics'); var DOMMetrics = require('./DOMMetrics'); var GridScrollMixin = { componentDidMount() { this._scrollLeft = this.refs.viewport.getScroll().scrollLeft; this._onScroll(); }, componentDidUpdate() { this._onScroll(); }, componentWillMount() { this._scrollLeft = undefined; }, componentWillUnmount() { this._scrollLeft = undefined; }, onScroll({scrollLeft}) { if (this._scrollLeft !== scrollLeft) { this._scrollLeft = scrollLeft; this._onScroll(); } }, _onScroll() { if (this._scrollLeft !== undefined) { this.refs.header.setScrollLeft(this._scrollLeft); this.refs.viewport.setScrollLeft(this._scrollLeft); } } }; var Grid = React.createClass({ mixins: [ GridScrollMixin, ColumnMetrics.Mixin, DOMMetrics.MetricsComputatorMixin ], propTypes: { rows: PropTypes.oneOfType([PropTypes.array, PropTypes.func]).isRequired, columns: PropTypes.array.isRequired }, getStyle: function(){ return{ overflowX: 'scroll', overflowY: 'hidden', outline: 0, position: 'relative', minHeight: this.props.minHeight } }, render() { var headerRows = this.props.headerRows || [{ref : 'row'}]; return ( <div {...this.props} style={this.getStyle()} className="react-grid-Grid"> <Header ref="header" columns={this.state.columns} onColumnResize={this.onColumnResize} height={this.props.rowHeight} totalWidth={this.DOMMetrics.gridWidth()} headerRows={headerRows} /> <Viewport ref="viewport" width={this.state.columns.width} rowHeight={this.props.rowHeight} rowRenderer={this.props.rowRenderer} cellRenderer={this.props.cellRenderer} rows={this.props.rows} selectedRows={this.props.selectedRows} expandedRows={this.props.expandedRows} length={this.props.length} columns={this.state.columns} totalWidth={this.DOMMetrics.gridWidth()} onScroll={this.onScroll} onRows={this.props.onRows} rowOffsetHeight={this.props.rowOffsetHeight || this.props.rowHeight * headerRows.length} /> </div> ); }, getDefaultProps() { return { rowHeight: 35, minHeight: 350 }; }, }); module.exports = Grid;
adazzle/react-grid
src/Grid.js
JavaScript
mit
2,744
import './turn-order-a2314c0f.js'; import 'redux'; import 'immer'; import './reducer-4d135cbd.js'; import './Debug-1ad6801e.js'; import 'flatted'; import './ai-ce6b7ece.js'; import './initialize-ec2b5846.js'; export { C as Client } from './client-abd9e531.js';
cdnjs/cdnjs
ajax/libs/boardgame-io/0.39.12/esm/client.js
JavaScript
mit
261
'use strict'; angular.module('shoprApp') .controller('BookrCtrl', function ($scope, localStorageService, Auth, $http, $routeParams, $location) { $scope.Auth = Auth; //$scope.books = Auth.getCurrentUser().books; $scope.mySubs = Auth.getCurrentUser().books; function getById(books, id) { for(var b in books) { if(books[b]._id === id) return books[b]; } } function loadMore(book) { var page = book.recent[book.recent.length-book.pageIndex-1]; if(page && !page.src) { $http.get('/api/pages/'+book._id+'/'+page.issue).success(function(fullPage) { for(var k in fullPage[0]) page[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } var forward = book.recent[book.recent.length-book.pageIndex]; if(forward && !forward.src) { $http.get('/api/pages/'+book._id+'/'+forward.issue).success(function(fullPage) { for(var k in fullPage[0]) forward[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } var back = book.recent[book.recent.length-book.pageIndex-2]; if(back && !back.src) { $http.get('/api/pages/'+book._id+'/'+back.issue).success(function(fullPage) { for(var k in fullPage[0]) back[k]=fullPage[0][k]; setTimeout(function(){ $scope.$digest(); }, 500); }); } } function init(book, pageIndex) { book.pageIndex = pageIndex; $scope.$watch(function(){ return this.pageIndex; }.bind(book), function(newValue, oldValue){ console.log(this); loadMore(this); // $location.path('/bookr/'+this._id+'/'+this.pageIndex, false); var elm = $('book[ng-id="'+this._id+'"]')[0]; elm && $('html, body').animate({ scrollTop: elm.offsetTop }, 450); }.bind(book)); $scope.books.push(book); } function pad(books) { for(var b in books) { var book = books[b]; console.log(book); var recentLength = book.recent.length; for(var i = 0; i < book.count-recentLength; i++) book.recent.push({_id:book._id+'_'+(book.count-(recentLength+1)-i), issue:book.count-(recentLength+1)-i}); console.log(book); } } var books = [$routeParams]; $scope.books = []; for(var b in books) { var book = getById($scope.mySubs, books[b].book); if(!book) { var page = books[b].page; $http.get('/api/books/'+books[b].book).success(function(book){ pad([book]); console.log(book); $scope.mySubs.push(book); init(book, page); console.log('wtf?'); }); continue; } init(book, parseInt(books[b].page)); } });
samsface/reads
client/app/bookr/bookr.controller.js
JavaScript
mit
2,642
'use strict'; var express = require("express"); var http = require("http"); var app = express(); var httpServer = http.Server(app); var io = require('socket.io')(httpServer); // Users array. var users = []; // Channels pre-defined array. var channels = [ 'Angular', 'React', 'Laravel', 'Symfony' ]; // Start http server. httpServer.listen(3000, function () { }); // Use static files 'app' folder for '/' path. app.use(express.static(__dirname + '/app/')); // Channels endpoint. app.get('/channels', function (req, res) { res.send(channels); }); // On connection event. io.on('connection', function (socket) { // Join event. socket.on('join', function (data) { // Join socket to channel. socket.join(data.channel); // Add user to users lists. users.push({id: socket.id, name: data.user}); // Bind username to socket object. socket.username = data.user; // If socket already exists in a channel, leave. if (typeof socket.channel != 'undefined') { socket.leave(socket.channel); } // Bind channel to socket. socket.channel = data.channel; }); // Message event. socket.on('message', function (data) { // Send to selected channel user's message. io.sockets.in(data.channel).emit('message', {message: data.message, user: data.username}); }); // Private message event. socket.on('private', function (data) { // Split message to take receiver name. var message = data.message.split(" "); // Get username from message array. var to_user = message[0].slice(1); // Filter users to find user's socket id and send message. users.filter(function (user) { if (user.name == to_user) { // Format message. var private_message = "(private) " + data.message.slice(to_user.length + 2); // Send message to user who sent the message. io.sockets.connected[socket.id].emit('message', {message: private_message, user: "me -> " + to_user}); // Send message to receiver. io.sockets.connected[user.id].emit('message', {message: private_message, user: data.username}); } }); }); // Disconnect event. socket.on('disconnect', function () { // Check if user joined any room and clean users array. users = users.filter(function (user) { if (user.id == socket.id) { return false; } return true }); }); });
tkorakas/chat-application
server/index.js
JavaScript
mit
2,630
import globalize from 'globalize'; import configure from '../src/configure'; export default function testLocalizer() { function getCulture(culture){ return culture ? globalize.findClosestCulture(culture) : globalize.culture() } function shortDay(dayOfTheWeek, culture) { let names = getCulture(culture).calendar.days.namesShort; return names[dayOfTheWeek.getDay()]; } var date = { formats: { date: 'd', time: 't', default: 'f', header: 'MMMM yyyy', footer: 'D', weekday: shortDay, dayOfMonth: 'dd', month: 'MMM', year: 'yyyy', decade: 'yyyy', century: 'yyyy', }, firstOfWeek(culture) { culture = getCulture(culture) return (culture && culture.calendar.firstDay) || 0 }, parse(value, format, culture){ return globalize.parseDate(value, format, culture) }, format(value, format, culture){ return globalize.format(value, format, culture) } } function formatData(format, _culture){ var culture = getCulture(_culture) , numFormat = culture.numberFormat if (typeof format === 'string') { if (format.indexOf('p') !== -1) numFormat = numFormat.percent if (format.indexOf('c') !== -1) numFormat = numFormat.curency } return numFormat } var number = { formats: { default: 'D' }, parse(value, culture) { return globalize.parseFloat(value, 10, culture) }, format(value, format, culture){ return globalize.format(value, format, culture) }, decimalChar(format, culture){ var data = formatData(format, culture) return data['.'] || '.' }, precision(format, _culture){ var data = formatData(format, _culture) if (typeof format === 'string' && format.length > 1) return parseFloat(format.substr(1)) return data ? data.decimals : null } } configure.setLocalizers({ date, number }) }
haneev/react-widgets
packages/react-widgets/test/test-localizer.js
JavaScript
mit
1,970
var instance = null; OptionSelect = function OptionSelect(optionSelectFunction, id, options) { this.optionSelect = optionSelectFunction; this.containerId = id; this.options = options; instance.instanceData.set(this); } OptionSelect.prototype.open = function() { $(this.containerId).show(); }; Template.optionSelect.onCreated(function() { this.instanceData = new ReactiveVar({}); instance = this; }); Template.optionSelect.helpers({ options: function() { return instance.instanceData.get().options; } }); Template.optionSelect.events({ 'click .option-select__selection': function() { var obj = instance.instanceData.get(); obj.optionSelect(this); $(obj.containerId).hide(); }, 'click #option-select-close': function() { $(instance.instanceData.get().containerId).hide(); } });
Spartano/fl-maps
client/templates/eventsForm/optionSelect/optionSelect.js
JavaScript
mit
805
// Ember.merge only supports 2 arguments // Ember.assign isn't available in older Embers // Ember.$.extend isn't available in Fastboot import Ember from 'ember'; export default function(...objects) { let merged = {}; objects.forEach(obj => { merged = Ember.merge(merged, obj); }); return merged; }
rlivsey/fireplace
addon/utils/merge.js
JavaScript
mit
311
var fs = require('fs'); var dot = require('dot'); var defaults = require('defaults'); var Block = require('glint-block'); var Style = require('glint-plugin-block-style-editable'); var TextBlock = require('glint-block-text'); var MDBlock = require('glint-block-markdown'); var MetaBlock = require('glint-block-meta'); var CKEditorBlock = require('glint-block-ckeditor'); var Adapter = require('glint-adapter'); var PageAdapter = require('page-adapter'); var Container = require('glint-container'); var Wrap = require('glint-wrap'); var Widget = require('glint-widget'); var LayoutWrap = require('wrap-layout'); var template = fs.readFileSync(__dirname + '/index.dot', 'utf-8'); var compiled = dot.template(template); function text() { return Block(TextBlock()).use(Style()); } function markdown() { return Block(MDBlock()).use(Style()); } function editor() { return Block(CKEditorBlock()).use(Style()); } exports = module.exports = function wrap(o) { o = o || {}; var wrap = Wrap(); var blocks = { 'home-title': text().selector('[data-id=home-title]'), 'home-teaser': editor().selector('[data-id=home-teaser]'), 'home-subtitle': markdown().selector('[data-id=home-subtitle]'), 'home-box-1': markdown().selector('[data-id=home-box-1]'), 'home-box-2': markdown().selector('[data-id=home-box-2]'), 'home-box-3': markdown().selector('[data-id=home-box-3]'), 'home-box-4': markdown().selector('[data-id=home-box-4]'), 'home-box-5': markdown().selector('[data-id=home-box-5]'), 'home-box-6': markdown().selector('[data-id=home-box-6]'), 'www-title': text().selector('[data-id=www-title]'), 'www-content': editor().selector('[data-id=www-content]'), 'bb-title': text().selector('[data-id=bb-title]'), 'bb-content': markdown().selector('[data-id=bb-content]'), 'doc-title': text().selector('[data-id=doc-title]'), 'doc-content': markdown().selector('[data-id=doc-content]'), 'img-title': text().selector('[data-id=img-title]'), 'img-content': editor().selector('[data-id=img-content]'), 'contact-title': text().selector('[data-id=contact-title]'), 'contact-content': markdown().selector('[data-id=doc-content]'), meta: Block(MetaBlock()) }; var adapter = o.adapter || PageAdapter(o); var db = o.db || 'glint'; var type = o.type || 'main'; var id = o.id || 'main'; var templateData = o.templateData || '__template__'; var homeAdapter = Adapter(adapter) .db(db) .type(type) var container = Container(blocks, homeAdapter) .id(id) .template(templateData); wrap .parallel(container) .series('content', Widget(function(options) { return compiled(options) }).place('force:server')) .series(LayoutWrap(o.layout).place('force:server')) wrap.routes = adapter.routes; return wrap; };
glintcms/glintcms-starter-glintcms
local_modules/page-main/wrap.js
JavaScript
mit
2,840
var Logger = require("./Logger.js"); var Level = require("./Level.js"); var PrintPattern = require("./PrintPattern.js"); module.exports = (function() { /* STATE VARIABLES */ // OUT configuration var OUT_INTERVAL = undefined; // 1sec var OUT_INTERVAL_TIMEOUT = 1000; // 1sec var OUT_SIZE = 1000; // logger objects var loggers = {}; // appender list var appenders = {}; appenders[Level.trace] = {}; appenders[Level.log] = {}; appenders[Level.info] = {}; appenders[Level.warn] = {}; appenders[Level.error] = {}; // information to log var records = new Array(); // -------------------------------------------------------------------------- /* METHODS */ // add a logger to the map // logger_name should be something like group.subgroup.name var createLogger = function(logger_name) { if (loggers[logger_name] == undefined) { loggers[logger_name] = new Logger(logger_name, function(record) { records.push(record); writeLog(); }); } return loggers[logger_name]; } // create the appender objects // the appender_config should be something like // [{ // "name": "appender name", // "type": "appender implementation", // "level": "level that appender listens", // "loggers": ["logger1", "logger2", "group.logger3"], // Follows the optional attributes // -------------------------------------------------- // "print_pattern": "[{y}/{M}/{d} {w} {h}:{m}:{s}.{ms}] [{lvl}] [{lg}] // {out}", // "config": {...[appender exclusive configuration]} // }, ...] var loadAppenderConfig = function(appender_configs) { realeaseAppenders(); for ( var i in appender_configs) { // get an appender config var appender_config = appender_configs[i]; // create appender object var AppenderType = require("./appender/" + appender_config.type + "Appender.js"); var appender_object = new AppenderType(appender_config.name, new PrintPattern(appender_config.print_pattern), appender_config.config); for ( var l in appender_config.loggers) { var listened_logger = appender_config.loggers[l]; // initialize listened logger appender list if (appenders[Level[appender_config.level]][listened_logger] == undefined) { appenders[Level[appender_config.level]][listened_logger] = new Array(); } appenders[Level[appender_config.level]][listened_logger] .push(appender_object); } } } // realease appenders internal resources; var realeaseAppenders = function() { for (lv in appenders) { var level_appender = appenders[lv]; for (lg in level_appender) { var logger_appender = level_appender[lg]; if (logger_appender.length > 0) { for (i in logger_appender) { var appender = logger_appender[i]; appender.release(); } } delete level_appender[lg]; } } }; // Wrapper that decides when the app will log without hold the process var writeLog = function() { if (OUT_INTERVAL == undefined) { OUT_INTERVAL = setTimeout(writeLogImpl, OUT_INTERVAL_TIMEOUT); } }; // real log process var writeLogImpl = function() { for (var i = 0; i < OUT_SIZE; i++) { // getting message record var record = records[i]; // stop the loop when ther record list is empty; if (record == undefined) { break; } // the record should be logged on all appender that listen the same // level or the appenders that listen lower levels for (var level = record.level; level >= 1; level--) { // getting appender list by level var level_appenders = appenders[level]; // try to catch all appenders as possible var logger_composition = record.logger.split("."); var logger_name = undefined; for (var lc = 0; lc < logger_composition.length; lc++) { // logger name rebuild process if (logger_name == undefined) { logger_name = logger_composition[lc]; } else { logger_name = logger_name + "." + logger_composition[lc]; } // getting appender list by logger var logger_appenders = level_appenders[logger_name]; // using appender if (logger_appenders != undefined) { for (a in logger_appenders) { var appender = logger_appenders[a]; appender.write(record); } } } } } records.splice(0, OUT_SIZE); // clean interval identifier OUT_INTERVAL = undefined; // if still remain any record, start again the log process if (records.length > 0) { writeLog(); } }; // public interface return { "createLogger" : createLogger, "loadAppenderConfig" : loadAppenderConfig } })();
michelwooller/LogAPI
index.js
JavaScript
mit
4,562
/** * @constructor */ var TwoSum = function() { this.dict = {}; }; /** * @param {number} input * @returns {void} */ TwoSum.prototype.add = function(input) { // no need to bigger that 2 this.dict[input] = this.dict[input] ? 2 : 1; }; /** * @param {number} val * @returns {boolean} */ TwoSum.prototype.find = function(val) { var dict = this.dict; var keys = Object.keys(dict); for (var i = 0; i < keys.length; i++) { var key = parseInt(keys[i]); var target = val - key; if (!dict[target]) continue; if ((target === key && dict[target] === 2) || target !== key) { return true; } } return false; }; var eq = require('assert').equal; var ts = new TwoSum(); ts.add(0); ts.find(0) eq(ts.find(0), false); ts = new TwoSum(); ts.add(0); ts.add(0); ts.find(0) eq(ts.find(0), true); ts = new TwoSum(); ts.add(1); ts.add(3); ts.add(5); eq(ts.find(1), false); eq(ts.find(4), true); eq(ts.find(7), false);
zhiyelee/leetcode
js/twoSumIiiDataStructureDesign/two_sum_iii_data_structure_design.js
JavaScript
mit
959
import Element from './Element' export default class extends Element { constructor ( val ) { super({ 'w:type': {} }) if (val) this.setVal(val || null) } setVal (value) { if (value) { this.src['w:type']['@w:val'] = value } else { delete this.src['w:type']['@w:val'] } } getVal () { return this.src['w:type']['@w:val'] || null } }
zuck/jsdocx
src/SectionType.js
JavaScript
mit
390
/** * Module dependencies. */ var express = require('express'); var http = require('http'); var path = require('path'); var handlebars = require('express3-handlebars'); var index = require('./routes/index'); var project = require('./routes/project'); var palette = require('./routes/palette'); // Example route // var user = require('./routes/user'); var app = express(); // all environments app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.engine('handlebars', handlebars()); app.set('view engine', 'handlebars'); app.use(express.favicon()); app.use(express.logger('dev')); app.use(express.json()); app.use(express.urlencoded()); app.use(express.methodOverride()); app.use(express.cookieParser('Intro HCI secret key')); app.use(express.session()); app.use(app.router); app.use(express.static(path.join(__dirname, 'public'))); // development only if ('development' == app.get('env')) { app.use(express.errorHandler()); } // Add routes here app.get('/', index.view); app.get('/project/:id', project.projectInfo); app.get('/palette', palette.randomPalette); // Example route // app.get('/users', user.list); http.createServer(app).listen(app.get('port'), function(){ console.log('Express server listening on port ' + app.get('port')); });
ryanjhill/lab6
app.js
JavaScript
mit
1,298
var model = require('../model'); // ROUTES exports.saveAvailabilityChange = function(req, res) { console.log('hi im here') function afterSave(err){ if(err) { console.log(err) res.send(500) } else { backURL = req.header('Referer') || '/'; res.redirect(backURL); } } if(req.query.optionsRadios == 'available') { var curr_user = req.session.user req.session.user.isAvailable = true model.User.update({ "email":req.session.user.email }, { "isAvailable":true }).exec(afterSave) } else { var curr_user = req.session.user req.session.user.isAvailable = false model.User.update({ "email":req.session.user.email }, { "isAvailable":false }).exec(afterSave) } } exports.viewEditIntervieweeProfile = function(req, res) {
 function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewee/editIntervieweeProfile', req.session.user); } } ) } } if (req.query.email){ // form submit /* fname or firstname?? */ model.User.update({"email":req.session.user.email}, { "firstname":req.query.fname, "lastname":req.query.lname, "email":req.query.email, "education":req.query.education, "occupation":req.query.occupation, "location":req.query.location }).exec(afterFind); } else afterFind(null) 
} exports.viewEditInterviewerProfile = function(req, res) {
 function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewer/editInterviewerProfile', req.session.user); } } ) } } if (req.query.email){ // form submit /* fname or firstname?? */ model.User.update({"email":req.session.user.email}, { "firstname":req.query.fname, "lastname":req.query.lname, "email":req.query.email, "education":req.query.education, "occupation":req.query.occupation, "location":req.query.location, "company":req.query.company }).exec(afterFind); } else afterFind(null) 
} exports.view = function(req, res){ if (req.query.invalid) res.render('prelogin/index', { 'invalid': req.query.invalid }) else res.render('prelogin/index'); }; exports.viewIntervieweeAreasToImprove = function(req, res){ function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; console.log(req.session.user.isAlternate) res.render('interviewee/intervieweeAreasToImprove', req.session.user); } } ) } } if (req.query.improvements){ // form submit model.User.update({"email":req.session.user.email}, {"improvements":req.query.improvements}).exec(afterFind); } else afterFind(null) }; exports.viewIntervieweeFeedback = function(req, res){ model.User.find({"email":req.session.user.email}).exec(renderFeedbacks); function renderFeedbacks(err, users) { var user = users[0] console.log(user.feedback) res.render('interviewee/intervieweeFeedback', { 'feedbacks': user.feedback, 'isAvailable':req.session.user.isAvailable }); } }; exports.viewInterviewerFeedback = function(req, res){ model.User.find({"email":req.session.user.email}).exec(renderFeedbacks); function renderFeedbacks(err, users) { var user = users[0] console.log(user.feedback) res.render('interviewer/interviewerFeedback', { 'feedbacks': user.feedback, 'isAvailable':req.session.user.isAvailable }); } }; exports.viewIntervieweeSkills = function(req, res){ console.log('Skills + isAvailable:' + req.session.user.isAvailable) function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var curr_user = users[0] req.session.user = curr_user; res.render('interviewee/intervieweeSkills',req.session.user); } } ) } } if (req.query.programmingLang){ // form submit model.User.update({ "email":req.session.user.email }, { "programmingLang":req.query.programmingLang, "softSkills":req.query.softSkills, "frameworks":req.query.frameworks }) .exec(afterFind); } else afterFind(null) }; exports.dosurveyInterviewee = function(req, res) {
 model.User.find({ "email": req.query.email }).exec(function(err, users){ if (err) { console.log(err); res.send(500) } else { if (users.length == 0){ var random = Math.random() var isAlternate = true //(random > 0.5), chose alternate version var newUser = model.User({ "firstname": req.query.fname, "lastname": req.query.lname, "email": req.query.email, "password": req.query.password, "ghangout": req.query.ghangout, "interviewer": false, "education": req.query.education, "occupation": req.query.occupation, "location": req.query.location, "programmingLang": "For example: Java, C++, Python", "softSkills": "For example: Good communication skills, Experience managing teams", "frameworks": "For example: DJango, MongoDB, Google AppEngine", "improvements": "For example: practicing more technical questions, learning to clearly express ideas", "isAlternate": isAlternate, "isAvailable": true }); console.log(newUser) newUser.save(function(err){ if (err) { console.log(err) res.send(500) } else { req.session.user = newUser res.render('interviewee/intervieweeSurvey',newUser); } }); } else { console.log('Associated email address already used.') res.send(500) } } }); 
} exports.viewInterviewerAboutMe = function(req, res){ function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({"email":req.session.user.email}).exec( function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewer/interviewerAboutMe', req.session.user); } } ) } } if (req.query.mission){ // form submit model.User.update({"email":req.session.user.email}, {"mission":req.query.mission,"hobbies":req.query.hobbies}).exec(afterFind); } else afterFind(null) }; exports.viewInterviewerPastExp = function(req, res){ function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({ "email":req.session.user.email }).exec(function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewer/interviewerPastExp', req.session.user); } }) } } if (req.query.description1){ // form submit model.User.update({ "email":req.session.user.email }, { "description1":req.query.description1, "description2":req.query.description2 }).exec(afterFind); } else afterFind(null) }; exports.dosurveyInterviewer = function(req, res) {
 model.User.find({ "email": req.query.email }).exec(function(err, users){ if (err) console.log(err); else { if (users.length == 0){ var randnum = Math.random() var isAlternate = true; // (randnum > 0.5) chose alternate version var newUser = model.User({ "firstname": req.query.fname, "lastname": req.query.lname, "email": req.query.email, "password": req.query.password, "ghangout": req.query.ghangout, "interviewer": true, "education": req.query.education, "occupation": req.query.occupation, "location": req.query.location, "company": req.query.company, "mission": "Tell us more about yourself.", "hobbies": "What are your hobbies?", "description1": "What did you do? Where did you work?", "description2": "What did you do? Where did you work?", "isAlternate": isAlternate, "isAvailable": true }); console.log(isAlternate) newUser.save(function(err){ if (err) { console.log(err) res.send(500) } else { req.session.user = newUser res.render('interviewer/interviewerSurvey',newUser); } }); } else { console.log('Associated email address already used.') res.send(500) } } }); }; exports.viewLogin = function(req, res){ res.render('prelogin/login'); }; exports.viewMatchForInterviewer = function(req, res){ // get occupation console.log(req.session) if (req.session.user) occupation = req.session.user.occupation else occupation = '' // find users with matching occupation // eventually create req.session.set and store people already viewed // only allow non-viewed people into matching_occupation_users // also allow match page to let you know when you have exhausted all options matching_occupation_users = [] model.User.find({"occupation":occupation,"interviewer":false}).exec(afterFind); function afterFind(err,users){ if(err) { console.log(err) res.send(500) } else { for (i = 0; i < users.length; i++){ matching_occupation_users.push(users[i]); }; // select a random person num_matching = matching_occupation_users.length rand_index = Math.floor(Math.random() * num_matching) matched_user = matching_occupation_users[rand_index] var curr_user = req.session.user res.render('matchForInterviewer', { 'match': matched_user, 'curr_user': curr_user }); } }; }; exports.viewMatchForInterviewee = function(req, res){ // get occupation console.log(req.session) if (req.session.user) occupation = req.session.user.occupation else occupation = '' // find users with matching occupation // eventually create req.session.set and store people already viewed // only allow non-viewed people into matching_occupation_users // also allow match page to let you know when you have exhausted all options matching_occupation_users = [] model.User.find({"occupation":occupation,"interviewer":true}).exec(afterFind); function afterFind(err,users){ if(err) { console.log(err) res.send(500) } else { for (i = 0; i < users.length; i++){ matching_occupation_users.push(users[i]); }; // select a random person num_matching = matching_occupation_users.length rand_index = Math.floor(Math.random() * num_matching) matched_user = matching_occupation_users[rand_index] var curr_user = req.session.user res.render('matchForInterviewee', { 'match': matched_user, 'curr_user': curr_user, 'isAvailable':req.session.user.isAvailable }); } }; }; exports.kickoff = function(req, res) {
 var curr_user = req.session.user res.render('startInterview', { 'match':req.params.match, 'curr_user': curr_user, 'isAvailable':req.session.user.isAvailable }); }; exports.kickoffWithInterviewee = function(req, res){ res.render('interviewee/intervieweeSkills', req.session.user); }; exports.viewUnimplemented = function(req, res){ res.render('unimplemented'); }; exports.logout = function(req, res){ req.session.destroy(function(err){ if (err) console.log(err) console.log('cleared session') res.redirect('/'); }) }; exports.viewSignup = function(req, res){ res.render('prelogin/signup'); }; exports.viewInterviewerProfile = function(req, res) { // this route is only called after session is set res.render('interviewer/interviewerProfile', req.session.user); }; exports.viewInterviewerProfileAlter = function(req,res){ res.render('interviewer/interviewerProfileAlter',req.session.user); } exports.viewIntervieweeProfileAlter = function(req,res){ res.render('interviewee/intervieweeProfileAlter',req.session.user); } exports.viewIntervieweeProfile = function(req, res) { if (req.session && req.session.user){ console.log(req.session.user.isAlternate) if (req.query.persontype) { // means came from signup surveys console.log('came from signup') if (req.query.persontype == "interviewee") {// interviewee console.log('interviewee') // update user obj in db model.User.update({ '_id': req.session.user._id }, { 'occupation': req.query.occupation, 'education': req.query.education, 'location': req.query.location }).exec(function(err){ if (err) { console.log(err) res.send(500) } else { model.User.find({ '_id': req.session.user._id }).exec(function(err, users){ if (err) { console.log(err) res.send(500) } else { var user = users[0] req.session.user = user res.redirect('intervieweeProfile/alternate'); } }) } }) } else {// interviewer console.log('interviewer') model.User.update({'_id': req.session.user._id}, { 'occupation': req.query.occupation, 'education': req.query.education, 'location': req.query.location, 'company':req.query.company, }).exec(function(err){ if (err) { console.log(err) res.send(500) } else { model.User.find({ '_id': req.session.user._id }).exec(function(err, users){ if (err) { console.log(err) res.send(500) } else { var user = users[0] req.session.user = user res.redirect('interviewerProfile/alternate'); } }) } }); } } else { // just returning to the page if (req.session.user.interviewer){ res.redirect('interviewerProfile/alternate'); } else { res.redirect('intervieweeProfile/alternate'); } } } else if (req.query && req.query.uname){ // after login console.log('came from login') console.log('email:', req.query.uname) console.log('password:', req.query.password) model.User.find({ "email": req.query.uname, "password": req.query.password }).exec(afterFind); function afterFind(err, users){ if (err) { console.log(err) res.send(500) } else if (users.length > 0){ var user = users[0] console.log(user); console.log(user.password); console.log(user.isAlternate) req.session.user = user if (user.interviewer){ res.redirect('interviewerProfile/alternate'); } else { console.log('I AM HERE') res.redirect('intervieweeProfile/alternate'); } } else res.redirect('/?invalid=1') } } else res.redirect('/?invalid=1'); } exports.postFeedback = function(req,res){ function afterUpdate(err){ if(err) { console.log(err) res.send(500) } else { res.render('feedback', { 'match':req.params.match, 'curr_user':curr_user, 'isAvailable':req.session.user.isAvailable }); } } if(req.query.feedback){// form submit console.log("I came here! Pay attention!") var curr_user = req.session.user model.User.update({"email":req.params.match}, { $push: {"feedback":{"text":req.query.feedback,"by":curr_user.firstname}} }).exec(afterUpdate); } else afterUpdate(null); } exports.viewInterviewerPastExp = function(req, res){ function afterFind(err){ if(err) { console.log(err) res.send(500) } else { model.User.find({ "email":req.session.user.email }).exec(function(err,users){ if (err) { console.log(err) res.send(500) } else { var found = users[0] req.session.user = found; res.render('interviewer/interviewerPastExp', req.session.user); } }) } } if (req.query.description1){ // form submit model.User.update({ "email":req.session.user.email }, { "description1":req.query.description1, "description2":req.query.description2 }).exec(afterFind); } else afterFind(null) };
govindad/interviewroulette
routes/routes.js
JavaScript
mit
16,653
System.register(['core-js', './map-change-records', './collection-observation'], function (_export) { var core, getChangeRecords, ModifyCollectionObserver, _classCallCheck, _inherits, mapProto, ModifyMapObserver; _export('getMapObserver', getMapObserver); function getMapObserver(taskQueue, map) { return ModifyMapObserver.create(taskQueue, map); } return { setters: [function (_coreJs) { core = _coreJs['default']; }, function (_mapChangeRecords) { getChangeRecords = _mapChangeRecords.getChangeRecords; }, function (_collectionObservation) { ModifyCollectionObserver = _collectionObservation.ModifyCollectionObserver; }], execute: function () { 'use strict'; _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; _inherits = function (subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }; mapProto = Map.prototype; ModifyMapObserver = (function (_ModifyCollectionObserver) { function ModifyMapObserver(taskQueue, map) { _classCallCheck(this, ModifyMapObserver); _ModifyCollectionObserver.call(this, taskQueue, map); } _inherits(ModifyMapObserver, _ModifyCollectionObserver); ModifyMapObserver.create = function create(taskQueue, map) { var observer = new ModifyMapObserver(taskQueue, map); map.set = function () { var oldValue = map.get(arguments[0]); var type = oldValue ? 'update' : 'add'; var methodCallResult = mapProto.set.apply(map, arguments); observer.addChangeRecord({ type: type, object: map, key: arguments[0], oldValue: oldValue }); return methodCallResult; }; map['delete'] = function () { var oldValue = map.get(arguments[0]); var methodCallResult = mapProto['delete'].apply(map, arguments); observer.addChangeRecord({ type: 'delete', object: map, key: arguments[0], oldValue: oldValue }); return methodCallResult; }; map.clear = function () { var methodCallResult = mapProto.clear.apply(map, arguments); observer.addChangeRecord({ type: 'clear', object: map }); return methodCallResult; }; return observer; }; return ModifyMapObserver; })(ModifyCollectionObserver); } }; });
martingust/martingust.github.io
jspm_packages/github/aurelia/binding@0.6.1/map-observation.js
JavaScript
mit
3,025
var BoardVo = require(_path.src + "/vo/BoardVo.js"); var BoardDao = require(_path.src + "/dao/BoardDao.js"); var RoleDao = require(_path.src + "/dao/RoleDao.js"); module.exports.board = function($, el, param, req, next) { var template = this.getTemplate($, el); BoardDao.getBoard(param.id, function(board) { $(el).html(template(board)); next(); }); }; module.exports.boardList = function($, el, param, req, next) { var vo = new BoardVo(); if(req.session.user != null) { vo.signinUserId = req.session.user.id; vo.signinUserLevel = req.session.user.level; } var template = this.getTemplate($, el); BoardDao.getBoardList(vo, function(boardList) { RoleDao.getRoleList(function(roleList) { $(el).html(template({boardList : boardList, roleList : roleList})); next(); }); }); };
tonite31/Imboard
src/module/BoardModule.js
JavaScript
mit
807
/** * Created by sh on 15/7/6. */ "use strict"; var type = require("../type"); exports.parse = function (object, define, addition) { return type.dataParse(object, {type: Object, contents: String}, addition); };
LightCircle/LightCore
lib/db/mongo/operator/$rename.js
JavaScript
mit
218
/** * Created with JetBrains WebStorm. * User: gbox3d * Date: 13. 3. 30. * Time: 오후 3:35 * version : 0.8 * it is parts of pig2d engine * this engine is base on html5 css3 최종수정 2015.11.5 - 배경적용안되는 버그 수정, 2015.11.5 */ Pig2d = { version : '1.0.0' }; ///////////////////// ///model Pig2d.model = Backbone.Model.extend({ initialize: function() { var element = document.createElement('div'); var name = this.get('name'); if(name != undefined) { element.setAttribute('id',name); } //2.3 이전 버전을 위한 if(element.classList != undefined) { element.classList.add('pig2d-node'); } else { $(element).addClass('pig2d-node'); } this.attributes.element = element; this.attributes.update_signal = 'none'; this.attributes.translation = new gbox3d.core.Vect2d(0,0); this.attributes.scale = new gbox3d.core.Vect2d(1,1); //this.attributes.matrix = mat2d.create(); //this.attributes.matrix = new WebKitCSSMatrix(); this.attributes.flipX = false; this.attributes.flipY = false; this.attributes.cssupdate = true; this.attributes.cancelTransition = false; this.attributes.offset = { x:0, y:0 }; }, defaults: { rotation : 0 }, getPosition : function() { //if(decompose == true) { //행렬분해후 적용 // this.decomposeCssMatrix(this.getCssMatrix()); //} return this.attributes.translation; }, getRotation : function() { return this.attributes.rotation; }, setPosition : function(x,y) { this.attributes.translation.set(x,y); return this; }, setRotation : function(angle) { this.attributes.rotation = angle; return this; }, rotate : function(angle_delata) { this.attributes.rotation += angle_delata; return this; }, setScale : function(x,y) { this.attributes.scale.set(x,y); return this; }, getScale : function() { return this.attributes.scale; }, translate: function () { var v1 = new gbox3d.core.Vect2d(); var center = new gbox3d.core.Vect2d(0,0); return function ( distance, axis ) { // axis is assumed to be normalized v1.copy( axis ); v1.multiply( distance ); v1.rotate( gbox3d.core.degToRad(-this.attributes.rotation),center); if(this.attributes.flipX) { v1.X *= -1; } if(this.attributes.flipY) { v1.Y *= -1; } this.attributes.translation.addToThis( v1 ); return this; }; }(), show : function(visible) { this.get('element').style.visibility = visible ? 'inherit' : 'hidden'; }, isVisible : function() { return (this.get('element').style.visibility == 'hidden') ? false : true; }, ///////////////////// ////행렬관련 ////////////////// getCssMatrix : function() { var el = this.get('element'); var computedStyle = window.getComputedStyle(el); var trans = computedStyle.getPropertyValue('-webkit-transform'); var cssmat = new WebKitCSSMatrix(trans); return cssmat; }, //주어진 행렬을 분해하여 노드변환값에 역적용하기 decomposeCssMatrix : function(cssmat) { //var cssmat = this.getCssMatrix(); //이동변환 얻기 this.attributes.translation.X = cssmat.e; this.attributes.translation.Y = cssmat.f; //스케일 얻기 var scalex = Math.sqrt(cssmat.a*cssmat.a + cssmat.b*cssmat.b); var scaley = Math.sqrt(cssmat.c*cssmat.c + cssmat.d*cssmat.d); this.attributes.scale.X = scalex; this.attributes.scale.Y = scaley; //회전 얻기 var angle = Math.round(Math.atan2(cssmat.b/scalex, cssmat.a/scalex) * (180/Math.PI)); this.attributes.rotation = angle; }, getDecomposePosition : function() { var cssmat = this.getCssMatrix(); return new gbox3d.core.Vect2d(cssmat.e,cssmat.f); }, ////////////// animator setupTransition : function(param) { var element = this.get('element'); element.style.WebkitTransition = ''; this.attributes.TransitionEndCallBack = param.TransitionEndCallBack; if(this.attributes._TransitionEndCallBack != undefined) { element.removeEventListener('webkitTransitionEnd',this.attributes._TransitionEndCallBack); } this.attributes._TransitionEndCallBack = function(event) { if(this.attributes.cancelTransition == true) { this.attributes.cancelTransition = false; } else { this.attributes.cssupdate = true; element.style.WebkitTransition = ''; if(this.attributes.TransitionEndCallBack != undefined) { this.attributes.TransitionEndCallBack.apply(this); } } //이밴트 전달 금지 event.cancelBubble = true; event.stopPropagation(); }.bind(this); element.addEventListener('webkitTransitionEnd',this.attributes._TransitionEndCallBack,false); // if(param.timing_function != undefined) { // element.style.webkitTransitionTimingFunction = 'linear'; // } return this; }, transition : function(param) { var element = this.get('element'); param.timing_function = param.timing_function ? param.timing_function : 'linear'; if(element.style.WebkitTransition !== '') return; if(param.position != undefined) { if(param.position.X == this.attributes.translation.X && param.position.Y == this.attributes.translation.Y ) { } else { if(element.style.WebkitTransition === '') { element.style.WebkitTransition = '-webkit-transform ' + param.time + 's ' + param.timing_function; this.setPosition(param.position.X,param.position.Y); } } } if(param.rotation != undefined) { if(param.rotation == this.attributes.rotation) { } else { if(element.style.WebkitTransition === '') { element.style.WebkitTransition = '-webkit-transform ' + param.time + 's '+ param.timing_function; } this.setRotation(param.rotation); } } if(param.scale != undefined) { if(param.scale.X == this.attributes.scale.X && param.scale.Y == this.attributes.scale.Y) { } else { if(element.style.WebkitTransition === '') { element.style.WebkitTransition = '-webkit-transform ' + param.time + 's ' + param.timing_function; } this.setScale(param.scale.X,param.scale.Y); } } }, stopTransition : function(param) { this.attributes.update_signal = 'stop_transition'; this.attributes.cancelTransition = true; return this; }, clearTransition : function() { var el = this.get('element'); el.removeEventListener('webkitTransitionEnd',this.attributes._TransitionEndCallBack); this.attributes.update_signal = 'stop_transition'; }, //////////////////// updateCSS : function() { //if(this.attributes.cssupdate == false) return; var el = this.get('element'); switch (this.attributes.update_signal) { case 'none': (function() { //오브잭트변환값을 앨리먼트쪽으로 갱신해주기 if(this.attributes.cssupdate == true) { var trans = this.attributes.translation; var rot = this.attributes.rotation; var scalex = this.attributes.scale.X; var scaley = this.attributes.scale.Y; //반전 적용 if(this.attributes.flipX) { scaley = -scaley; } if(this.attributes.flipY) { scalex = -scalex; } var css_val = 'translate(' + trans.X + 'px,' + trans.Y +'px) ' + 'rotate(' + rot + 'deg) ' + 'scale(' + scalex + ',' + scaley + ')'; //브라우져 호환성을 위한 코드 el.style.WebkitTransform = css_val; el.style.MozTransform = css_val; el.style.oTransform = css_val; el.style.transform = css_val; //트랜지션 상태이면 css를 더이상 업데이트 못하게 한다 if(el.style.WebkitTransition !== '') { this.attributes.cssupdate = false; } } else { //현재 트랜지션 상태이므로 트래지션 취소는 무효화 된다. this.attributes.cancelTransition = false; } }).bind(this)(); break; case 'stop_transition': (function() { //행렬분해후 적용 this.decomposeCssMatrix(this.getCssMatrix()); el.style.WebkitTransition = ''; this.attributes.update_signal = 'none'; this.attributes.cssupdate = true; this.updateCSS(); }).bind(this)(); break; } return this; }, /////////////////////////////////////////// setupCssAnimation : function(option) { var element = this.get('element'); element.style.WebkitAnimationName = option.name; element.style.WebkitAnimationDuration = option.duration; if(option.timing_function) { element.style.WebkitAnimationTimingFunction = option.timing_function; } if(option.delay) { element.style.WebkitAnimationDelay = option.delay; } if(option.direction) { element.style.WebkitAnimationDirection = option.direction; } if(option.iteration_count) { element.style.WebkitAnimationIterationCount = option.iteration_count; } element.style.WebkitAnimationPlayState = 'running'; this.attributes.CssAnimationEndCallBack = option.EndCallBack; if(this.attributes._CssAnimationEndCallBack != undefined) { element.removeEventListener('webkitAnimationEnd',this.attributes._CssAnimationEndCallBack); } this.attributes._CssAnimationEndCallBack = function(event) { element.style.WebkitAnimation = ''; if(this.attributes.CssAnimationEndCallBack != undefined) { this.attributes.CssAnimationEndCallBack.apply(this); } //이밴트 전달 금지 event.cancelBubble = true; event.stopPropagation(); }.bind(this); element.addEventListener('webkitAnimationEnd',this.attributes._CssAnimationEndCallBack,false); return this; }, ////////////////////////// //노드에서 완전히 제거할때 사용됨 destroy : function() { var el = this.get('element'); //el.removeEventListener('webkitTransitionEnd'); this.clearTransition(); el.parentNode.removeChild(el); }, clone : function() { var model = Backbone.Model.prototype.clone.call(this); // console.log(model); model.set("element",this.get('element').cloneNode(true)); return model; } }); //end of base model ////////////////////// Pig2d.SpriteModel = Pig2d.model.extend({ initialize: function(param) { Pig2d.model.prototype.initialize.call(this); this.attributes.currentFrame = 0; //애니메이션 타이머 핸들 this.attributes.animationHID = null; var sheet = document.createElement('canvas'); sheet.classList.add('pig2d-sheet'); sheet.style.position = 'absolute'; this.get('element').appendChild(sheet); this.set('sheet',sheet); this.set('sheetCTX',sheet.getContext('2d')); this.attributes.currentTick = 0; this.attributes.scaler = 1; if(this.attributes.data.canvas_size) { sheet.width = this.attributes.data.canvas_size.width; sheet.height = this.attributes.data.canvas_size.height; } //캔버스 클리어 일부 삼성폰들은 초기화를 안할경우 잔상이 생긴다. //this.get('sheetCTX').clearRect(0,0,sheet.width,sheet.height); //this.setFrame(-1); //this.attributes.AnimationStatus = 'ready'; }, setScaler : function(scale) { this.attributes.scaler = scale; if(this.attributes.data.canvas_size) { var sheet = this.get('sheet'); this.attributes.data.canvas_size.width *= scale; this.attributes.data.canvas_size.height *= scale; sheet.width = this.attributes.data.canvas_size.width; sheet.height = this.attributes.data.canvas_size.height; } }, changeDress : function(param) { this.attributes.imgObj = param.texture; this.attributes.data = param.animation; var sheet = this.get('sheet'); if(this.attributes.data.canvas_size) { sheet.width = this.attributes.data.canvas_size.width; sheet.height = this.attributes.data.canvas_size.height; } this.setFrame(this.attributes.currentFrame); }, clone : function() { var model = Backbone.Model.prototype.clone.call(this); console.log('SpriteModel clone'); //model.set("element",this.get('element').cloneNode(true)); return model; }, updateCSS : function (deltaTime) { deltaTime = deltaTime || 0; this.applyAnimation(deltaTime); return Pig2d.model.prototype.updateCSS.call(this); }, ////////////////////////////////////////////// //애니메이션 관련 기능 ////////////////////////////////////////////// setFrame : function(index) { //프레임 노드 얻기 var imgObj = this.attributes.imgObj; if(this.attributes.data.frames.length <= index) { console.log('error exeed frame number : ' + index + ',' + this.attributes.data.frames.length); index = 0; } if(imgObj != undefined) { this.set('currentFrame',index); var sheet = this.attributes.sheet; var ctx = this.attributes.sheetCTX; /* 공백프레임을 만든 이유 : 일부 폰들(삼성폰)에서 캔버스를 처음생성한후 맨처음 랜더링된 이미지가 지워지지않고 남아 있는 현상들이 발생함 그래서 캔버스처음생성할때(changeDress,createSprite)할때는 반드시 공백프레임을 화면에 한번출력을 해주어야함 */ if(index < 0) { //공프레임 이면.. if(this.attributes.data.canvas_size) { sheet.width = this.attributes.data.canvas_size.width; sheet.height = this.attributes.data.canvas_size.height; ctx.clearRect(0,0,this.attributes.data.canvas_size.width,this.attributes.data.canvas_size.height); } } else { var frame = this.attributes.data.frames[this.attributes.currentFrame]; //console.log(this.attributes.currentFrame); var sheet_data = frame.sheets[0]; var scaler = this.attributes.scaler; if(this.attributes.data.canvas_size) { ctx.clearRect(0,0,this.attributes.data.canvas_size.width,this.attributes.data.canvas_size.height); //sheet.width = 1; //sheet.width = this.attributes.data.canvas_size.width; } else { sheet.width = sheet_data.width; sheet.height = sheet_data.height; } var offsetX = sheet_data.centerOffset.x; var offsetY = sheet_data.centerOffset.y; var destW = sheet_data.width; var destH = sheet_data.height; var cutx = -sheet_data.bp_x; var cuty = -sheet_data.bp_y; var srcW = sheet_data.width; var srcH = sheet_data.height; if(scaler < 1.0) { offsetX *= scaler; offsetY *= scaler; destW *= scaler; destH *= scaler; } sheet.style.webkitTransform = "translate(" + offsetX + "px," + offsetY + "px)"; ctx.drawImage( imgObj, cutx,cuty,srcW,srcH, 0,0,destW,destH ); } } return this; }, ///////////////////////////////////////////// /////new animation system//////////////////// ///////////////////////////////////////////// setupAnimation : function(param) { param = param ? param : {}; this.attributes.startFrame = param.startFrame ? param.startFrame : 0 ; this.attributes.endFrame = param.endFrame ? param.endFrame : (this.get('data').frames.length-1); if(param.isAnimationLoop !== undefined) { this.attributes.isAnimationLoop = param.isAnimationLoop; } else { this.attributes.isAnimationLoop = true; } this.attributes.AnimationEndCallback = param.AnimationEndCallback; this.attributes.AnimationStatus = param.AnimationStatus ? param.AnimationStatus : 'stop'; this.setFrame(this.attributes.startFrame); }, applyAnimation : function(delataTick) { if(this.attributes.AnimationStatus == 'play') { this.attributes.currentTick += delataTick; var frameindex = this.attributes.currentFrame; var Ani_data = this.get('data'); var delay = 300; if(frameindex >= 0) { delay = Ani_data.frames[frameindex].delay / 1000; } //var delay = Ani_data.frames[frameindex].delay / 1000; if(this.attributes.currentTick > delay) { this.attributes.currentTick = 0; ++frameindex; if(frameindex > this.attributes.endFrame) {//마지막 프레임이면 if(this.attributes.isAnimationLoop) { frameindex = this.attributes.startFrame; this.setFrame(frameindex); } else { this.attributes.AnimationStatus = 'stop'; frameindex = this.attributes.endFrame; } if(this.attributes.AnimationEndCallback != undefined) { this.attributes.AnimationEndCallback.bind(this)(); } } else { this.setFrame(frameindex); } } } else if(this.attributes.AnimationStatus == 'ready') { this.setFrame(-1); this.attributes.AnimationStatus = 'play'; this.attributes.currentFrame = this.attributes.startFrame; } }, stopAnimation : function() { this.attributes.AnimationStatus = 'stop'; }, //////////////////////// destroy : function() { //this.stop_animate(); //슈퍼 클래싱 Pig2d.model.prototype.destroy.call(this); } }); //end of sprite model /////////////////////// //////////////////node// ///////////////////////// Pig2d.node = Backbone.Model.extend({ initialize: function() { this.attributes.children = this.attributes.chiledren = new Array(); // _.bindAll(this,"update","clone"); }, traverse : function(callback,param) { callback.bind(this)(param); for(var index = 0;index < this.attributes.chiledren.length;index++ ) { this.attributes.chiledren[index].traverse(callback,param); } }, update: function(applyChild,deltaTime) { this.get('model').updateCSS(deltaTime); if( applyChild == true) { for(var index = 0;index < this.attributes.chiledren.length;index++ ) { this.attributes.chiledren[index].update(applyChild,deltaTime); } } return this; }, clone : function() { //딥 클로닝 var node = Backbone.Model.prototype.clone.call(this); if(node.get('model')) { var model = node.get('model').clone(); node.set({model:model}); } var chiledren = this.get('chiledren'); for(var i=0;i<chiledren.length;i++) { node.add(chiledren[i].clone()); } return node; }, findByName : function(name) { if(name == this.attributes.name) return this; for(var index in this.attributes.chiledren ) { var obj = this.attributes.chiledren[index].findByName(name); if(obj != null) return obj; } return null; }, findByID : function(cid) { if(cid == this.cid) return this; for(var index in this.attributes.chiledren ) { var obj = this.attributes.chiledren[index].findByID(cid); if(obj != null) return obj; } return null; }, add : function(child_node,parents) { if(parents == undefined || parents == null) { parents = this; } parents.get('chiledren').push(child_node); //child_node.setParent(parents); //모델이 존재하면 if(parents.get('model')) { var par_el = parents.get('model').get('element'); var child_el = child_node.get('model').get('element'); } par_el.appendChild(child_el); child_node.attributes.parent = parents; return this; }, //부모노드 바꾸기 setParent : function(parent) { var old_parent = this.get('parent'); var chiledren = old_parent.get('chiledren'); for(var i= chiledren.length-1;i >= 0;i--) { if(chiledren[i] === this) { chiledren.splice(i,1); parent.add(this); } } }, removeChild : function(node) { for(var i= this.attributes.chiledren.length-1;i >= 0;i--) { var _node = this.attributes.chiledren[i]; if(_node === node) { this.attributes.chiledren.splice(i,1); node.get('model').destroy(); return true; } else { _node.removeChild(node); //자식노드까지 검사 } } return false; }, removeChildAll : function() { for(var i= this.attributes.chiledren.length-1;i >= 0;i--) { this.removeChild(this.attributes.chiledren[i]); } return false; }, show : function(visible) { //console.log(this.get('model').get('element')); //this.get('model').get('element').style.visibility = visible ? 'inherit' : 'hidden'; this.get('model').show(visible); }, isVisible : function() { //return (this.get('model').get('element').style.visibility == 'hidden') ? false : true; return this.get('model').isVisible(); } }); //end of node /////////////// /// Pig2d.SceneManager = Backbone.Model.extend({ initialize: function(param) { var rootNode = new Pig2d.node( { model : new Pig2d.model({ name : 'root_' + (new Date()).getTime() + '_' }) } ); rootNode.get('model').setPosition(0,0); //this.attributes.container.append(rootNode.get('model').get('element')); var rootElement = rootNode.get('model').get('element'); //console.log(rootElement); if(param.window_size != undefined) { rootElement.style.overflow = 'hidden'; rootElement.style.width = param.window_size.width + 'px' ; rootElement.style.height = param.window_size.height + 'px' ; } if(param.bkg_color != undefined) { //2015.11.5 수정 ,배경적용안되는 버그 수정 this.attributes.container.style.backgroundColor = param.bkg_color; } this.attributes.container.appendChild(rootElement); this.attributes.rootNode = rootNode; }, getRootNode : function() { return this.attributes.rootNode; }, updateAll : function(deltaTime) { deltaTime = deltaTime ? deltaTime : 0.01; this.attributes.rootNode.update(true,deltaTime); }, add : function(node,parent) { if(parent == undefined) { this.attributes.rootNode.add(node); } else { parent.add(node); } }, addImageNode : function(param) { //var node = Pig2d.util.createImage(param.img_info); //this.add(node,param.parent); var center_x = param.center ? param.center.x : 0; var center_y = param.center ? param.center.y : 0; var node = Pig2d.util.createDummy(); var imgObj = new Image(); imgObj.onload = function(evt) { //console.log(this.width); imgObj.style.position = 'absolute'; imgObj.style.left = -this.width/2 + parseInt(center_x) + 'px'; imgObj.style.top = -this.height/2 + parseInt(center_y) + 'px'; var element = node.get('model').get('element'); element.appendChild(imgObj); node.get('model').set('imgObj', imgObj); if(param.onload) { param.onload(node); } } imgObj.src = param.src; this.add(node,param.parent); return node; }, addSpriteSceneNode : function(param) { var node = Pig2d.util.createSprite(param.spr_info); node.show(true); this.add(node,param.parent); return node; } }); //end of scene manager
gbox3d/pig2d
from_old/libs/pig2d/js/node2d.js
JavaScript
mit
27,176
/** * @author Iftikhar Ul Hassan * @date 4/10/17. */ const util = require('../util'); module.exports = function (length) { length = length || 21; var isValid; var kidNumber; do { kidNumber = util.generateRandomNumber(0, 9, length) + ""; var controlDigit = kidNumber.charAt(kidNumber.length - 1); isValid = parseInt(controlDigit, 10) === util.mod11(kidNumber) || parseInt(controlDigit, 10) === util.luhnValue(kidNumber); } while (!isValid); return kidNumber; };
khiftikhar/random-no
lib/no/kid.js
JavaScript
mit
518
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), concat: { options: { separator: ';' }, dist: { src: ['assets/magnific.js', 'assets/jquery-vimeothumb.js'], dest: 'magnific_popup/blocks/magnific_popup/magnific/magnific-combined-1.0.0.js' } }, uglify: { options: { // the banner is inserted at the top of the output banner: '/*! <%= pkg.name %> <%= grunt.template.today("dd-mm-yyyy") %> */\n' }, dist: { files: { 'magnific_popup/blocks/magnific_popup/magnific/magnific-combined-1.0.0.min.js': ['<%= concat.dist.dest %>'] } } }, }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.registerTask('default', ['concat', 'uglify']); };
cdowdy/concrete5-Magnific-Popup
Gruntfile.js
JavaScript
mit
870
'use strict'; // ================================== // // Load modules. // // ================================== var config = require('../config.js'); var gulp = require('gulp'); // ================================== // // Fonts // // ================================== gulp.task('fonts', function () { gulp.src([config.fonts.src]) .pipe(gulp.dest(config.fonts.dest)); });
Futoshi0620/jet-penguin
www/wordpress/wp-content/themes/jet-penguin/gulp/tasks/fonts.js
JavaScript
mit
381
export default { name: 'help-view', data() { return { } }, methods: { } }
freelogfe/console
src/views/help/index.js
JavaScript
mit
94
var counter = require('mongodb-counter'); var s3redirect = require('./s3redirect'); module.exports = shortener; module.exports.redis = require('./redisStore'); module.exports.mongodb = require('./mongoStore'); module.exports.s3 = s3redirect; module.exports.counter = counter; function shortener(options) { var store = options.store || s3redirect(options); var uniqueIdGenerator = options.uniqueIdGenerator || (options.counters || counter.createCounters( _({}).assign(options).assign({collectionName: options.countersCollectionName}).value() ))(options.uniqueIdCounterName || 'shortener'); return { shorten: shorten, shortenUnique: shortenUnique, unshorten: unshorten }; function shorten(longUrl, done) { getUniqueId(function (err, uniqueId) { if (err) return done(err); store.set(uniqueId, longUrl, finish); function finish(err, path) { return done(null, options.shortUrlPrefix + uniqueId); } }); } function shortenUnique(longUrl, done) { getUniqueId(function (err, uniqueId) { if (err) return done(err); store.getOrSet(uniqueId, longUrl, finish); function finish(err, path) { return done(null, options.shortUrlPrefix + uniqueId); } }); } function unshorten(shortUrl, done) { store.get(shortUrl.replace(options.shortUrlPrefix, ''), done); } function getUniqueId(done) { if (typeof(uniqueIdGenerator) == 'function') return uniqueIdGenerator(complete); return uniqueIdGenerator.getUniqueId(complete); function complete(err, value) { if (err) return done(err); var prefix = config.uniqueIdPrefix || ''; if (typeof(value) == 'number') return done(null, prefix + value.toString(36)); return done(null, prefix + value.toString()); } } }
Like-Falling-Leaves/url-shorten
shorten.js
JavaScript
mit
1,774
var todolist = require("./lib"); var assert = require("assert"); describe('findMarks', function() { it('Find TODOs, NOTES, and FIXMEs', function() { var result = todolist.findMarks("// TODO: This is a TODO\n// NOTE: This is a Note\n// FIXME: This is a fixme.\n"); assert.deepEqual(result, [{ content: 'TODO: This is a TODO', line: 0, assignee: null, type: 'TODOs' }, { content: 'NOTE: This is a Note', line: 1, assignee: null, type: 'NOTEs' }, { content: 'FIXME: This is a fixme.', line: 2, assignee: null, type: 'FIXMEs' }]); }); it('Case-insensitive matching', function() { var result = todolist.findMarks("// todo: This is a TODO\n// note: This is a Note\n// fixme: This is a fixme.\n"); assert.deepEqual(result, [{ content: 'todo: This is a TODO', line: 0, assignee: null, type: 'TODOs' }, { content: 'note: This is a Note', line: 1, assignee: null, type: 'NOTEs' }, { content: 'fixme: This is a fixme.', line: 2, assignee: null, type: 'FIXMEs' }]); }); it('Parse the assignee of a task', function() { var result = todolist.findMarks("// TODO(bob): This is a TODO assigned to bob."); assert.deepEqual(result, [{ content: 'TODO(bob): This is a TODO assigned to bob.', line: 0, assignee: 'bob', type: 'TODOs' }]); }); });
rameshvarun/todo-list
test.js
JavaScript
mit
1,615
import { ADD_HISTORY_FILTER_EXCLUDE_TAG, REMOVE_HISTORY_FILTER_EXCLUDE_TAG, SAVE_HISTORY_FILTER_EXCLUDES_TAGS, DISMISS_HISTORY_FILTER_EXCLUDES_TAGS, } from 'app/configs+constants/ActionTypes'; export const saveTags = (tags = []) => ({ type: SAVE_HISTORY_FILTER_EXCLUDES_TAGS, tags: tags, }); export const dismissTags = () => ({ type: DISMISS_HISTORY_FILTER_EXCLUDES_TAGS }); export const cancelTags = () => ({ type: DISMISS_HISTORY_FILTER_EXCLUDES_TAGS });; export const tappedPill = () => ({ type: REMOVE_HISTORY_FILTER_EXCLUDE_TAG }); export const addPill = () => ({ type: ADD_HISTORY_FILTER_EXCLUDE_TAG });
squatsandsciencelabs/OpenBarbellApp
app/features/history/history_filter/tags/tagsToExclude/EditHistoryFilterTagsToExcludeActions.js
JavaScript
mit
639
var Service = require("./../service.js"); function DistanceService(deviceId, serviceId) { var distanceService = {} , _characteristics = { 'distance' : 1 , 'unit' : 2 } , _requests = { 'read-distance' : function () { return { packetType : 'read' , packetData :[_characteristics['distance']] } } , 'read-unit' : function () { return { packetType : 'read' , packetData :[_characteristics['unit']] } } , 'read-distance-with-unit' : function () { return { packetType : 'read' , packetData :[_characteristics['distance'], _characteristics['unit']] } } , 'set-unit' : function (unit) { return { packetType : 'write' , packetData :[ {id : _characteristics['unit'], data : new Buffer(unit)} ] } } } , _responses = {}; _responses[_characteristics['distance']] = function (distanceBufer) { var distance = distanceBufer.readUInt8(0, true); return { response : 'distance' , data : "" + (distance === undefined ? 0 : distance) }; }; _responses[_characteristics['unit']] = function (unitBuffer) { return { response : 'unit' , data : unitBuffer.toString() }; }; distanceService.__proto__ = Service( deviceId , serviceId , _requests , _responses ); return distanceService; } module.exports = DistanceService; (function(){ var assert = require("assert"); var ResponsePacket = require("../device-packets/response-packet"); var serviceId = 3 , distanceService = DistanceService("my-device-id", serviceId); (function(){ console.log("Should process read distance json message."); assert.deepEqual( distanceService.processRequest(JSON.stringify( {request: 'read-distance'} )), new Buffer([1, 1, 0, 0, 0, serviceId, 1, 1]) ); })(); (function(){ console.log("Should process read unit json message."); assert.deepEqual( distanceService.processRequest(JSON.stringify( {request: 'read-unit'} )), new Buffer([1, 1, 0, 0, 0, serviceId, 1, 2]) ); })(); (function(){ console.log("Should process read distance with unit json message."); assert.deepEqual( distanceService.processRequest(JSON.stringify( {request: 'read-distance-with-unit'} )), new Buffer([1, 1, 0, 0, 0, serviceId, 2, 1, 2]) ); })(); (function(){ console.log("Should process set unit json message."); var unit = "cm" , unitBuffer = new Buffer(unit); assert.deepEqual( distanceService.processRequest(JSON.stringify( {request: 'set-unit', data: unit} )), Buffer.concat([ new Buffer([1, 2, 0, 0, 0, serviceId, 1, 2, unitBuffer.length]) , unitBuffer ]) ); })(); (function(){ console.log("Should process distance response packet."); assert.deepEqual( distanceService.processResponse(ResponsePacket(new Buffer([ 1, 4, 0, 0, 0, serviceId, 1, 1, 1, 23 ]))), [{response: 'distance', data: 23}] ); })(); (function(){ console.log("Should process unit response packet."); var unit = "cm" , unitBuffer = new Buffer(unit); assert.deepEqual( distanceService.processResponse(ResponsePacket(Buffer.concat([ new Buffer([1, 4, 0, 0, 0, serviceId, 1, 2, unitBuffer.length]) , unitBuffer ]))), [{response: 'unit', data: 'cm'}] ); })(); (function(){ console.log("Should process distance with unit response packet."); var unit = "cm" , unitBuffer = new Buffer(unit); assert.deepEqual( distanceService.processResponse(ResponsePacket(Buffer.concat([ new Buffer([1, 4, 0, 0, 0, serviceId, 2, 1, 1, 54, 2, unitBuffer.length]) , unitBuffer ]))), [ {response: 'distance', data: '54'} , {response: 'unit', data: 'cm'} ] ); })(); })(this);
ThoughtWorksIoTGurgaon/queenbee
services/distance-service.js
JavaScript
mit
4,788
/** * @summary Returns deep equality between objects * {@link https://gist.github.com/egardner/efd34f270cc33db67c0246e837689cb9} * @param obj1 * @param obj2 * @return {boolean} * @private */ export function deepEqual(obj1, obj2) { if (obj1 === obj2) { return true; } else if (isObject(obj1) && isObject(obj2)) { if (Object.keys(obj1).length !== Object.keys(obj2).length) { return false; } for (const prop of Object.keys(obj1)) { if (!deepEqual(obj1[prop], obj2[prop])) { return false; } } return true; } else { return false; } } function isObject(obj) { return typeof obj === 'object' && obj != null; }
mistic100/Photo-Sphere-Viewer
src/plugins/resolution/utils.js
JavaScript
mit
679
define(['jquery','xing'],function($,xing) { var $body = $('body'), $progress = $($body.data('progressDisplay')), $status = $($body.data('statusMessage')), curPath = window.location.pathname, baseDir = curPath.substring(0, curPath.lastIndexOf('/')), sitePath = '//'+window.location.host+baseDir, stackCount = 0, stackCall = function() { if( $progress.length > 0 ) { $progress.show(); stackCount++; } }, unstackCall = function() { if( --stackCount < 1 ) { stackCount = 0; $progress.hide(); } }, getErrorHandler = function( callback, doUnstack ) { return function( xhr ) { if( doUnstack ) { unstackCall(); } callback($.parseJSON(xhr.response)); }; } ; xing.http = { BasePath : baseDir, SitePath : sitePath, redirect : function( path ) { stackCall(); // show our processing loader when changing pages window.location.href = path.replace('~',this.BasePath); }, get : function( path, data, callback, stopLoadingIcon ) { xing.http.ajax('GET',path,data,callback,stopLoadingIcon); }, post : function( path, data, callback, stopLoadingIcon ) { xing.http.ajax('POST',path,data,callback,stopLoadingIcon); }, put : function( path, data, callback, stopLoadingIcon ) { xing.http.ajax('PUT',path,data,callback,stopLoadingIcon); }, ajax : function( type, path, data, callback, stopLoadingIcon ) { stopLoadingIcon = stopLoadingIcon || false; $.ajax( { type : type, url : path.replace('~',this.BasePath), data : data, success : stopLoadingIcon ? callback : function(response) { unstackCall(); callback(response); }, error : getErrorHandler(callback, !stopLoadingIcon) } ); if( !stopLoadingIcon ) { stackCall(); } }, stackCall : stackCall, unstackCall : unstackCall, forceEndStack : function() { stackCount = 0; unstackCall(); }, message : function( msg, isError, timeoutSecs, callback ) { if( $status.length ) { $status.find('.content').html(msg); $status.toggleClass('error',!!isError).show('fast'); // force isError to boolean with !! setTimeout( function() { $status.hide('fast'); if( callback ) { callback(); } }, typeof timeoutSecs == 'undefined' ? 1400 : (timeoutSecs * 1000)); } } }; return xing.http; });
lanwise/dojo-twtapi
scripts/xing/http.src.js
JavaScript
mit
3,118
var present = require('present-express'); var Base = require('./base'); module.exports = present.extend(Base, function(data) { if (data.title) { this.data.title = data.title; } })
glenjamin/CanDB
presents/index.present.js
JavaScript
mit
197
'use strict'; var isA = require("Espresso/oop").isA; var oop = require("Espresso/oop").oop; var init = require("Espresso/oop").init; var trim = require("Espresso/trim").trim; var isA = require("Espresso/oop").isA; var oop = require("Espresso/oop").oop; var ScalarNode = require("Espresso/Config/Definition/ScalarNode"); var InvalidTypeException = require("Espresso/Config/Definition/Exception/InvalidTypeException"); var format = require("util").format; function BooleanNode(name,parent){ init(this,ScalarNode,name,parent); oop(this,"Espresso/Config/Definition/BooleanNode"); } /** * {@inheritdoc} */ function validateType($value) { if ( typeof $value !== 'boolean') { var $ex = new InvalidTypeException(format( 'Invalid type for path "%s". Expected boolean, but got %s.', this.getPath(), getClass($value) )); var $hint = this.getInfo(); if ($hint) { $ex.addHint($hint); } $ex.setPath(this.getPath()); throw $ex; } } /** * {@inheritdoc} */ function isValueEmpty($value) { // a boolean value cannot be empty return false; } BooleanNode.prototype = Object.create( ScalarNode.prototype ); BooleanNode.prototype.validateType = validateType; BooleanNode.prototype.isValueEmpty = isValueEmpty; module.exports = BooleanNode;
quimsy/espresso
Config/Definition/BooleanNode.js
JavaScript
mit
1,355
/** * COMMON WEBPACK CONFIGURATION */ const path = require('path'); const webpack = require('webpack'); module.exports = (options) => ({ entry: options.entry, output: Object.assign({ // Compile into js/build.js path: path.resolve(process.cwd(), 'build'), publicPath: '/', }, options.output), // Merge with env dependent settings module: { loaders: [{ test: /\.js$/, // Transform all .js files required somewhere with Babel loader: 'babel', exclude: /node_modules/, query: options.babelQuery, }, { // Do not transform vendor's CSS with CSS-modules // The point is that they remain in global scope. // Since we require these CSS files in our JS or CSS files, // they will be a part of our compilation either way. // So, no need for ExtractTextPlugin here. test: /\.css$/, include: /node_modules/, loaders: ['style-loader', 'css-loader'], }, { test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'file-loader', }, { test: /\.(jpg|png|gif)$/, loaders: [ 'file-loader', { loader: 'image-webpack', query: { progressive: true, optimizationLevel: 7, interlaced: false, pngquant: { quality: '65-90', speed: 4, }, }, }, ], }, { test: /\.html$/, loader: 'html-loader', }, { test: /\.json$/, loader: 'json-loader', }, { test: /\.(mp4|webm)$/, loader: 'url-loader', query: { limit: 10000, }, }], }, plugins: options.plugins.concat([ new webpack.ProvidePlugin({ // make fetch available fetch: 'exports?self.fetch!whatwg-fetch', }), // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV` // inside your code for any environment checks; UglifyJS will automatically // drop any unreachable code. new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV), }, }), new webpack.NamedModulesPlugin(), ]), resolve: { modules: ['app', 'node_modules'], extensions: [ '.js', '.jsx', '.react.js', ], mainFields: [ 'browser', 'jsnext:main', 'main', ], }, devtool: options.devtool, target: 'web', // Make web variables accessible to webpack, e.g. window });
samit4me/react-boilerplate
internals/webpack/webpack.base.babel.js
JavaScript
mit
2,464
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define({widgetLabel:"Altl\u0131k haritay\u0131 a\u00e7/kapa"});
ycabon/presentations
2020-devsummit/arcgis-js-api-road-ahead/js-api/esri/widgets/BasemapToggle/nls/tr/BasemapToggle.js
JavaScript
mit
220
"use strict" const process = require(`process`) const fs = require(`fs`) const path = require(`path`) const js2xmlparser = require(`js2xmlparser`) const abbrevJson = require(`../abbrevJson`) const asset = require(`../asset.js`) const loadMappoMap = require(`../loadMappoMap`) const mapFilename = process.argv[2] const mappoMap = loadMappoMap({mapFilename}) console.log(abbrevJson(mappoMap)) const tileset = mappoMap.tileset const tileWidth = tileset.tileWidth const tileHeight = tileset.tileHeight const vspFilename = path.basename(tileset.imageFilename) const tileColumns = 20 const tileRows = ~~((tileset.tileCount + 19) / 20) const vspPngWidth = tileWidth * tileColumns const vspPngHeight = tileHeight * tileRows const obj = { '@': { version: `1.0`, orientation: `orthogonal`, width: mappoMap.tileLayers[0].width, height: mappoMap.tileLayers[0].height, tilewidth: tileWidth, tileheight: tileHeight, }, tileset: { '@': { firstgid: 1, name: vspFilename, tilewidth: tileWidth, tileheight: tileHeight, spacing: 0, margin: 0, tilecount: tileset.tileCount, columns: tileColumns, }, image: { '@': { source: vspFilename, width: vspPngWidth, height: vspPngHeight, } }, } } obj.layer = mappoMap.mapLayerOrder.map(layerIndex => { const tileLayer = mappoMap.tileLayers[layerIndex] return { '@': { name: tileLayer.description, width: tileLayer.width, height: tileLayer.height, }, data: { '@': { encoding: `csv`, }, '#': tileLayer.tileIndexGrid.map(v => ++v).join(`,`), } } }) const targetFilename = mapFilename + `.tmx` const xml = js2xmlparser.parse(`map`, obj) fs.writeFileSync(targetFilename, xml) console.log(`converted`, mapFilename, `to`, targetFilename)
chuckrector/mappo
src/cli/map2tmx.js
JavaScript
mit
1,856
/* * * LoginContainer constants * */ export const LOGIN_REQUEST = 'app/LoginContainer/LOGIN_REQUEST'; export const LOGIN_SUCCESS = 'app/LoginContainer/LOGIN_SUCCESS'; export const LOGIN_FAILURE = 'app/LoginContainer/LOGIN_FAILURE';
vinhtran19950804/procure_react
app/containers/LoginContainer/constants.js
JavaScript
mit
238
'use strict'; /** * data-set module * @module data-set * @see module:index */ const _ = require('lodash'); const try2get = require('try2get'); const Connector = require('../connector/base'); const util = require('../util/index'); function isValidDataSet(dataSet) { /** * Simply check the data structure of the data set. * @function isValidDataSet * @param {Array} data * @return {Boolean} * @example * // a valid data structure should be like this: * // `schema` is not strictly required. * { * data: [ * {genre: 'Sports', sold: 275}, * {genre: 'Strategy', sold: 115}, * {genre: 'Action', sold: 120}, * {genre: 'Shooter', sold: 350}, * {genre: 'Other', sold: 150} * ], * schema: [ * {name: 'genre', comments: '种类'}, * {name: 'sold', comments: '销量', formatter: '', type: 'number'} * ] * } * @example * isValidDataSet(dataSet); */ if (!_.isPlainObject(dataSet)) { return false; } const data = dataSet.data; if (!_.isArray(data)) { return false; } if (data.length && _.some(data, row => !_.isPlainObject(row))) { return false; } for (let i = 1; i < data.length; i++) { if (data[i] && !util.containsSameItems(_.keys(data[i]), _.keys(data[i - 1]))) { return false; } } return true; } class DataSet { constructor(source) { source = source || []; const me = this; if (source.constructor === me.constructor) { return source; } if (_.isArray(source)) { return new DataSet({ data: source, }); } if (!isValidDataSet(source)) { throw new TypeError('new DataSet(source): invalid data set'); } me.data = source.data; me.schema = source.schema || []; return me.processData(); } processData() { const me = this; const data = me.data; /* * schema info of every column: * [ * { * name, * index, * comments, * } * ] */ if (!me.schema.length) { if (data.length) { const keys = _.keys(data[0]); me.schema = _.map(keys, (name, index) => ({ index, name, })); } } // comments (default is name) _.each(me.schema, (colInfo) => { if (!_.has(colInfo, 'comments')) { colInfo.comments = colInfo.displayName || colInfo.name; } }); // 整理schema和data const currentSchemaNames = _.map(me.schema, item => item.name); _.each(me.data, (row) => { _.forIn(row, (value, key) => { if (!_.includes(currentSchemaNames, key)) { // 补全schema me.schema.push({ name: key, comments: key, index: currentSchemaNames.length, }); currentSchemaNames.push(key); } }); }); _.each(me.data, (row) => { _.each(currentSchemaNames, (name) => { if (!_.has(row, name)) { // 补全data row[name] = ''; } }); }); // flatten rows me.flattenRows = _.map(me.data, (row) => { const resultRow = []; _.each(me.schema, (colInfo, index) => { colInfo.index = index; resultRow.push(row[colInfo.name]); }); return resultRow; }); // colValuesByName me.colValuesByName = {}; _.each(me.data, (row) => { _.forIn(row, (value, key) => { me.colValuesByName[key] = me.colValuesByName[key] || []; me.colValuesByName[key].push(value); }); }); // type (by guessing or pre-defined) // colNames by type // col by name // cols by type // unique column values rate me.colNamesByType = { string: [], number: [], }; me.colsByType = {}; me.colByName = {}; _.each(me.schema, (colInfo) => { const name = colInfo.name; const colValues = me.colValuesByName[name]; colInfo.values = colValues; // add values const type = colInfo.type = colInfo.type || util.guessItemsTypes(colValues); if (!me.colNamesByType[type]) { me.colNamesByType[type] = []; } if (!me.colsByType[type]) { me.colsByType[type] = []; } if (colValues.length) { colInfo.uniqueRate = _.uniq(colValues).length / colValues.length; } else { colInfo.uniqueRate = 0; } me.colNamesByType[type].push(colInfo.name); me.colsByType[type].push(colInfo); me.colByName[colInfo.name] = colInfo; }); // alias me.cols = me.schema; // rows and cols info me.rowsCount = data.length; me.colsCount = me.cols.length; return me; } isEmpty() { const me = this; if (me.rowsCount === 0 && me.colsCount === 0) { return true; } return false; } } // connectors const connectors = []; _.assign(DataSet, { registerConnector(connector) { if (connector instanceof Connector) { connectors.push(connector); } else { try { connectors.push(new Connector(connector)); } catch (e) { } } connectors.sort((a, b) => (b.priority - a.priority)); }, registerConnectors(cs) { _.each(cs, (connector) => { DataSet.registerConnector(connector); }); }, try2init(source) { // the default DataSet is an empty DataSet return try2get.one(_.map(connectors, connector => () => connector.toDataSet(source))); }, }); require('../connector/csv')(DataSet); require('../connector/default')(DataSet); require('../connector/flatten-data')(DataSet); require('../connector/mock')(DataSet); module.exports = DataSet;
leungwensen/d2recharts
lib/source/data-set.js
JavaScript
mit
5,636
'use strict'; module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), banner: [ '/**', ' * <%= pkg.name %> <%= pkg.version %>', ' * Copyright (C) <%= grunt.template.today("yyyy") %> <%= pkg.author %>', ' * Licensed under the MIT license.', ' * <%= _.pluck(pkg.licenses, "url").join(", ") %>', ' */\n' ].join('\n'), clean: { all: [ 'dist', 'tmp' ] }, jshint: { all: [ '*.js', 'lib/**/*.js', 'test/**/*.js', 'benchmark/**/*.js', 'tasks/**/*.js' ], options: { force: true, jshintrc: true } }, browserify: { dist: { src: 'index.js', dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.js' }, test: { src: 'test/unit/**/*.js', dest: 'tmp/test-browser.js', options: { transform: [ 'espowerify' ] } }, 'benchmark-equip': { src: 'benchmark/equip-simu.js', dest: 'tmp/benchmark/equip-simu.js' }, 'benchmark-deco': { src: 'benchmark/deco-simu.js', dest: 'tmp/benchmark/deco-simu.js' }, 'benchmark-util': { src: 'benchmark/util.js', dest: 'tmp/benchmark/util.js' } }, usebanner: { dist: { options: { position: 'top', banner: '<%= banner %>', linebreak: false }, files: { src: [ '<%= browserify.dist.dest %>' ] } } }, uglify: { options: { banner: '<%= banner %>', report: 'min' }, js: { src: '<%= browserify.dist.dest %>', dest: 'dist/<%= pkg.name %>-<%= pkg.version %>.min.js' } }, testdata: { mh4: { dest: 'tmp/testdata.js', urls: { 'equip_head' : 'http://sakusimu.net/data/mh4/equip_head.json', 'equip_body' : 'http://sakusimu.net/data/mh4/equip_body.json', 'equip_arm' : 'http://sakusimu.net/data/mh4/equip_arm.json', 'equip_waist': 'http://sakusimu.net/data/mh4/equip_waist.json', 'equip_leg' : 'http://sakusimu.net/data/mh4/equip_leg.json', 'deco' : 'http://sakusimu.net/data/mh4/deco.json', 'skill': 'http://sakusimu.net/data/mh4/skill.json' } } }, espower: { test: { files: [ { expand: true, cwd: 'test/unit', src: [ '**/*.js' ], dest: 'tmp/espowered/', ext: '.js' } ] } }, mochaTest: { test: { options: { reporter: 'spec' }, src: [ 'tmp/espowered/**/*.js' ] } }, karma: { test: { configFile: 'test/karma-conf.js', singleRun: true, options: { files: [ '<%= testdata.mh4.dest %>', '<%= browserify.test.dest %>' ] } } } }); require('load-grunt-tasks')(grunt); grunt.loadTasks('tasks'); grunt.registerTask('default', [ 'clean:all', 'test', 'dist' ]); grunt.registerTask('dist', [ 'browserify:dist', 'usebanner:dist', 'uglify' ]); grunt.registerTask('test', function (type, file) { switch (type) { case 'browser': grunt.task.run([ 'browserify:test', 'karma:test' ]); break; case 'node': var files = grunt.config.data.mochaTest.test.src; if (file) { file = file.replace('test/unit/', 'tmp/espowered/'); files.splice(-1, 1, file); } grunt.task.run([ 'jshint', 'espower:test', 'mochaTest:test' ]); /* falls through */ default: } }); grunt.registerTask('benchmark', [ 'browserify:benchmark-equip', 'browserify:benchmark-deco', 'browserify:benchmark-util' ]); };
sakusimu/mh4-skillsimu
Gruntfile.js
JavaScript
mit
4,695
'use strict'; var generators = require('yeoman-generator'); var chalk = require('chalk'); var path = require('path'); var extend = require('deep-extend'); var guid = require('uuid'); module.exports = generators.Base.extend({ /** * Setup the generator */ constructor: function () { generators.Base.apply(this, arguments); this.option('skip-install', { type: Boolean, required: false, defaults: false, desc: 'Skip running package managers (NPM, bower, etc) post scaffolding' }); this.option('name', { type: String, desc: 'Title of the Office Add-in', required: false }); this.option('root-path', { type: String, desc: 'Relative path where the Add-in should be created (blank = current directory)', required: false }); this.option('tech', { type: String, desc: 'Technology to use for the Add-in (html = HTML; ng = Angular)', required: false }); // create global config object on this generator this.genConfig = {}; }, // constructor() /** * Prompt users for options */ prompting: { askFor: function () { var done = this.async(); var prompts = [ // friendly name of the generator { name: 'name', message: 'Project name (display name):', default: 'My Office Add-in', when: this.options.name === undefined }, // root path where the addin should be created; should go in current folder where // generator is being executed, or within a subfolder? { name: 'root-path', message: 'Root folder of project?' + ' Default to current directory\n (' + this.destinationRoot() + '), or specify relative path\n' + ' from current (src / public): ', default: 'current folder', when: this.options['root-path'] === undefined, filter: /* istanbul ignore next */ function (response) { if (response === 'current folder') return ''; else return response; } }, // technology used to create the addin (html / angular / etc) { name: 'tech', message: 'Technology to use:', type: 'list', when: this.options.tech === undefined, choices: [ { name: 'HTML, CSS & JavaScript', value: 'html' }, { name: 'Angular', value: 'ng' }, { name: 'Manifest.xml only (no application source files)', value: 'manifest-only' }] }]; // trigger prompts this.prompt(prompts, function (responses) { this.genConfig = extend(this.genConfig, this.options); this.genConfig = extend(this.genConfig, responses); done(); }.bind(this)); }, // askFor() /** * If user specified tech:manifest-only, prompt for start page. */ askForStartPage: function () { if (this.genConfig.tech !== 'manifest-only') return; var done = this.async(); var prompts = [ // if tech = manifest only, prompt for start page { name: 'startPage', message: 'Add-in start URL:', when: this.options.startPage === undefined, }]; // trigger prompts this.prompt(prompts, function (responses) { this.genConfig = extend(this.genConfig, responses); done(); }.bind(this)); } // askForStartPage() }, // prompting() /** * save configurations & config project */ configuring: function () { // add the result of the question to the generator configuration object this.genConfig.projectnternalName = this.genConfig.name.toLowerCase().replace(/ /g, "-"); this.genConfig.projectDisplayName = this.genConfig.name; this.genConfig.rootPath = this.genConfig['root-path']; }, // configuring() /** * write generator specific files */ writing: { /** * If there is already a package.json in the root of this project, * get the name of the project from that file as that should be used * in bower.json & update packages. */ upsertPackage: function () { if (this.genConfig.tech !== 'manifest-only') { var done = this.async(); // default name for the root project = addin project this.genConfig.rootProjectName = this.genConfig.projectnternalName; // path to package.json var pathToPackageJson = this.destinationPath('package.json'); // if package.json doesn't exist if (!this.fs.exists(pathToPackageJson)) { // copy package.json to target this.fs.copyTpl(this.templatePath('common/_package.json'), this.destinationPath('package.json'), this.genConfig); } else { // load package.json var packageJson = this.fs.readJSON(pathToPackageJson, 'utf8'); // .. get it's name property this.genConfig.rootProjectName = packageJson.name; // update devDependencies /* istanbul ignore else */ if (!packageJson.devDependencies) { packageJson.devDependencies = {} } /* istanbul ignore else */ if (!packageJson.devDependencies['gulp']) { packageJson.devDependencies['gulp'] = "^3.9.0" } /* istanbul ignore else */ if (!packageJson.devDependencies['gulp-webserver']) { packageJson.devDependencies['gulp-webserver'] = "^0.9.1" } // overwrite existing package.json this.log(chalk.yellow('Adding additional packages to package.json')); this.fs.writeJSON(pathToPackageJson, packageJson); } done(); } }, // upsertPackage() /** * If bower.json already exists in the root of this project, update it * with the necessary addin packages. */ upsertBower: function () { if (this.genConfig.tech !== 'manifest-only') { var done = this.async(); var pathToBowerJson = this.destinationPath('bower.json'); // if doesn't exist... if (!this.fs.exists(pathToBowerJson)) { // copy bower.json => project switch (this.genConfig.tech) { case "ng": this.fs.copyTpl(this.templatePath('ng/_bower.json'), this.destinationPath('bower.json'), this.genConfig); break; case "html": this.fs.copyTpl(this.templatePath('html/_bower.json'), this.destinationPath('bower.json'), this.genConfig); break; } } else { // verify the necessary package references are present in bower.json... // if not, add them var bowerJson = this.fs.readJSON(pathToBowerJson, 'utf8'); // all addins need these if (!bowerJson.dependencies["microsoft.office.js"]) { bowerJson.dependencies["microsoft.office.js"] = "*"; } if (!bowerJson.dependencies["jquery"]) { bowerJson.dependencies["jquery"] = "~1.9.1"; } switch (this.genConfig.tech) { // if angular... case "ng": if (!bowerJson.dependencies["angular"]) { bowerJson.dependencies["angular"] = "~1.4.4"; } if (!bowerJson.dependencies["angular-route"]) { bowerJson.dependencies["angular-route"] = "~1.4.4"; } if (!bowerJson.dependencies["angular-sanitize"]) { bowerJson.dependencies["angular-sanitize"] = "~1.4.4"; } break; } // overwrite existing bower.json this.log(chalk.yellow('Adding additional packages to bower.json')); this.fs.writeJSON(pathToBowerJson, bowerJson); } done(); } }, // upsertBower() app: function () { // helper function to build path to the file off root path this._parseTargetPath = function (file) { return path.join(this.genConfig['root-path'], file); }; var done = this.async(); // create a new ID for the project this.genConfig.projectId = guid.v4(); if (this.genConfig.tech === 'manifest-only') { // create the manifest file this.fs.copyTpl(this.templatePath('common/manifest.xml'), this.destinationPath('manifest.xml'), this.genConfig); } else { // copy .bowerrc => project this.fs.copyTpl( this.templatePath('common/_bowerrc'), this.destinationPath('.bowerrc'), this.genConfig); // create common assets this.fs.copy(this.templatePath('common/gulpfile.js'), this.destinationPath('gulpfile.js')); this.fs.copy(this.templatePath('common/content/Office.css'), this.destinationPath(this._parseTargetPath('content/Office.css'))); this.fs.copy(this.templatePath('common/images/close.png'), this.destinationPath(this._parseTargetPath('images/close.png'))); this.fs.copy(this.templatePath('common/scripts/MicrosoftAjax.js'), this.destinationPath(this._parseTargetPath('scripts/MicrosoftAjax.js'))); switch (this.genConfig.tech) { case 'html': // determine startpage for addin this.genConfig.startPage = 'https://localhost:8443/app/home/home.html'; // create the manifest file this.fs.copyTpl(this.templatePath('common/manifest.xml'), this.destinationPath('manifest.xml'), this.genConfig); // copy addin files this.fs.copy(this.templatePath('html/app.css'), this.destinationPath(this._parseTargetPath('app/app.css'))); this.fs.copy(this.templatePath('html/app.js'), this.destinationPath(this._parseTargetPath('app/app.js'))); this.fs.copy(this.templatePath('html/home/home.html'), this.destinationPath(this._parseTargetPath('app/home/home.html'))); this.fs.copy(this.templatePath('html/home/home.css'), this.destinationPath(this._parseTargetPath('app/home/home.css'))); this.fs.copy(this.templatePath('html/home/home.js'), this.destinationPath(this._parseTargetPath('app/home/home.js'))); break; case 'ng': // determine startpage for addin this.genConfig.startPage = 'https://localhost:8443/index.html'; // create the manifest file this.fs.copyTpl(this.templatePath('common/manifest.xml'), this.destinationPath('manifest.xml'), this.genConfig); // copy addin files this.genConfig.startPage = '{https-addin-host-site}/index.html'; this.fs.copy(this.templatePath('ng/index.html'), this.destinationPath(this._parseTargetPath('index.html'))); this.fs.copy(this.templatePath('ng/app.module.js'), this.destinationPath(this._parseTargetPath('app/app.module.js'))); this.fs.copy(this.templatePath('ng/app.routes.js'), this.destinationPath(this._parseTargetPath('app/app.routes.js'))); this.fs.copy(this.templatePath('ng/home/home.controller.js'), this.destinationPath(this._parseTargetPath('app/home/home.controller.js'))); this.fs.copy(this.templatePath('ng/home/home.html'), this.destinationPath(this._parseTargetPath('app/home/home.html'))); this.fs.copy(this.templatePath('ng/services/data.service.js'), this.destinationPath(this._parseTargetPath('app/services/data.service.js'))); break; } } done(); } // app() }, // writing() /** * conflict resolution */ // conflicts: { }, /** * run installations (bower, npm, tsd, etc) */ install: function () { if (!this.options['skip-install'] && this.genConfig.tech !== 'manifest-only') { this.npmInstall(); this.bowerInstall(); } } // install () /** * last cleanup, goodbye, etc */ // end: { } });
mauricionr/generator-office
generators/content/index.js
JavaScript
mit
12,198
function(){ var db = $$(this).app.db, term = $(this).val(), nonce = Math.random(); $$($(this)).nonce = nonce; db.view("icd9lookup/by_code", { startkey : term, endkey : term+"\u9999", //I don't know why only \u9999 works, not \uFFFF limit : 100, success : function(names){ if($$($(this)).nonce = nonce){ $("#results").html( "<tr><th>ICD-9 Code</th><th>Long Description</th><th>Short Description</th></tr>"+ names.rows.map(function(r){ return '<tr><td>'+r.value.icd9code+'</td><td>'+r.value.long_description+'</td><td>'+r.value.short_description+'</td></tr>'; }).join("")); }}}); }
drobbins/icd9lookup
evently/icd9lookup/_init/selectors/#code/keyup.js
JavaScript
mit
664
import cx from 'classnames' import _ from 'lodash' import React, { PropTypes } from 'react' import { createShorthandFactory, customPropTypes, getElementType, getUnhandledProps, META, } from '../../lib' /** * A message can contain a header. */ function MessageHeader(props) { const { children, className, content } = props const classes = cx('header', className) const rest = getUnhandledProps(MessageHeader, props) const ElementType = getElementType(MessageHeader, props) return ( <ElementType {...rest} className={classes}> {_.isNil(children) ? content : children} </ElementType> ) } MessageHeader._meta = { name: 'MessageHeader', parent: 'Message', type: META.TYPES.COLLECTION, } MessageHeader.propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Shorthand for primary content. */ content: customPropTypes.itemShorthand, } MessageHeader.create = createShorthandFactory(MessageHeader, val => ({ content: val })) export default MessageHeader
koenvg/Semantic-UI-React
src/collections/Message/MessageHeader.js
JavaScript
mit
1,165
export default { userData: {}, isAuthenticated: false, registrationMode: false, registrationFailed: false, attemptFailed: false, reviewData: [] }
Shobhit1/ReactRedux-FrontEnd
src/js/redux/initialStates/login.js
JavaScript
mit
158
import Ember from 'ember'; const $ = Ember.$; import layout from './template'; import styles from './styles'; /* * Turn header transparent after scrolling * down a few pixels: */ const HEADER_OFFSET = 60; export default Ember.Component.extend({ layout, styles, tagName: 'nav', localClassNames: 'nav', localClassNameBindings: [ 'isSmall', 'invert', 'showComponents', ], isSmall: false, componentsTitle: "More components", showComponents: false, invertLogoColors: Ember.computed('isSmall', 'invert', function() { return !this.get('isSmall') && !this.get('invert'); }), githubURL: Ember.computed('config', function() { return this.get('config.githubURL'); }), _scrollListener: null, didInsertElement() { this._scrollListener = Ember.run.bind(this, this.didScroll); $(window).on('scroll', this._scrollListener); }, willDestroyElement() { if (this._scrollListener) { $(window).off('scroll', this._scrollListener); } }, didScroll() { let scrollPos = $(window).scrollTop(); let reachedOffset = (scrollPos > HEADER_OFFSET); this.set('isSmall', reachedOffset); }, /* * Determine if the user is on a touch device: */ hasTouch: Ember.computed(function() { return (('ontouchstart' in window) || window.DocumentTouch); }), actions: { toggleComponents(value, e) { if (e && e.stopPropagation) { e.stopPropagation(); } if (value !== null && value !== undefined) { this.set('showComponents', value); } else { this.toggleProperty('showComponents'); } }, }, });
ember-sparks/ember-sparks.github.io
addon/components/spark-header/component.js
JavaScript
mit
1,639
'use strict'; // Configuring the Articles module angular.module('states').run(['Menus', function(Menus) { // Set top bar menu items Menus.addMenuItem('topbar', 'States', 'states', 'dropdown', '/states(/create)?'); Menus.addSubMenuItem('topbar', 'states', 'List States', 'states'); Menus.addSubMenuItem('topbar', 'states', 'New State', 'states/create'); } ]);
LMafra/sistema_mej
public/modules/states/config/states.client.config.js
JavaScript
mit
369
console.log('----加载开始----'); module.exports = (num) => { return num + 1; } console.log('----加载结束----');
yuzexia/learn-365
learn/node/laohei/demo1/main/index.js
JavaScript
mit
128
const {classes: Cc, interfaces: Ci, utils: Cu} = Components; Cu.import("resource://gre/modules/Services.jsm"); Cu.import("resource://gre/modules/XPCOMUtils.jsm"); function FileBlock() {} FileBlock.prototype = { appDir: null, profileDir: null, tempDir: null, // List of domains for the whitelist whitelist: [], // Chrome pages that should not be shown chromeBlacklist: ["browser", "mozapps", "marionette", "specialpowers", "branding", "alerts"], initialize: function() { this.appDir = Services.io.newFileURI(Services.dirsvc.get("CurProcD", Ci.nsIFile)).spec; var profileDir = Services.dirsvc.get("ProfD", Ci.nsIFile); this.profileDir = Services.io.newFileURI(profileDir).spec this.tempDir = Services.io.newFileURI(Services.dirsvc.get("TmpD", Ci.nsIFile)).spec; try { var whitelist = Services.prefs.getCharPref("extensions.webconverger.whitelist"); this.whitelist = whitelist.split(","); for (var i=0; i < this.whitelist.length; i++) { this.whitelist[i] = this.whitelist[i].trim(); } } catch(e) {} var whitelistFile = profileDir.clone(); whitelistFile.append("webconverger.whitelist"); if (!whitelistFile.exists()) { return; } var stream = Cc["@mozilla.org/network/file-input-stream;1"] .createInstance(Ci.nsIFileInputStream); stream.init(whitelist, 0x01, 0644, 0); var lis = stream.QueryInterface(Components.interfaces.nsILineInputStream); var line = {value:null}; do { var more = lis.readLine(line); try { var file = Cc["@mozilla.org/file/local;1"] .createInstance(Ci.nsILocalFile); file.initWithPath(line.value); this.whitelist.push(ioService.newFileURI(file).spec.toLowerCase()); } catch (ex) { /* Invalid path */ } } while (more); stream.close(); }, shouldLoad: function(aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra) { if (!this.appDir) { this.initialize(); } // We need to allow access to any files in the profile directory, // application directory or the temporary directory. Without these, // Firefox won't start if (aContentLocation.spec.match(this.profileDir) || aContentLocation.spec.match(this.appDir) || aContentLocation.spec.match(this.tempDir)) { return Ci.nsIContentPolicy.ACCEPT; } // Allow everything on the whitelist first if (aContentLocation.scheme == "http" || aContentLocation.scheme == "https") { for (var i=0; i< this.whitelist.length; i++) { if (aContentLocation.host == this.whitelist[i] || aContentLocation.host.substr(aContentLocation.host.length - this.whitelist[i].length - 1) == "." + this.whitelist[i]) { return Ci.nsIContentPolicy.ACCEPT; } } } if (aContentLocation.scheme == "chrome") { // This prevents loading of chrome files into the browser window if (aRequestOrigin && (aRequestOrigin.spec == "chrome://browser/content/browser.xul" || aRequestOrigin.scheme == "moz-nullprincipal")) { for (var i=0; i < this.chromeBlacklist.length; i++) { if (aContentLocation.host == this.chromeBlacklist[i]) { return Ci.nsIContentPolicy.REJECT_REQUEST; } } } // All chrome requests come through here, so we have to allow them // (Like loading the main browser window for instance) return Ci.nsIContentPolicy.ACCEPT; } // Prevent the loading of resource files into the main browser window if (aContentLocation.scheme == "resource") { if (aRequestOrigin && aRequestOrigin.scheme == "moz-nullprincipal") { return Ci.nsIContentPolicy.REJECT_REQUEST; } return Ci.nsIContentPolicy.ACCEPT; } // Only allow these three about URLs if (aContentLocation.scheme == "about") { if (aContentLocation.spec == "about:" || /^about:certerror/.test(aContentLocation.spec) || /^about:neterror/.test(aContentLocation.spec) || /^about:buildconfig/.test(aContentLocation.spec) || /^about:credits/.test(aContentLocation.spec) || /^about:license/.test(aContentLocation.spec) || // /^about:srcdoc/.test(aContentLocation.spec) || // Needed for Australis // /^about:customizing/.test(aContentLocation.spec) || // Needed for Australis /^about:blank/.test(aContentLocation.spec)) { return Ci.nsIContentPolicy.ACCEPT; } return Ci.nsIContentPolicy.REJECT_REQUEST; } // We allow all javascript and data URLs if (aContentLocation.scheme == "data" || aContentLocation.scheme == "javascript") { return Ci.nsIContentPolicy.ACCEPT; } // Deny all files if (aContentLocation.scheme == "file") { return Ci.nsIContentPolicy.REJECT_REQUEST; } // Allow view source // if (aContentLocation.scheme == "view-source") { // return Ci.nsIContentPolicy.ACCEPT; // } // If we had a whitelist, reject everything else if (this.whitelist.length > 0) { if (aContentType == Ci.nsIContentPolicy.TYPE_DOCUMENT) { // Services.prompt.alert(null, "Webconverger", "Not allowed, whitelist only permits: " + this.whitelist.join(", ")); return Ci.nsIContentPolicy.REJECT_REQUEST; } } // If there is no whitelist, allow everything (because we denied file URLs) return Ci.nsIContentPolicy.ACCEPT; }, shouldProcess: function(aContentType, aContentLocation, aRequestOrigin, aContext, aMimeTypeGuess, aExtra) { return Ci.nsIContentPolicy.ACCEPT; }, classDescription: "Webconverger FileBlock Service", contractID: "@webconverger.com/fileblock-service;1", classID: Components.ID('{607c1749-dc0a-463c-96cf-8ec6c3901319}'), QueryInterface: XPCOMUtils.generateQI([Ci.nsIContentPolicy]) } var NSGetFactory = XPCOMUtils.generateNSGetFactory([FileBlock]);
Webconverger/webconverger-addon
components/fileBlockService.js
JavaScript
mit
6,010
/*! supercache - v0.0.1 * Release on: 2014-12-13 * Copyright (c) 2014 Stéphane Bachelier * Licensed MIT */ !function(a,b){"use strict";"function"==typeof define&&define.amd?define(function(){return b()}):"undefined"!=typeof exports?module.exports=b():a.supercache=b()}(this,function(){"use strict";var a=Object.create(null),b=function(b){a[b.req.url]={content:b.text,parse:b.req.parse[b.req.type]}},c=function(b){var c=a[b];return c&&c.content&&c.parse?c.parse(c.text):null},d=function(){a=null},e=function(a){a&&a.on("response",b)};return{writeToCache:e,readFromCache:c,clearCache:d}});
stephanebachelier/supercache
dist/supercache.min.js
JavaScript
mit
594
/* Ship.js KC3改 Ship Object */ (function(){ "use strict"; var deferList = {}; window.KC3Ship = function( data, toClone ){ // Default object properties included in stringifications this.rosterId = 0; this.masterId = 0; this.level = 0; this.exp = [0,0,0]; this.hp = [0,0]; this.afterHp = [0,0]; this.fp = [0,0]; this.tp = [0,0]; this.aa = [0,0]; this.ar = [0,0]; this.ev = [0,0]; this.as = [0,0]; this.ls = [0,0]; this.lk = [0,0]; this.range = 0; // corresponds to "api_slot" in the API, // but devs change it to length == 5 someday, // and item of ex slot still not at 5th. // extended to 5 slots on 2018-02-16 for Musashi Kai Ni. this.items = [-1,-1,-1,-1,-1]; // corresponds to "api_slot_ex" in the API, // which has special meanings on few values: // 0: ex slot is not available // -1: ex slot is available but nothing is equipped this.ex_item = 0; // "api_onslot" in API, also changed to length 5 now. this.slots = [0,0,0,0,0]; this.slotnum = 0; this.speed = 0; // corresponds to "api_kyouka" in the API, // represents [fp,tp,aa,ar,lk] in the past. // expanded to 7-length array since 2017-09-29 // last new twos are [hp,as] this.mod = [0,0,0,0,0,0,0]; this.fuel = 0; this.ammo = 0; this.repair = [0,0,0]; this.stars = 0; this.morale = 0; this.lock = 0; this.sally = 0; this.akashiMark = false; this.preExpedCond = [ /* Data Example ["exped300",12,20, 0], // fully supplied ["exped301", 6,10, 0], // not fully supplied NOTE: this will be used against comparison of pendingConsumption that hardly to detect expedition activities */ ]; this.pendingConsumption = { /* Data Example typeName: type + W {WorldNum} + M {MapNum} + literal underscore + type_id type_id can be described as sortie/pvp/expedition id valueStructure: typeName int[3][3] of [fuel, ammo, bauxites] and [fuel, steel, buckets] and [steel] "sortie3000":[[12,24, 0],[ 0, 0, 0]], // OREL (3 nodes) "sortie3001":[[ 8,16, 0],[ 0, 0, 0]], // SPARKLE GO 1-1 (2 nodes) "sortie3002":[[ 4,12, 0],[ 0, 0, 0]], // PVP (1 node+yasen) "sortie3003":[[ 0, 0, 0],[ 0, 0, 0],[-88]], // 1 node with Jet battle of 36 slot Practice and Expedition automatically ignore repair consumption. For every action will be recorded before the sortie. */ }; this.lastSortie = ['sortie0']; // Define properties not included in stringifications Object.defineProperties(this,{ didFlee: { value: false, enumerable: false, configurable: false, writable: true }, mvp: { value: false, enumerable: false, configurable: false, writable: true }, // useful when making virtual ship objects. // requirements: // * "GearManager.get( itemId )" should get the intended equipment // * "itemId" is taken from either "items" or "ex_item" // * "shipId === -1 or 0" should always return a dummy gear GearManager: { value: null, enumerable: false, configurable: false, writable: true } }); // If specified with data, fill this object if(typeof data != "undefined"){ // Initialized with raw data if(typeof data.api_id != "undefined"){ this.rosterId = data.api_id; this.masterId = data.api_ship_id; this.level = data.api_lv; this.exp = data.api_exp; this.hp = [data.api_nowhp, data.api_maxhp]; this.afterHp = [data.api_nowhp, data.api_maxhp]; this.fp = data.api_karyoku; this.tp = data.api_raisou; this.aa = data.api_taiku; this.ar = data.api_soukou; this.ev = data.api_kaihi; this.as = data.api_taisen; this.ls = data.api_sakuteki; this.lk = data.api_lucky; this.range = data.api_leng; this.items = data.api_slot; if(typeof data.api_slot_ex != "undefined"){ this.ex_item = data.api_slot_ex; } if(typeof data.api_sally_area != "undefined"){ this.sally = data.api_sally_area; } this.slotnum = data.api_slotnum; this.slots = data.api_onslot; this.speed = data.api_soku; this.mod = data.api_kyouka; this.fuel = data.api_fuel; this.ammo = data.api_bull; this.repair = [data.api_ndock_time].concat(data.api_ndock_item); this.stars = data.api_srate; this.morale = data.api_cond; this.lock = data.api_locked; // Initialized with formatted data, deep clone if demanded } else { if(!!toClone) $.extend(true, this, data); else $.extend(this, data); } if(this.getDefer().length <= 0) this.checkDefer(); } }; // Define complex properties on prototype Object.defineProperties(KC3Ship.prototype,{ bull: { get: function(){return this.ammo;}, set: function(newAmmo){this.ammo = newAmmo;}, configurable:false, enumerable :true } }); KC3Ship.prototype.getGearManager = function(){ return this.GearManager || KC3GearManager; }; KC3Ship.prototype.exists = function(){ return this.rosterId > 0 && this.masterId > 0; }; KC3Ship.prototype.isDummy = function(){ return ! this.exists(); }; KC3Ship.prototype.master = function(){ return KC3Master.ship( this.masterId ); }; KC3Ship.prototype.name = function(){ return KC3Meta.shipName( this.master().api_name ); }; KC3Ship.prototype.stype = function(){ return KC3Meta.stype( this.master().api_stype ); }; KC3Ship.prototype.equipment = function(slot){ switch(typeof slot) { case 'number': case 'string': /* Number/String => converted as equipment slot key */ return this.getGearManager().get( slot < 0 || slot >= this.items.length ? this.ex_item : this.items[slot] ); case 'boolean': /* Boolean => return all equipments with ex item if true */ return slot ? this.equipment().concat(this.exItem()) : this.equipment(); case 'undefined': /* Undefined => returns whole equipment as equip object array */ return this.items // cloned and fixed to max 4 slots if 5th or more slots not found .slice(0, Math.max(this.slotnum, 4)) .map(Number.call, Number) .map(i => this.equipment(i)); case 'function': /* Function => iterates over given callback for every equipment */ var equipObjs = this.equipment(); equipObjs.forEach((item, index) => { slot.call(this, item.itemId, index, item); }); // forEach always return undefined, return equipment for chain use return equipObjs; } }; KC3Ship.prototype.slotSize = function(slotIndex){ // ex-slot is always assumed to be 0 for now return (slotIndex < 0 || slotIndex >= this.slots.length ? 0 : this.slots[slotIndex]) || 0; }; KC3Ship.prototype.slotCapacity = function(slotIndex){ // no API data defines the capacity for ex-slot var maxeq = (this.master() || {}).api_maxeq; return (Array.isArray(maxeq) ? maxeq[slotIndex] : 0) || 0; }; KC3Ship.prototype.areAllSlotsFull = function(){ // to leave unfulfilled slots in-game, make bauxite insufficient or use supply button at expedition var maxeq = (this.master() || {}).api_maxeq; return Array.isArray(maxeq) ? maxeq.every((expectedSize, index) => !expectedSize || expectedSize <= this.slotSize(index)) : true; }; KC3Ship.prototype.isFast = function(){ return (this.speed || this.master().api_soku) >= 10; }; KC3Ship.prototype.getSpeed = function(){ return this.speed || this.master().api_soku; }; KC3Ship.prototype.exItem = function(){ return this.getGearManager().get(this.ex_item); }; KC3Ship.prototype.isStriped = function(){ return (this.hp[1]>0) && (this.hp[0]/this.hp[1] <= 0.5); }; // Current HP < 25% but already in the repair dock not counted KC3Ship.prototype.isTaiha = function(){ return (this.hp[1]>0) && (this.hp[0]/this.hp[1] <= 0.25) && !this.isRepairing(); }; // To indicate the face grey out ship, retreated or sunk (before her data removed from API) KC3Ship.prototype.isAbsent = function(){ return (this.didFlee || this.hp[0] <= 0 || this.hp[1] <= 0); }; KC3Ship.prototype.speedName = function(){ return KC3Meta.shipSpeed(this.speed); }; KC3Ship.prototype.rangeName = function(){ return KC3Meta.shipRange(this.range); }; KC3Ship.getMarriedLevel = function(){ return 100; }; KC3Ship.getMaxLevel = function(){ return 175; }; // hard-coded at `Core.swf/vo.UserShipData.VHP` / `main.js#ShipModel.prototype.VHP` KC3Ship.getMaxHpModernize = function() { return 2; }; // hard-coded at `Core.swf/vo.UserShipData.VAS` / `main.js#ShipModel.prototype.VAS` KC3Ship.getMaxAswModernize = function() { return 9; }; KC3Ship.prototype.isMarried = function(){ return this.level >= KC3Ship.getMarriedLevel(); }; KC3Ship.prototype.levelClass = function(){ return this.level === KC3Ship.getMaxLevel() ? "married max" : this.level >= KC3Ship.getMarriedLevel() ? "married" : this.level >= 80 ? "high" : this.level >= 50 ? "medium" : ""; }; /** @return full url of ship face icon according her hp percent. */ KC3Ship.prototype.shipIcon = function(){ return KC3Meta.shipIcon(this.masterId, undefined, true, this.isStriped()); }; KC3Ship.shipIcon = function(masterId, mhp = 0, chp = mhp){ const isStriped = mhp > 0 && (chp / mhp) <= 0.5; return KC3Meta.shipIcon(masterId, undefined, true, isStriped); }; /** @return icon file name only without path and extension suffix. */ KC3Ship.prototype.moraleIcon = function(){ return KC3Ship.moraleIcon(this.morale); }; KC3Ship.moraleIcon = function(morale){ return morale > 49 ? "4" : // sparkle morale > 29 ? "3" : // normal morale > 19 ? "2" : // orange face "1"; // red face }; /** * The reason why 53 / 33 is the bound of morale effect being taken: * on entering battle, morale is subtracted -3 (day) or -2 (night) before its value gets in, * so +3 value is used as the indeed morale bound for sparkle or fatigue. * * @param {Array} valuesArray - values to be returned based on morale section. * @param {boolean} onBattle - if already on battle, not need to use the bounds mentioned above. */ KC3Ship.prototype.moraleEffectLevel = function(valuesArray = [0, 1, 2, 3, 4], onBattle = false){ return onBattle ? ( this.morale > 49 ? valuesArray[4] : this.morale > 29 ? valuesArray[3] : this.morale > 19 ? valuesArray[2] : this.morale >= 0 ? valuesArray[1] : valuesArray[0] ) : ( this.morale > 52 ? valuesArray[4] : this.morale > 32 ? valuesArray[3] : this.morale > 22 ? valuesArray[2] : this.morale >= 0 ? valuesArray[1] : valuesArray[0]); }; KC3Ship.prototype.getDefer = function(){ // returns a new defer if possible return deferList[this.rosterId] || []; }; KC3Ship.prototype.checkDefer = function() { // reset defer if it does not in normal state var self= this, ca = this.getDefer(), // get defer array cd = ca[0]; // current collection of deferred if(ca && cd && cd.state() == "pending") return ca; //console.debug("replacing",this.rosterId,"cause",!cd ? typeof cd : cd.state()); ca = deferList[this.rosterId] = Array.apply(null,{length:2}).map(function(){return $.Deferred();}); cd = $.when.apply(null,ca); ca.unshift(cd); return ca; }; /* DAMAGE STATUS Get damage status of the ship, return one of the following string: * "dummy" if this is a dummy ship * "taiha" (HP <= 25%) * "chuuha" (25% < HP <= 50%) * "shouha" (50% < HP <= 75%) * "normal" (75% < HP < 100%) * "full" (100% HP) --------------------------------------------------------------*/ KC3Ship.prototype.damageStatus = function() { if (this.hp[1] > 0) { if (this.hp[0] === this.hp[1]) { return "full"; } var hpPercent = this.hp[0] / this.hp[1]; if (hpPercent <= 0.25) { return "taiha"; } else if (hpPercent <= 0.5) { return "chuuha"; } else if (hpPercent <= 0.75) { return "shouha"; } else { return "normal"; } } else { return "dummy"; } }; KC3Ship.prototype.isSupplied = function(){ if(this.isDummy()){ return true; } return this.fuel >= this.master().api_fuel_max && this.ammo >= this.master().api_bull_max; }; KC3Ship.prototype.isNeedSupply = function(isEmpty){ if(this.isDummy()){ return false; } var fpc = function(x,y){return Math.qckInt("round",(x / y) * 10);}, fuel = fpc(this.fuel,this.master().api_fuel_max), ammo = fpc(this.ammo,this.master().api_bull_max); return Math.min(fuel,ammo) <= (ConfigManager.alert_supply) * (!isEmpty); }; KC3Ship.prototype.onFleet = function(){ var fleetNum = 0; PlayerManager.fleets.find((fleet, index) => { if(fleet.ships.some(rid => rid === this.rosterId)){ fleetNum = index + 1; return true; } }); return fleetNum; }; /** * @return a tuple for [position in fleet (0-based), fleet total ship amount, fleet number (1-based)]. * return [-1, 0, 0] if this ship is not on any fleet. */ KC3Ship.prototype.fleetPosition = function(){ var position = -1, total = 0, fleetNum = 0; if(this.exists()) { fleetNum = this.onFleet(); if(fleetNum > 0) { var fleet = PlayerManager.fleets[fleetNum - 1]; position = fleet.ships.indexOf(this.rosterId); total = fleet.countShips(); } } return [position, total, fleetNum]; }; KC3Ship.prototype.isRepairing = function(){ return PlayerManager.repairShips.indexOf(this.rosterId) >= 0; }; KC3Ship.prototype.isAway = function(){ return this.onFleet() > 1 /* ensures not in main fleet */ && (KC3TimerManager.exped(this.onFleet()) || {active:false}).active; /* if there's a countdown on expedition, means away */ }; KC3Ship.prototype.isFree = function(){ return !(this.isRepairing() || this.isAway()); }; KC3Ship.prototype.resetAfterHp = function(){ this.afterHp[0] = this.hp[0]; this.afterHp[1] = this.hp[1]; }; KC3Ship.prototype.applyRepair = function(){ this.hp[0] = this.hp[1]; // also keep afterHp consistent this.resetAfterHp(); this.morale = Math.max(40, this.morale); this.repair.fill(0); }; /** * Return max HP of a ship. Static method for library. * Especially after marriage, api_taik[1] is hard to reach in game. * Since 2017-09-29, HP can be modernized, and known max value is within 2. * @return false if ship ID belongs to abyssal or nonexistence * @see http://wikiwiki.jp/kancolle/?%A5%B1%A5%C3%A5%B3%A5%F3%A5%AB%A5%C3%A5%B3%A5%AB%A5%EA * @see https://github.com/andanteyk/ElectronicObserver/blob/develop/ElectronicObserver/Other/Information/kcmemo.md#%E3%82%B1%E3%83%83%E3%82%B3%E3%83%B3%E3%82%AB%E3%83%83%E3%82%B3%E3%82%AB%E3%83%AA%E5%BE%8C%E3%81%AE%E8%80%90%E4%B9%85%E5%80%A4 */ KC3Ship.getMaxHp = function(masterId, currentLevel, isModernized){ var masterHpArr = KC3Master.isNotRegularShip(masterId) ? [] : (KC3Master.ship(masterId) || {"api_taik":[]}).api_taik; var masterHp = masterHpArr[0], maxLimitHp = masterHpArr[1]; var expected = ((currentLevel || KC3Ship.getMaxLevel()) < KC3Ship.getMarriedLevel() ? masterHp : masterHp > 90 ? masterHp + 9 : masterHp >= 70 ? masterHp + 8 : masterHp >= 50 ? masterHp + 7 : masterHp >= 40 ? masterHp + 6 : masterHp >= 30 ? masterHp + 5 : masterHp >= 8 ? masterHp + 4 : masterHp + 3) || false; if(isModernized) expected += KC3Ship.getMaxHpModernize(); return maxLimitHp && expected > maxLimitHp ? maxLimitHp : expected; }; KC3Ship.prototype.maxHp = function(isModernized){ return KC3Ship.getMaxHp(this.masterId, this.level, isModernized); }; // Since 2017-09-29, asw stat can be modernized, known max value is within 9. KC3Ship.prototype.maxAswMod = function(){ // the condition `Core.swf/vo.UserShipData.hasTaisenAbility()` also used var maxAswBeforeMarriage = this.as[1]; var maxModAsw = this.nakedAsw() + KC3Ship.getMaxAswModernize() - (this.mod[6] || 0); return maxAswBeforeMarriage > 0 ? maxModAsw : 0; }; /** * Return total count of aircraft slots of a ship. Static method for library. * @return -1 if ship ID belongs to abyssal or nonexistence */ KC3Ship.getCarrySlots = function(masterId){ var maxeq = KC3Master.isNotRegularShip(masterId) ? undefined : (KC3Master.ship(masterId) || {}).api_maxeq; return Array.isArray(maxeq) ? maxeq.sumValues() : -1; }; KC3Ship.prototype.carrySlots = function(){ return KC3Ship.getCarrySlots(this.masterId); }; /** * @param isExslotIncluded - if equipment on ex-slot is counted, here true by default * @return current equipped pieces of equipment */ KC3Ship.prototype.equipmentCount = function(isExslotIncluded = true){ let amount = (this.items.indexOf(-1) + 1 || (this.items.length + 1)) - 1; // 0 means ex-slot not opened, -1 means opened but none equipped amount += (isExslotIncluded && this.ex_item > 0) & 1; return amount; }; /** * @param isExslotIncluded - if ex-slot is counted, here true by default * @return amount of all equippable slots */ KC3Ship.prototype.equipmentMaxCount = function(isExslotIncluded = true){ return this.slotnum + ((isExslotIncluded && (this.ex_item === -1 || this.ex_item > 0)) & 1); }; /** * @param stypeValue - specific a ship type if not refer to this ship * @return true if this (or specific) ship is a SS or SSV */ KC3Ship.prototype.isSubmarine = function(stypeValue){ if(this.isDummy()) return false; const stype = stypeValue || this.master().api_stype; return [13, 14].includes(stype); }; /** * @return true if this ship type is CVL, CV or CVB */ KC3Ship.prototype.isCarrier = function(){ if(this.isDummy()) return false; const stype = this.master().api_stype; return [7, 11, 18].includes(stype); }; /** * @return true if this ship is a CVE, which is Light Carrier and her initial ASW stat > 0 */ KC3Ship.prototype.isEscortLightCarrier = function(){ if(this.isDummy()) return false; const stype = this.master().api_stype; // Known implementations: Taiyou series, Gambier Bay series, Zuihou K2B const minAsw = (this.master().api_tais || [])[0]; return stype === 7 && minAsw > 0; }; /* REPAIR TIME Get ship's docking and Akashi times when optAfterHp is true, return repair time based on afterHp --------------------------------------------------------------*/ KC3Ship.prototype.repairTime = function(optAfterHp){ var hpArr = optAfterHp ? this.afterHp : this.hp, HPPercent = hpArr[0] / hpArr[1], RepairCalc = PS['KanColle.RepairTime']; var result = { akashi: 0 }; if (HPPercent > 0.5 && HPPercent < 1.00 && this.isFree()) { var dockTimeMillis = optAfterHp ? RepairCalc.dockingInSecJSNum(this.master().api_stype, this.level, hpArr[0], hpArr[1]) * 1000 : this.repair[0]; var repairTime = KC3AkashiRepair.calculateRepairTime(dockTimeMillis); result.akashi = Math.max( Math.hrdInt('floor', repairTime, 3, 1), // convert to seconds 20 * 60 // should be at least 20 minutes ); } if (optAfterHp) { result.docking = RepairCalc.dockingInSecJSNum(this.master().api_stype, this.level, hpArr[0], hpArr[1]); } else { result.docking = this.isRepairing() ? Math.ceil(KC3TimerManager.repair(PlayerManager.repairShips.indexOf(this.rosterId)).remainingTime()) / 1000 : /* RepairCalc. dockingInSecJSNum( this.master().api_stype, this.level, this.hp[0], this.hp[1] ) */ Math.hrdInt('floor', this.repair[0], 3, 1); } return result; }; /* Calculate resupply cost ---------------------------------- 0 <= fuelPercent <= 1, < 0 use current fuel 0 <= ammoPercent <= 1, < 0 use current ammo to calculate bauxite cost: bauxiteNeeded == true to calculate steel cost per battles: steelNeeded == true costs of expeditions simulate rounding by adding roundUpFactor(0.4/0.5?) before flooring returns an object: {fuel: <fuelCost>, ammo: <ammoCost>, steel: <steelCost>, bauxite: <bauxiteCost>} */ KC3Ship.prototype.calcResupplyCost = function(fuelPercent, ammoPercent, bauxiteNeeded, steelNeeded, roundUpFactor) { var self = this; var result = { fuel: 0, ammo: 0 }; if(this.isDummy()) { if(bauxiteNeeded) result.bauxite = 0; if(steelNeeded) result.steel = 0; return result; } var master = this.master(); var fullFuel = master.api_fuel_max; var fullAmmo = master.api_bull_max; var mulRounded = function (a, percent) { return Math.floor( a * percent + (roundUpFactor || 0) ); }; var marriageConserve = function (v) { return self.isMarried() && v > 1 ? Math.floor(0.85 * v) : v; }; result.fuel = fuelPercent < 0 ? fullFuel - this.fuel : mulRounded(fullFuel, fuelPercent); result.ammo = ammoPercent < 0 ? fullAmmo - this.ammo : mulRounded(fullAmmo, ammoPercent); // After testing, 85% is applied to resupply value, not max value. and cannot be less than 1 result.fuel = marriageConserve(result.fuel); result.ammo = marriageConserve(result.ammo); if(bauxiteNeeded){ var slotsBauxiteCost = (current, max) => ( current < max ? (max - current) * KC3GearManager.carrierSupplyBauxiteCostPerSlot : 0 ); result.bauxite = self.equipment() .map((g, i) => slotsBauxiteCost(self.slots[i], master.api_maxeq[i])) .sumValues(); // Bauxite cost to fill slots not affected by marriage. // via http://kancolle.wikia.com/wiki/Marriage //result.bauxite = marriageConserve(result.bauxite); } if(steelNeeded){ result.steel = this.calcJetsSteelCost(); } return result; }; /** * Calculate steel cost of jet aircraft for 1 battle based on current slot size. * returns total steel cost for this ship at this time */ KC3Ship.prototype.calcJetsSteelCost = function(currentSortieId) { var totalSteel = 0, consumedSteel = 0; if(this.isDummy()) { return totalSteel; } this.equipment().forEach((item, i) => { // Is Jet aircraft and left slot > 0 if(item.exists() && this.slots[i] > 0 && KC3GearManager.jetAircraftType2Ids.includes(item.master().api_type[2])) { consumedSteel = Math.round( this.slots[i] * item.master().api_cost * KC3GearManager.jetBomberSteelCostRatioPerSlot ) || 0; totalSteel += consumedSteel; if(!!currentSortieId) { let pc = this.pendingConsumption[currentSortieId]; if(!Array.isArray(pc)) { pc = [[0,0,0],[0,0,0],[0]]; this.pendingConsumption[currentSortieId] = pc; } if(!Array.isArray(pc[2])) { pc[2] = [0]; } pc[2][0] -= consumedSteel; } } }); if(!!currentSortieId && totalSteel > 0) { KC3ShipManager.save(); } return totalSteel; }; /** * Get or calculate repair cost of this ship. * @param currentHp - assumed current HP value if this ship is not damaged effectively. * @return an object: {fuel: <fuelCost>, steel: <steelCost>} */ KC3Ship.prototype.calcRepairCost = function(currentHp){ const result = { fuel: 0, steel: 0 }; if(this.isDummy()) { return result; } if(currentHp > 0 && currentHp <= this.hp[1]) { // formula see http://kancolle.wikia.com/wiki/Docking const fullFuel = this.master().api_fuel_max; const hpLost = this.hp[1] - currentHp; result.fuel = Math.floor(fullFuel * hpLost * 0.032); result.steel = Math.floor(fullFuel * hpLost * 0.06); } else { result.fuel = this.repair[1]; result.steel = this.repair[2]; } return result; }; /** * Naked stats of this ship. * @return stats without the equipment but with modernization. */ KC3Ship.prototype.nakedStats = function(statAttr){ if(this.isDummy()) { return false; } const stats = { aa: this.aa[0], ar: this.ar[0], as: this.as[0], ev: this.ev[0], fp: this.fp[0], // Naked HP maybe mean HP before marriage hp: (this.master().api_taik || [])[0] || this.hp[1], lk: (this.master().api_luck || [])[0] || this.lk[0], ls: this.ls[0], tp: this.tp[0], // Accuracy not shown in-game, so naked value might be plus-minus 0 ht: 0 }; // Limited to currently used stats only, // all implemented see `KC3Meta.js#statApiNameMap` const statApiNames = { "tyku": "aa", "souk": "ar", "tais": "as", "houk": "ev", "houg": "fp", "saku": "ls", "raig": "tp", "houm": "ht", "leng": "rn", "soku": "sp", }; for(const apiName in statApiNames) { const equipStats = this.equipmentTotalStats(apiName); stats[statApiNames[apiName]] -= equipStats; } return !statAttr ? stats : stats[statAttr]; }; KC3Ship.prototype.statsBonusOnShip = function(statAttr){ if(this.isDummy()) { return false; } const stats = {}; const statApiNames = { "houg": "fp", "souk": "ar", "raig": "tp", "houk": "ev", "tyku": "aa", "tais": "as", "saku": "ls", "houm": "ht", "leng": "rn", "soku": "sp", }; for(const apiName in statApiNames) { stats[statApiNames[apiName]] = this.equipmentTotalStats(apiName, true, true, true); } return !statAttr ? stats : stats[statAttr]; }; KC3Ship.prototype.equipmentStatsMap = function(apiName, isExslotIncluded = true){ return this.equipment(isExslotIncluded).map(equip => { if(equip.exists()) { return equip.master()["api_" + apiName]; } return undefined; }); }; KC3Ship.prototype.equipmentTotalStats = function(apiName, isExslotIncluded = true, isOnShipBonusIncluded = true, isOnShipBonusOnly = false, includeEquipTypes = null, includeEquipIds = null, excludeEquipTypes = null, excludeEquipIds = null){ var total = 0; const bonusDefs = isOnShipBonusIncluded || isOnShipBonusOnly ? KC3Gear.explicitStatsBonusGears() : false; // Accumulates displayed stats from equipment, and count for special equipment this.equipment(isExslotIncluded).forEach(equip => { if(equip.exists()) { const gearMst = equip.master(), mstId = gearMst.api_id, type2 = gearMst.api_type[2]; if(Array.isArray(includeEquipTypes) && !includeEquipTypes.includes(type2) || Array.isArray(includeEquipIds) && !includeEquipIds.includes(mstId) || Array.isArray(excludeEquipTypes) && excludeEquipTypes.includes(type2) || Array.isArray(excludeEquipIds) && excludeEquipIds.includes(mstId) ) { return; } total += gearMst["api_" + apiName] || 0; if(bonusDefs) KC3Gear.accumulateShipBonusGear(bonusDefs, equip); } }); // Add explicit stats bonuses (not masked, displayed on ship) from equipment on specific ship if(bonusDefs) { const onShipBonus = KC3Gear.equipmentTotalStatsOnShipBonus(bonusDefs, this, apiName); total = isOnShipBonusOnly ? onShipBonus : total + onShipBonus; } return total; }; KC3Ship.prototype.equipmentBonusGearAndStats = function(newGearObj){ const newGearMstId = (newGearObj || {}).masterId; let gearFlag = false; let synergyFlag = false; const bonusDefs = KC3Gear.explicitStatsBonusGears(); const synergyGears = bonusDefs.synergyGears; const allGears = this.equipment(true); allGears.forEach(g => g.exists() && KC3Gear.accumulateShipBonusGear(bonusDefs, g)); const masterIdList = allGears.map(g => g.masterId) .filter((value, index, self) => value > 0 && self.indexOf(value) === index); let bonusGears = masterIdList.map(mstId => bonusDefs[mstId]) .concat(masterIdList.map(mstId => { const typeDefs = bonusDefs[`t2_${KC3Master.slotitem(mstId).api_type[2]}`]; if (!typeDefs) return; else return $.extend(true, {}, typeDefs); })); masterIdList.push(...masterIdList); // Check if each gear works on the equipped ship const shipId = this.masterId; const originId = RemodelDb.originOf(shipId); const ctype = String(this.master().api_ctype); const stype = this.master().api_stype; const checkByShip = (byShip, shipId, originId, stype, ctype) => (byShip.ids || []).includes(shipId) || (byShip.origins || []).includes(originId) || (byShip.stypes || []).includes(stype) || (byShip.classes || []).includes(Number(ctype)) || (!byShip.ids && !byShip.origins && !byShip.stypes && !byShip.classes); // Check if ship is eligible for equip bonus and add synergy/id flags bonusGears = bonusGears.filter((gear, idx) => { if (!gear) { return false; } const synergyFlags = []; const synergyIds = []; const matchGearByMstId = (g) => g.masterId === masterIdList[idx]; let flag = false; for (const type in gear) { if (type === "byClass") { for (const key in gear[type]) { if (key == ctype) { if (Array.isArray(gear[type][key])) { for (let i = 0; i < gear[type][key].length; i++) { gear.path = gear.path || []; gear.path.push(gear[type][key][i]); } } else { gear.path = gear[type][key]; } } } } else if (type === "byShip") { if (Array.isArray(gear[type])) { for (let i = 0; i < gear[type].length; i++) { if (checkByShip(gear[type][i], shipId, originId, stype, ctype)) { gear.path = gear.path || []; gear.path.push(gear[type][i]); } } } else if (checkByShip(gear[type], shipId, originId, stype, ctype)) { gear.path = gear[type]; } } if (gear.path) { if (typeof gear.path !== "object") { gear.path = gear[type][gear.path]; } if (!Array.isArray(gear.path)) { gear.path = [gear.path]; } const count = gear.count; for (let pathIdx = 0; pathIdx < gear.path.length; pathIdx++) { const check = gear.path[pathIdx]; if (check.excludes && check.excludes.includes(shipId)) { continue; } if (check.excludeOrigins && check.excludeOrigins.includes(originId)) { continue; } if (check.excludeClasses && check.excludeClasses.includes(ctype)) { continue; } if (check.excludeStypes && check.excludeStypes.includes(stype)) { continue; } if (check.remodel && RemodelDb.remodelGroup(shipId).indexOf(shipId) < check.remodel) { continue; } if (check.remodelCap && RemodelDb.remodelGroup(shipId).indexOf(shipId) > check.remodelCap) { continue; } if (check.origins && !check.origins.includes(originId)) { continue; } if (check.stypes && !check.stypes.includes(stype)) { continue; } if (check.classes && !check.classes.includes(ctype)) { continue; } // Known issue: exact corresponding stars will not be found since identical equipment merged if (check.minStars && allGears.find(matchGearByMstId).stars < check.minStars) { continue; } if (check.single) { gear.count = 1; flag = true; } if (check.multiple) { gear.count = count; flag = true; } // countCap/minCount take priority if (check.countCap) { gear.count = Math.min(check.countCap, count); } if (check.minCount) { gear.count = count; } // Synergy check if (check.synergy) { let synergyCheck = check.synergy; if (!Array.isArray(synergyCheck)) { synergyCheck = [synergyCheck]; } for (let checkIdx = 0; checkIdx < synergyCheck.length; checkIdx++) { const flagList = synergyCheck[checkIdx].flags; for (let flagIdx = 0; flagIdx < flagList.length; flagIdx++) { const equipFlag = flagList[flagIdx]; if (equipFlag.endsWith("Nonexist")) { if (!synergyGears[equipFlag]) { break; } } else if (synergyGears[equipFlag] > 0) { if (synergyGears[equipFlag + "Ids"].includes(newGearMstId)) { synergyFlag = true; } synergyFlags.push(equipFlag); synergyIds.push(masterIdList.find(id => synergyGears[equipFlag + "Ids"].includes(id))); } } } flag |= synergyFlags.length > 0; } } } } gear.synergyFlags = synergyFlags; gear.synergyIds = synergyIds; gear.byType = idx >= Math.floor(masterIdList.length / 2); gear.id = masterIdList[idx]; return flag; }); if (!bonusGears.length) { return false; } // Trim bonus gear object and add icon ids const byIdGears = bonusGears.filter(g => !g.byType).map(g => g.id); const result = bonusGears.filter(g => !g.byType || !byIdGears.includes(g.id)).map(gear => { const obj = {}; obj.count = gear.count; const g = allGears.find(eq => eq.masterId === gear.id); obj.name = g.name(); if (g.masterId === newGearMstId) { gearFlag = true; } obj.icon = g.master().api_type[3]; obj.synergyFlags = gear.synergyFlags.filter((value, index, self) => self.indexOf(value) === index && !!value); obj.synergyNames = gear.synergyIds.map(id => allGears.find(eq => eq.masterId === id).name()); obj.synergyIcons = obj.synergyFlags.map(flag => { if (flag.includes("Radar")) { return 11; } else if (flag.includes("Torpedo")) { return 5; } else if (flag.includes("LargeGunMount")) { return 3; } else if (flag.includes("MediumGunMount")) { return 2; } else if (flag.includes("SmallGunMount")) { return 1; } else if (flag.includes("skilledLookouts")) { return 32; } else if (flag.includes("searchlight")) { return 24; } else if (flag.includes("rotorcraft") || flag.includes("helicopter")) { return 21; } else if (flag.includes("Boiler")) { return 19; } return 0; // Unknown synergy type }); return obj; }); const stats = this.statsBonusOnShip(); return { isShow: gearFlag || synergyFlag, bonusGears: result, stats: stats, }; }; // faster naked asw stat method since frequently used KC3Ship.prototype.nakedAsw = function(){ var asw = this.as[0]; var equipAsw = this.equipmentTotalStats("tais"); return asw - equipAsw; }; KC3Ship.prototype.nakedLoS = function(){ var los = this.ls[0]; var equipLos = this.equipmentTotalLoS(); return los - equipLos; }; KC3Ship.prototype.equipmentTotalLoS = function (){ return this.equipmentTotalStats("saku"); }; KC3Ship.prototype.effectiveEquipmentTotalAsw = function(canAirAttack = false, includeImprovedAttack = false, forExped = false){ var equipmentTotalAsw = 0; if(!forExped) { // When calculating asw warefare relevant thing, // asw stat from these known types of equipment not taken into account: // main gun, recon seaplane, seaplane/carrier fighter, radar, large flying boat, LBAA // KC Vita counts only carrier bomber, seaplane bomber, sonar (both), depth charges, rotorcraft and as-pby. // All visible bonuses from equipment not counted towards asw attacks for now. const noCountEquipType2Ids = [1, 2, 3, 6, 10, 12, 13, 41, 45, 47]; if(!canAirAttack) { const stype = this.master().api_stype; const isHayasuiKaiWithTorpedoBomber = this.masterId === 352 && this.hasEquipmentType(2, 8); // CAV, CVL, BBV, AV, LHA, CVL-like Hayasui Kai const isAirAntiSubStype = [6, 7, 10, 16, 17].includes(stype) || isHayasuiKaiWithTorpedoBomber; if(isAirAntiSubStype) { // exclude carrier bomber, seaplane bomber, rotorcraft, as-pby too if not able to air attack noCountEquipType2Ids.push(...[7, 8, 11, 25, 26, 57, 58]); } } equipmentTotalAsw = this.equipment(true) .map(g => g.exists() && g.master().api_tais > 0 && noCountEquipType2Ids.includes(g.master().api_type[2]) ? 0 : g.master().api_tais + (!!includeImprovedAttack && g.attackPowerImprovementBonus("asw")) ).sumValues(); } else { // For expeditions, asw from aircraft affected by proficiency and equipped slot size: // https://wikiwiki.jp/kancolle/%E9%81%A0%E5%BE%81#about_stat // https://docs.google.com/spreadsheets/d/1o-_-I8GXuJDkSGH0Dhjo7mVYx9Kpay2N2h9H3HMyO_E/htmlview equipmentTotalAsw = this.equipment(true) .map((g, i) => g.exists() && g.master().api_tais > 0 && // non-aircraft counts its actual asw value, land base plane cannot be used by expedition anyway !KC3GearManager.carrierBasedAircraftType3Ids.includes(g.master().api_type[3]) ? g.master().api_tais : // aircraft in 0-size slot take no effect, and // current formula for 0 proficiency aircraft only, // max level may give additional asw up to +2 (!this.slotSize(i) ? 0 : Math.floor(g.master().api_tais * (0.65 + 0.1 * Math.sqrt(Math.max(0, this.slotSize(i) - 2))))) ).sumValues() // unconfirmed: all visible bonuses counted? or just like OASW, only some types counted? or none counted? + this.equipmentTotalStats("tais", true, true, true/*, null, null, [1, 6, 7, 8]*/); } return equipmentTotalAsw; }; // estimated basic stats without equipments based on master data and modernization KC3Ship.prototype.estimateNakedStats = function(statAttr) { if(this.isDummy()) { return false; } const shipMst = this.master(); if(!shipMst) { return false; } const stats = { fp: shipMst.api_houg[0] + this.mod[0], tp: shipMst.api_raig[0] + this.mod[1], aa: shipMst.api_tyku[0] + this.mod[2], ar: shipMst.api_souk[0] + this.mod[3], lk: shipMst.api_luck[0] + this.mod[4], hp: this.maxHp(false) + (this.mod[5] || 0), }; // shortcuts for following funcs if(statAttr === "ls") return this.estimateNakedLoS(); if(statAttr === "as") return this.estimateNakedAsw() + (this.mod[6] || 0); if(statAttr === "ev") return this.estimateNakedEvasion(); return !statAttr ? stats : stats[statAttr]; }; // estimated LoS without equipments based on WhoCallsTheFleetDb KC3Ship.prototype.estimateNakedLoS = function() { var losInfo = WhoCallsTheFleetDb.getLoSInfo( this.masterId ); var retVal = WhoCallsTheFleetDb.estimateStat(losInfo, this.level); return retVal === false ? 0 : retVal; }; KC3Ship.prototype.estimateNakedAsw = function() { var aswInfo = WhoCallsTheFleetDb.getStatBound(this.masterId, "asw"); var retVal = WhoCallsTheFleetDb.estimateStat(aswInfo, this.level); return retVal === false ? 0 : retVal; }; KC3Ship.prototype.estimateNakedEvasion = function() { var evaInfo = WhoCallsTheFleetDb.getStatBound(this.masterId, "evasion"); var retVal = WhoCallsTheFleetDb.estimateStat(evaInfo, this.level); return retVal === false ? 0 : retVal; }; // estimated the base value (on lv1) of the 3-stats (evasion, asw, los) missing in master data, // based on current naked stats and max value (on lv99), // in case whoever wanna submit this in order to collect ship's exact stats quickly. // NOTE: naked stats needed, so should ensure no equipment equipped or at least no on ship bonus. // btw, exact evasion and asw values can be found at in-game picture book api data, but los missing still. KC3Ship.prototype.estimateBaseMasterStats = function() { if(this.isDummy()) { return false; } const info = { // evasion for ship should be `api_kaih`, here uses gear one instead houk: [0, this.ev[1], this.ev[0]], tais: [0, this.as[1], this.as[0]], saku: [0, this.ls[1], this.ls[0]], }; const level = this.level; Object.keys(info).forEach(apiName => { const lv99Stat = info[apiName][1]; const nakedStat = info[apiName][2] - this.equipmentTotalStats(apiName); info[apiName][3] = nakedStat; if(level && level > 99) { info[apiName][0] = false; } else { info[apiName][0] = WhoCallsTheFleetDb.estimateStatBase(nakedStat, lv99Stat, level); // try to get stats on maxed married level too info[apiName][4] = WhoCallsTheFleetDb.estimateStat({base: info[apiName][0], max: lv99Stat}, KC3Ship.getMaxLevel()); } }); info.level = level; info.mstId = this.masterId; info.equip = this.equipment(true).map(g => g.masterId); return info; }; KC3Ship.prototype.equipmentTotalImprovementBonus = function(attackType){ return this.equipment(true) .map(gear => gear.attackPowerImprovementBonus(attackType)) .sumValues(); }; /** * Maxed stats of this ship. * @return stats without the equipment but with modernization at Lv.99, * stats at Lv.175 can be only estimated by data from known database. */ KC3Ship.prototype.maxedStats = function(statAttr, isMarried = this.isMarried()){ if(this.isDummy()) { return false; } const stats = { aa: this.aa[1], ar: this.ar[1], as: this.as[1], ev: this.ev[1], fp: this.fp[1], hp: this.hp[1], // Maxed Luck includes full modernized + marriage bonus lk: this.lk[1], ls: this.ls[1], tp: this.tp[1] }; if(isMarried){ stats.hp = KC3Ship.getMaxHp(this.masterId); const asBound = WhoCallsTheFleetDb.getStatBound(this.masterId, "asw"); const asw = WhoCallsTheFleetDb.estimateStat(asBound, KC3Ship.getMaxLevel()); if(asw !== false) { stats.as = asw; } const lsBound = WhoCallsTheFleetDb.getStatBound(this.masterId, "los"); const los = WhoCallsTheFleetDb.estimateStat(lsBound, KC3Ship.getMaxLevel()); if(los !== false) { stats.ls = los; } const evBound = WhoCallsTheFleetDb.getStatBound(this.masterId, "evasion"); const evs = WhoCallsTheFleetDb.estimateStat(evBound, KC3Ship.getMaxLevel()); if(evs !== false) { stats.ev = evs; } } // Unlike stats fp, tp, ar and aa, // increase final maxed asw since modernized asw is not included in both as[1] and db if(this.mod[6] > 0) { stats.as += this.mod[6]; } return !statAttr ? stats : stats[statAttr]; }; /** * Left modernize-able stats of this ship. * @return stats to be maxed modernization */ KC3Ship.prototype.modernizeLeftStats = function(statAttr){ if(this.isDummy()) { return false; } const shipMst = this.master(); const stats = { fp: shipMst.api_houg[1] - shipMst.api_houg[0] - this.mod[0], tp: shipMst.api_raig[1] - shipMst.api_raig[0] - this.mod[1], aa: shipMst.api_tyku[1] - shipMst.api_tyku[0] - this.mod[2], ar: shipMst.api_souk[1] - shipMst.api_souk[0] - this.mod[3], lk: this.lk[1] - this.lk[0], // or: shipMst.api_luck[1] - shipMst.api_luck[0] - this.mod[4], // current stat (hp[1], as[0]) already includes the modded stat hp: this.maxHp(true) - this.hp[1], as: this.maxAswMod() - this.nakedAsw() }; return !statAttr ? stats : stats[statAttr]; }; /** * Get number of equipments of specific masterId(s). * @param masterId - slotitem master ID to be matched, can be an Array. * @return count of specific equipment. */ KC3Ship.prototype.countEquipment = function(masterId, isExslotIncluded = true) { return this.findEquipmentById(masterId, isExslotIncluded) .reduce((acc, v) => acc + (!!v & 1), 0); }; /** * Get number of equipments of specific type(s). * @param typeIndex - the index of `slotitem.api_type[]`, see `equiptype.json` for more. * @param typeValue - the expected type value(s) to be matched, can be an Array. * @return count of specific type(s) of equipment. */ KC3Ship.prototype.countEquipmentType = function(typeIndex, typeValue, isExslotIncluded = true) { return this.findEquipmentByType(typeIndex, typeValue, isExslotIncluded) .reduce((acc, v) => acc + (!!v & 1), 0); }; /** * Get number of some equipment (aircraft usually) equipped on non-0 slot. */ KC3Ship.prototype.countNonZeroSlotEquipment = function(masterId, isExslotIncluded = false) { return this.findEquipmentById(masterId, isExslotIncluded) .reduce((acc, v, i) => acc + ((!!v && this.slots[i] > 0) & 1), 0); }; /** * Get number of some specific types of equipment (aircraft usually) equipped on non-0 slot. */ KC3Ship.prototype.countNonZeroSlotEquipmentType = function(typeIndex, typeValue, isExslotIncluded = false) { return this.findEquipmentByType(typeIndex, typeValue, isExslotIncluded) .reduce((acc, v, i) => acc + ((!!v && this.slots[i] > 0) & 1), 0); }; /** * Get number of drums held by this ship. */ KC3Ship.prototype.countDrums = function(){ return this.countEquipment( 75 ); }; /** * Indicate if some specific equipment equipped. */ KC3Ship.prototype.hasEquipment = function(masterId, isExslotIncluded = true) { return this.findEquipmentById(masterId, isExslotIncluded).some(v => !!v); }; /** * Indicate if some specific types of equipment equipped. */ KC3Ship.prototype.hasEquipmentType = function(typeIndex, typeValue, isExslotIncluded = true) { return this.findEquipmentByType(typeIndex, typeValue, isExslotIncluded).some(v => !!v); }; /** * Indicate if some specific equipment (aircraft usually) equipped on non-0 slot. */ KC3Ship.prototype.hasNonZeroSlotEquipment = function(masterId, isExslotIncluded = false) { return this.findEquipmentById(masterId, isExslotIncluded) .some((v, i) => !!v && this.slots[i] > 0); }; /** * Indicate if some specific types of equipment (aircraft usually) equipped on non-0 slot. */ KC3Ship.prototype.hasNonZeroSlotEquipmentType = function(typeIndex, typeValue, isExslotIncluded = false) { return this.findEquipmentByType(typeIndex, typeValue, isExslotIncluded) .some((v, i) => !!v && this.slots[i] > 0); }; /** * Indicate if only specific equipment equipped (empty slot not counted). */ KC3Ship.prototype.onlyHasEquipment = function(masterId, isExslotIncluded = true) { const equipmentCount = this.equipmentCount(isExslotIncluded); return equipmentCount > 0 && equipmentCount === this.countEquipment(masterId, isExslotIncluded); }; /** * Indicate if only specific types of equipment equipped (empty slot not counted). */ KC3Ship.prototype.onlyHasEquipmentType = function(typeIndex, typeValue, isExslotIncluded = true) { const equipmentCount = this.equipmentCount(isExslotIncluded); return equipmentCount > 0 && equipmentCount === this.countEquipmentType(typeIndex, typeValue, isExslotIncluded); }; /** * Simple method to find equipment by Master ID from current ship's equipment. * @return the mapped Array to indicate equipment found or not at corresponding position, * max 6-elements including ex-slot. */ KC3Ship.prototype.findEquipmentById = function(masterId, isExslotIncluded = true) { return this.equipment(isExslotIncluded).map(gear => Array.isArray(masterId) ? masterId.includes(gear.masterId) : masterId === gear.masterId ); }; /** * Simple method to find equipment by Type ID from current ship's equipment. * @return the mapped Array to indicate equipment found or not at corresponding position, * max 6-elements including ex-slot. */ KC3Ship.prototype.findEquipmentByType = function(typeIndex, typeValue, isExslotIncluded = true) { return this.equipment(isExslotIncluded).map(gear => gear.exists() && ( Array.isArray(typeValue) ? typeValue.includes(gear.master().api_type[typeIndex]) : typeValue === gear.master().api_type[typeIndex] ) ); }; /* FIND DAMECON Find first available damecon. search order: extra slot -> 1st slot -> 2ns slot -> 3rd slot -> 4th slot -> 5th slot return: {pos: <pos>, code: <code>} pos: 1-5 for normal slots, 0 for extra slot, -1 if not found. code: 0 if not found, 1 for repair team, 2 for goddess ----------------------------------------- */ KC3Ship.prototype.findDameCon = function() { const allItems = [ {pos: 0, item: this.exItem() } ]; allItems.push(...this.equipment(false).map((g, i) => ({pos: i + 1, item: g}) )); const damecon = allItems.filter(x => ( // 42: repair team // 43: repair goddess x.item.masterId === 42 || x.item.masterId === 43 )).map(x => ( {pos: x.pos, code: x.item.masterId === 42 ? 1 : x.item.masterId === 43 ? 2 : 0} )); return damecon.length > 0 ? damecon[0] : {pos: -1, code: 0}; }; /** * Static method of the same logic to find available damecon to be used first. * @param equipArray - the master ID array of ship's all equipment including ex-slot at the last. * for 5-slot ship, array supposed to be 6 elements; otherwise should be always 5 elements. * @see KC3Ship.prototype.findDameCon * @see main.js#ShipModelReplica.prototype.useRepairItem - the repair items using order and the type codes */ KC3Ship.findDamecon = function(equipArray = []) { // push last item from ex-slot to 1st const sortedMstIds = equipArray.slice(-1); sortedMstIds.push(...equipArray.slice(0, -1)); const dameconId = sortedMstIds.find(id => id === 42 || id === 43); // code 1 for repair team, 2 for repair goddess return dameconId === 42 ? 1 : dameconId === 43 ? 2 : 0; }; /* CALCULATE TRANSPORT POINT Retrieve TP object related to the current ship ** TP Object Detail -- value: known value that were calculated for clear: is the value already clear or not? it's a NaN like. ** --------------------------------------------------------------*/ KC3Ship.prototype.obtainTP = function() { var tp = KC3Meta.tpObtained(); if (this.isDummy()) { return tp; } if (!(this.isAbsent() || this.isTaiha())) { var tp1,tp2,tp3; tp1 = String(tp.add(KC3Meta.tpObtained({stype:this.master().api_stype}))); tp2 = String(tp.add(KC3Meta.tpObtained({slots:this.equipment().map(function(slot){return slot.masterId;})}))); tp3 = String(tp.add(KC3Meta.tpObtained({slots:[this.exItem().masterId]}))); // Special case of Kinu Kai 2: Daihatsu embedded :) if (this.masterId == 487) { tp.add(KC3Meta.tpObtained({slots:[68]})); } } return tp; }; /* FIGHTER POWER Get fighter power of this ship --------------------------------------------------------------*/ KC3Ship.prototype.fighterPower = function(){ if(this.isDummy()){ return 0; } return this.equipment().map((g, i) => g.fighterPower(this.slots[i])).sumValues(); }; /* FIGHTER POWER with WHOLE NUMBER BONUS Get fighter power of this ship as an array with consideration to whole number proficiency bonus --------------------------------------------------------------*/ KC3Ship.prototype.fighterVeteran = function(){ if(this.isDummy()){ return 0; } return this.equipment().map((g, i) => g.fighterVeteran(this.slots[i])).sumValues(); }; /* FIGHTER POWER with LOWER AND UPPER BOUNDS Get fighter power of this ship as an array with consideration to min-max bonus --------------------------------------------------------------*/ KC3Ship.prototype.fighterBounds = function(forLbas = false){ if(this.isDummy()){ return [0, 0]; } const powerBounds = this.equipment().map((g, i) => g.fighterBounds(this.slots[i], forLbas)); const reconModifier = this.fighterPowerReconModifier(forLbas); return [ Math.floor(powerBounds.map(b => b[0]).sumValues() * reconModifier), Math.floor(powerBounds.map(b => b[1]).sumValues() * reconModifier) ]; }; /** * @return value under verification of LB Recon modifier to LBAS sortie fighter power. */ KC3Ship.prototype.fighterPowerReconModifier = function(forLbas = false){ var reconModifier = 1; this.equipment(function(id, idx, gear){ if(!id || gear.isDummy()){ return; } const type2 = gear.master().api_type[2]; // LB Recon Aircraft if(forLbas && type2 === 49){ const los = gear.master().api_saku; reconModifier = Math.max(reconModifier, los >= 9 ? 1.18 : 1.15 ); } }); return reconModifier; }; /* FIGHTER POWER on Air Defense with INTERCEPTOR FORMULA Recon plane gives a modifier to total interception power --------------------------------------------------------------*/ KC3Ship.prototype.interceptionPower = function(){ if(this.isDummy()){ return 0; } var reconModifier = 1; this.equipment(function(id, idx, gear){ if(!id || gear.isDummy()){ return; } const type2 = gear.master().api_type[2]; if(KC3GearManager.landBaseReconnType2Ids.includes(type2)){ const los = gear.master().api_saku; // Carrier Recon Aircraft if(type2 === 9){ reconModifier = Math.max(reconModifier, (los <= 7) ? 1.2 : (los >= 9) ? 1.3 : 1.2 // unknown ); // LB Recon Aircraft } else if(type2 === 49){ reconModifier = Math.max(reconModifier, (los <= 7) ? 1.18 : // unknown (los >= 9) ? 1.23 : 1.18 ); // Recon Seaplane, Flying Boat, etc } else { reconModifier = Math.max(reconModifier, (los <= 7) ? 1.1 : (los >= 9) ? 1.16 : 1.13 ); } } }); var interceptionPower = this.equipment() .map((g, i) => g.interceptionPower(this.slots[i])) .sumValues(); return Math.floor(interceptionPower * reconModifier); }; /* SUPPORT POWER * Get support expedition shelling power of this ship * http://kancolle.wikia.com/wiki/Expedition/Support_Expedition * http://wikiwiki.jp/kancolle/?%BB%D9%B1%E7%B4%CF%C2%E2 --------------------------------------------------------------*/ KC3Ship.prototype.supportPower = function(){ if(this.isDummy()){ return 0; } const fixedFP = this.estimateNakedStats("fp") - 1; var supportPower = 0; // for carrier series: CV, CVL, CVB if(this.isCarrier()){ supportPower = fixedFP; supportPower += this.equipmentTotalStats("raig"); supportPower += Math.floor(1.3 * this.equipmentTotalStats("baku")); // will not attack if no dive/torpedo bomber equipped if(supportPower === fixedFP){ supportPower = 0; } else { supportPower = Math.floor(1.5 * supportPower); supportPower += 55; } } else { // Explicit fire power bonus from equipment on specific ship taken into account: // http://ja.kancolle.wikia.com/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89:2354#13 // so better to use current fp value from `api_karyoku` (including naked fp + all equipment fp), // to avoid the case that fp bonus not accurately updated in time. supportPower = 5 + this.fp[0] - 1; // should be the same value with above if `equipmentTotalStats` works properly //supportPower = 5 + fixedFP + this.equipmentTotalStats("houg"); } return supportPower; }; /** * Get basic pre-cap shelling fire power of this ship (without pre-cap / post-cap modifiers). * * @param {number} combinedFleetFactor - additional power if ship is on a combined fleet. * @param {boolean} isTargetLand - if the power is applied to a land-installation target. * @return {number} computed fire power, return 0 if unavailable. * @see http://kancolle.wikia.com/wiki/Damage_Calculation * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#ua92169d */ KC3Ship.prototype.shellingFirePower = function(combinedFleetFactor = 0, isTargetLand = false){ if(this.isDummy()) { return 0; } let isCarrierShelling = this.isCarrier(); if(!isCarrierShelling) { // Hayasui Kai gets special when any Torpedo Bomber equipped isCarrierShelling = this.masterId === 352 && this.hasEquipmentType(2, 8); } let shellingPower = this.fp[0]; if(isCarrierShelling) { if(isTargetLand) { // https://wikiwiki.jp/kancolle/%E6%88%A6%E9%97%98%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6#od036af3 // https://wikiwiki.jp/kancolle/%E5%AF%BE%E5%9C%B0%E6%94%BB%E6%92%83#AGCalcCV // TP from all Torpedo Bombers not taken into account, DV power counted, // current TB with DV power: TBM-3W+3S // Regular Dive Bombers make carrier cannot attack against land-installation, // except following: Ju87C Kai, Prototype Nanzan, F4U-1D, FM-2, Ju87C Kai Ni (variants), // Suisei Model 12 (634 Air Group w/Type 3 Cluster Bombs) // DV power from items other than previous ones should not be counted const tbBaku = this.equipmentTotalStats("baku", true, false, false, [8, 58]); const dbBaku = this.equipmentTotalStats("baku", true, false, false, [7, 57], KC3GearManager.antiLandDiveBomberIds); shellingPower += Math.floor(1.3 * (tbBaku + dbBaku)); } else { // Should limit to TP from equippable aircraft? // TP visible bonus from Torpedo Bombers no effect. // DV visible bonus not implemented yet, unknown. shellingPower += this.equipmentTotalStats("raig", true, false); shellingPower += Math.floor(1.3 * this.equipmentTotalStats("baku"), true, false); } shellingPower += combinedFleetFactor; shellingPower += this.equipmentTotalImprovementBonus("airattack"); shellingPower = Math.floor(1.5 * shellingPower); shellingPower += 50; } else { shellingPower += combinedFleetFactor; shellingPower += this.equipmentTotalImprovementBonus("fire"); } // 5 is attack power constant also used everywhere shellingPower += 5; return shellingPower; }; /** * Get pre-cap torpedo power of this ship. * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#n377a90c */ KC3Ship.prototype.shellingTorpedoPower = function(combinedFleetFactor = 0){ if(this.isDummy()) { return 0; } return 5 + this.tp[0] + combinedFleetFactor + this.equipmentTotalImprovementBonus("torpedo"); }; KC3Ship.prototype.isAswAirAttack = function(){ // check asw attack type, 1530 is Abyssal Submarine Ka-Class return this.estimateDayAttackType(1530, false)[0] === "AirAttack"; }; /** * Get pre-cap anti-sub power of this ship. * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#AntiSubmarine */ KC3Ship.prototype.antiSubWarfarePower = function(aswDiff = 0){ if(this.isDummy()) { return 0; } const isAirAttack = this.isAswAirAttack(); const attackMethodConst = isAirAttack ? 8 : 13; const nakedAsw = this.nakedAsw() + aswDiff; // only asw stat from partial types of equipment taken into account const equipmentTotalAsw = this.effectiveEquipmentTotalAsw(isAirAttack); let aswPower = attackMethodConst; aswPower += 2 * Math.sqrt(nakedAsw); aswPower += 1.5 * equipmentTotalAsw; aswPower += this.equipmentTotalImprovementBonus("asw"); // should move synergy modifier to pre-cap? let synergyModifier = 1; // new DC + DCP synergy (x1.1 / x1.25) const isNewDepthChargeEquipped = this.equipment(true).some(g => g.isDepthCharge()); const isDepthChargeProjectorEquipped = this.equipment(true).some(g => g.isDepthChargeProjector()); if(isNewDepthChargeEquipped && isDepthChargeProjectorEquipped) { // Large Sonar, like T0 Sonar, not counted here const isSonarEquipped = this.hasEquipmentType(2, 14); synergyModifier = isSonarEquipped ? 1.25 : 1.1; } // legacy all types of sonar + all DC(P) synergy (x1.15) synergyModifier *= this.hasEquipmentType(3, 18) && this.hasEquipmentType(3, 17) ? 1.15 : 1; aswPower *= synergyModifier; return aswPower; }; /** * Get anti-installation power against all possible types of installations. * Will choose meaningful installation types based on current equipment. * Special attacks and battle conditions are not taken into consideration. * @return {array} with element {Object} that has attributes: * * enemy: Enemy ID to get icon * * dayPower: Day attack power of ship * * nightPower: Night attack power of ship * * modifiers: Known anti-installation modifiers * * damagedPowers: Day & night attack power tuple on Chuuha ship * @see estimateInstallationEnemyType for kc3-unique installation types */ KC3Ship.prototype.shipPossibleAntiLandPowers = function(){ if(this.isDummy()) { return []; } let possibleTypes = []; const hasAntiLandRocket = this.hasEquipment([126, 346, 347, 348, 349]); const hasT3Shell = this.hasEquipmentType(2, 18); const hasLandingCraft = this.hasEquipmentType(2, [24, 46]); // WG42 variants/landing craft-type eligible for all if (hasAntiLandRocket || hasLandingCraft){ possibleTypes = [1, 2, 3, 4, 5, 6]; } // T3 Shell eligible for all except Pillbox else if(hasT3Shell){ possibleTypes = [1, 3, 4, 5, 6]; } // Return empty if no anti-installation weapon found else { return []; } // Dummy target enemy IDs, also used for abyssal icons // 1573: Harbor Princess, 1665: Artillery Imp, 1668: Isolated Island Princess // 1656: Supply Depot Princess - Damaged, 1699: Summer Harbor Princess // 1753: Summer Supply Depot Princess const dummyEnemyList = [1573, 1665, 1668, 1656, 1699, 1753]; const basicPower = this.shellingFirePower(); const resultList = []; // Fill damage lists for each enemy type possibleTypes.forEach(installationType => { const obj = {}; const dummyEnemy = dummyEnemyList[installationType - 1]; // Modifiers from special attacks, battle conditions are not counted for now const fixedPreConds = ["Shelling", 1, undefined, [], false, false, dummyEnemy], fixedPostConds = ["Shelling", [], 0, false, false, 0, false, dummyEnemy]; const {power: precap, antiLandModifier, antiLandAdditive} = this.applyPrecapModifiers(basicPower, ...fixedPreConds); let {power} = this.applyPowerCap(precap, "Day", "Shelling"); const postcapInfo = this.applyPostcapModifiers(power, ...fixedPostConds); power = postcapInfo.power; obj.enemy = dummyEnemy; obj.modifiers = { antiLandModifier, antiLandAdditive, postCapAntiLandModifier: postcapInfo.antiLandModifier, postCapAntiLandAdditive: postcapInfo.antiLandAdditive }; obj.dayPower = Math.floor(power); // Still use day time pre-cap shelling power, without TP value. // Power constant +5 included, if assumes night contact is triggered. power = precap; ({power} = this.applyPowerCap(power, "Night", "Shelling")); ({power} = this.applyPostcapModifiers(power, ...fixedPostConds)); obj.nightPower = Math.floor(power); // Get Chuuha day attack power (in case of nuke setups) fixedPreConds.push("chuuha"); const {power: damagedPrecap} = this.applyPrecapModifiers(basicPower, ...fixedPreConds); ({power} = this.applyPowerCap(damagedPrecap, "Day", "Shelling")); ({power} = this.applyPostcapModifiers(power, ...fixedPostConds)); obj.damagedPowers = [Math.floor(power)]; // Get Chuuha night power ({power} = this.applyPowerCap(damagedPrecap, "Night", "Shelling")); ({power} = this.applyPostcapModifiers(power, ...fixedPostConds)); obj.damagedPowers.push(Math.floor(power)); resultList.push(obj); }); return resultList; }; /** * Calculate landing craft pre-cap/post-cap bonus depending on installation type. * @param installationType - kc3-unique installation types * @return {number} multiplier of landing craft * @see estimateInstallationEnemyType * @see http://kancolle.wikia.com/wiki/Partials/Anti-Installation_Weapons * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#antiground */ KC3Ship.prototype.calcLandingCraftBonus = function(installationType = 0){ if(this.isDummy() || ![1, 2, 3, 4, 5, 6].includes(installationType)) { return 0; } // 6 types of Daihatsu Landing Craft with known bonus: // * 167: Special Type 2 Amphibious Tank // * 166: Daihatsu Landing Craft (Type 89 Medium Tank & Landing Force) // * 68 : Daihatsu Landing Craft // * 230: Toku Daihatsu Landing Craft + 11th Tank Regiment // * 193: Toku Daihatsu Landing Craft (most bonuses unknown) // * 355: M4A1 DD const landingCraftIds = [167, 166, 68, 230, 193, 355]; const landingCraftCounts = landingCraftIds.map(id => this.countEquipment(id)); const landingModifiers = KC3GearManager.landingCraftModifiers[installationType - 1] || {}; const getModifier = (type, forImp = false) => ( (landingModifiers[forImp ? "improvement" : "modifier"] || [])[type] || (forImp ? 0 : 1) ); let tankBonus = 1; const landingBonus = [1], landingImprovementBonus = [0]; /** * Highest landing craft modifier is selected * (Speculative) Then, highest landing craft improvement modifier is selected * If two or more of the same equipment present, take average improvement level * * Then, multiply total landing modifier with tank modifier * There are some enemies with recorded modifiers for two or more of same equipment, * those will take priority */ // Arrange equipment in terms of priority landingCraftCounts.forEach((count, type) => { let improvement = 0; this.equipment().forEach((g, i) => { if(g.exists() && g.masterId === landingCraftIds[type]) { improvement += g.stars; } }); // Two (or more) Type 2 Tank bonus (Currently only for Supply Depot and Pillbox) if(count > 1 && type === 0 && [2, 4].includes(installationType)) { tankBonus = installationType === 2 ? 3.2 : 2.5; tankBonus *= 1 + improvement / count / 30; } // Type 2 Tank bonus else if(count > 0 && type === 0) { tankBonus = getModifier(type) + getModifier(type, true) * improvement / count; } // Bonus for two Type 89 Tank (Pillbox, Supply Depot and Isolated Island) else if(count > 1 && type === 1 && [2, 3, 4].includes(installationType)) { landingBonus.push(installationType === 4 ? 2.08 : 3 ); landingImprovementBonus.push((installationType === 4 ? 0.0416 : 0.06) * improvement / count); } // Otherwise, match modifier and improvement else if(count > 0) { landingBonus.push(getModifier(type)); landingImprovementBonus.push(getModifier(type, true) * improvement / count); } }); // Multiply modifiers return tankBonus * (Math.max(...landingBonus) + Math.max(...landingImprovementBonus)); }; /** * Get anti land installation power bonus & multiplier of this ship. * @param targetShipMasterId - target land installation master ID. * @param precap - type of bonus, false for post-cap, pre-cap by default. * @param warfareType - to indicate if use different modifiers for phases other than day shelling. * @see https://kancolle.fandom.com/wiki/Combat/Installation_Type * @see https://wikiwiki.jp/kancolle/%E5%AF%BE%E5%9C%B0%E6%94%BB%E6%92%83#AGBonus * @see https://twitter.com/T3_1206/status/994258061081505792 * @see https://twitter.com/KennethWWKK/status/1045315639127109634 * @see https://yy406myon.hatenablog.jp/entry/2018/09/14/213114 * @see https://cdn.discordapp.com/attachments/425302689887289344/614879250419417132/ECrra66VUAAzYMc.jpg_orig.jpg * @see https://github.com/Nishisonic/UnexpectedDamage/blob/master/UnexpectedDamage.js * @see estimateInstallationEnemyType * @see calcLandingCraftBonus * @return {Array} of [additive damage boost, multiplicative damage boost, precap submarine additive, precap tank additive, precap m4a1dd multiplicative] */ KC3Ship.prototype.antiLandWarfarePowerMods = function(targetShipMasterId = 0, precap = true, warfareType = "Shelling"){ if(this.isDummy()) { return [0, 1]; } const installationType = this.estimateInstallationEnemyType(targetShipMasterId, precap); if(!installationType) { return [0, 1]; } const wg42Count = this.countEquipment(126); const mortarCount = this.countEquipment(346); const mortarCdCount = this.countEquipment(347); const type4RocketCount = this.countEquipment(348); const type4RocketCdCount = this.countEquipment(349); const hasT3Shell = this.hasEquipmentType(2, 18); const alDiveBomberCount = this.countEquipment(KC3GearManager.antiLandDiveBomberIds); let wg42Bonus = 1; let type4RocketBonus = 1; let mortarBonus = 1; let t3Bonus = 1; let apShellBonus = 1; let seaplaneBonus = 1; let alDiveBomberBonus = 1; let airstrikeBomberBonus = 1; const submarineBonus = this.isSubmarine() ? 30 : 0; const landingBonus = this.calcLandingCraftBonus(installationType); const shikonCount = this.countEquipment(230); const m4a1ddCount = this.countEquipment(355); const shikonBonus = 25 * (shikonCount + m4a1ddCount); const m4a1ddModifier = m4a1ddCount ? 1.4 : 1; if(precap) { // [0, 70, 110, 140, 160] additive for each WG42 from PSVita KCKai, unknown for > 4 const wg42Additive = !wg42Count ? 0 : [0, 75, 110, 140, 160][wg42Count] || 160; const type4RocketAdditive = !type4RocketCount ? 0 : [0, 55, 115, 160, 190][type4RocketCount] || 190; const type4RocketCdAdditive = !type4RocketCdCount ? 0 : [0, 80, 170][type4RocketCdCount] || 170; const mortarAdditive = !mortarCount ? 0 : [0, 30, 55, 75, 90][mortarCount] || 90; const mortarCdAdditive = !mortarCdCount ? 0 : [0, 60, 110, 150][mortarCdCount] || 150; const rocketsAdditive = wg42Additive + type4RocketAdditive + type4RocketCdAdditive + mortarAdditive + mortarCdAdditive; switch(installationType) { case 1: // Soft-skinned, general type of land installation // 2.5x multiplicative for at least one T3 t3Bonus = hasT3Shell ? 2.5 : 1; seaplaneBonus = this.hasEquipmentType(2, [11, 45]) ? 1.2 : 1; wg42Bonus = [1, 1.3, 1.82][wg42Count] || 1.82; type4RocketBonus = [1, 1.25, 1.25 * 1.5][type4RocketCount + type4RocketCdCount] || 1.875; mortarBonus = [1, 1.2, 1.2 * 1.3][mortarCount + mortarCdCount] || 1.56; return [rocketsAdditive, t3Bonus * seaplaneBonus * wg42Bonus * type4RocketBonus * mortarBonus * landingBonus, submarineBonus, shikonBonus, m4a1ddModifier]; case 2: // Pillbox, Artillery Imp // Works even if slot is zeroed seaplaneBonus = this.hasEquipmentType(2, [11, 45]) ? 1.5 : 1; alDiveBomberBonus = [1, 1.5, 1.5 * 2.0][alDiveBomberCount] || 3; // DD/CL bonus const lightShipBonus = [2, 3].includes(this.master().api_stype) ? 1.4 : 1; // Multiplicative WG42 bonus wg42Bonus = [1, 1.6, 2.72][wg42Count] || 2.72; type4RocketBonus = [1, 1.5, 1.5 * 1.8][type4RocketCount + type4RocketCdCount] || 2.7; mortarBonus = [1, 1.3, 1.3 * 1.5][mortarCount + mortarCdCount] || 1.95; apShellBonus = this.hasEquipmentType(2, 19) ? 1.85 : 1; // Set additive modifier, multiply multiplicative modifiers return [rocketsAdditive, seaplaneBonus * alDiveBomberBonus * lightShipBonus * wg42Bonus * type4RocketBonus * mortarBonus * apShellBonus * landingBonus, submarineBonus, shikonBonus, m4a1ddModifier]; case 3: // Isolated Island Princess alDiveBomberBonus = [1, 1.4, 1.4 * 1.75][alDiveBomberCount] || 2.45; t3Bonus = hasT3Shell ? 1.75 : 1; wg42Bonus = [1, 1.4, 2.1][wg42Count] || 2.1; type4RocketBonus = [1, 1.3, 1.3 * 1.65][type4RocketCount + type4RocketCdCount] || 2.145; mortarBonus = [1, 1.2, 1.2 * 1.4][mortarCount + mortarCdCount] || 1.68; // Set additive modifier, multiply multiplicative modifiers return [rocketsAdditive, alDiveBomberBonus * t3Bonus * wg42Bonus * type4RocketBonus * mortarBonus * landingBonus, 0, shikonBonus, m4a1ddModifier]; case 5: // Summer Harbor Princess seaplaneBonus = this.hasEquipmentType(2, [11, 45]) ? 1.3 : 1; alDiveBomberBonus = [1, 1.3, 1.3 * 1.2][alDiveBomberCount] || 1.56; wg42Bonus = [1, 1.4, 2.1][wg42Count] || 2.1; t3Bonus = hasT3Shell ? 1.75 : 1; type4RocketBonus = [1, 1.25, 1.25 * 1.4][type4RocketCount + type4RocketCdCount] || 1.75; mortarBonus = [1, 1.1, 1.1 * 1.15][mortarCount + mortarCdCount] || 1.265; apShellBonus = this.hasEquipmentType(2, 19) ? 1.3 : 1; // Set additive modifier, multiply multiplicative modifiers return [rocketsAdditive, seaplaneBonus * alDiveBomberBonus * t3Bonus * wg42Bonus * type4RocketBonus * mortarBonus * apShellBonus * landingBonus, 0, shikonBonus, m4a1ddModifier]; } } else { // Post-cap types switch(installationType) { case 2: // Pillbox, Artillery Imp // Dive Bomber, Seaplane Bomber, LBAA, Jet Bomber on airstrike phase airstrikeBomberBonus = warfareType === "Aerial" && this.hasEquipmentType(2, [7, 11, 47, 57]) ? 1.55 : 1; return [0, airstrikeBomberBonus, 0, 0, 1]; case 3: // Isolated Island Princess airstrikeBomberBonus = warfareType === "Aerial" && this.hasEquipmentType(2, [7, 11, 47, 57]) ? 1.7 : 1; return [0, airstrikeBomberBonus, 0, 0, 1]; case 4: // Supply Depot Princess wg42Bonus = [1, 1.45, 1.625][wg42Count] || 1.625; type4RocketBonus = [1, 1.2, 1.2 * 1.4][type4RocketCount + type4RocketCdCount] || 1.68; mortarBonus = [1, 1.15, 1.15 * 1.2][mortarCount + mortarCdCount] || 1.38; return [0, wg42Bonus * type4RocketBonus * mortarBonus * landingBonus, 0, 0, 1]; case 6: // Summer Supply Depot Princess (shikon bonus only) return [0, landingBonus, 0, 0, 1]; } } return [0, 1, 0, 0, 1]; }; /** * Get post-cap airstrike power tuple of this ship. * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#b8c008fa * @see KC3Gear.prototype.airstrikePower */ KC3Ship.prototype.airstrikePower = function(combinedFleetFactor = 0, isJetAssaultPhase = false, contactPlaneId = 0, isCritical = false){ const totalPower = [0, 0, false]; if(this.isDummy()) { return totalPower; } // no ex-slot by default since no plane can be equipped on ex-slot for now this.equipment().forEach((gear, i) => { if(this.slots[i] > 0 && gear.isAirstrikeAircraft()) { const power = gear.airstrikePower(this.slots[i], combinedFleetFactor, isJetAssaultPhase); const isRange = !!power[2]; const capped = [ this.applyPowerCap(power[0], "Day", "Aerial").power, isRange ? this.applyPowerCap(power[1], "Day", "Aerial").power : 0 ]; const postCapped = [ Math.floor(this.applyPostcapModifiers(capped[0], "Aerial", undefined, contactPlaneId, isCritical).power), isRange ? Math.floor(this.applyPostcapModifiers(capped[1], "Aerial", undefined, contactPlaneId, isCritical).power) : 0 ]; totalPower[0] += postCapped[0]; totalPower[1] += isRange ? postCapped[1] : postCapped[0]; totalPower[2] = totalPower[2] || isRange; } }); return totalPower; }; /** * Get pre-cap night battle power of this ship. * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#b717e35a */ KC3Ship.prototype.nightBattlePower = function(isNightContacted = false){ if(this.isDummy()) { return 0; } // Night contact power bonus based on recon accuracy value: 1: 5, 2: 7, >=3: 9 // but currently only Type 98 Night Recon implemented (acc: 1), so always +5 return (isNightContacted ? 5 : 0) + this.fp[0] + this.tp[0] + this.equipmentTotalImprovementBonus("yasen"); }; /** * Get pre-cap carrier night aerial attack power of this ship. * This formula is the same with the one above besides slot bonus part and filtered equipment stats. * @see http://kancolle.wikia.com/wiki/Damage_Calculation * @see https://wikiwiki.jp/kancolle/%E6%88%A6%E9%97%98%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6#nightAS * @see https://wikiwiki.jp/kancolle/%E5%AF%BE%E5%9C%B0%E6%94%BB%E6%92%83#AGCalcCVN */ KC3Ship.prototype.nightAirAttackPower = function(isNightContacted = false, isTargetLand = false){ if(this.isDummy()) { return 0; } const equipTotals = { fp: 0, tp: 0, dv: 0, slotBonus: 0, improveBonus: 0 }; // Generally, power from only night capable aircraft will be taken into account. // For Ark Royal (Kai) + Swordfish - Night Aircraft (despite of NOAP), only Swordfish counted. const isThisArkRoyal = [515, 393].includes(this.masterId); const isLegacyArkRoyal = isThisArkRoyal && !this.canCarrierNightAirAttack(); this.equipment().forEach((gear, idx) => { if(gear.exists()) { const master = gear.master(); const slot = this.slots[idx]; const isNightAircraftType = KC3GearManager.nightAircraftType3Ids.includes(master.api_type[3]); // Swordfish variants as special torpedo bombers const isSwordfish = [242, 243, 244].includes(gear.masterId); // Zero Fighter Model 62 (Fighter-bomber Iwai Squadron) // Suisei Model 12 (Type 31 Photoelectric Fuze Bombs) const isSpecialNightPlane = [154, 320].includes(gear.masterId); const isNightPlane = isLegacyArkRoyal ? isSwordfish : isNightAircraftType || isSwordfish || isSpecialNightPlane; if(isNightPlane && slot > 0) { equipTotals.fp += master.api_houg || 0; if(!isTargetLand) equipTotals.tp += master.api_raig || 0; equipTotals.dv += master.api_baku || 0; if(!isLegacyArkRoyal) { // Bonus from night aircraft slot which also takes bombing and asw stats into account equipTotals.slotBonus += slot * (isNightAircraftType ? 3 : 0); const ftbaPower = master.api_houg + master.api_raig + master.api_baku + master.api_tais; equipTotals.slotBonus += Math.sqrt(slot) * ftbaPower * (isNightAircraftType ? 0.45 : 0.3); } equipTotals.improveBonus += gear.attackPowerImprovementBonus("yasen"); } } }); // No effect for both visible fp and tp bonus let shellingPower = this.estimateNakedStats("fp"); shellingPower += equipTotals.fp + equipTotals.tp + equipTotals.dv; shellingPower += equipTotals.slotBonus; shellingPower += equipTotals.improveBonus; shellingPower += isNightContacted ? 5 : 0; return shellingPower; }; /** * Apply known pre-cap modifiers to attack power. * @return {Object} capped power and applied modifiers. * @see http://kancolle.wikia.com/wiki/Damage_Calculation * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#beforecap * @see https://twitter.com/Nishisonic/status/893030749913227264 */ KC3Ship.prototype.applyPrecapModifiers = function(basicPower, warfareType = "Shelling", engagementId = 1, formationId = ConfigManager.aaFormation, nightSpecialAttackType = [], isNightStart = false, isCombined = false, targetShipMasterId = 0, damageStatus = this.damageStatus()){ // Engagement modifier let engagementModifier = (warfareType === "Aerial" ? [] : [0, 1, 0.8, 1.2, 0.6])[engagementId] || 1; // Formation modifier, about formation IDs: // ID 1~5: Line Ahead / Double Line / Diamond / Echelon / Line Abreast // ID 6: new Vanguard formation since 2017-11-17 // ID 11~14: 1st anti-sub / 2nd forward / 3rd diamond / 4th battle // 0 are placeholders for non-exists ID let formationModifier = ( warfareType === "Antisub" ? [0, 0.6, 0.8, 1.2, 1.1 , 1.3, 1, 0, 0, 0, 0, 1.3, 1.1, 1 , 0.7] : warfareType === "Shelling" ? [0, 1 , 0.8, 0.7, 0.75, 0.6, 1, 0, 0, 0, 0, 0.8, 1 , 0.7, 1.1] : warfareType === "Torpedo" ? [0, 1 , 0.8, 0.7, 0.6 , 0.6, 1, 0, 0, 0, 0, 0.8, 1 , 0.7, 1.1] : // other warefare types like Aerial Opening Airstrike not affected [] )[formationId] || 1; // TODO Any side Echelon vs Combined Fleet, shelling mod is 0.6? // Modifier of vanguard formation depends on the position in the fleet if(formationId === 6) { const [shipPos, shipCnt] = this.fleetPosition(); // Vanguard formation needs 4 ships at least, fake ID make no sense if(shipCnt >= 4) { // Guardian ships counted from 3rd or 4th ship const isGuardian = shipPos >= Math.floor(shipCnt / 2); if(warfareType === "Shelling") { formationModifier = isGuardian ? 1 : 0.5; } else if(warfareType === "Antisub") { formationModifier = isGuardian ? 0.6 : 1; } } } // Non-empty attack type tuple means this supposed to be night battle const isNightBattle = nightSpecialAttackType.length > 0; const canNightAntisub = warfareType === "Antisub" && (isNightStart || isCombined); // No engagement and formation modifier except night starts / combined ASW attack // Vanguard still applies for night battle if(isNightBattle && !canNightAntisub) { engagementModifier = 1; formationModifier = formationId !== 6 ? 1 : formationModifier; } // Damage percent modifier // http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#m8aa1749 const damageModifier = (!isNightBattle && warfareType === "Torpedo" ? { // Day time only affect Opening Torpedo in fact, Chuuha cannot Closing at all // Night time unmentioned, assume to be the same with shelling "chuuha": 0.8, "taiha": 0.0 } : (isNightBattle && warfareType === "Torpedo") || warfareType === "Shelling" || warfareType === "Antisub" ? { "chuuha": 0.7, "taiha": 0.4 } : // Aerial Opening Airstrike not affected {})[damageStatus] || 1; // Night special attack modifier, should not x2 although some types attack 2 times const nightCutinModifier = nightSpecialAttackType[0] === "Cutin" && nightSpecialAttackType[3] > 0 ? nightSpecialAttackType[3] : 1; // Anti-installation modifiers const targetShipType = this.estimateTargetShipType(targetShipMasterId); let antiLandAdditive = 0, antiLandModifier = 1, subAntiLandAdditive = 0, tankAdditive = 0, tankModifier = 1; if(targetShipType.isLand) { [antiLandAdditive, antiLandModifier, subAntiLandAdditive, tankAdditive, tankModifier] = this.antiLandWarfarePowerMods(targetShipMasterId, true, warfareType); } // Apply modifiers, flooring unknown, multiply and add anti-land modifiers first let result = (((basicPower + subAntiLandAdditive) * antiLandModifier + tankAdditive) * tankModifier + antiLandAdditive) * engagementModifier * formationModifier * damageModifier * nightCutinModifier; // Light Cruiser fit gun bonus, should not applied before modifiers const stype = this.master().api_stype; const ctype = this.master().api_ctype; const isThisLightCruiser = [2, 3, 21].includes(stype); let lightCruiserBonus = 0; if(isThisLightCruiser && warfareType !== "Antisub") { // 14cm, 15.2cm const singleMountCnt = this.countEquipment([4, 11]); const twinMountCnt = this.countEquipment([65, 119, 139]); lightCruiserBonus = Math.sqrt(singleMountCnt) + 2 * Math.sqrt(twinMountCnt); result += lightCruiserBonus; } // Italian Heavy Cruiser (Zara class) fit gun bonus const isThisZaraClass = ctype === 64; let italianHeavyCruiserBonus = 0; if(isThisZaraClass) { // 203mm/53 const itaTwinMountCnt = this.countEquipment(162); italianHeavyCruiserBonus = Math.sqrt(itaTwinMountCnt); result += italianHeavyCruiserBonus; } // Night battle anti-sub regular battle condition forced to no damage const aswLimitation = isNightBattle && warfareType === "Antisub" && !canNightAntisub ? 0 : 1; result *= aswLimitation; return { power: result, engagementModifier, formationModifier, damageModifier, nightCutinModifier, antiLandModifier, antiLandAdditive, lightCruiserBonus, italianHeavyCruiserBonus, aswLimitation, }; }; /** * Apply cap to attack power according warfare phase. * @param {number} precapPower - pre-cap power, see applyPrecapModifiers * @return {Object} capped power, cap value and is capped flag. * @see http://kancolle.wikia.com/wiki/Damage_Calculation * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#k5f74647 */ KC3Ship.prototype.applyPowerCap = function(precapPower, time = "Day", warfareType = "Shelling"){ const cap = time === "Night" ? 300 : // increased from 150 to 180 since 2017-03-18 warfareType === "Shelling" ? 180 : // increased from 100 to 150 since 2017-11-10 warfareType === "Antisub" ? 150 : 150; // default cap for other phases const isCapped = precapPower > cap; const power = Math.floor(isCapped ? cap + Math.sqrt(precapPower - cap) : precapPower); return { power, cap, isCapped }; }; /** * Apply known post-cap modifiers to capped attack power. * @return {Object} capped power and applied modifiers. * @see http://kancolle.wikia.com/wiki/Damage_Calculation * @see http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#aftercap * @see https://github.com/Nishisonic/UnexpectedDamage/blob/master/UnexpectedDamage.js */ KC3Ship.prototype.applyPostcapModifiers = function(cappedPower, warfareType = "Shelling", daySpecialAttackType = [], contactPlaneId = 0, isCritical = false, isAirAttack = false, targetShipStype = 0, isDefenderArmorCounted = false, targetShipMasterId = 0){ // Artillery spotting modifier, should not x2 although some types attack 2 times const dayCutinModifier = daySpecialAttackType[0] === "Cutin" && daySpecialAttackType[3] > 0 ? daySpecialAttackType[3] : 1; let airstrikeConcatModifier = 1; // Contact modifier only applied to aerial warfare airstrike power if(warfareType === "Aerial" && contactPlaneId > 0) { const contactPlaneAcc = KC3Master.slotitem(contactPlaneId).api_houm; airstrikeConcatModifier = contactPlaneAcc >= 3 ? 1.2 : contactPlaneAcc >= 2 ? 1.17 : 1.12; } const isNightBattle = daySpecialAttackType.length === 0; let apshellModifier = 1; // AP Shell modifier applied to specific target ship types: // CA, CAV, BB, FBB, BBV, CV, CVB and Land installation const isTargetShipTypeMatched = [5, 6, 8, 9, 10, 11, 18].includes(targetShipStype); if(isTargetShipTypeMatched && !isNightBattle) { const mainGunCnt = this.countEquipmentType(2, [1, 2, 3]); const apShellCnt = this.countEquipmentType(2, 19); const secondaryCnt = this.countEquipmentType(2, 4); const radarCnt = this.countEquipmentType(2, [12, 13]); if(mainGunCnt >= 1 && secondaryCnt >= 1 && apShellCnt >= 1) apshellModifier = 1.15; else if(mainGunCnt >= 1 && apShellCnt >= 1 && radarCnt >= 1) apshellModifier = 1.1; else if(mainGunCnt >= 1 && apShellCnt >= 1) apshellModifier = 1.08; } // Standard critical modifier const criticalModifier = isCritical ? 1.5 : 1; // Additional aircraft proficiency critical modifier // Applied to open airstrike and shelling air attack including anti-sub let proficiencyCriticalModifier = 1; if(isCritical && (isAirAttack || warfareType === "Aerial")) { if(daySpecialAttackType[0] === "Cutin" && daySpecialAttackType[1] === 7) { // special proficiency critical modifier for CVCI // http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#FAcutin const firstSlotType = (cutinType => { switch(cutinType) { case "CutinFDBTB": return [6, 7, 8]; case "CutinDBDBTB": case "CutinDBTB": return [7, 8]; default: return []; } })(daySpecialAttackType[2]); const hasNonZeroSlotCaptainPlane = (type2Ids) => { const firstGear = this.equipment(0); return this.slots[0] > 0 && firstGear.exists() && type2Ids.includes(firstGear.master().api_type[2]); }; // detail modifier affected by (internal) proficiency under verification // might be an average value from participants, simply use max modifier (+0.1 / +0.25) here proficiencyCriticalModifier += 0.1; proficiencyCriticalModifier += hasNonZeroSlotCaptainPlane(firstSlotType) ? 0.15 : 0; } else { // http://wikiwiki.jp/kancolle/?%B4%CF%BA%DC%B5%A1%BD%CF%CE%FD%C5%D9#v3f6d8dd const expBonus = [0, 1, 2, 3, 4, 5, 7, 10]; this.equipment().forEach((g, i) => { if(g.isAirstrikeAircraft()) { const aceLevel = g.ace || 0; const internalExpLow = KC3Meta.airPowerInternalExpBounds(aceLevel)[0]; let mod = Math.floor(Math.sqrt(internalExpLow) + (expBonus[aceLevel] || 0)) / 100; if(i > 0) mod /= 2; proficiencyCriticalModifier += mod; } }); } } const targetShipType = this.estimateTargetShipType(targetShipMasterId); // Against PT Imp modifier let antiPtImpModifier = 1; if(targetShipType.isPtImp) { const lightGunBonus = this.countEquipmentType(2, 1) >= 2 ? 1.2 : 1; const aaGunBonus = this.countEquipmentType(2, 21) >= 2 ? 1.1 : 1; const secondaryGunBonus = this.countEquipmentType(2, 4) >= 2 ? 1.2 : 1; const t3Bonus = this.hasEquipmentType(2, 18) ? 1.3 : 1; antiPtImpModifier = lightGunBonus * aaGunBonus * secondaryGunBonus * t3Bonus; } // Anti-installation modifier let antiLandAdditive = 0, antiLandModifier = 1; if(targetShipType.isLand) { [antiLandAdditive, antiLandModifier] = this.antiLandWarfarePowerMods(targetShipMasterId, false, warfareType); } // About rounding and position of anti-land modifier: // http://ja.kancolle.wikia.com/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89:925#33 let result = Math.floor(Math.floor( Math.floor(cappedPower * antiLandModifier + antiLandAdditive) * apshellModifier ) * criticalModifier * proficiencyCriticalModifier ) * dayCutinModifier * airstrikeConcatModifier * antiPtImpModifier; // New Depth Charge armor penetration, not attack power bonus let newDepthChargeBonus = 0; if(warfareType === "Antisub") { const type95ndcCnt = this.countEquipment(226); const type2ndcCnt = this.countEquipment(227); if(type95ndcCnt > 0 || type2ndcCnt > 0) { const deShipBonus = this.master().api_stype === 1 ? 1 : 0; newDepthChargeBonus = type95ndcCnt * (Math.sqrt(KC3Master.slotitem(226).api_tais - 2) + deShipBonus) + type2ndcCnt * (Math.sqrt(KC3Master.slotitem(227).api_tais - 2) + deShipBonus); // Applying this to enemy submarine's armor, result will be capped to at least 1 if(isDefenderArmorCounted) result += newDepthChargeBonus; } } // Remaining ammo percent modifier, applied to final damage, not only attack power const ammoPercent = Math.floor(this.ammo / this.master().api_bull_max * 100); const remainingAmmoModifier = ammoPercent >= 50 ? 1 : ammoPercent * 2 / 100; if(isDefenderArmorCounted) { result *= remainingAmmoModifier; } return { power: result, criticalModifier, proficiencyCriticalModifier, dayCutinModifier, airstrikeConcatModifier, apshellModifier, antiPtImpModifier, antiLandAdditive, antiLandModifier, newDepthChargeBonus, remainingAmmoModifier, }; }; /** * Collect battle conditions from current battle node if available. * Do not fall-back to default value here if not available, leave it to appliers. * @return {Object} an object contains battle properties we concern at. * @see CalculatorManager.collectBattleConditions */ KC3Ship.prototype.collectBattleConditions = function(){ return KC3Calc.collectBattleConditions(); }; /** * @return extra power bonus for combined fleet battle. * @see http://wikiwiki.jp/kancolle/?%CF%A2%B9%E7%B4%CF%C2%E2#offense */ KC3Ship.prototype.combinedFleetPowerBonus = function(playerCombined, enemyCombined, warfareType = "Shelling"){ const powerBonus = { main: 0, escort: 0 }; switch(warfareType) { case "Shelling": if(!enemyCombined) { // CTF if(playerCombined === 1) { powerBonus.main = 2; powerBonus.escort = 10; } // STF if(playerCombined === 2) { powerBonus.main = 10; powerBonus.escort = -5; } // TCF if(playerCombined === 3) { powerBonus.main = -5; powerBonus.escort = 10; } } else { if(playerCombined === 1) { powerBonus.main = 2; powerBonus.escort = -5; } if(playerCombined === 2) { powerBonus.main = 2; powerBonus.escort = -5; } if(playerCombined === 3) { powerBonus.main = -5; powerBonus.escort = -5; } if(!playerCombined) { powerBonus.main = 5; powerBonus.escort = 5; } } break; case "Torpedo": if(playerCombined) { if(!enemyCombined) { powerBonus.main = -5; powerBonus.escort = -5; } else { powerBonus.main = 10; powerBonus.escort = 10; } } break; case "Aerial": if(!playerCombined && enemyCombined) { // differentiated by target enemy fleet, targeting main: powerBonus.main = -10; powerBonus.escort = -10; // targeting escort: //powerBonus.main = -20; powerBonus.escort = -20; } break; } return powerBonus; }; // Check if specified equipment (or equip type) can be equipped on this ship. KC3Ship.prototype.canEquip = function(gearMstId, gearType2) { return KC3Master.equip_on_ship(this.masterId, gearMstId, gearType2); }; // check if this ship is capable of equipping Amphibious Tank (Ka-Mi tank only for now, no landing craft variants) KC3Ship.prototype.canEquipTank = function() { if(this.isDummy()) { return false; } return KC3Master.equip_type(this.master().api_stype, this.masterId).includes(46); }; // check if this ship is capable of equipping Daihatsu (landing craft variants, amphibious tank not counted) KC3Ship.prototype.canEquipDaihatsu = function() { if(this.isDummy()) { return false; } const master = this.master(); // Phase2 method: lookup Daihatsu type2 ID 24 in her master equip types return KC3Master.equip_type(master.api_stype, this.masterId).includes(24); // Phase1 method: /* // ship types: DD=2, CL=3, BB=9, AV=16, LHA=17, AO=22 // so far only ships with types above can equip daihatsu. if ([2,3,9,16,17,22].indexOf( master.api_stype ) === -1) return false; // excluding Akitsushima(445), Hayasui(460), Commandant Teste(491), Kamoi(162) // (however their remodels are capable of equipping daihatsu if ([445, 460, 491, 162].indexOf( this.masterId ) !== -1) return false; // only few DDs, CLs and 1 BB are capable of equipping daihatsu // see comments below. if ([2, 3, 9].indexOf( master.api_stype ) !== -1 && [ // Abukuma K2(200), Tatsuta K2(478), Kinu K2(487), Yura K2(488), Tama K2(547) 200, 478, 487, 488, 547, // Satsuki K2(418), Mutsuki K2(434), Kisaragi K2(435), Fumizuki(548) 418, 434, 435, 548, // Kasumi K2(464), Kasumi K2B(470), Arare K2 (198), Ooshio K2(199), Asashio K2D(468), Michishio K2(489), Arashio K2(490) 464, 470, 198, 199, 468, 489, 490, // Verniy(147), Kawakaze K2(469), Murasame K2(498) 147, 469, 498, // Nagato K2(541) 541 ].indexOf( this.masterId ) === -1) return false; return true; */ }; /** * @return true if this ship is capable of equipping (Striking Force) Fleet Command Facility. */ KC3Ship.prototype.canEquipFCF = function() { if(this.isDummy()) { return false; } const masterId = this.masterId, stype = this.master().api_stype; // Phase2 method: lookup FCF type2 ID 34 in her master equip types return KC3Master.equip_type(stype, masterId).includes(34); // Phase1 method: /* // Excluding DE, DD, XBB, SS, SSV, AO, AR, which can be found at master.stype.api_equip_type[34] const capableStypes = [3, 4, 5, 6, 7, 8, 9, 10, 11, 16, 17, 18, 20, 21]; // These can be found at `RemodelMain.swf/scene.remodel.view.changeEquip._createType3List()` // DD Kasumi K2, DD Shiratsuyu K2, DD Murasame K2, AO Kamoi Kai-Bo, DD Yuugumo K2, DD Naganami K2, DD Shiranui K2 const capableShips = [464, 497, 498, 500, 542, 543, 567]; // CVL Kasugamaru const incapableShips = [521]; return incapableShips.indexOf(masterId) === -1 && (capableShips.includes(masterId) || capableStypes.includes(stype)); */ }; // is this ship able to do OASW unconditionally KC3Ship.prototype.isOaswShip = function() { // Isuzu K2, Tatsuta K2, Jervis Kai, Janus Kai, Samuel B.Roberts Kai, Fletcher-Class, Yuubari K2D return [141, 478, 394, 893, 681, 562, 689, 596, 624, 628, 629, 692].includes(this.masterId); }; /** * Test to see if this ship (with equipment) is capable of opening ASW. References: * @see https://kancolle.fandom.com/wiki/Partials/Opening_ASW * @see https://wikiwiki.jp/kancolle/%E5%AF%BE%E6%BD%9C%E6%94%BB%E6%92%83#oasw */ KC3Ship.prototype.canDoOASW = function (aswDiff = 0) { if(this.isDummy()) { return false; } if(this.isOaswShip()) { return true; } const stype = this.master().api_stype; const isEscort = stype === 1; const isLightCarrier = stype === 7; // is CVE? (Taiyou-class series, Gambier Bay series, Zuihou K2B) const isEscortLightCarrier = this.isEscortLightCarrier(); // is regular ASW method not supposed to depth charge attack? (CAV, BBV, AV, LHA) // but unconfirmed for AO and Hayasui Kai const isAirAntiSubStype = [6, 10, 16, 17].includes(stype); // is Sonar equipped? also counted large one: Type 0 Sonar const hasSonar = this.hasEquipmentType(1, 10); const isHyuugaKaiNi = this.masterId === 554; const isKagaK2Go = this.masterId === 646; // lower condition for DE and CVL, even lower if equips Sonar const aswThreshold = isLightCarrier && hasSonar ? 50 : isEscort ? 60 // May apply to CVL, but only CVE can reach 65 for now (Zuihou K2 modded asw +9 +13x4 = 61) : isEscortLightCarrier ? 65 // Kaga Kai Ni Go asw starts from 82 on Lv84, let her pass just like Hyuuga K2 : isKagaK2Go ? 80 // Hyuuga Kai Ni can OASW even asw < 100, but lower threshold unknown, // guessed from her Lv90 naked asw 79 + 12 (1x helicopter, without bonus and mod) : isHyuugaKaiNi ? 90 : 100; // ship stats not updated in time when equipment changed, so take the diff if necessary, // and explicit asw bonus from Sonars taken into account confirmed. const shipAsw = this.as[0] + aswDiff // Visible asw bonus from Fighters, Dive Bombers and Torpedo Bombers still not counted, // confirmed since 2019-06-29: https://twitter.com/trollkin_ball/status/1144714377024532480 // 2019-08-08: https://wikiwiki.jp/kancolle/%E5%AF%BE%E6%BD%9C%E6%94%BB%E6%92%83#trigger_conditions // but bonus from other aircraft like Rotorcraft not (able to be) confirmed, // perhaps a similar logic to exclude some types of equipment, see #effectiveEquipmentTotalAsw // Green (any small?) gun (DE +1 asw from 12cm Single High-angle Gun Mount Model E) not counted, // confirmed since 2020-06-19: https://twitter.com/99_999999999/status/1273937773225893888 - this.equipmentTotalStats("tais", true, true, true, [1, 6, 7, 8]); // shortcut on the stricter condition first if (shipAsw < aswThreshold) return false; // For CVE like Taiyou-class, initial asw stat is high enough to reach 50 / 65, // but for Kasugamaru, since not possible to reach high asw for now, tests are not done. // For Taiyou-class Kai/Kai Ni, any equippable aircraft with asw should work. // only Autogyro or PBY equipped will not let CVL anti-sub in day shelling phase, // but OASW still can be performed. only Sonar equipped can do neither. // For other CVL possible but hard to reach 50 asw and do OASW with Sonar and high ASW aircraft. // For CV Kaga K2Go, can perform OASW with any asw aircraft like Taiyou-class Kai+: // https://twitter.com/noobcyan/status/1299886834919510017 if(isLightCarrier || isKagaK2Go) { const isTaiyouKaiAfter = RemodelDb.remodelGroup(521).indexOf(this.masterId) > 1 || RemodelDb.remodelGroup(534).indexOf(this.masterId) > 0; const hasAswAircraft = this.equipment(true).some(gear => gear.isAswAircraft(false)); return ((isTaiyouKaiAfter || isKagaK2Go) && hasAswAircraft) // ship visible asw irrelevant || this.equipment(true).some(gear => gear.isHighAswBomber(false)) // mainly asw 50/65, dive bomber not work || (shipAsw >= 100 && hasSonar && hasAswAircraft); // almost impossible for pre-marriage } // DE can OASW without Sonar, but total asw >= 75 and equipped total plus asw >= 4 if(isEscort) { if(hasSonar) return true; const equipAswSum = this.equipmentTotalStats("tais"); return shipAsw >= 75 && equipAswSum >= 4; } // Hyuuga Kai Ni can OASW with 2 Autogyro or 1 Helicopter, // but her initial naked asw too high to verify the lower threshold. // Fusou-class Kai Ni can OASW with at least 1 Helicopter + Sonar and asw >= 100. // https://twitter.com/cat_lost/status/1146075888636710912 // Hyuuga Kai Ni cannot OASW with Sonar only, just like BBV cannot ASW with Depth Charge. // perhaps all AirAntiSubStype doesn't even they can equip Sonar and asw >= 100? // at least 1 slot of ASW capable aircraft needed. if(isAirAntiSubStype) { return (isHyuugaKaiNi || hasSonar) && (this.countEquipmentType(1, 15) >= 2 || this.countEquipmentType(1, 44) >= 1); } // for other ship types who can do ASW with Depth Charge return hasSonar; }; /** * @return true if this ship can do ASW attack. */ KC3Ship.prototype.canDoASW = function(time = "Day") { if(this.isDummy() || this.isAbsent()) { return false; } const stype = this.master().api_stype; const isHayasuiKaiWithTorpedoBomber = this.masterId === 352 && this.hasEquipmentType(2, 8); const isKagaK2Go = this.masterId === 646; // CAV, CVL, BBV, AV, LHA, CVL-like Hayasui Kai, Kaga Kai Ni Go const isAirAntiSubStype = [6, 7, 10, 16, 17].includes(stype) || isHayasuiKaiWithTorpedoBomber || isKagaK2Go; if(isAirAntiSubStype) { // CV Kaga Kai Ni Go implemented since 2020-08-27, can do ASW under uncertained conditions (using CVL's currently), // but any CV form (converted back from K2Go) may ASW either if her asw modded > 0, fixed on the next day // see https://twitter.com/Synobicort_SC/status/1298998245893394432 const isCvlLike = stype === 7 || isHayasuiKaiWithTorpedoBomber || isKagaK2Go; // At night, most ship types cannot do ASW, // only CVL can ASW with depth charge if naked asw is not 0 and not taiha, // even no plane equipped or survived, such as Taiyou Kai Ni, Hayasui Kai. // but CVE will attack surface target first if NCVCI met. // *Some Abyssal AV/BBV can do ASW with air attack at night. if(time === "Night") return isCvlLike && !this.isTaiha() && this.as[1] > 0; // For day time, false if CVL or CVL-like chuuha if(isCvlLike && this.isStriped()) return false; // and if ASW plane equipped and its slot > 0 return this.equipment().some((g, i) => this.slots[i] > 0 && g.isAswAircraft(isCvlLike)); } // DE, DD, CL, CLT, CT, AO(*) // *AO: Hayasui base form and Kamoi Kai-Bo can only depth charge, Kamoi base form cannot asw const isAntiSubStype = [1, 2, 3, 4, 21, 22].includes(stype); // if max ASW stat before marriage (Lv99) not 0, can do ASW, // which also used at `Core.swf/vo.UserShipData.hasTaisenAbility()` // if as[1] === 0, naked asw stat should be 0, but as[0] may not. return isAntiSubStype && this.as[1] > 0; }; /** * @return true if this ship can do opening torpedo attack. */ KC3Ship.prototype.canDoOpeningTorpedo = function() { if(this.isDummy() || this.isAbsent()) { return false; } const hasKouhyouteki = this.hasEquipmentType(2, 22); const isThisSubmarine = this.isSubmarine(); return hasKouhyouteki || (isThisSubmarine && this.level >= 10); }; /** * @return {Object} target (enemy) ship category flags defined by us, possible values are: * `isSurface`, `isSubmarine`, `isLand`, `isPtImp`. */ KC3Ship.prototype.estimateTargetShipType = function(targetShipMasterId = 0) { const targetShip = KC3Master.ship(targetShipMasterId); // land installation const isLand = targetShip && targetShip.api_soku === 0; const isSubmarine = targetShip && this.isSubmarine(targetShip.api_stype); // regular surface vessel by default const isSurface = !isLand && !isSubmarine; // known PT Imp Packs (also belong to surface) const isPtImp = [1637, 1638, 1639, 1640].includes(targetShipMasterId); return { isSubmarine, isLand, isSurface, isPtImp, }; }; /** * Divide Abyssal land installation into KC3-unique types: * Type 0: Not land installation * Type 1: Soft-skinned, eg: Harbor Princess * Type 2: Artillery Imp, aka. Pillbox * Type 3: Isolated Island Princess * Type 4: Supply Depot Princess * Type 5: Summer Harbor Princess * Type 6: Summer Supply Depot Princess * @param precap - specify true if going to calculate pre-cap modifiers * @return the numeric type identifier * @see http://kancolle.wikia.com/wiki/Installation_Type */ KC3Ship.prototype.estimateInstallationEnemyType = function(targetShipMasterId = 0, precap = true){ const targetShip = KC3Master.ship(targetShipMasterId); if(!this.masterId || !targetShip) { return 0; } if(!this.estimateTargetShipType(targetShipMasterId).isLand) { return 0; } // Supply Depot Princess if([1653, 1654, 1655, 1656, 1657, 1658, 1921, 1922, 1923, 1924, 1925, 1926, // B 1933, 1934, 1935, 1936, 1937, 1938 // B Summer Landing Mode ].includes(targetShipMasterId)) { // Unique case: takes soft-skinned pre-cap but unique post-cap return precap ? 1 : 4; } // Summer Supply Depot Princess if([1753, 1754].includes(targetShipMasterId)) { // Same unique case as above return precap ? 1 : 6; } const abyssalIdTypeMap = { // Summer Harbor Princess "1699": 5, "1700": 5, "1701": 5, "1702": 5, "1703": 5, "1704": 5, // Isolated Island Princess "1668": 3, "1669": 3, "1670": 3, "1671": 3, "1672": 3, // Artillery Imp "1665": 2, "1666": 2, "1667": 2, }; return abyssalIdTypeMap[targetShipMasterId] || 1; }; /** * @return false if this ship (and target ship) can attack at day shelling phase. */ KC3Ship.prototype.canDoDayShellingAttack = function(targetShipMasterId = 0) { if(this.isDummy() || this.isAbsent()) { return false; } const targetShipType = this.estimateTargetShipType(targetShipMasterId); const isThisSubmarine = this.isSubmarine(); const isHayasuiKaiWithTorpedoBomber = this.masterId === 352 && this.hasEquipmentType(2, 8); const isThisCarrier = this.isCarrier() || isHayasuiKaiWithTorpedoBomber; if(isThisCarrier) { if(this.isTaiha()) return false; const isNotCvb = this.master().api_stype !== 18; if(isNotCvb && this.isStriped()) return false; if(targetShipType.isSubmarine) return this.canDoASW(); // can not attack land installation if dive bomber equipped, except some exceptions if(targetShipType.isLand && this.equipment().some((g, i) => this.slots[i] > 0 && g.master().api_type[2] === 7 && !KC3GearManager.antiLandDiveBomberIds.includes(g.masterId) )) return false; // can not attack if no bomber with slot > 0 equipped return this.equipment().some((g, i) => this.slots[i] > 0 && g.isAirstrikeAircraft()); } // submarines can only landing attack against land installation if(isThisSubmarine) return this.estimateLandingAttackType(targetShipMasterId) > 0; // can attack any enemy ship type by default return true; }; /** * @return true if this ship (and target ship) can do closing torpedo attack. */ KC3Ship.prototype.canDoClosingTorpedo = function(targetShipMasterId = 0) { if(this.isDummy() || this.isAbsent()) { return false; } if(this.isStriped()) return false; const targetShipType = this.estimateTargetShipType(targetShipMasterId); if(targetShipType.isSubmarine || targetShipType.isLand) return false; // DD, CL, CLT, CA, CAV, FBB, BB, BBV, SS, SSV, AV, CT const isTorpedoStype = [2, 3, 4, 5, 6, 8, 9, 10, 13, 14, 16, 21].includes(this.master().api_stype); return isTorpedoStype && this.estimateNakedStats("tp") > 0; }; /** * Conditions under verification, known for now: * Flagship is healthy Nelson, Double Line variants formation selected. * Min 6 ships fleet needed, main fleet only for Combined Fleet. * 3rd, 5th ship not carrier, no any submarine in fleet. * No AS/AS+ air battle needed like regular Artillery Spotting. * * No PvP sample found for now. * Can be triggered in 1 battle per sortie, max 3 chances to roll (if yasen). * * @return true if this ship (Nelson) can do Nelson Touch cut-in attack. * @see http://kancolle.wikia.com/wiki/Nelson * @see https://wikiwiki.jp/kancolle/Nelson */ KC3Ship.prototype.canDoNelsonTouch = function() { if(this.isDummy() || this.isAbsent()) { return false; } // is this ship Nelson and not even Chuuha // still okay even 3th and 5th ship are Taiha if(KC3Meta.nelsonTouchShips.includes(this.masterId) && !this.isStriped()) { const [shipPos, shipCnt, fleetNum] = this.fleetPosition(); // Nelson is flagship of a fleet, which min 6 ships needed if(fleetNum > 0 && shipPos === 0 && shipCnt >= 6 // not in any escort fleet of Combined Fleet && (!PlayerManager.combinedFleet || fleetNum !== 2)) { // Double Line variants selected const isDoubleLine = [2, 12].includes( this.collectBattleConditions().formationId || ConfigManager.aaFormation ); const fleetObj = PlayerManager.fleets[fleetNum - 1], // 3th and 5th ship are not carrier or absent? invalidCombinedShips = [fleetObj.ship(2), fleetObj.ship(4)] .some(ship => ship.isAbsent() || ship.isCarrier()), // submarine in any position of the fleet? hasSubmarine = fleetObj.ship().some(s => s.isSubmarine()), // no ship(s) sunk or retreated in mid-sortie? hasSixShips = fleetObj.countShips(true) >= 6; return isDoubleLine && !invalidCombinedShips && !hasSubmarine && hasSixShips; } } return false; }; /** * Most conditions are the same with Nelson Touch, except: * Flagship is healthy Nagato/Mutsu Kai Ni, Echelon formation selected. * 2nd ship is a battleship, Chuuha ok, Taiha no good. * * Additional ammo consumption for Nagato/Mutsu & 2nd battleship: * + Math.floor(or ceil?)(total ammo cost of this battle (yasen may included) / 2) * * @return true if this ship (Nagato/Mutsu Kai Ni) can do special cut-in attack. * @see http://kancolle.wikia.com/wiki/Nagato * @see https://wikiwiki.jp/kancolle/%E9%95%B7%E9%96%80%E6%94%B9%E4%BA%8C * @see http://kancolle.wikia.com/wiki/Mutsu * @see https://wikiwiki.jp/kancolle/%E9%99%B8%E5%A5%A5%E6%94%B9%E4%BA%8C */ KC3Ship.prototype.canDoNagatoClassCutin = function(flagShipIds = KC3Meta.nagatoClassCutinShips) { if(this.isDummy() || this.isAbsent()) { return false; } if(flagShipIds.includes(this.masterId) && !this.isStriped()) { const [shipPos, shipCnt, fleetNum] = this.fleetPosition(); if(fleetNum > 0 && shipPos === 0 && shipCnt >= 6 && (!PlayerManager.combinedFleet || fleetNum !== 2)) { const isEchelon = [4, 12].includes( this.collectBattleConditions().formationId || ConfigManager.aaFormation ); const fleetObj = PlayerManager.fleets[fleetNum - 1], // 2nd ship not battle ship? invalidCombinedShips = [fleetObj.ship(1)].some(ship => ship.isAbsent() || ship.isTaiha() || ![8, 9, 10].includes(ship.master().api_stype)), hasSubmarine = fleetObj.ship().some(s => s.isSubmarine()), hasSixShips = fleetObj.countShips(true) >= 6; return isEchelon && !invalidCombinedShips && !hasSubmarine && hasSixShips; } } return false; }; /** * Nagato/Mutsu Kai Ni special cut-in attack modifiers are variant depending on the fleet 2nd ship. * And there are different modifiers for 2nd ship's 3rd attack. * @param modifierFor2ndShip - to indicate the returned modifier is used for flagship or 2nd ship. * @return the modifier, 1 by default for unknown conditions. * @see https://wikiwiki.jp/kancolle/%E9%95%B7%E9%96%80%E6%94%B9%E4%BA%8C */ KC3Ship.prototype.estimateNagatoClassCutinModifier = function(modifierFor2ndShip = false) { const locatedFleet = PlayerManager.fleets[this.onFleet() - 1]; if(!locatedFleet) return 1; const flagshipMstId = locatedFleet.ship(0).masterId; if(!KC3Meta.nagatoClassCutinShips.includes(flagshipMstId)) return 1; const ship2ndMstId = locatedFleet.ship(1).masterId; const partnerModifierMap = KC3Meta.nagatoCutinShips.includes(flagshipMstId) ? (modifierFor2ndShip ? { "573": 1.4, // Mutsu Kai Ni "276": 1.35, // Mutsu Kai, base form unverified? "576": 1.25, // Nelson Kai, base form unverified? } : { "573": 1.2, // Mutsu Kai Ni "276": 1.15, // Mutsu Kai, base form unverified? "576": 1.1, // Nelson Kai, base form unverified? }) : KC3Meta.mutsuCutinShips.includes(flagshipMstId) ? (modifierFor2ndShip ? { "541": 1.4, // Nagato Kai Ni "275": 1.35, // Nagato Kai "576": 1.25, // Nelson Kai } : { "541": 1.2, // Nagato Kai Ni "275": 1.15, // Nagato Kai "576": 1.1, // Nelson Kai }) : {}; const baseModifier = modifierFor2ndShip ? 1.2 : 1.4; const partnerModifier = partnerModifierMap[ship2ndMstId] || 1; const apShellModifier = this.hasEquipmentType(2, 19) ? 1.35 : 1; // Surface Radar modifier not always limited to post-cap and AP Shell synergy now, // can be applied to night battle (pre-cap) independently? const surfaceRadarModifier = this.equipment(true).some(gear => gear.isSurfaceRadar()) ? 1.15 : 1; return baseModifier * partnerModifier * apShellModifier * surfaceRadarModifier; }; /** * Most conditions are the same with Nelson Touch, except: * Flagship is healthy Colorado, Echelon formation selected. * 2nd and 3rd ships are healthy battleship, neither Taiha nor Chuuha. * * The same additional ammo consumption like Nagato/Mutsu cutin for top 3 battleships. * * 4 types of smoke animation effects will be used according corresponding position of partener ships, * see `main.js#CutinColoradoAttack.prototype._getSmoke`. * * @return true if this ship (Colorado) can do Colorado special cut-in attack. * @see http://kancolle.wikia.com/wiki/Colorado * @see https://wikiwiki.jp/kancolle/Colorado */ KC3Ship.prototype.canDoColoradoCutin = function() { if(this.isDummy() || this.isAbsent()) { return false; } // is this ship Colorado and not even Chuuha if(KC3Meta.coloradoCutinShips.includes(this.masterId) && !this.isStriped()) { const [shipPos, shipCnt, fleetNum] = this.fleetPosition(); if(fleetNum > 0 && shipPos === 0 && shipCnt >= 6 && (!PlayerManager.combinedFleet || fleetNum !== 2)) { const isEchelon = [4, 12].includes( this.collectBattleConditions().formationId || ConfigManager.aaFormation ); const fleetObj = PlayerManager.fleets[fleetNum - 1], // 2nd and 3rd ship are (F)BB(V) only, not even Chuuha? validCombinedShips = [fleetObj.ship(1), fleetObj.ship(2)] .some(ship => !ship.isAbsent() && !ship.isStriped() && [8, 9, 10].includes(ship.master().api_stype)), // submarine in any position of the fleet? hasSubmarine = fleetObj.ship().some(s => s.isSubmarine()), // uncertain: ship(s) sunk or retreated in mid-sortie can prevent proc? hasSixShips = fleetObj.countShips(true) >= 6; return isEchelon && validCombinedShips && !hasSubmarine && hasSixShips; } } return false; }; /** * Colorado special cut-in attack modifiers are variant, * depending on equipment and 2nd and 3rd ship in the fleet. * @see https://twitter.com/syoukuretin/status/1132763536222969856 */ KC3Ship.prototype.estimateColoradoCutinModifier = function(forShipPos = 0) { const locatedFleet = PlayerManager.fleets[this.onFleet() - 1]; if(!locatedFleet) return 1; const flagshipMstId = locatedFleet.ship(0).masterId; if(!KC3Meta.coloradoCutinShips.includes(flagshipMstId)) return 1; const combinedModifierMaps = [ // No more mods for flagship? {}, // x1.1 for Big-7 2nd ship { "80": 1.1, "275": 1.1, "541": 1.1, // Nagato "81": 1.1, "276": 1.1, "573": 1.1, // Mutsu "571": 1.1, "576": 1.1, // Nelson }, // x1.15 for Big-7 3rd ship { "80": 1.15, "275": 1.15, "541": 1.15, "81": 1.15, "276": 1.15, "573": 1.15, "571": 1.15, "576": 1.15, }, ]; forShipPos = (forShipPos || 0) % 3; const baseModifier = [1.3, 1.15, 1.15][forShipPos]; const targetShip = locatedFleet.ship(forShipPos), targetShipMstId = targetShip.masterId, targetShipModifier = combinedModifierMaps[forShipPos][targetShipMstId] || 1; // Bug 'mods of 2nd ship's apshell/radar and on-5th-slot-empty-exslot spread to 3rd ship' not applied here const apShellModifier = targetShip.hasEquipmentType(2, 19) ? 1.35 : 1; const surfaceRadarModifier = targetShip.equipment(true).some(gear => gear.isSurfaceRadar()) ? 1.15 : 1; const ship2ndMstId = locatedFleet.ship(1).masterId, ship2ndModifier = combinedModifierMaps[1][ship2ndMstId] || 1; return baseModifier * targetShipModifier * (forShipPos === 2 && targetShipModifier > 1 ? ship2ndModifier : 1) * apShellModifier * surfaceRadarModifier; }; /** * Most conditions are the same with Nelson Touch, except: * Flagship is healthy Kongou-class Kai Ni C, Line Ahead formation selected, night battle only. * 2nd ship is healthy one of the following: * * Kongou K2C flagship: Hiei K2C / Haruna K2 / Warspite * * Hiei K2C flagship: Kongou K2C / Kirishima K2 * Surface ships in fleet >= 5 (that means 1 submarine is okay for single fleet) * * Since it's a night battle only cutin, have to be escort fleet of any Combined Fleet. * And it's impossible to be triggered after any other daytime Big-7 special cutin, * because all ship-combined spcutins only trigger 1-time per sortie? * * The additional 30% ammo consumption, see: * * https://twitter.com/myteaGuard/status/1254040809365618690 * * https://twitter.com/myteaGuard/status/1254048759559778305 * * @return true if this ship (Kongou-class K2C) can do special cut-in attack. * @see https://kancolle.fandom.com/wiki/Kongou/Special_Cut-In * @see https://wikiwiki.jp/kancolle/%E6%AF%94%E5%8F%A1%E6%94%B9%E4%BA%8C%E4%B8%99 */ KC3Ship.prototype.canDoKongouCutin = function() { if(this.isDummy() || this.isAbsent()) { return false; } // is this ship Kongou-class K2C and not even Chuuha if(KC3Meta.kongouCutinShips.includes(this.masterId) && !this.isStriped()) { const [shipPos, shipCnt, fleetNum] = this.fleetPosition(); if(fleetNum > 0 && shipPos === 0 && shipCnt >= 5 && (!PlayerManager.combinedFleet || fleetNum === 2)) { const isLineAhead = [1, 14].includes( this.collectBattleConditions().formationId || ConfigManager.aaFormation ); const fleetObj = PlayerManager.fleets[fleetNum - 1], // 2nd ship is valid partener and not even Chuuha validCombinedShips = ({ // Kongou K2C: Hiei K2C, Haruna K2, Warspite "591": [592, 151, 439, 364], // Hiei K2C: Kongou K2C, Kirishima K2 "592": [591, 152], }[this.masterId] || []).includes(fleetObj.ship(1).masterId) && !fleetObj.ship(1).isStriped(), // uncertain: ship(s) sunk or retreated in mid-sortie can prevent proc? hasFiveSurfaceShips = fleetObj.shipsUnescaped().filter(s => !s.isSubmarine()).length >= 5; return isLineAhead && validCombinedShips && hasFiveSurfaceShips; } } return false; }; /** * @return the landing attack kind ID, return 0 if can not attack. * Since Phase 2, defined by `_getDaihatsuEffectType` at `PhaseHougekiOpening, PhaseHougeki, PhaseHougekiBase`, * all the ID 1 are replaced by 3, ID 2 except the one at `PhaseHougekiOpening` replaced by 3. */ KC3Ship.prototype.estimateLandingAttackType = function(targetShipMasterId = 0) { const targetShip = KC3Master.ship(targetShipMasterId); if(!this.masterId || !targetShip) return 0; const isLand = targetShip.api_soku <= 0; // new equipment: M4A1 DD if(this.hasEquipment(355) && isLand) return 6; // higher priority: Toku Daihatsu + 11th Tank if(this.hasEquipment(230)) return isLand ? 5 : 0; // Abyssal hard land installation could be landing attacked const isTargetLandable = [1668, 1669, 1670, 1671, 1672, // Isolated Island Princess 1665, 1666, 1667, // Artillery Imp 1653, 1654, 1655, 1656, 1657, 1658, // Supply Depot Princess // but why Summer Supply Depot Princess not counted? 1809, 1810, 1811, 1812, 1813, 1814, // Supply Depot Princess Vacation Mode 1921, 1922, 1923, 1924, 1925, 1926, // Supply Depot Princess B 1933, 1934, 1935, 1936, 1937, 1938, // Supply Depot Princess B Summer Landing Mode 1815, 1816, 1817, 1818, 1819, 1820, // Anchorage Water Demon Vacation Mode 1556, 1631, 1632, 1633, 1650, 1651, 1652, 1889, 1890, 1891, 1892, 1893, 1894 // Airfield Princess ].includes(targetShipMasterId); // T2 Tank if(this.hasEquipment(167)) { const isThisSubmarine = this.isSubmarine(); if(isThisSubmarine && isLand) return 4; if(isTargetLandable) return 4; return 0; } if(isTargetLandable) { // M4A1 DD if(this.hasEquipment(355)) return 6; // T89 Tank if(this.hasEquipment(166)) return 3; // Toku Daihatsu if(this.hasEquipment(193)) return 3; // Daihatsu if(this.hasEquipment(68)) return 3; } return 0; }; /** * @param atType - id from `api_hougeki?.api_at_type` which indicates the special attack. * @param altCutinTerm - different term string for cutin has different variant, like CVCI. * @param altModifier - different power modifier for cutin has different variant, like CVCI. * @return known special attack (aka Cut-In) types definition tuple. * will return an object mapped all IDs and tuples if atType is omitted. * will return `["SingleAttack", 0]` if no matched ID found. * @see estimateDayAttackType */ KC3Ship.specialAttackTypeDay = function(atType, altCutinTerm, altModifier){ const knownDayAttackTypes = { 1: ["Cutin", 1, "Laser"], // no longer exists now 2: ["Cutin", 2, "DoubleAttack", 1.2], 3: ["Cutin", 3, "CutinMainSecond", 1.1], 4: ["Cutin", 4, "CutinMainRadar", 1.2], 5: ["Cutin", 5, "CutinMainApshell", 1.3], 6: ["Cutin", 6, "CutinMainMain", 1.5], 7: ["Cutin", 7, "CutinCVCI", 1.25], 100: ["Cutin", 100, "CutinNelsonTouch", 2.0], 101: ["Cutin", 101, "CutinNagatoSpecial", 2.27], 102: ["Cutin", 102, "CutinMutsuSpecial", 2.27], 103: ["Cutin", 103, "CutinColoradoSpecial", 2.26], 200: ["Cutin", 200, "CutinZuiunMultiAngle", 1.35], 201: ["Cutin", 201, "CutinAirSeaMultiAngle", 1.3], }; if(atType === undefined) return knownDayAttackTypes; const matched = knownDayAttackTypes[atType] || ["SingleAttack", 0]; if(matched[0] === "Cutin") { if(altCutinTerm) matched[2] = altCutinTerm; if(altModifier) matched[3] = altModifier; } return matched; }; /** * Estimate day time attack type of this ship. * Only according ship type and equipment, ignoring factors such as ship status, target-able. * @param {number} targetShipMasterId - a Master ID of being attacked ship, used to indicate some * special attack types. eg: attacking a submarine, landing attack an installation. * The ID can be just an example to represent this type of target. * @param {boolean} trySpTypeFirst - specify true if want to estimate special attack type. * @param {number} airBattleId - air battle result id, to indicate if special attacks can be triggered, * special attacks require AS / AS +, default is AS+. * @return {Array} day time attack type constants tuple: * [name, regular attack id / cutin id / landing id, cutin name, modifier]. * cutin id is from `api_hougeki?.api_at_type` which indicates the special attacks. * NOTE: Not take 'can not be targeted' into account yet, * such as: CV/CVB against submarine; submarine against land installation; * asw aircraft all lost against submarine; torpedo bomber only against land, * should not pass targetShipMasterId at all for these scenes. * @see https://github.com/andanteyk/ElectronicObserver/blob/master/ElectronicObserver/Other/Information/kcmemo.md#%E6%94%BB%E6%92%83%E7%A8%AE%E5%88%A5 * @see BattleMain.swf#battle.models.attack.AttackData#setOptionsAtHougeki - client side codes of day attack type. * @see BattleMain.swf#battle.phase.hougeki.PhaseHougekiBase - client side hints of special cutin attack type. * @see main.js#PhaseHougeki.prototype._getNormalAttackType - since Phase 2 * @see specialAttackTypeDay * @see estimateNightAttackType * @see canDoOpeningTorpedo * @see canDoDayShellingAttack * @see canDoASW * @see canDoClosingTorpedo */ KC3Ship.prototype.estimateDayAttackType = function(targetShipMasterId = 0, trySpTypeFirst = false, airBattleId = 1) { if(this.isDummy()) { return []; } // if attack target known, will give different attack according target ship const targetShipType = this.estimateTargetShipType(targetShipMasterId); const isThisCarrier = this.isCarrier(); const isThisSubmarine = this.isSubmarine(); // Special cutins do not need isAirSuperiorityBetter if(trySpTypeFirst) { // Nelson Touch since 2018-09-15 if(this.canDoNelsonTouch()) { const isRedT = this.collectBattleConditions().engagementId === 4; return KC3Ship.specialAttackTypeDay(100, null, isRedT ? 2.5 : 2.0); } // Nagato cutin since 2018-11-16 if(this.canDoNagatoClassCutin(KC3Meta.nagatoCutinShips)) { // To clarify: here only indicates the modifier of flagship's first 2 attacks return KC3Ship.specialAttackTypeDay(101, null, this.estimateNagatoClassCutinModifier()); } // Mutsu cutin since 2019-02-27 if(this.canDoNagatoClassCutin(KC3Meta.mutsuCutinShips)) { return KC3Ship.specialAttackTypeDay(102, null, this.estimateNagatoClassCutinModifier()); } // Colorado cutin since 2019-05-25 if(this.canDoColoradoCutin()) { return KC3Ship.specialAttackTypeDay(103, null, this.estimateColoradoCutinModifier()); } } const isAirSuperiorityBetter = airBattleId === 1 || airBattleId === 2; // Special Multi-Angle cutins do not need recon plane and probably higher priority if(trySpTypeFirst && isAirSuperiorityBetter) { const isThisIseClassK2 = [553, 554].includes(this.masterId); const mainGunCnt = this.countEquipmentType(2, [1, 2, 3, 38]); if(isThisIseClassK2 && mainGunCnt > 0 && !this.isTaiha()) { // Ise-class Kai Ni Zuiun Multi-Angle Attack since 2019-03-27 const spZuiunCnt = this.countNonZeroSlotEquipment( // All seaplane bombers named Zuiun capable? [26, 79, 80, 81, 207, 237, 322, 323] ); // Zuiun priority to Air/Sea Attack when they are both equipped if(spZuiunCnt > 1) return KC3Ship.specialAttackTypeDay(200); // Ise-class Kai Ni Air/Sea Multi-Angle Attack since 2019-03-27 const spSuiseiCnt = this.countNonZeroSlotEquipment( // Only Suisei named 634th Air Group capable? [291, 292, 319] ); if(spSuiseiCnt > 1) return KC3Ship.specialAttackTypeDay(201); } } const hasRecon = this.hasNonZeroSlotEquipmentType(2, [10, 11]); if(trySpTypeFirst && hasRecon && isAirSuperiorityBetter) { /* * To estimate if can do day time special attacks (aka Artillery Spotting). * In game, special attack types are judged and given by server API result. * By equip compos, multiply types are possible to be selected to trigger, such as * CutinMainMain + Double, CutinMainAPShell + CutinMainRadar + CutinMainSecond. * Here just check by strictness & modifier desc order and return one of them. */ const mainGunCnt = this.countEquipmentType(2, [1, 2, 3, 38]); const apShellCnt = this.countEquipmentType(2, 19); if(mainGunCnt >= 2 && apShellCnt >= 1) return KC3Ship.specialAttackTypeDay(6); const secondaryCnt = this.countEquipmentType(2, 4); if(mainGunCnt >= 1 && secondaryCnt >= 1 && apShellCnt >= 1) return KC3Ship.specialAttackTypeDay(5); const radarCnt = this.countEquipmentType(2, [12, 13]); if(mainGunCnt >= 1 && secondaryCnt >= 1 && radarCnt >= 1) return KC3Ship.specialAttackTypeDay(4); if(mainGunCnt >= 1 && secondaryCnt >= 1) return KC3Ship.specialAttackTypeDay(3); if(mainGunCnt >= 2) return KC3Ship.specialAttackTypeDay(2); } else if(trySpTypeFirst && isThisCarrier && isAirSuperiorityBetter) { // day time carrier shelling cut-in // http://wikiwiki.jp/kancolle/?%C0%EF%C6%AE%A4%CB%A4%C4%A4%A4%A4%C6#FAcutin // https://twitter.com/_Kotoha07/status/907598964098080768 // https://twitter.com/arielugame/status/908343848459317249 const fighterCnt = this.countNonZeroSlotEquipmentType(2, 6); const diveBomberCnt = this.countNonZeroSlotEquipmentType(2, 7); const torpedoBomberCnt = this.countNonZeroSlotEquipmentType(2, 8); if(diveBomberCnt >= 1 && torpedoBomberCnt >= 1 && fighterCnt >= 1) return KC3Ship.specialAttackTypeDay(7, "CutinFDBTB", 1.25); if(diveBomberCnt >= 2 && torpedoBomberCnt >= 1) return KC3Ship.specialAttackTypeDay(7, "CutinDBDBTB", 1.2); if(diveBomberCnt >= 1 && torpedoBomberCnt >= 1) return KC3Ship.specialAttackTypeDay(7, "CutinDBTB", 1.15); } // is target a land installation if(targetShipType.isLand) { const landingAttackType = this.estimateLandingAttackType(targetShipMasterId); if(landingAttackType > 0) { return ["LandingAttack", landingAttackType]; } // see `main.js#PhaseHougeki.prototype._hasRocketEffect` or same method of `PhaseHougekiBase`, // and if base attack method is NOT air attack const hasRocketLauncher = this.hasEquipmentType(2, 37) || this.hasEquipment([346, 347]); // no such ID -1, just mean higher priority if(hasRocketLauncher) return ["Rocket", -1]; } // is this ship Hayasui Kai if(this.masterId === 352) { if(targetShipType.isSubmarine) { // air attack if asw aircraft equipped const aswEquip = this.equipment().find(g => g.isAswAircraft(false)); return aswEquip ? ["AirAttack", 1] : ["DepthCharge", 2]; } // air attack if torpedo bomber equipped, otherwise fall back to shelling if(this.hasEquipmentType(2, 8)) return ["AirAttack", 1]; else return ["SingleAttack", 0]; } if(isThisCarrier) { return ["AirAttack", 1]; } // only torpedo attack possible if this ship is submarine (but not shelling phase) if(isThisSubmarine) { return ["Torpedo", 3]; } if(targetShipType.isSubmarine) { const stype = this.master().api_stype; // CAV, BBV, AV, LHA can only air attack against submarine return ([6, 10, 16, 17].includes(stype)) ? ["AirAttack", 1] : ["DepthCharge", 2]; } // default single shelling fire attack return ["SingleAttack", 0]; }; /** * @return true if this ship (and target ship) can attack at night. */ KC3Ship.prototype.canDoNightAttack = function(targetShipMasterId = 0) { // no count for escaped ship too if(this.isDummy() || this.isAbsent()) { return false; } // no ship can night attack on taiha if(this.isTaiha()) return false; const initYasen = this.master().api_houg[0] + this.master().api_raig[0]; const isThisCarrier = this.isCarrier(); // even carrier can do shelling or air attack if her yasen power > 0 (no matter chuuha) // currently known ships: Graf / Graf Kai, Saratoga, Taiyou Class Kai Ni, Kaga Kai Ni Go if(isThisCarrier && initYasen > 0) return true; // carriers without yasen power can do air attack under some conditions: if(isThisCarrier) { // only CVB can air attack on chuuha (taiha already excluded) const isNotCvb = this.master().api_stype !== 18; if(isNotCvb && this.isStriped()) return false; // Ark Royal (Kai) can air attack without NOAP if Swordfish variants equipped and slot > 0 if([515, 393].includes(this.masterId) && this.hasNonZeroSlotEquipment([242, 243, 244])) return true; // night aircraft + NOAP equipped return this.canCarrierNightAirAttack(); } // can not night attack for any ship type if initial FP + TP is 0 return initYasen > 0; }; /** * @return true if a carrier can do air attack at night thank to night aircraft, * which should be given via `api_n_mother_list`, not judged by client side. * @see canDoNightAttack - those yasen power carriers not counted in `api_n_mother_list`. * @see http://wikiwiki.jp/kancolle/?%CC%EB%C0%EF#NightCombatByAircrafts */ KC3Ship.prototype.canCarrierNightAirAttack = function() { if(this.isDummy() || this.isAbsent()) { return false; } if(this.isCarrier()) { const hasNightAircraft = this.hasEquipmentType(3, KC3GearManager.nightAircraftType3Ids); const hasNightAvPersonnel = this.hasEquipment([258, 259]); // night battle capable carriers: Saratoga Mk.II, Akagi Kai Ni E/Kaga Kai Ni E const isThisNightCarrier = [545, 599, 610].includes(this.masterId); // ~~Swordfish variants are counted as night aircraft for Ark Royal + NOAP~~ // Ark Royal + Swordfish variants + NOAP - night aircraft will not get `api_n_mother_list: 1` //const isThisArkRoyal = [515, 393].includes(this.masterId); //const isSwordfishArkRoyal = isThisArkRoyal && this.hasEquipment([242, 243, 244]); // if night aircraft + (NOAP equipped / on Saratoga Mk.2/Akagi K2E/Kaga K2E) return hasNightAircraft && (hasNightAvPersonnel || isThisNightCarrier); } return false; }; /** * @param spType - id from `api_hougeki.api_sp_list` which indicates the special attack. * @param altCutinTerm - different term string for cutin has different variant, like SS TCI, CVNCI, DDCI. * @param altModifier - different power modifier for cutin has different variant, like SS TCI, CVNCI, DDCI. * @return known special attack (aka Cut-In) types definition tuple. * will return an object mapped all IDs and tuples if atType is omitted. * will return `["SingleAttack", 0]` if no matched ID found. * @see estimateNightAttackType */ KC3Ship.specialAttackTypeNight = function(spType, altCutinTerm, altModifier){ const knownNightAttackTypes = { 1: ["Cutin", 1, "DoubleAttack", 1.2], 2: ["Cutin", 2, "CutinTorpTorpMain", 1.3], 3: ["Cutin", 3, "CutinTorpTorpTorp", 1.5], 4: ["Cutin", 4, "CutinMainMainSecond", 1.75], 5: ["Cutin", 5, "CutinMainMainMain", 2.0], 6: ["Cutin", 6, "CutinCVNCI", 1.25], 7: ["Cutin", 7, "CutinMainTorpRadar", 1.3], 8: ["Cutin", 8, "CutinTorpRadarLookout", 1.2], 100: ["Cutin", 100, "CutinNelsonTouch", 2.0], 101: ["Cutin", 101, "CutinNagatoSpecial", 2.27], 102: ["Cutin", 102, "CutinMutsuSpecial", 2.27], 103: ["Cutin", 103, "CutinColoradoSpecial", 2.26], 104: ["Cutin", 104, "CutinKongouSpecial", 1.9], }; if(spType === undefined) return knownNightAttackTypes; const matched = knownNightAttackTypes[spType] || ["SingleAttack", 0]; if(matched[0] === "Cutin") { if(altCutinTerm) matched[2] = altCutinTerm; if(altModifier) matched[3] = altModifier; } return matched; }; /** * Estimate night battle attack type of this ship. * Also just give possible attack type, no responsibility to check can do attack at night, * or that ship can be targeted or not, etc. * @param {number} targetShipMasterId - a Master ID of being attacked ship. * @param {boolean} trySpTypeFirst - specify true if want to estimate special attack type. * @return {Array} night battle attack type constants tuple: [name, cutin id, cutin name, modifier]. * cutin id is partially from `api_hougeki.api_sp_list` which indicates the special attacks. * @see BattleMain.swf#battle.models.attack.AttackData#setOptionsAtNight - client side codes of night attack type. * @see BattleMain.swf#battle.phase.night.PhaseAttack - client side hints of special cutin attack type. * @see main.js#PhaseHougekiBase.prototype._getNormalAttackType - since Phase 2 * @see specialAttackTypeNight * @see estimateDayAttackType * @see canDoNightAttack */ KC3Ship.prototype.estimateNightAttackType = function(targetShipMasterId = 0, trySpTypeFirst = false) { if(this.isDummy()) { return []; } const targetShipType = this.estimateTargetShipType(targetShipMasterId); const isThisCarrier = this.isCarrier(); const isThisSubmarine = this.isSubmarine(); const stype = this.master().api_stype; const isThisLightCarrier = stype === 7; const isThisDestroyer = stype === 2; const isThisKagaK2Go = this.masterId === 646; const torpedoCnt = this.countEquipmentType(2, [5, 32]); // simulate server-side night air attack flag: `api_n_mother_list` const isCarrierNightAirAttack = isThisCarrier && this.canCarrierNightAirAttack(); if(trySpTypeFirst && !targetShipType.isSubmarine) { // to estimate night special attacks, which should be given by server API result. // will not trigger if this ship is taiha or targeting submarine. // carrier night cut-in, NOAP or Saratoga Mk.II/Akagi K2E/Kaga K2E needed if(isCarrierNightAirAttack) { // https://kancolle.fandom.com/wiki/Combat#Setups_and_Attack_Types // http://wikiwiki.jp/kancolle/?%CC%EB%C0%EF#x397cac6 const nightFighterCnt = this.countNonZeroSlotEquipmentType(3, 45); const nightTBomberCnt = this.countNonZeroSlotEquipmentType(3, 46); // Zero Fighter Model 62 (Fighter-bomber Iwai Squadron) const iwaiDBomberCnt = this.countNonZeroSlotEquipment(154); // Swordfish variants const swordfishTBomberCnt = this.countNonZeroSlotEquipment([242, 243, 244]); // new patterns for Suisei Model 12 (Type 31 Photoelectric Fuze Bombs) since 2019-04-30, // it more likely acts as yet unimplemented Night Dive Bomber type const photoDBomberCnt = this.countNonZeroSlotEquipment(320); // might extract this out for estimating unexpected damage actual pattern modifier const ncvciModifier = (() => { const otherCnt = photoDBomberCnt + iwaiDBomberCnt + swordfishTBomberCnt; if(nightFighterCnt >= 2 && nightTBomberCnt >= 1) return 1.25; if(nightFighterCnt + nightTBomberCnt + otherCnt === 2) return 1.2; if(nightFighterCnt + nightTBomberCnt + otherCnt >= 3) return 1.18; return 1; // should not reach here })(); // first place thank to its highest mod 1.25 if(nightFighterCnt >= 2 && nightTBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNFNTB", ncvciModifier); // 3 planes mod 1.18 if(nightFighterCnt >= 3) return KC3Ship.specialAttackTypeNight(6, "CutinNFNFNF", ncvciModifier); if(nightFighterCnt >= 1 && nightTBomberCnt >= 2) return KC3Ship.specialAttackTypeNight(6, "CutinNFNTBNTB", ncvciModifier); if(nightFighterCnt >= 2 && iwaiDBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNFFBI", ncvciModifier); if(nightFighterCnt >= 2 && swordfishTBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNFSF", ncvciModifier); if(nightFighterCnt >= 1 && iwaiDBomberCnt >= 2) return KC3Ship.specialAttackTypeNight(6, "CutinNFFBIFBI", ncvciModifier); if(nightFighterCnt >= 1 && swordfishTBomberCnt >= 2) return KC3Ship.specialAttackTypeNight(6, "CutinNFSFSF", ncvciModifier); if(nightFighterCnt >= 1 && iwaiDBomberCnt >= 1 && swordfishTBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFFBISF", ncvciModifier); if(nightFighterCnt >= 1 && nightTBomberCnt >= 1 && iwaiDBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNTBFBI", ncvciModifier); if(nightFighterCnt >= 1 && nightTBomberCnt >= 1 && swordfishTBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNTBSF", ncvciModifier); if(nightFighterCnt >= 2 && photoDBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNFNDB", ncvciModifier); if(nightFighterCnt >= 1 && photoDBomberCnt >= 2) return KC3Ship.specialAttackTypeNight(6, "CutinNFNDBNDB", ncvciModifier); if(nightFighterCnt >= 1 && nightTBomberCnt >= 1 && photoDBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNTBNDB", ncvciModifier); if(nightFighterCnt >= 1 && photoDBomberCnt >= 1 && iwaiDBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNDBFBI", ncvciModifier); if(nightFighterCnt >= 1 && photoDBomberCnt >= 1 && swordfishTBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNDBSF", ncvciModifier); // 2 planes mod 1.2, put here not to mask previous patterns, tho proc rate might be higher if(nightFighterCnt >= 1 && nightTBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNTB", ncvciModifier); if(nightFighterCnt >= 1 && photoDBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNFNDB", ncvciModifier); if(nightTBomberCnt >= 1 && photoDBomberCnt >= 1) return KC3Ship.specialAttackTypeNight(6, "CutinNTBNDB", ncvciModifier); } else { // special Nelson Touch since 2018-09-15 if(this.canDoNelsonTouch()) { const isRedT = this.collectBattleConditions().engagementId === 4; return KC3Ship.specialAttackTypeNight(100, null, isRedT ? 2.5 : 2.0); } // special Nagato Cutin since 2018-11-16 if(this.canDoNagatoClassCutin(KC3Meta.nagatoCutinShips)) { return KC3Ship.specialAttackTypeNight(101, null, this.estimateNagatoClassCutinModifier()); } // special Mutsu Cutin since 2019-02-27 if(this.canDoNagatoClassCutin(KC3Meta.mutsuCutinShips)) { return KC3Ship.specialAttackTypeNight(102, null, this.estimateNagatoClassCutinModifier()); } // special Colorado Cutin since 2019-05-25 if(this.canDoColoradoCutin()) { return KC3Ship.specialAttackTypeNight(103, null, this.estimateColoradoCutinModifier()); } // special Kongou-class K2C Cutin since 2020-04-23 if(this.canDoKongouCutin()) { // Basic precap modifier is 1.9: https://twitter.com/CC_jabberwock/status/1253677320629399552 const engagementMod = [1, 1, 1, 1.25, 0.75][this.collectBattleConditions().engagementId] || 1.0; return KC3Ship.specialAttackTypeNight(104, null, 1.9 * engagementMod); } // special torpedo radar cut-in for destroyers since 2017-10-25 // http://wikiwiki.jp/kancolle/?%CC%EB%C0%EF#dfcb6e1f if(isThisDestroyer && torpedoCnt >= 1) { // according tests, any radar with accuracy stat >= 3 capable, // even large radars (Kasumi K2 can equip), air radars okay too, see: // https://twitter.com/nicolai_2501/status/923172168141123584 // https://twitter.com/nicolai_2501/status/923175256092581888 const hasCapableRadar = this.equipment(true).some(gear => gear.isSurfaceRadar()); const hasSkilledLookout = this.hasEquipmentType(2, 39); const smallMainGunCnt = this.countEquipmentType(2, 1); // Extra bonus if small main gun is 12.7cm Twin Gun Mount Model D Kai Ni/3 // https://twitter.com/ayanamist_m2/status/944176834551222272 // https://docs.google.com/spreadsheets/d/1_e0M6asJUbu9EEW4PrGCu9hOxZnY7OQEDHH2DUAzjN8/htmlview const modelDK2SmallGunCnt = this.countEquipment(267), modelDK3SmallGunCnt = this.countEquipment(366); // Possible to equip 2 D guns for 4 slots Tashkent // https://twitter.com/Xe_UCH/status/1011398540654809088 const modelDSmallGunModifier = ([1, 1.25, 1.4][modelDK2SmallGunCnt + modelDK3SmallGunCnt] || 1.4) * (1 + modelDK3SmallGunCnt * 0.05); if(hasCapableRadar && smallMainGunCnt >= 1) return KC3Ship.specialAttackTypeNight(7, null, 1.3 * modelDSmallGunModifier); if(hasCapableRadar && hasSkilledLookout) return KC3Ship.specialAttackTypeNight(8, null, 1.2 * modelDSmallGunModifier); } // special torpedo cut-in for late model submarine torpedo const lateTorpedoCnt = this.countEquipment([213, 214, 383]); const submarineRadarCnt = this.countEquipmentType(2, 51); if(lateTorpedoCnt >= 1 && submarineRadarCnt >= 1) return KC3Ship.specialAttackTypeNight(3, "CutinLateTorpRadar", 1.75); if(lateTorpedoCnt >= 2) return KC3Ship.specialAttackTypeNight(3, "CutinLateTorpTorp", 1.6); // although modifier lower than Main CI / Mix CI, but seems be more frequently used // will not mutex if 5 slots ships can equip torpedo if(torpedoCnt >= 2) return KC3Ship.specialAttackTypeNight(3); const mainGunCnt = this.countEquipmentType(2, [1, 2, 3, 38]); if(mainGunCnt >= 3) return KC3Ship.specialAttackTypeNight(5); const secondaryCnt = this.countEquipmentType(2, 4); if(mainGunCnt === 2 && secondaryCnt >= 1) return KC3Ship.specialAttackTypeNight(4); if((mainGunCnt === 2 && secondaryCnt === 0 && torpedoCnt === 1) || (mainGunCnt === 1 && torpedoCnt === 1)) return KC3Ship.specialAttackTypeNight(2); // double attack can be torpedo attack animation if topmost slot is torpedo if((mainGunCnt === 2 && secondaryCnt === 0 && torpedoCnt === 0) || (mainGunCnt === 1 && secondaryCnt >= 1) || (secondaryCnt >= 2 && torpedoCnt <= 1)) return KC3Ship.specialAttackTypeNight(1); } } if(targetShipType.isLand) { const landingAttackType = this.estimateLandingAttackType(targetShipMasterId); if(landingAttackType > 0) { return ["LandingAttack", landingAttackType]; } const hasRocketLauncher = this.hasEquipmentType(2, 37); if(hasRocketLauncher) return ["Rocket", -1]; } // priority to use server flag if(isCarrierNightAirAttack) { return ["AirAttack", 1, true]; } if(targetShipType.isSubmarine && (isThisLightCarrier || isThisKagaK2Go)) { return ["DepthCharge", 2]; } if(isThisCarrier) { // these abyssal ships can only be shelling attacked, // see `main.js#PhaseHougekiBase.prototype._getNormalAttackType` const isSpecialAbyssal = [ 1679, 1680, 1681, 1682, 1683, // Lycoris Princess 1711, 1712, 1713, // Jellyfish Princess ].includes[targetShipMasterId]; const isSpecialCarrier = [ 432, 353, // Graf & Graf Kai 433 // Saratoga (base form) ].includes(this.masterId); if(isSpecialCarrier || isSpecialAbyssal) return ["SingleAttack", 0]; // here just indicates 'attack type', not 'can attack or not', see #canDoNightAttack // Taiyou Kai Ni fell back to shelling attack if no bomber equipped, but ninja changed by devs. // now she will air attack against surface ships, but no plane appears if no aircraft equipped. return ["AirAttack", 1]; } if(isThisSubmarine) { return ["Torpedo", 3]; } if(targetShipType.isSubmarine) { // CAV, BBV, AV, LHA return ([6, 10, 16, 17].includes(stype)) ? ["AirAttack", 1] : ["DepthCharge", 2]; } // torpedo attack if any torpedo equipped at top most, otherwise single shelling fire const topGear = this.equipment().find(gear => gear.exists() && [1, 2, 3].includes(gear.master().api_type[1])); return topGear && topGear.master().api_type[1] === 3 ? ["Torpedo", 3] : ["SingleAttack", 0]; }; /** * Calculates base value used in day battle artillery spotting process chance. * Likely to be revamped as formula comes from PSVita and does not include CVCI, * uncertain about Combined Fleet interaction. * @see https://kancolle.wikia.com/wiki/User_blog:Shadow27X/Artillery_Spotting_Rate_Formula * @see KC3Fleet.prototype.artillerySpottingLineOfSight */ KC3Ship.prototype.daySpAttackBaseRate = function() { if (this.isDummy() || !this.onFleet()) { return {}; } const [shipPos, shipCnt, fleetNum] = this.fleetPosition(); const fleet = PlayerManager.fleets[fleetNum - 1]; const fleetLoS = fleet.artillerySpottingLineOfSight(); const adjFleetLoS = Math.floor(Math.sqrt(fleetLoS) + fleetLoS / 10); const adjLuck = Math.floor(Math.sqrt(this.lk[0]) + 10); // might exclude equipment on ship LoS bonus for now, // to include LoS bonus, use `this.equipmentTotalLoS()` instead const equipLoS = this.equipmentTotalStats("saku", true, false); // assume to best condition AS+ by default (for non-battle) const airBattleId = this.collectBattleConditions().airBattleId || 1; const baseValue = airBattleId === 1 ? adjLuck + 0.7 * (adjFleetLoS + 1.6 * equipLoS) + 10 : airBattleId === 2 ? adjLuck + 0.6 * (adjFleetLoS + 1.2 * equipLoS) : 0; return { baseValue, isFlagship: shipPos === 0, equipLoS, fleetLoS, dispSeiku: airBattleId }; }; /** * Calculates base value used in night battle cut-in process chance. * @param {number} currentHp - used by simulating from battle prediction or getting different HP value. * @see https://kancolle.wikia.com/wiki/Combat/Night_Battle#Night_Cut-In_Chance * @see https://wikiwiki.jp/kancolle/%E5%A4%9C%E6%88%A6#nightcutin1 * @see KC3Fleet.prototype.estimateUsableSearchlight */ KC3Ship.prototype.nightSpAttackBaseRate = function(currentHp) { if (this.isDummy()) { return {}; } let baseValue = 0; if (this.lk[0] < 50) { baseValue += 15 + this.lk[0] + 0.75 * Math.sqrt(this.level); } else { baseValue += 65 + Math.sqrt(this.lk[0] - 50) + 0.8 * Math.sqrt(this.level); } const [shipPos, shipCnt, fleetNum] = this.fleetPosition(); // Flagship bonus const isFlagship = shipPos === 0; if (isFlagship) { baseValue += 15; } // Chuuha bonus const isChuuhaOrWorse = (currentHp || this.hp[0]) <= (this.hp[1] / 2); if (isChuuhaOrWorse) { baseValue += 18; } // Skilled lookout bonus if (this.hasEquipmentType(2, 39)) { baseValue += 5; } // Searchlight bonus, large SL unknown for now const fleetSearchlight = fleetNum > 0 && PlayerManager.fleets[fleetNum - 1].estimateUsableSearchlight(); if (fleetSearchlight) { baseValue += 7; } // Starshell bonus/penalty const battleConds = this.collectBattleConditions(); const playerStarshell = battleConds.playerFlarePos > 0; const enemyStarshell = battleConds.enemyFlarePos > 0; if (playerStarshell) { baseValue += 4; } if (enemyStarshell) { baseValue += -10; } return { baseValue, isFlagship, isChuuhaOrWorse, fleetSearchlight, playerStarshell, enemyStarshell }; }; /** * Calculate Nelson Touch process rate, currently only known in day * @param {boolean} isNight - Nelson Touch has lower modifier at night? * @return {number} special attack rate * @see https://twitter.com/Xe_UCH/status/1180283907284979713 */ KC3Ship.prototype.nelsonTouchRate = function(isNight) { if (this.isDummy() || isNight) { return false; } const [shipPos, shipCnt, fleetNum] = this.fleetPosition(); // Nelson Touch prerequisite should be fulfilled before calling this, see also #canDoNelsonTouch // here only to ensure fleetObj and combinedShips below not undefined if this invoked unexpectedly if (shipPos !== 0 || shipCnt < 6 || !fleetNum) { return false; } const fleetObj = PlayerManager.fleets[fleetNum - 1]; const combinedShips = [2, 4].map(pos => fleetObj.ship(pos)); const combinedShipsLevel = combinedShips.reduce((acc, ship) => acc + ship.level, 0); const combinedShipsPenalty = combinedShips.some(ship => [2, 16].includes(ship.master().api_stype)) ? 10 : 0; // estimate return (0.08 * this.level + 0.04 * combinedShipsLevel + 0.24 * this.lk[0] + 36 - combinedShipsPenalty) / 100; }; /** * Calculate ship day time artillery spotting process rate based on known type factors. * @param {number} atType - based on api_at_type value of artillery spotting type. * @param {string} cutinSubType - sub type of cut-in like CVCI. * @return {number} artillery spotting percentage, false if unable to arty spot or unknown special attack. * @see daySpAttackBaseRate * @see estimateDayAttackType * @see Type factors: https://wikiwiki.jp/kancolle/%E6%88%A6%E9%97%98%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6#Observation * @see Type factors for multi-angle cutin: https://wikiwiki.jp/kancolle/%E4%BC%8A%E5%8B%A2%E6%94%B9%E4%BA%8C */ KC3Ship.prototype.artillerySpottingRate = function(atType = 0, cutinSubType = "") { // type 1 laser attack has gone forever, ship not on fleet cannot be evaluated if (atType < 2 || this.isDummy() || !this.onFleet()) { return false; } const formatPercent = num => Math.floor(num * 1000) / 10; // Nelson Touch if (atType === 100) { return formatPercent(this.nelsonTouchRate(false)); } const typeFactor = { 2: 150, 3: 120, 4: 130, 5: 130, 6: 140, 7: ({ "CutinFDBTB" : 125, "CutinDBDBTB": 140, "CutinDBTB" : 155, })[cutinSubType], // 100~103 might use different formula, see #nelsonTouchRate 200: 120, 201: undefined, }[atType]; if (!typeFactor) { return false; } const {baseValue, isFlagship} = this.daySpAttackBaseRate(); return formatPercent(((Math.floor(baseValue) + (isFlagship ? 15 : 0)) / typeFactor) || 0); }; /** * Calculate ship night battle special attack (cut-in and double attack) process rate based on known type factors. * @param {number} spType - based on api_sp_list value of night special attack type. * @param {string} cutinSubType - sub type of cut-in like CVNCI, submarine cut-in. * @return {number} special attack percentage, false if unable to perform or unknown special attack. * @see nightSpAttackBaseRate * @see estimateNightAttackType * @see Type factors: https://wikiwiki.jp/kancolle/%E5%A4%9C%E6%88%A6#nightcutin1 */ KC3Ship.prototype.nightCutinRate = function(spType = 0, cutinSubType = "") { if (spType < 1 || this.isDummy()) { return false; } // not sure: DA success rate almost 99% if (spType === 1) { return 99; } const typeFactor = { 2: 115, 3: ({ // submarine late torp cutin should be different? "CutinLateTorpRadar": undefined, "CutinLateTorpTorp": undefined, })[cutinSubType] || 122, // regular CutinTorpTorpTorp 4: 130, 5: 140, 6: ({ // CVNCI factors unknown, placeholders "CutinNFNFNTB": undefined, // should be 3 types, for mod 1.25 "CutinNFNTB" : undefined, // 2 planes for mod 1.2 "CutinNFNDB" : undefined, "CutinNTBNDB": undefined, "CutinNFNFNF" : undefined, // 3 planes for mod 1.18 "CutinNFNTBNTB": undefined, "CutinNFNFFBI" : undefined, "CutinNFNFSF" : undefined, "CutinNFFBIFBI": undefined, "CutinNFSFSF" : undefined, "CutinNFFBISF" : undefined, "CutinNFNTBFBI": undefined, "CutinNFNTBSF" : undefined, "CutinNFNFNDB" : undefined, "CutinNFNDBNDB": undefined, "CutinNFNTBNDB": undefined, "CutinNFNDBFBI": undefined, "CutinNFNDBSF" : undefined, })[cutinSubType], // This two DD cutins can be rolled after regular cutin, more chance to be processed 7: 130, 8: undefined, // CutinTorpRadarLookout unknown // 100~104 might be different, even with day one }[spType]; if (!typeFactor) { return false; } const {baseValue} = this.nightSpAttackBaseRate(); const formatPercent = num => Math.floor(num * 1000) / 10; return formatPercent((Math.floor(baseValue) / typeFactor) || 0); }; /** * Calculate ship's Taiha rate when taken an overkill damage. * This is related to the '4n+3 is better than 4n' theory, * '4n+x' only refer to the rounded Taiha HP threshold, rate is also affected by current HP in fact. * @param {number} currentHp - expected current hp value, use ship's real current hp by default. * @param {number} maxHp - expected full hp value, use ship's real max hp by default. * @return {number} Taiha percentage, 100% for already Taiha or red morale or dummy ship. * @see https://wikiwiki.jp/kancolle/%E6%88%A6%E9%97%98%E3%81%AB%E3%81%A4%E3%81%84%E3%81%A6#eb18c7e5 */ KC3Ship.prototype.overkillTaihaRate = function(currentHp = this.hp[0], maxHp = this.hp[1]) { if (this.isDummy()) { return 100; } const taihaHp = Math.max(1, Math.floor(0.25 * maxHp)); const battleConds = this.collectBattleConditions(); // already taiha (should get rid of fasly or negative hp value) // or red morale (hit red morale hp will be left fixed 1) if (currentHp <= taihaHp || this.moraleEffectLevel([1, 1, 0, 0, 0], battleConds.isOnBattle)) { return 100; } // sum all random cases of taiha const taihaCases = Array.numbers(0, currentHp - 1).map(rndint => ( (currentHp - Math.floor(currentHp * 0.5 + rndint * 0.3)) <= taihaHp ? 1 : 0 )).sumValues(); // percentage with 2 decimal return Math.round(taihaCases / currentHp * 10000) / 100; }; /** * Get current shelling attack accuracy related info of this ship. * NOTE: Only attacker accuracy part, not take defender evasion part into account at all, not final hit/critical rate. * @param {number} formationModifier - see #estimateShellingFormationModifier. * @param {boolean} applySpAttackModifiers - if special equipment and attack modifiers should be applied. * @return {Object} accuracy factors of this ship. * @see http://kancolle.wikia.com/wiki/Combat/Accuracy_and_Evasion * @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6 * @see https://twitter.com/Nishisonic/status/890202416112480256 */ KC3Ship.prototype.shellingAccuracy = function(formationModifier = 1, applySpAttackModifiers = true) { if(this.isDummy()) { return {}; } const byLevel = 2 * Math.sqrt(this.level); // formula from PSVita is sqrt(1.5 * lk) anyway, // but verifications have proved this one gets more accurate // http://ja.kancolle.wikia.com/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89:450#68 const byLuck = 1.5 * Math.sqrt(this.lk[0]); const byEquip = -this.nakedStats("ht"); const byImprove = this.equipment(true) .map(g => g.accStatImprovementBonus("fire")) .sumValues(); const byGunfit = this.shellingGunFitAccuracy(); const battleConds = this.collectBattleConditions(); const moraleModifier = this.moraleEffectLevel([1, 0.5, 0.8, 1, 1.2], battleConds.isOnBattle); const basic = 90 + byLevel + byLuck + byEquip + byImprove; const beforeSpModifier = basic * formationModifier * moraleModifier + byGunfit; let artillerySpottingModifier = 1; // there is trigger chance rate for Artillery Spotting itself, see #artillerySpottingRate if(applySpAttackModifiers) { artillerySpottingModifier = (type => { if(type[0] === "Cutin") { return ({ // IDs from `api_hougeki.api_at_type`, see #specialAttackTypeDay "2": 1.1, "3": 1.3, "4": 1.5, "5": 1.3, "6": 1.2, // modifier for 7 (CVCI) still unknown // modifiers for [100, 201] (special cutins) still unknown })[type[1]] || 1; } return 1; })(this.estimateDayAttackType(undefined, true, battleConds.airBattleId)); } const apShellModifier = (() => { // AP Shell combined with Large cal. main gun only mainly for battleships const hasApShellAndMainGun = this.hasEquipmentType(2, 19) && this.hasEquipmentType(2, 3); if(hasApShellAndMainGun) { const hasSecondaryGun = this.hasEquipmentType(2, 4); const hasRadar = this.hasEquipmentType(2, [12, 13]); if(hasRadar && hasSecondaryGun) return 1.3; if(hasRadar) return 1.25; if(hasSecondaryGun) return 1.2; return 1.1; } return 1; })(); // penalty for combined fleets under verification const accuracy = Math.floor(beforeSpModifier * artillerySpottingModifier * apShellModifier); return { accuracy, basicAccuracy: basic, preSpAttackAccuracy: beforeSpModifier, equipmentStats: byEquip, equipImprovement: byImprove, equipGunFit: byGunfit, moraleModifier, formationModifier, artillerySpottingModifier, apShellModifier }; }; /** * @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6#hitterm1 * @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6#avoidterm1 */ KC3Ship.prototype.estimateShellingFormationModifier = function( playerFormationId = ConfigManager.aaFormation, enemyFormationId = 0, type = "accuracy") { let modifier = 1; switch(type) { case "accuracy": // Default is no bonus for regular fleet // Still unknown for combined fleet formation // Line Ahead, Diamond: modifier = 1; switch(playerFormationId) { case 2: // Double Line, cancelled by Line Abreast modifier = enemyFormationId === 5 ? 1.0 : 1.2; break; case 4: // Echelon, cancelled by Line Ahead modifier = enemyFormationId === 1 ? 1.0 : 1.2; break; case 5: // Line Abreast, cancelled by Echelon modifier = enemyFormationId === 4 ? 1.0 : 1.2; break; case 6:{// Vanguard, depends on fleet position const [shipPos, shipCnt] = this.fleetPosition(), isGuardian = shipCnt >= 4 && shipPos >= Math.floor(shipCnt / 2); modifier = isGuardian ? 1.2 : 0.8; break; } } break; case "evasion": // Line Ahead, Double Line: modifier = 1; switch(playerFormationId) { case 3: // Diamond modifier = 1.1; break; case 4: // Echelon // enhanced by Double Line / Echelon? // mods: https://twitter.com/Xe_UCH/status/1304783506275409920 modifier = enemyFormationId === 2 ? 1.45 : 1.4; break; case 5: // Line Abreast, enhanced by Echelon / Line Abreast unknown modifier = 1.3; break; case 6:{// Vanguard, depends on fleet position and ship type const [shipPos, shipCnt] = this.fleetPosition(), isGuardian = shipCnt >= 4 && shipPos >= (Math.floor(shipCnt / 2) + 1), isThisDestroyer = this.master().api_stype === 2; modifier = isThisDestroyer ? (isGuardian ? 1.4 : 1.2) : (isGuardian ? 1.2 : 1.05); break; } } break; default: console.warn("Unknown modifier type:", type); } return modifier; }; /** * Get current shelling accuracy bonus (or penalty) from equipped guns. * @see http://kancolle.wikia.com/wiki/Combat/Overweight_Penalty_and_Fit_Gun_Bonus * @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6#fitarms */ KC3Ship.prototype.shellingGunFitAccuracy = function(time = "Day") { if(this.isDummy()) { return 0; } var result = 0; // Fit bonus or overweight penalty for ship types: const stype = this.master().api_stype; const ctype = this.master().api_ctype; switch(stype) { case 2: // for Destroyers // fit bonus under verification since 2017-06-23 // 12.7cm Single High-angle Gun Mount (Late Model) const singleHighAngleMountCnt = this.countEquipment(229); // for Mutsuki class including Satsuki K2 result += (ctype === 28 ? 5 : 0) * Math.sqrt(singleHighAngleMountCnt); // for Kamikaze class still unknown break; case 3: case 4: case 21: // for Light Cruisers // overhaul implemented in-game since 2017-06-23, not fully verified const singleMountIds = [4, 11]; const twinMountIds = [65, 119, 139]; const tripleMainMountIds = [5, 235]; const singleHighAngleMountId = 229; const isAganoClass = ctype === 41; const isOoyodoClass = ctype === 52; result = -2; // only fit bonus, but -2 fixed (might disappeared?) // for all CLs result += 4 * Math.sqrt(this.countEquipment(singleMountIds)); // for twin mount on Agano class / Ooyodo class / general CLs result += (isAganoClass ? 8 : isOoyodoClass ? 5 : 3) * Math.sqrt(this.countEquipment(twinMountIds)); // for 15.5cm triple main mount on Ooyodo class result += (isOoyodoClass ? 7 : 0) * Math.sqrt(this.countEquipment(tripleMainMountIds)); // for 12.7cm single HA late model on Yura K2 result += (this.masterId === 488 ? 10 : 0) * Math.sqrt(this.countEquipment(singleHighAngleMountId)); break; case 5: case 6: // for Heavy Cruisers // fit bonus at night battle for 20.3cm variants if(time === "Night") { const has203TwinGun = this.hasEquipment(6); const has203No3TwinGun = this.hasEquipment(50); const has203No2TwinGun = this.hasEquipment(90); // 20.3cm priority to No.3, No.2 might also result += has203TwinGun ? 10 : has203No2TwinGun ? 10 : has203No3TwinGun ? 15 : 0; } // for 15.5cm triple main mount on Mogami class const isMogamiClass = ctype === 9; if(isMogamiClass) { const count155TripleMainGun = this.countEquipment(5); const count155TripleMainGunKai = this.countEquipment(235); result += 2 * Math.sqrt(count155TripleMainGun) + 5 * Math.sqrt(count155TripleMainGunKai); } // for 203mm/53 twin mount on Zara class const isZaraClass = ctype === 64; if(isZaraClass) { result += 1 * Math.sqrt(this.countEquipment(162)); } break; case 8: case 9: case 10: // for Battleships // Large cal. main gun gives accuracy bonus if it's fit, // and accuracy penalty if it's overweight. const gunCountFitMap = {}; this.equipment(true).forEach(g => { if(g.itemId && g.masterId && g.master().api_type[2] === 3) { const fitInfo = KC3Meta.gunfit(this.masterId, g.masterId); if(fitInfo && !fitInfo.unknown) { const gunCount = (gunCountFitMap[fitInfo.weight] || [0])[0]; gunCountFitMap[fitInfo.weight] = [gunCount + 1, fitInfo]; } } }); $.each(gunCountFitMap, (_, fit) => { const count = fit[0]; let value = fit[1][time.toCamelCase()] || 0; if(this.isMarried()) value *= fit[1].married || 1; result += value * Math.sqrt(count); }); break; case 16: // for Seaplane Tender // Medium cal. guns for partial AVs, no formula summarized // https://docs.google.com/spreadsheets/d/1wl9v3NqPuRawSuFadokgYh1R1R1W82H51JNC66DH2q8/htmlview break; default: // not found for other ships } return result; }; /** * Get current shelling attack evasion related info of this ship. * @param {number} formationModifier - see #estimateShellingFormationModifier * @return {Object} evasion factors of this ship. * @see http://kancolle.wikia.com/wiki/Combat/Accuracy_and_Evasion * @see http://wikiwiki.jp/kancolle/?%CC%BF%C3%E6%A4%C8%B2%F3%C8%F2%A4%CB%A4%C4%A4%A4%A4%C6 */ KC3Ship.prototype.shellingEvasion = function(formationModifier = 1) { if(this.isDummy()) { return {}; } // already naked ev + equipment total ev stats const byStats = this.ev[0]; const byEquip = this.equipmentTotalStats("houk"); const byLuck = Math.sqrt(2 * this.lk[0]); const preCap = Math.floor((byStats + byLuck) * formationModifier); const postCap = preCap >= 65 ? Math.floor(55 + 2 * Math.sqrt(preCap - 65)) : preCap >= 40 ? Math.floor(40 + 3 * Math.sqrt(preCap - 40)) : preCap; const byImprove = this.equipment(true) .map(g => g.evaStatImprovementBonus("fire")) .sumValues(); // under verification const stypeBonus = 0; const searchlightModifier = this.hasEquipmentType(1, 18) ? 0.2 : 1; const postCapForYasen = Math.floor(postCap + stypeBonus) * searchlightModifier; const fuelPercent = Math.floor(this.fuel / this.master().api_fuel_max * 100); const fuelPenalty = fuelPercent < 75 ? 75 - fuelPercent : 0; // final hit % = ucap(floor(lcap(attackerAccuracy - defenderEvasion) * defenderMoraleModifier)) + aircraftProficiencyBonus // capping limits its lower / upper bounds to [10, 96] + 1%, +1 since random number is 0-based, ranged in [0, 99] // ship morale modifier not applied here since 'evasion' may be looked reduced when sparkle const battleConds = this.collectBattleConditions(); const moraleModifier = this.moraleEffectLevel([1, 1.4, 1.2, 1, 0.7], battleConds.isOnBattle); const evasion = Math.floor(postCap + byImprove - fuelPenalty); const evasionForYasen = Math.floor(postCapForYasen + byImprove - fuelPenalty); return { evasion, evasionForYasen, preCap, postCap, postCapForYasen, equipmentStats: byEquip, equipImprovement: byImprove, fuelPenalty, moraleModifier, formationModifier }; }; KC3Ship.prototype.equipmentAntiAir = function(forFleet) { return AntiAir.shipEquipmentAntiAir(this, forFleet); }; KC3Ship.prototype.adjustedAntiAir = function() { const floor = AntiAir.specialFloor(this); return floor(AntiAir.shipAdjustedAntiAir(this)); }; KC3Ship.prototype.proportionalShotdownRate = function() { return AntiAir.shipProportionalShotdownRate(this); }; KC3Ship.prototype.proportionalShotdown = function(n) { return AntiAir.shipProportionalShotdown(this, n); }; // note: // - fixed shotdown makes no sense if the current ship is not in a fleet. // - formationId takes one of the following: // - 1/4/5 (for line ahead / echelon / line abreast) // - 2 (for double line) // - 3 (for diamond) // - 6 (for vanguard) // - all possible AACIs are considered and the largest AACI modifier // is used for calculation the maximum number of fixed shotdown KC3Ship.prototype.fixedShotdownRange = function(formationId) { if(!this.onFleet()) return false; const fleetObj = PlayerManager.fleets[ this.onFleet() - 1 ]; return AntiAir.shipFixedShotdownRangeWithAACI(this, fleetObj, AntiAir.getFormationModifiers(formationId || 1) ); }; KC3Ship.prototype.maxAaciShotdownBonuses = function() { return AntiAir.shipMaxShotdownAllBonuses( this ); }; /** * Anti-air Equipment Attack Effect implemented since 2018-02-05 in-game. * @return a tuple indicates the effect type ID and its term key. * NOTE: type ID shifted to 1-based since Phase 2, but internal values here unchanged. * @see `TaskAircraftFlightBase.prototype._getAntiAircraftAbility` * @see `TaskAirWarAntiAircraft._type` - AA attack animation types */ KC3Ship.prototype.estimateAntiAirEffectType = function() { const aaEquipType = (() => { // Escaped or sunk ship cannot anti-air if(this.isDummy() || this.isAbsent()) return -1; const stype = this.master().api_stype; // CAV, BBV, CV/CVL/CVB, AV can use Rocket Launcher K2 const isStypeForRockeLaunK2 = [6, 7, 10, 11, 16, 18].includes(stype); // Type 3 Shell if(this.hasEquipmentType(2, 18)) { if(isStypeForRockeLaunK2 && this.hasEquipment(274)) return 5; return 4; } // 12cm 30tube Rocket Launcher Kai Ni if(isStypeForRockeLaunK2 && this.hasEquipment(274)) return 3; // 12cm 30tube Rocket Launcher if(this.hasEquipment(51)) return 2; // Any HA Mount if(this.hasEquipmentType(3, 16)) return 1; // Any AA Machine Gun if(this.hasEquipmentType(2, 21)) return 0; // Any Radar plus any Seaplane bomber with AA stat if(this.hasEquipmentType(3, 11) && this.equipment().some( g => g.masterId > 0 && g.master().api_type[2] === 11 && g.master().api_tyku > 0 )) return 0; return -1; })(); switch(aaEquipType) { case -1: return [0, "None"]; case 0: return [1, "Normal"]; case 1: return [2, "HighAngleMount"]; case 2: return [3, "RocketLauncher"]; case 3: return [4, "RocketLauncherK2"]; case 4: return [5, "Type3Shell"]; case 5: return [6, "Type3ShellRockeLaunK2"]; default: return [NaN, "Unknown"]; } }; /** * To calculate 12cm 30tube Rocket Launcher Kai Ni (Rosa K2) trigger chance (for now), * we need adjusted AA of ship, number of Rosa K2, ctype and luck stat. * @see https://twitter.com/noratako5/status/1062027534026428416 - luck modifier * @see https://twitter.com/kankenRJ/status/979524073934893056 - current formula * @see http://ja.kancolle.wikia.com/wiki/%E3%82%B9%E3%83%AC%E3%83%83%E3%83%89:2471 - old formula verifying thread */ KC3Ship.prototype.calcAntiAirEffectChance = function() { if(this.isDummy() || this.isAbsent()) return 0; // Number of 12cm 30tube Rocket Launcher Kai Ni let rosaCount = this.countEquipment(274); if(rosaCount === 0) return 0; // Not tested yet on more than 3 Rosa K2, capped to 3 just in case of exceptions rosaCount = rosaCount > 3 ? 3 : rosaCount; const rosaAdjustedAntiAir = 48; // 70 for Ise-class, 0 otherwise const classBonus = this.master().api_ctype === 2 ? 70 : 0; // Rounding to x% return Math.qckInt("floor", (this.adjustedAntiAir() + this.lk[0] * 0.9) / (400 - (rosaAdjustedAntiAir + 30 + 40 * rosaCount + classBonus)) * 100, 0); }; /** * Check known possible effects on equipment changed. * @param {Object} newGearObj - the equipment just equipped, pseudo empty object if unequipped. * @param {Object} oldGearObj - the equipment before changed, pseudo empty object if there was empty. * @param {Object} oldShipObj - the cloned old ship instance with stats and item IDs before equipment changed. */ KC3Ship.prototype.equipmentChangedEffects = function(newGearObj = {}, oldGearObj = {}, oldShipObj = this) { if(!this.masterId) return {isShow: false}; const gunFit = newGearObj.masterId ? KC3Meta.gunfit(this.masterId, newGearObj.masterId) : false; let isShow = gunFit !== false; const shipAacis = AntiAir.sortedPossibleAaciList(AntiAir.shipPossibleAACIs(this)); isShow = isShow || shipAacis.length > 0; // NOTE: shipObj here to be returned will be the 'old' ship instance, // whose stats, like fp, tp, asw, are the values before equipment change. // but its items array (including ex item) are post-change values. const shipObj = this; // To get the 'latest' ship stats, should defer `GunFit` event after `api_get_member/ship3` call, // and retrieve latest ship instance via KC3ShipManager.get method like this: // const newShipObj = KC3ShipManager.get(data.shipObj.rosterId); // It can not be latest ship at the timing of this equipmentChangedEffects invoked, // because the api call above not executed, KC3ShipManager data not updated yet. // Or you can compute the simple stat difference manually like this: const oldEquipAsw = oldGearObj.masterId > 0 ? oldGearObj.master().api_tais : 0; const newEquipAsw = newGearObj.masterId > 0 ? newGearObj.master().api_tais : 0; const aswDiff = newEquipAsw - oldEquipAsw // explicit asw bonus from new equipment + shipObj.equipmentTotalStats("tais", true, true, true) // explicit asw bonus from old equipment - oldShipObj.equipmentTotalStats("tais", true, true, true); const oaswPower = shipObj.canDoOASW(aswDiff) ? shipObj.antiSubWarfarePower(aswDiff) : false; isShow = isShow || (oaswPower !== false); const antiLandPowers = shipObj.shipPossibleAntiLandPowers(); isShow = isShow || antiLandPowers.length > 0; const equipBonus = shipObj.equipmentBonusGearAndStats(newGearObj); isShow = isShow || (equipBonus !== false && equipBonus.isShow); // Possible TODO: // can opening torpedo // can cut-in (fire / air) // can night attack for CV // can night cut-in return { isShow, shipObj, shipOld: oldShipObj, gearObj: newGearObj.masterId ? newGearObj : false, gunFit, shipAacis, oaswPower, antiLandPowers: antiLandPowers.length > 0, equipBonus, }; }; /* Expedition Supply Change Check */ KC3Ship.prototype.perform = function(command,args) { try { args = $.extend({noFuel:0,noAmmo:0},args); command = command.slice(0,1).toUpperCase() + command.slice(1).toLowerCase(); this["perform"+command].call(this,args); return true; } catch (e) { console.error("Failed when perform" + command, e); return false; } }; KC3Ship.prototype.performSupply = function(args) { consumePending.call(this,0,{0:0,1:1,2:3,c: 1 - (this.isMarried() && 0.15),i: 0},[0,1,2],args); }; KC3Ship.prototype.performRepair = function(args) { consumePending.call(this,1,{0:0,1:2,2:6,c: 1,i: 0},[0,1,2],args); }; function consumePending(index,mapping,clear,args) { /*jshint validthis: true */ if(!(this instanceof KC3Ship)) { throw new Error("Cannot modify non-KC3Ship instance!"); } var self = this, mult = mapping.c, lastN = Object.keys(this.pendingConsumption).length - mapping.i; delete mapping.c; delete mapping.i; if(args.noFuel) delete mapping['0']; if(args.noAmmo) delete mapping['1']; /* clear pending consumption, by iterating each keys */ var rmd = [0,0,0,0,0,0,0,0], lsFirst = this.lastSortie[0]; Object.keys(this.pendingConsumption).forEach(function(shipConsumption,iterant){ var dat = self.pendingConsumption[shipConsumption], rsc = [0,0,0,0,0,0,0,0], sid = self.lastSortie.indexOf(shipConsumption); // Iterate supplied ship part Object.keys(mapping).forEach(function(key){ var val = dat[index][key] * (mapping[key]===3 ? 5 : mult); // Calibrate for rounding towards zero rmd[mapping[key]] += val % 1; rsc[mapping[key]] += Math.ceil(val) + parseInt(rmd[mapping[key]]); rmd[mapping[key]] %= 1; // Checks whether current iteration is last N pending item if((iterant < lastN) && (clear.indexOf(parseInt(key))>=0)) dat[index][key] = 0; }); console.log("Ship " + self.rosterId + " consumed", shipConsumption, sid, [iterant, lastN].join('/'), rsc.map(x => -x), dat[index]); // Store supplied resource count to database by updating the source KC3Database.Naverall({ data: rsc },shipConsumption); if(dat.every(function(consumptionData){ return consumptionData.every(function(resource){ return !resource; }); })) { delete self.pendingConsumption[shipConsumption]; } /* Comment Stopper */ }); var lsi = 1, lsk = ""; while(lsi < this.lastSortie.length && this.lastSortie[lsi] != 'sortie0') { lsk = this.lastSortie[lsi]; if(this.pendingConsumption[ lsk ]){ lsi++; }else{ this.lastSortie.splice(lsi,1); } } if(this.lastSortie.indexOf(lsFirst) < 0) { this.lastSortie.unshift(lsFirst); } KC3ShipManager.save(); } /** * Fill data of this Ship into predefined tooltip HTML elements. Used by Panel/Strategy Room. * @param tooltipBox - the object of predefined tooltip HTML jq element * @return return back the jq element of param `tooltipBox` */ KC3Ship.prototype.htmlTooltip = function(tooltipBox) { return KC3Ship.buildShipTooltip(this, tooltipBox); }; KC3Ship.buildShipTooltip = function(shipObj, tooltipBox) { //const shipDb = WhoCallsTheFleetDb.getShipStat(shipObj.masterId); const nakedStats = shipObj.nakedStats(), maxedStats = shipObj.maxedStats(), bonusStats = shipObj.statsBonusOnShip(), maxDiffStats = {}, equipDiffStats = {}, modLeftStats = shipObj.modernizeLeftStats(); Object.keys(maxedStats).map(s => {maxDiffStats[s] = maxedStats[s] - nakedStats[s];}); Object.keys(nakedStats).map(s => {equipDiffStats[s] = nakedStats[s] - (shipObj[s]||[])[0];}); const signedNumber = n => (n > 0 ? '+' : n === 0 ? '\u00b1' : '') + n; const optionalNumber = (n, pre = '\u21d1', show0 = false) => !n && (!show0 || n !== 0) ? '' : pre + n; const replaceFilename = (file, newName) => file.slice(0, file.lastIndexOf("/") + 1) + newName; $(".stat_value span", tooltipBox).css("display", "inline"); $(".ship_full_name .ship_masterId", tooltipBox).text("[{0}]".format(shipObj.masterId)); $(".ship_full_name span.value", tooltipBox).text(shipObj.name()); $(".ship_full_name .ship_yomi", tooltipBox).text(ConfigManager.info_ship_class_name ? KC3Meta.ctypeName(shipObj.master().api_ctype) : KC3Meta.shipReadingName(shipObj.master().api_yomi) ); $(".ship_rosterId span", tooltipBox).text(shipObj.rosterId); $(".ship_stype", tooltipBox).text(shipObj.stype()); $(".ship_level span.value", tooltipBox).text(shipObj.level); //$(".ship_level span.value", tooltipBox).addClass(shipObj.levelClass()); $(".ship_hp span.hp", tooltipBox).text(shipObj.hp[0]); $(".ship_hp span.mhp", tooltipBox).text(shipObj.hp[1]); $(".ship_morale img", tooltipBox).attr("src", replaceFilename($(".ship_morale img", tooltipBox).attr("src"), shipObj.moraleIcon() + ".png") ); $(".ship_morale span.value", tooltipBox).text(shipObj.morale); $(".ship_exp_next span.value", tooltipBox).text(shipObj.exp[1]); $(".stat_hp .current", tooltipBox).text(shipObj.hp[1]); $(".stat_hp .mod", tooltipBox).text(signedNumber(modLeftStats.hp)) .toggle(!!modLeftStats.hp); $(".stat_fp .current", tooltipBox).text(shipObj.fp[0]); $(".stat_fp .mod", tooltipBox).text(signedNumber(modLeftStats.fp)) .toggle(!!modLeftStats.fp); $(".stat_fp .equip", tooltipBox) .text("({0}{1})".format(nakedStats.fp, optionalNumber(bonusStats.fp))) .toggle(!!equipDiffStats.fp || !!bonusStats.fp); $(".stat_ar .current", tooltipBox).text(shipObj.ar[0]); $(".stat_ar .mod", tooltipBox).text(signedNumber(modLeftStats.ar)) .toggle(!!modLeftStats.ar); $(".stat_ar .equip", tooltipBox) .text("({0}{1})".format(nakedStats.ar, optionalNumber(bonusStats.ar))) .toggle(!!equipDiffStats.ar || !!bonusStats.ar); $(".stat_tp .current", tooltipBox).text(shipObj.tp[0]); $(".stat_tp .mod", tooltipBox).text(signedNumber(modLeftStats.tp)) .toggle(!!modLeftStats.tp); $(".stat_tp .equip", tooltipBox) .text("({0}{1})".format(nakedStats.tp, optionalNumber(bonusStats.tp))) .toggle(!!equipDiffStats.tp || !!bonusStats.tp); $(".stat_ev .current", tooltipBox).text(shipObj.ev[0]); $(".stat_ev .level", tooltipBox).text(signedNumber(maxDiffStats.ev)) .toggle(!!maxDiffStats.ev); $(".stat_ev .equip", tooltipBox) .text("({0}{1})".format(nakedStats.ev, optionalNumber(bonusStats.ev))) .toggle(!!equipDiffStats.ev || !!bonusStats.ev); $(".stat_aa .current", tooltipBox).text(shipObj.aa[0]); $(".stat_aa .mod", tooltipBox).text(signedNumber(modLeftStats.aa)) .toggle(!!modLeftStats.aa); $(".stat_aa .equip", tooltipBox) .text("({0}{1})".format(nakedStats.aa, optionalNumber(bonusStats.aa))) .toggle(!!equipDiffStats.aa || !!bonusStats.aa); $(".stat_ac .current", tooltipBox).text(shipObj.carrySlots()); const canOasw = shipObj.canDoOASW(); $(".stat_as .current", tooltipBox).text(shipObj.as[0]) .toggleClass("oasw", canOasw); $(".stat_as .level", tooltipBox).text(signedNumber(maxDiffStats.as)) .toggle(!!maxDiffStats.as); $(".stat_as .equip", tooltipBox) .text("({0}{1})".format(nakedStats.as, optionalNumber(bonusStats.as))) .toggle(!!equipDiffStats.as || !!bonusStats.as); $(".stat_as .mod", tooltipBox).text(signedNumber(modLeftStats.as)) .toggle(!!modLeftStats.as); $(".stat_sp", tooltipBox).text(shipObj.speedName()) .addClass(KC3Meta.shipSpeed(shipObj.speed, true)); $(".stat_ls .current", tooltipBox).text(shipObj.ls[0]); $(".stat_ls .level", tooltipBox).text(signedNumber(maxDiffStats.ls)) .toggle(!!maxDiffStats.ls); $(".stat_ls .equip", tooltipBox) .text("({0}{1})".format(nakedStats.ls, optionalNumber(bonusStats.ls))) .toggle(!!equipDiffStats.ls || !!bonusStats.ls); $(".stat_rn", tooltipBox).text(shipObj.rangeName()) .toggleClass("RangeChanged", shipObj.range != shipObj.master().api_leng); $(".stat_lk .current", tooltipBox).text(shipObj.lk[0]); $(".stat_lk .luck", tooltipBox).text(signedNumber(modLeftStats.lk)); $(".stat_lk .equip", tooltipBox).text("({0})".format(nakedStats.lk)) .toggle(!!equipDiffStats.lk); if(!(ConfigManager.info_stats_diff & 1)){ $(".equip", tooltipBox).hide(); } if(!(ConfigManager.info_stats_diff & 2)){ $(".mod,.level,.luck", tooltipBox).hide(); } // Fill more stats need complex calculations KC3Ship.fillShipTooltipWideStats(shipObj, tooltipBox, canOasw); return tooltipBox; }; KC3Ship.fillShipTooltipWideStats = function(shipObj, tooltipBox, canOasw = false) { const signedNumber = n => (n > 0 ? '+' : n === 0 ? '\u00b1' : '') + n; const optionalModifier = (m, showX1) => (showX1 || m !== 1 ? 'x' + m : ''); // show possible critical power and mark capped power with different color const joinPowerAndCritical = (p, cp, cap) => (cap ? '<span class="power_capped">{0}</span>' : "{0}") .format(String(Math.qckInt("floor", p, 0))) + (!cp ? "" : (cap ? '(<span class="power_capped">{0}</span>)' : "({0})") .format(Math.qckInt("floor", cp, 0)) ); const shipMst = shipObj.master(); const onFleetNum = shipObj.onFleet(); const battleConds = shipObj.collectBattleConditions(); const attackTypeDay = shipObj.estimateDayAttackType(); const warfareTypeDay = { "Torpedo" : "Torpedo", "DepthCharge" : "Antisub", "LandingAttack" : "AntiLand", "Rocket" : "AntiLand" }[attackTypeDay[0]] || "Shelling"; const canAsw = shipObj.canDoASW(); if(canAsw){ const aswAttackType = shipObj.estimateDayAttackType(1530, false); let power = shipObj.antiSubWarfarePower(); let criticalPower = false; let isCapped = false; const canShellingAttack = shipObj.canDoDayShellingAttack(); const canOpeningTorp = shipObj.canDoOpeningTorpedo(); const canClosingTorp = shipObj.canDoClosingTorpedo(); if(ConfigManager.powerCapApplyLevel >= 1) { ({power} = shipObj.applyPrecapModifiers(power, "Antisub", battleConds.engagementId, battleConds.formationId || 5)); } if(ConfigManager.powerCapApplyLevel >= 2) { ({power, isCapped} = shipObj.applyPowerCap(power, "Day", "Antisub")); } if(ConfigManager.powerCapApplyLevel >= 3) { if(ConfigManager.powerCritical) { criticalPower = shipObj.applyPostcapModifiers( power, "Antisub", undefined, undefined, true, aswAttackType[0] === "AirAttack").power; } ({power} = shipObj.applyPostcapModifiers(power, "Antisub")); } let attackTypeIndicators = !canShellingAttack || !canAsw ? KC3Meta.term("ShipAttackTypeNone") : KC3Meta.term("ShipAttackType" + aswAttackType[0]); if(canOpeningTorp) attackTypeIndicators += ", {0}" .format(KC3Meta.term("ShipExtraPhaseOpeningTorpedo")); if(canClosingTorp) attackTypeIndicators += ", {0}" .format(KC3Meta.term("ShipExtraPhaseClosingTorpedo")); $(".dayAswPower", tooltipBox).html( KC3Meta.term("ShipDayAttack").format( KC3Meta.term("ShipWarfareAntisub"), joinPowerAndCritical(power, criticalPower, isCapped), attackTypeIndicators ) ); } else { $(".dayAswPower", tooltipBox).html("-"); } const isAswPowerShown = canAsw && (canOasw && !shipObj.isOaswShip() || shipObj.onlyHasEquipmentType(1, [10, 15, 16, 32])); // Show ASW power if Opening ASW conditions met, or only ASW equipment equipped if(isAswPowerShown){ $(".dayAttack", tooltipBox).parent().parent().hide(); } else { $(".dayAswPower", tooltipBox).parent().parent().hide(); } let combinedFleetBonus = 0; if(onFleetNum) { const powerBonus = shipObj.combinedFleetPowerBonus( battleConds.playerCombinedFleetType, battleConds.isEnemyCombined, warfareTypeDay ); combinedFleetBonus = onFleetNum === 1 ? powerBonus.main : onFleetNum === 2 ? powerBonus.escort : 0; } let power = warfareTypeDay === "Torpedo" ? shipObj.shellingTorpedoPower(combinedFleetBonus) : shipObj.shellingFirePower(combinedFleetBonus); let criticalPower = false; let isCapped = false; const canShellingAttack = warfareTypeDay === "Torpedo" || shipObj.canDoDayShellingAttack(); const canOpeningTorp = shipObj.canDoOpeningTorpedo(); const canClosingTorp = shipObj.canDoClosingTorpedo(); const spAttackType = shipObj.estimateDayAttackType(undefined, true, battleConds.airBattleId); const dayCutinRate = shipObj.artillerySpottingRate(spAttackType[1], spAttackType[2]); // Apply power cap by configured level if(ConfigManager.powerCapApplyLevel >= 1) { ({power} = shipObj.applyPrecapModifiers(power, warfareTypeDay, battleConds.engagementId, battleConds.formationId)); } if(ConfigManager.powerCapApplyLevel >= 2) { ({power, isCapped} = shipObj.applyPowerCap(power, "Day", warfareTypeDay)); } if(ConfigManager.powerCapApplyLevel >= 3) { if(ConfigManager.powerCritical) { criticalPower = shipObj.applyPostcapModifiers( power, warfareTypeDay, spAttackType, undefined, true, attackTypeDay[0] === "AirAttack").power; } ({power} = shipObj.applyPostcapModifiers(power, warfareTypeDay, spAttackType)); } let attackTypeIndicators = !canShellingAttack ? KC3Meta.term("ShipAttackTypeNone") : spAttackType[0] === "Cutin" ? KC3Meta.cutinTypeDay(spAttackType[1]) + (dayCutinRate ? " {0}%".format(dayCutinRate) : "") : KC3Meta.term("ShipAttackType" + attackTypeDay[0]); if(canOpeningTorp) attackTypeIndicators += ", {0}" .format(KC3Meta.term("ShipExtraPhaseOpeningTorpedo")); if(canClosingTorp) attackTypeIndicators += ", {0}" .format(KC3Meta.term("ShipExtraPhaseClosingTorpedo")); $(".dayAttack", tooltipBox).html( KC3Meta.term("ShipDayAttack").format( KC3Meta.term("ShipWarfare" + warfareTypeDay), joinPowerAndCritical(power, criticalPower, isCapped), attackTypeIndicators ) ); const attackTypeNight = shipObj.estimateNightAttackType(); const canNightAttack = shipObj.canDoNightAttack(); // See functions in previous 2 lines, ships whose night attack is AirAttack, // but power formula seems be shelling: Taiyou Kai Ni, Shinyou Kai Ni const hasYasenPower = (shipMst.api_houg || [])[0] + (shipMst.api_raig || [])[0] > 0; const hasNightFlag = attackTypeNight[0] === "AirAttack" && attackTypeNight[2] === true; const warfareTypeNight = { "Torpedo" : "Torpedo", "DepthCharge" : "Antisub", "LandingAttack" : "AntiLand", "Rocket" : "AntiLand" }[attackTypeNight[0]] || "Shelling"; if(attackTypeNight[0] === "AirAttack" && canNightAttack && (hasNightFlag || !hasYasenPower)){ let power = shipObj.nightAirAttackPower(battleConds.contactPlaneId == 102); let criticalPower = false; let isCapped = false; const spAttackType = shipObj.estimateNightAttackType(undefined, true); const nightCutinRate = shipObj.nightCutinRate(spAttackType[1], spAttackType[2]); if(ConfigManager.powerCapApplyLevel >= 1) { ({power} = shipObj.applyPrecapModifiers(power, "Shelling", battleConds.engagementId, battleConds.formationId, spAttackType, battleConds.isStartFromNight, battleConds.playerCombinedFleetType > 0)); } if(ConfigManager.powerCapApplyLevel >= 2) { ({power, isCapped} = shipObj.applyPowerCap(power, "Night", "Shelling")); } if(ConfigManager.powerCapApplyLevel >= 3) { if(ConfigManager.powerCritical) { criticalPower = shipObj.applyPostcapModifiers( power, "Shelling", undefined, undefined, true, true).power; } ({power} = shipObj.applyPostcapModifiers(power, "Shelling")); } $(".nightAttack", tooltipBox).html( KC3Meta.term("ShipNightAttack").format( KC3Meta.term("ShipWarfareShelling"), joinPowerAndCritical(power, criticalPower, isCapped), spAttackType[0] === "Cutin" ? KC3Meta.cutinTypeNight(spAttackType[1]) + (nightCutinRate ? " {0}%".format(nightCutinRate) : "") : KC3Meta.term("ShipAttackType" + spAttackType[0]) ) ); } else { let power = shipObj.nightBattlePower(battleConds.contactPlaneId == 102); let criticalPower = false; let isCapped = false; const spAttackType = shipObj.estimateNightAttackType(undefined, true); const nightCutinRate = shipObj.nightCutinRate(spAttackType[1], spAttackType[2]); // Apply power cap by configured level if(ConfigManager.powerCapApplyLevel >= 1) { ({power} = shipObj.applyPrecapModifiers(power, warfareTypeNight, battleConds.engagementId, battleConds.formationId, spAttackType, battleConds.isStartFromNight, battleConds.playerCombinedFleetType > 0)); } if(ConfigManager.powerCapApplyLevel >= 2) { ({power, isCapped} = shipObj.applyPowerCap(power, "Night", warfareTypeNight)); } if(ConfigManager.powerCapApplyLevel >= 3) { if(ConfigManager.powerCritical) { criticalPower = shipObj.applyPostcapModifiers( power, warfareTypeNight, undefined, undefined, true).power; } ({power} = shipObj.applyPostcapModifiers(power, warfareTypeNight)); } let attackTypeIndicators = !canNightAttack ? KC3Meta.term("ShipAttackTypeNone") : spAttackType[0] === "Cutin" ? KC3Meta.cutinTypeNight(spAttackType[1]) + (nightCutinRate ? " {0}%".format(nightCutinRate) : "") : KC3Meta.term("ShipAttackType" + spAttackType[0]); $(".nightAttack", tooltipBox).html( KC3Meta.term("ShipNightAttack").format( KC3Meta.term("ShipWarfare" + warfareTypeNight), joinPowerAndCritical(power, criticalPower, isCapped), attackTypeIndicators ) ); } // TODO implement other types of accuracy const shellingAccuracy = shipObj.shellingAccuracy( shipObj.estimateShellingFormationModifier(battleConds.formationId, battleConds.enemyFormationId), true ); $(".shellingAccuracy", tooltipBox).text( KC3Meta.term("ShipAccShelling").format( Math.qckInt("floor", shellingAccuracy.accuracy, 1), signedNumber(shellingAccuracy.equipmentStats), signedNumber(Math.qckInt("floor", shellingAccuracy.equipImprovement, 1)), signedNumber(Math.qckInt("floor", shellingAccuracy.equipGunFit, 1)), optionalModifier(shellingAccuracy.moraleModifier, true), optionalModifier(shellingAccuracy.artillerySpottingModifier), optionalModifier(shellingAccuracy.apShellModifier) ) ); const shellingEvasion = shipObj.shellingEvasion( shipObj.estimateShellingFormationModifier(battleConds.formationId, battleConds.enemyFormationId, "evasion") ); $(".shellingEvasion", tooltipBox).text( KC3Meta.term("ShipEvaShelling").format( Math.qckInt("floor", shellingEvasion.evasion, 1), signedNumber(shellingEvasion.equipmentStats), signedNumber(Math.qckInt("floor", shellingEvasion.equipImprovement, 1)), signedNumber(-shellingEvasion.fuelPenalty), optionalModifier(shellingEvasion.moraleModifier, true) ) ); const [aaEffectTypeId, aaEffectTypeTerm] = shipObj.estimateAntiAirEffectType(); $(".adjustedAntiAir", tooltipBox).text( KC3Meta.term("ShipAAAdjusted").format( "{0}{1}".format( shipObj.adjustedAntiAir(), /* Here indicates the type of AA ability, not the real attack animation in-game, * only special AA effect types will show a banner text in-game, * like the T3 Shell shoots or Rockets shoots, * regular AA gun animation triggered by equipping AA gun, Radar+SPB or HA mount. * btw1, 12cm Rocket Launcher non-Kai belongs to AA guns, no irregular attack effect. * btw2, flagship will fall-back to the effect user if none has any attack effect. */ aaEffectTypeId > 0 ? " ({0})".format( aaEffectTypeId === 4 ? // Show a trigger chance for RosaK2 Defense, still unknown if with Type3 Shell "{0}:{1}%".format(KC3Meta.term("ShipAAEffect" + aaEffectTypeTerm), shipObj.calcAntiAirEffectChance()) : KC3Meta.term("ShipAAEffect" + aaEffectTypeTerm) ) : "" ) ) ); $(".propShotdownRate", tooltipBox).text( KC3Meta.term("ShipAAShotdownRate").format( Math.qckInt("floor", shipObj.proportionalShotdownRate() * 100, 1) ) ); const maxAaciParams = shipObj.maxAaciShotdownBonuses(); if(maxAaciParams[0] > 0){ $(".aaciMaxBonus", tooltipBox).text( KC3Meta.term("ShipAACIMaxBonus").format( "+{0} (x{1})".format(maxAaciParams[1], maxAaciParams[2]) ) ); } else { $(".aaciMaxBonus", tooltipBox).text( KC3Meta.term("ShipAACIMaxBonus").format(KC3Meta.term("None")) ); } // Not able to get following anti-air things if not on a fleet if(onFleetNum){ const fixedShotdownRange = shipObj.fixedShotdownRange(ConfigManager.aaFormation); const fleetPossibleAaci = fixedShotdownRange[2]; if(fleetPossibleAaci > 0){ $(".fixedShotdown", tooltipBox).text( KC3Meta.term("ShipAAFixedShotdown").format( "{0}~{1} (x{2})".format(fixedShotdownRange[0], fixedShotdownRange[1], AntiAir.AACITable[fleetPossibleAaci].modifier) ) ); } else { $(".fixedShotdown", tooltipBox).text( KC3Meta.term("ShipAAFixedShotdown").format(fixedShotdownRange[0]) ); } const propShotdown = shipObj.proportionalShotdown(ConfigManager.imaginaryEnemySlot); const aaciFixedShotdown = fleetPossibleAaci > 0 ? AntiAir.AACITable[fleetPossibleAaci].fixed : 0; $.each($(".sd_title .aa_col", tooltipBox), function(idx, col){ $(col).text(KC3Meta.term("ShipAAShotdownTitles").split("/")[idx] || ""); }); $(".bomberSlot span", tooltipBox).text(ConfigManager.imaginaryEnemySlot); $(".sd_both span", tooltipBox).text( // Both succeeded propShotdown + fixedShotdownRange[1] + aaciFixedShotdown + 1 ); $(".sd_prop span", tooltipBox).text( // Proportional succeeded only propShotdown + aaciFixedShotdown + 1 ); $(".sd_fixed span", tooltipBox).text( // Fixed succeeded only fixedShotdownRange[1] + aaciFixedShotdown + 1 ); $(".sd_fail span", tooltipBox).text( // Both failed aaciFixedShotdown + 1 ); } else { $(".fixedShotdown", tooltipBox).text( KC3Meta.term("ShipAAFixedShotdown").format("-")); $.each($(".sd_title .aa_col", tooltipBox), function(idx, col){ $(col).text(KC3Meta.term("ShipAAShotdownTitles").split("/")[idx] || ""); }); } return tooltipBox; }; KC3Ship.onShipTooltipOpen = function(event, ui) { const setStyleVar = (name, value) => { const shipTooltipStyle = $(ui.tooltip).children().children().get(0).style; shipTooltipStyle.removeProperty(name); shipTooltipStyle.setProperty(name, value); }; // find which width of wide rows overflow, add slide animation to them // but animation might cost 10% more or less CPU even accelerated with GPU let maxOverflow = 0; $(".stat_wide div", ui.tooltip).each(function() { // scroll width only works if element is visible const sw = $(this).prop('scrollWidth'), w = $(this).width(), over = w - sw; maxOverflow = Math.min(maxOverflow, over); // allow overflow some pixels if(over < -8) { $(this).addClass("use-gpu slide"); } }); setStyleVar("--maxOverflow", maxOverflow + "px"); // show day shelling power instead of ASW power (if any) on holding Alt key if(event.altKey && $(".dayAswPower", ui.tooltip).is(":visible")) { $(".dayAswPower", ui.tooltip).parent().parent().hide(); $(".dayAttack", ui.tooltip).parent().parent().show(); } // show day ASW power instead of shelling power if can ASW on holding Ctrl/Meta key if((event.ctrlKey || event.metaKey) && !$(".dayAswPower", ui.tooltip).is(":visible") && $(".dayAswPower", ui.tooltip).text() !== "-") { $(".dayAswPower", ui.tooltip).parent().parent().show(); $(".dayAttack", ui.tooltip).parent().parent().hide(); } return true; }; KC3Ship.prototype.deckbuilder = function() { var itemsInfo = {}; var result = { id: this.masterId, lv: this.level, luck: this.lk[0], hp: this.hp[0], asw : this.nakedAsw(), items: itemsInfo }; var gearInfo; for(var i=0; i<5; ++i) { gearInfo = this.equipment(i).deckbuilder(); if (gearInfo) itemsInfo["i".concat(i+1)] = gearInfo; else break; } gearInfo = this.exItem().deckbuilder(); if (gearInfo) { // #1726 Deckbuilder: if max slot not reach 5, `ix` will not be used, // which means i? > ship.api_slot_num will be considered as the ex-slot. var usedSlot = Object.keys(itemsInfo).length; if(usedSlot < 5) { itemsInfo["i".concat(usedSlot+1)] = gearInfo; } else { itemsInfo.ix = gearInfo; } } return result; }; })();
DynamicSTOP/KC3Kai
src/library/objects/Ship.js
JavaScript
mit
200,140
var watchers = Object.create(null); var wait = function (linkid, callback) { watchers[linkid] = cross("options", "/:care-" + linkid).success(function (res) { if (watchers[linkid]) wait(linkid, callback); var a = JSAM.parse(res.responseText); if (isFunction(callback)) a.forEach(b => callback(b)); }).error(function () { if (watchers[linkid]) wait(linkid, callback); }); }; var kill = function (linkid) { var r = watchers[linkid]; delete watchers[linkid]; if (r) r.abort(); }; var block_size = 1024; var cast = function (linkid, data) { data = encode(data); var inc = 0, size = block_size; return new Promise(function (ok, oh) { var run = function () { if (inc > data.length) return ok(); cross("options", "/:cast-" + linkid + "?" + data.slice(inc, inc + size)).success(run).error(oh); inc += size; }; run(); }).then(function () { if (inc === data.length) { return cast(linkid, ''); } }); }; var encode = function (data) { var str = encodeURIComponent(data.replace(/\-/g, '--')).replace(/%/g, '-'); return str; }; var decode = function (params) { params = params.replace(/\-\-|\-/g, a => a === '-' ? '%' : '-'); params = decodeURIComponent(params); return params; }; function serve(listener) { return new Promise(function (ok, oh) { cross("options", "/:link").success(function (res) { var responseText = res.responseText; wait(responseText, listener); ok(responseText); }).error(oh); }) } function servd(getdata) { return serve(function (linkid) { cast(linkid, JSAM.stringify(getdata())); }); } function servp(linkto) { return new Promise(function (ok, oh) { var blocks = [], _linkid; serve(function (block) { blocks.push(block); if (block.length < block_size) { var data = decode(blocks.join('')); ok(JSAM.parse(data)); kill(_linkid); } }).then(function (linkid) { cast(linkto, linkid); _linkid = linkid; }, oh); }); } serve.servd = servd; serve.servp = servp; serve.kill = kill;
yunxu1019/efront
coms/zimoli/serve.js
JavaScript
mit
2,289
/** * This cli.js test file tests the `gnode` wrapper executable via * `child_process.spawn()`. Generator syntax is *NOT* enabled for these * test cases. */ var path = require('path'); var assert = require('assert'); var semver = require('semver'); var spawn = require('child_process').spawn; // node executable var node = process.execPath || process.argv[0]; var gnode = path.resolve(__dirname, '..', 'bin', 'gnode'); // chdir() to the "test" dir, so that relative test filenames work as expected process.chdir(path.resolve(__dirname, 'cli')); describe('command line interface', function () { this.slow(1000); this.timeout(2000); cli([ '-v' ], 'should output the version number', function (child, done) { buffer(child.stdout, function (err, data) { assert(semver.valid(data.trim())); done(); }); }); cli([ '--help' ], 'should output the "help" display', function (child, done) { buffer(child.stdout, function (err, data) { assert(/^Usage\: (node|iojs)/.test(data)); done(); }); }); cli([ 'check.js' ], 'should quit with a SUCCESS exit code', function (child, done) { child.on('exit', function (code) { assert(code == 0, 'gnode quit with exit code: ' + code); done(); }); }); cli([ 'nonexistant.js' ], 'should quit with a FAILURE exit code', function (child, done) { child.on('exit', function (code) { assert(code != 0, 'gnode quit with exit code: ' + code); done(); }); }); cli([ 'argv.js', '1', 'foo' ], 'should have a matching `process.argv`', function (child, done) { buffer(child.stdout, function (err, data) { if (err) return done(err); data = JSON.parse(data); assert('argv.js' == path.basename(data[1])); assert('1' == data[2]); assert('foo' == data[3]); done(); }); }); cli([ '--harmony_generators', 'check.js' ], 'should not output the "unrecognized flag" warning', function (child, done) { var async = 2; buffer(child.stderr, function (err, data) { if (err) return done(err); assert(!/unrecognized flag/.test(data), 'got stderr data: ' + JSON.stringify(data)); --async || done(); }); child.on('exit', function (code) { assert(code == 0, 'gnode quit with exit code: ' + code); --async || done(); }); }); cli([], 'should work properly over stdin', function (child, done) { child.stdin.end( 'var assert = require("assert");' + 'function *test () {};' + 'var t = test();' + 'assert("function" == typeof t.next);' + 'assert("function" == typeof t.throw);' ); child.on('exit', function (code) { assert(code == 0, 'gnode quit with exit code: ' + code); done(); }); }); if (!/^v0.8/.test(process.version)) cli(['-p', 'function *test () {yield 3}; test().next().value;'], 'should print result with -p', function (child, done) { var async = 2 buffer(child.stdout, function (err, data) { if (err) return done(err); assert('3' == data.trim(), 'gnode printed ' + data); --async || done(); }); child.on('exit', function (code) { assert(code == 0, 'gnode quit with exit code: ' + code); --async || done(); }); }); cli(['-e', 'function *test () {yield 3}; console.log(test().next().value);'], 'should print result with -e', function (child, done) { var async = 2 buffer(child.stdout, function (err, data) { if (err) return done(err); assert('3' == data.trim(), 'expected 3, got: ' + data); --async || done(); }); child.on('exit', function (code) { assert(code == 0, 'gnode quit with exit code: ' + code); --async || done(); }); }); cli(['--harmony_generators', '-e', 'function *test () {yield 3}; console.log(test().next().value);'], 'should print result with -e', function (child, done) { var async = 2 buffer(child.stdout, function (err, data) { if (err) return done(err); assert('3' == data.trim(), 'gnode printed ' + data); --async || done(); }); child.on('exit', function (code) { assert(code == 0, 'gnode quit with exit code: ' + code); --async || done(); }); }); cli(['-e', 'console.log(JSON.stringify(process.argv))', 'a', 'b', 'c'], 'should pass additional arguments after -e', function (child, done) { var async = 2 buffer(child.stdout, function (err, data) { if (err) return done(err); data = JSON.parse(data) assert.deepEqual(['a', 'b', 'c'], data.slice(2)) --async || done(); }); child.on('exit', function (code) { assert(code == 0, 'gnode quit with exit code: ' + code); --async || done(); }); }); }); function cli (argv, name, fn) { describe('gnode ' + argv.join(' '), function () { it(name, function (done) { var child = spawn(node, [ gnode ].concat(argv)); fn(child, done); }); }); } function buffer (stream, fn) { var buffers = ''; stream.setEncoding('utf8'); stream.on('data', ondata); stream.on('end', onend); stream.on('error', onerror); function ondata (b) { buffers += b; } function onend () { stream.removeListener('error', onerror); fn(null, buffers); } function onerror (err) { fn(err); } }
TooTallNate/gnode
test/cli.js
JavaScript
mit
5,286
var group___s_t_m32_f4xx___h_a_l___driver = [ [ "CRC", "group___c_r_c.html", "group___c_r_c" ], [ "GPIOEx", "group___g_p_i_o_ex.html", "group___g_p_i_o_ex" ], [ "AHB3 Peripheral Clock Enable Disable", "group___r_c_c_ex___a_h_b3___clock___enable___disable.html", null ], [ "HAL", "group___h_a_l.html", "group___h_a_l" ], [ "ADC", "group___a_d_c.html", "group___a_d_c" ], [ "ADCEx", "group___a_d_c_ex.html", "group___a_d_c_ex" ], [ "CORTEX", "group___c_o_r_t_e_x.html", "group___c_o_r_t_e_x" ], [ "DMA", "group___d_m_a.html", "group___d_m_a" ], [ "DMAEx", "group___d_m_a_ex.html", "group___d_m_a_ex" ], [ "FLASH", "group___f_l_a_s_h.html", "group___f_l_a_s_h" ], [ "FLASHEx", "group___f_l_a_s_h_ex.html", "group___f_l_a_s_h_ex" ], [ "GPIO", "group___g_p_i_o.html", "group___g_p_i_o" ], [ "I2C", "group___i2_c.html", "group___i2_c" ], [ "I2S", "group___i2_s.html", "group___i2_s" ], [ "I2SEx", "group___i2_s_ex.html", "group___i2_s_ex" ], [ "IRDA", "group___i_r_d_a.html", "group___i_r_d_a" ], [ "IWDG", "group___i_w_d_g.html", "group___i_w_d_g" ], [ "NAND", "group___n_a_n_d.html", null ], [ "NOR", "group___n_o_r.html", null ], [ "PWR", "group___p_w_r.html", "group___p_w_r" ], [ "PWREx", "group___p_w_r_ex.html", "group___p_w_r_ex" ], [ "RCC", "group___r_c_c.html", "group___r_c_c" ], [ "RCCEx", "group___r_c_c_ex.html", "group___r_c_c_ex" ], [ "RTC", "group___r_t_c.html", "group___r_t_c" ], [ "RTCEx", "group___r_t_c_ex.html", "group___r_t_c_ex" ], [ "SAI", "group___s_a_i.html", "group___s_a_i" ], [ "SAIEx", "group___s_a_i_ex.html", "group___s_a_i_ex" ], [ "SMARTCARD", "group___s_m_a_r_t_c_a_r_d.html", "group___s_m_a_r_t_c_a_r_d" ], [ "SPI", "group___s_p_i.html", "group___s_p_i" ], [ "TIM", "group___t_i_m.html", "group___t_i_m" ], [ "TIMEx", "group___t_i_m_ex.html", "group___t_i_m_ex" ], [ "UART", "group___u_a_r_t.html", "group___u_a_r_t" ], [ "USART", "group___u_s_a_r_t.html", "group___u_s_a_r_t" ], [ "WWDG", "group___w_w_d_g.html", "group___w_w_d_g" ], [ "FMC_LL", "group___f_m_c___l_l.html", "group___f_m_c___l_l" ], [ "FSMC_LL", "group___f_s_m_c___l_l.html", null ] ];
team-diana/nucleo-dynamixel
docs/html/group___s_t_m32_f4xx___h_a_l___driver.js
JavaScript
mit
2,228
import React from 'react' import { compose } from 'redux' import { connect } from 'react-redux' import { Field, FieldArray, reduxForm } from 'redux-form' import { amount, autocomplete, debitCredit } from './Fields' import { Button, FontIcon } from 'react-toolbox' import { getAutocomplete } from 'modules/autocomplete' import { create } from 'modules/entities/journalEntryCreatedEvents' import classes from './JournalEntryForm.scss' import { fetch as fetchLedgers } from 'modules/entities/ledgers' const validate = (values) => { const errors = {} return errors } const renderRecords = ({ fields, meta: { touched, error, submitFailed }, ledgers, financialFactId }) => ( <div> <div> <Button onClick={() => fields.push({})}> <FontIcon value='add' /></Button> {(touched || submitFailed) && error && <span>{error}</span>} </div> <div className={classes.recordsList}> {fields.map((record, index) => <div key={index}> <Button onClick={() => fields.remove(index)}> <FontIcon value='remove' /></Button> <div className={classes.journalEntryField}> <Field name={`${record}.ledger`} component={autocomplete} label='Ledger' source={ledgers} multiple={false} /> </div> <div className={classes.journalEntryField}> <Field name={`${record}.debitCredit`} component={debitCredit} label='Debit/credit' /> </div> <div className={classes.journalEntryField}> <Field name={`${record}.amount`} component={amount} label='Amount' /> </div> </div> )} </div> </div> ) const JournalEntryForm = (props) => { const { ledgers, handleSubmit, submitting, reset } = props return ( <div className={classes.journalEntryForm}> <form onSubmit={handleSubmit}> <FieldArray name='records' component={renderRecords} ledgers={ledgers} /> <Button type='submit' disabled={submitting}>Submit</Button> <Button type='button' disabled={submitting} onClick={reset}>Clear</Button> </form> </div> ) } const onSubmit = (values) => { return create({ values: { ...values } }) } const mapDispatchToProps = { onSubmit, fetchLedgers } const mapStateToProps = (state) => { return { ledgers: getAutocomplete(state, 'ledgers') } } export default compose( connect(mapStateToProps, mapDispatchToProps), reduxForm({ form: 'JournalEntryForm', validate }))(JournalEntryForm)
joris77/admin-web
src/forms/JournalEntryForm.js
JavaScript
mit
2,642
var _ = require('lodash'); var localConfig = {}; try { localConfig = require('./config.local'); } catch (e) { console.log(e.code === 'MODULE_NOT_FOUND'); if (e.code !== 'MODULE_NOT_FOUND' || e.message.indexOf('config.local') < 0) { //config.local module is broken, rethrow the exception throw e; } } var path = require('path'); var defaultConfig = { dataSources: [ { type: 'local', base: 'tmp/', endpoints: ['nodes.json', 'graph.json'], interval: 3000 } // { // type: 'remote', // base: 'http://example.com/ffmap/', // endpoints: ['nodes.json', 'graph.json'], // interval: 30000 // }, ], frontend: { path: path.join(__dirname, 'public') }, database: { host: 'rethinkdb', port: '28015', db: 'ffmap' }, port: 8000 }; module.exports = _.defaults({ defaults: defaultConfig }, localConfig, defaultConfig);
johnyb/ffmap-rethinkdb
config.js
JavaScript
mit
1,004
const frisby = require('frisby') const config = require('config') const URL = 'http://localhost:3000' let blueprint for (const product of config.get('products')) { if (product.fileForRetrieveBlueprintChallenge) { blueprint = product.fileForRetrieveBlueprintChallenge break } } describe('Server', () => { it('GET responds with index.html when visiting application URL', done => { frisby.get(URL) .expect('status', 200) .expect('header', 'content-type', /text\/html/) .expect('bodyContains', 'dist/juice-shop.min.js') .done(done) }) it('GET responds with index.html when visiting application URL with any path', done => { frisby.get(URL + '/whatever') .expect('status', 200) .expect('header', 'content-type', /text\/html/) .expect('bodyContains', 'dist/juice-shop.min.js') .done(done) }) it('GET a restricted file directly from file system path on server via Directory Traversal attack loads index.html instead', done => { frisby.get(URL + '/public/images/../../ftp/eastere.gg') .expect('status', 200) .expect('bodyContains', '<meta name="description" content="An intentionally insecure JavaScript Web Application">') .done(done) }) it('GET a restricted file directly from file system path on server via URL-encoded Directory Traversal attack loads index.html instead', done => { frisby.get(URL + '/public/images/%2e%2e%2f%2e%2e%2fftp/eastere.gg') .expect('status', 200) .expect('bodyContains', '<meta name="description" content="An intentionally insecure JavaScript Web Application">') .done(done) }) }) describe('/public/images/tracking', () => { it('GET tracking image for "Score Board" page access challenge', done => { frisby.get(URL + '/public/images/tracking/scoreboard.png') .expect('status', 200) .expect('header', 'content-type', 'image/png') .done(done) }) it('GET tracking image for "Administration" page access challenge', done => { frisby.get(URL + '/public/images/tracking/administration.png') .expect('status', 200) .expect('header', 'content-type', 'image/png') .done(done) }) it('GET tracking background image for "Geocities Theme" challenge', done => { frisby.get(URL + '/public/images/tracking/microfab.gif') .expect('status', 200) .expect('header', 'content-type', 'image/gif') .done(done) }) }) describe('/encryptionkeys', () => { it('GET serves a directory listing', done => { frisby.get(URL + '/encryptionkeys') .expect('status', 200) .expect('header', 'content-type', /text\/html/) .expect('bodyContains', '<title>listing directory /encryptionkeys</title>') .done(done) }) it('GET a non-existing file in will return a 404 error', done => { frisby.get(URL + '/encryptionkeys/doesnotexist.md') .expect('status', 404) .done(done) }) it('GET the Premium Content AES key', done => { frisby.get(URL + '/encryptionkeys/premium.key') .expect('status', 200) .done(done) }) it('GET a key file whose name contains a "/" fails with a 403 error', done => { frisby.fetch(URL + '/encryptionkeys/%2fetc%2fos-release%2500.md', {}, { urlEncode: false }) .expect('status', 403) .expect('bodyContains', 'Error: File names cannot contain forward slashes!') .done(done) }) }) describe('Hidden URL', () => { it('GET the second easter egg by visiting the Base64>ROT13-decrypted URL', done => { frisby.get(URL + '/the/devs/are/so/funny/they/hid/an/easter/egg/within/the/easter/egg') .expect('status', 200) .expect('header', 'content-type', /text\/html/) .expect('bodyContains', '<title>Welcome to Planet Orangeuze</title>') .done(done) }) it('GET the premium content by visiting the ROT5>Base64>z85>ROT5-decrypted URL', done => { frisby.get(URL + '/this/page/is/hidden/behind/an/incredibly/high/paywall/that/could/only/be/unlocked/by/sending/1btc/to/us') .expect('status', 200) .expect('header', 'content-type', 'image/gif') .done(done) }) it('GET Geocities theme CSS is accessible directly from file system path', done => { frisby.get(URL + '/css/geo-bootstrap/swatch/bootstrap.css') .expect('status', 200) .expect('bodyContains', 'Designed and built with all the love in the world @twitter by @mdo and @fat.') .done(done) }) it('GET Klingon translation file for "Extra Language" challenge', done => { frisby.get(URL + '/i18n/tlh_AA.json') .expect('status', 200) .expect('header', 'content-type', /application\/json/) .done(done) }) it('GET blueprint file for "Retrieve Blueprint" challenge', done => { frisby.get(URL + '/public/images/products/' + blueprint) .expect('status', 200) .done(done) }) })
m4l1c3/juice-shop
test/api/fileServingSpec.js
JavaScript
mit
4,853
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Navigation.css'; import Link from '../Link'; class Navigation extends React.Component { render() { return ( <div className={s.root} role="navigation"> <Link className={s.link} to="/catalog">Каталог продукції</Link> <Link className={s.link} to="/about">Про нас</Link> <Link className={s.link} to="/catalog">Наші роботи</Link> </div> ); } } export default withStyles(s)(Navigation);
MarynaHapon/Data-root-react
src/components/Navigation/Navigation.js
JavaScript
mit
572
/* */ 'use strict'; Object.defineProperty(exports, "__esModule", {value: true}); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactAddonsPureRenderMixin = require('react-addons-pure-render-mixin'); var _reactAddonsPureRenderMixin2 = _interopRequireDefault(_reactAddonsPureRenderMixin); var _svgIcon = require('../../svg-icon'); var _svgIcon2 = _interopRequireDefault(_svgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : {default: obj}; } var HardwarePhonelinkOff = _react2.default.createClass({ displayName: 'HardwarePhonelinkOff', mixins: [_reactAddonsPureRenderMixin2.default], render: function render() { return _react2.default.createElement(_svgIcon2.default, this.props, _react2.default.createElement('path', {d: 'M22 6V4H6.82l2 2H22zM1.92 1.65L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.27-1.27L3.89 3.62 1.92 1.65zM4 6.27L14.73 17H4V6.27zM23 8h-6c-.55 0-1 .45-1 1v4.18l2 2V10h4v7h-2.18l3 3H23c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z'})); } }); exports.default = HardwarePhonelinkOff; module.exports = exports['default'];
nayashooter/ES6_React-Bootstrap
public/jspm_packages/npm/material-ui@0.14.4/lib/svg-icons/hardware/phonelink-off.js
JavaScript
mit
1,131
define(function(require, exports) { 'use strict'; var Backbone = require('backbone') , global = require('global'); var teamColours = [ '#FFBBBB', '#FFE1BA', '#FDFFBA', '#D6FFBA', '#BAFFCE', '#BAFFFD', '#BAE6FF', '#BAC8FF', '#D3BAFF', '#EBBAFF', '#E4E0FF', '#BAFCE1', '#FCC6BB', '#E3F3CE', '#EEEEEE', '#D8FFF4' ]; exports.Problem = Backbone.Model.extend({}); exports.Team = Backbone.Model.extend({ colour: function() { return teamColours[this.id % teamColours.length]; } }); exports.Stage = Backbone.Model.extend({ glyphs: { 1: 'remove', 2: 'ok', 3: 'forward' }, glyph: function() { return this.glyphs[this.get('state')]; } }); });
hackcyprus/junior
static/javascript/game/models.js
JavaScript
mit
818
'use strict'; // Setting up route angular.module('socialevents').config(['$stateProvider', function($stateProvider) { // SocialEvents state routing $stateProvider. state('listSocialEvents', { url: '/socialevents', templateUrl: 'modules/socialevents/views/list-socialevents.client.view.html' }). state('createSocialEvent', { url: '/socialevents/create', templateUrl: 'modules/socialevents/views/create-socialevent.client.view.html' }). state('viewSocialEvent', { url: '/socialevents/:socialeventId', templateUrl: 'modules/socialevents/views/view-socialevent.client.view.html' }). state('editSocialEvent', { url: '/socialevents/:socialeventId/edit', templateUrl: 'modules/socialevents/views/edit-socialevent.client.view.html' }); } ]);
MahirZukic/MassSocialEventSender
public/modules/socialevents/config/socialevents.client.routes.js
JavaScript
mit
780
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.10.2.15_A1_T8; * @section: 15.10.2.15; * @assertion: The internal helper function CharacterRange takes two CharSet parameters A and B and performs the * following: * If A does not contain exactly one character or B does not contain exactly one character then throw * a SyntaxError exception; * @description: Checking if execution of "/[\Wb-G]/.exec("a")" leads to throwing the correct exception; */ //CHECK#1 try { $ERROR('#1.1: /[\\Wb-G]/.exec("a") throw SyntaxError. Actual: ' + (/[\Wb-G]/.exec("a"))); } catch (e) { if((e instanceof SyntaxError) !== true){ $ERROR('#1.2: /[\\Wb-G]/.exec("a") throw SyntaxError. Actual: ' + (e)); } }
Diullei/Storm
Storm.Test/SputnikV1/15_Native_ECMA_Script_Objects/15.10_RegExp_Objects/15.10.2_Pattern_Semantics/15.10.2.15_NonemptyClassRanges/S15.10.2.15_A1_T8.js
JavaScript
mit
823
const autoprefixer = require('autoprefixer'); const precss = require('precss'); const stylelint = require('stylelint'); const fontMagician = require('postcss-font-magician')({ // this is required due to a weird bug where if we let PFM use the `//` protocol Webpack style-loader // thinks it's a relative URL and won't load the font when sourceMaps are also enabled protocol: 'https:', display: 'swap', }); module.exports = { plugins: [stylelint, fontMagician, precss, autoprefixer], };
bjacobel/react-redux-boilerplate
postcss.config.js
JavaScript
mit
497
(function(window, document){ var chart; var pressure_chart; var lasttime; function drawCurrent(data) { var tempDHT, tempBMP; if (data.count_dht022 > 0) { lasttime = data.humidity[data.count_dht022-1][0]; tempDHT = data.temperature_dht022[data.count_dht022-1][1]; document.querySelector("span#humidityDHT022").innerHTML = data.humidity[data.count_dht022-1][1]; var date = new Date(lasttime); document.querySelector("span#time").innerHTML = date.toTimeString(); } if (data.count_bmp180 > 0) { lasttime = data.temperature_bmp180[data.count_bmp180-1][0]; tempBMP = data.temperature_bmp180[data.count_bmp180-1][1]; document.querySelector("span#pressureBMP180").innerHTML = data.pressure[data.count_bmp180-1][1] + 'mm hg (' + (data.pressure[data.count_bmp180-1][1] / 7.50061561303).toFixed(2) + ' kPa)' ; var date = new Date(lasttime); document.querySelector("span#time").innerHTML = date.toTimeString(); } document.querySelector("span#temperature").innerHTML = '<abbr title="BMP180 ' + tempBMP + ', DHT022 ' + tempDHT + '">' + ((tempDHT + tempBMP)/2).toFixed(1) + '</abbr>'; document.querySelector("span#lastupdate").innerHTML = new Date().toTimeString(); } function requestDelta() { $.ajax({ url: 'weather_new.php?mode=delta&delta='+lasttime, datatype: "json", success: function(data) { var i; if (data.count > 0) { for(i=0; i<data.count_dht022;i++) chart.series[0].addPoint(data.temperature_dht022[i], false, true); for(i=0; i<data.count_dht022;i++) chart.series[1].addPoint(data.humidity[i], false, true); for(i=0; i<data.count_bmp180;i++) chart.series[0].addPoint(data.temperature_bmp180[i], false, true); for(i=0; i<data.count_bmp180;i++) pressure_chart.series[0].addPoint(data.pressure[i], false, true); chart.redraw(); pressure_chart.redraw(); } drawCurrent(data); } }); } function requestData() { var daterange = document.querySelector("select#daterange").value; if (!daterange) daterange = "today"; $.ajax({ url: 'weather_new.php?mode='+daterange, datatype: "json", success: function(data) { chart.series[0].setData(data.temperature_dht022); chart.series[1].setData(data.humidity); chart.series[2].setData(data.temperature_bmp180); pressure_chart.series[0].setData(data.pressure); drawCurrent(data); setInterval(requestDelta, 5 * 60 * 1000); } }); } $(document).ready(function() { Highcharts.setOptions({ global: { useUTC: false } }); chart = new Highcharts.Chart({ chart: { renderTo: 'graph', type: 'spline', events: { load: requestData } }, title: { text: 'Monitoring' }, tooltip: { shared: true }, xAxis: { type: 'datetime', maxZoom: 20 * 1000 }, yAxis: { min: 10, minPadding: 0.2, maxPadding: 0.2, title: { text: 'Temperature/Humidity', margin: 80 } }, series: [{ name: 'Temperature DHT022', data: [] }, { name: 'Humidity', data: [] }, { name: 'Temperature BMP180', data: [] }] }); pressure_chart = new Highcharts.Chart({ chart: { renderTo: 'pressure_graph', type: 'spline', events: { load: requestData } }, title: { text: 'Pressure monitoring' }, tooltip: { shared: true }, xAxis: { type: 'datetime', maxZoom: 20 * 1000 }, yAxis: { min: 700, minPadding: 0.2, maxPadding: 0.2, title: { text: 'Pressure', margin: 80 } }, series: [{ name: 'Pressure', data: [] }] }); $('select#daterange').change(function() {requestData();}); }); })(window, document)
AndriiZ/RaspberryPI
SmartHouse/site/js/chart.js
JavaScript
mit
4,178
'use strict'; //Translations service used for translations REST endpoint angular.module('mean.translations').factory('deleteTranslations', ['$resource', function($resource) { return $resource('deleteTranslations/:translationId', { translationId: '@_id' }, { update: { method: 'PUT' } }); } ]);
Luka111/TDRAnketa
packages/translations/public/services/deleteTranslations.js
JavaScript
mit
337
/** * @flow */ import React from 'react'; import {storiesOf} from '@kadira/storybook'; import Textarea from './Textarea'; storiesOf('<Textarea />', module) .add('Default state', () => <Textarea />) .add('Error state', () => <Textarea error />) .add('Disabled state', () => <Textarea disabled />) .add('No border variant', () => <Textarea noBorder />);
prometheusresearch/react-ui
src/Textarea.story.js
JavaScript
mit
364
/* jshint node:true */ // var RSVP = require('rsvp'); // For details on each option run `ember help release` module.exports = { // local: true, // remote: 'some_remote', // annotation: "Release %@", // message: "Bumped version to %@", manifest: [ 'package.json', 'package-lock.json'] // publish: true, // strategy: 'date', // format: 'YYYY-MM-DD', // timezone: 'America/Los_Angeles', // // beforeCommit: function(project, versions) { // return new RSVP.Promise(function(resolve, reject) { // // Do custom things here... // }); // } };
mu-semtech/transform-helpers-ember-addon
config/release.js
JavaScript
mit
574
module.exports = function(player, playerSpec) { return ('data:image/svg+xml;utf-8,' + encodeURIComponent( `<svg width="${playerSpec.width}" height="${playerSpec.height}" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${playerSpec.width} ${playerSpec.height}" version="1.1" class="mapSvg"> \ <circle cx="${playerSpec.width/2}" cy="${playerSpec.height/2}" r="${playerSpec.height/4}" class="mapSvg__player" stroke="${playerSpec[player].color}" fill="${playerSpec[player].color}"/> \ </svg>` ) ); };
BoardFellows/scotland-yard-frontend
frontend/app/components/game/board/player-svg.js
JavaScript
mit
529
"use strict"; var chai = require('chai'), should = chai.should(), expect = chai.expect, XMLGrammers = require('../').XMLGrammers, Parameters = require('../').Parameters; describe('FMServerConstants', function(){ describe('XMLGrammers', function(){ it('should be frozen', function(){ expect(function(){ XMLGrammers.a = 1; }).to.throw("Can't add property a, object is not extensible"); }); }); describe('Parameters', function() { it('should be frozen', function () { expect(function () { Parameters.a = 1; }).to.throw("Can't add property a, object is not extensible"); }) }) })
toddgeist/filemakerjs-old
test/constants.js
JavaScript
mit
730
define( [ 'Magento_Checkout/js/model/error-processor', 'Magento_Checkout/js/model/full-screen-loader', 'Magento_Checkout/js/model/url-builder' ], function ( errorProcessor, fullScreenLoader, urlBuilder ) { 'use strict'; const RETURN_URL = '/orders/:order_id/omise-offsite'; return { /** * Get return URL for Magento (based on order id) * * @return {string} */ getMagentoReturnUrl: function (order_id) { return urlBuilder.createUrl( RETURN_URL, { order_id } ); }, /** * Get payment method code * * @return {string} */ getCode: function() { return this.code; }, /** * Is method available to display * * @return {boolean} */ isActive: function() { if (this.restrictedToCurrencies && this.restrictedToCurrencies.length) { let orderCurrency = this.getOrderCurrency(); return (this.getStoreCurrency() == orderCurrency) && this.restrictedToCurrencies.includes(orderCurrency); } else { return true; } }, /** * Get order currency * * @return {string} */ getOrderCurrency: function () { return window.checkoutConfig.quoteData.quote_currency_code.toLowerCase(); }, /** * Get store currency * * @return {string} */ getStoreCurrency: function () { return window.checkoutConfig.quoteData.store_currency_code.toLowerCase(); }, /** * Checks if sandbox is turned on * * @return {boolean} */ isSandboxOn: function () { return window.checkoutConfig.isOmiseSandboxOn; }, /** * Creates a fail handler for given context * * @return {boolean} */ buildFailHandler(context) { return function (response) { errorProcessor.process(response, context.messageContainer); fullScreenLoader.stopLoader(); context.isPlaceOrderActionAllowed(true); } } }; } );
omise/omise-magento
view/frontend/web/js/view/payment/omise-base-method-renderer.js
JavaScript
mit
2,689
// Parts of this source are modified from npm and lerna: // npm: https://github.com/npm/npm/blob/master/LICENSE // lerna: https://github.com/lerna/lerna/blob/master/LICENSE // @flow import fs from 'fs'; import path from 'path'; import _cmdShim from 'cmd-shim'; import _readCmdShim from 'read-cmd-shim'; import promisify from 'typeable-promisify'; import makeDir from 'make-dir'; import _rimraf from 'rimraf'; export function readFile(filePath: string): Promise<string> { return promisify(cb => fs.readFile(filePath, cb)); } export function writeFile( filePath: string, fileContents: string ): Promise<string> { return promisify(cb => fs.writeFile(filePath, fileContents, cb)); } export function mkdirp(filePath: string): Promise<void> { return makeDir(filePath); } export function rimraf(filePath: string): Promise<void> { return promisify(cb => _rimraf(filePath, cb)); } export function stat(filePath: string) { return promisify(cb => fs.stat(filePath, cb)); } export function lstat(filePath: string) { return promisify(cb => fs.lstat(filePath, cb)); } function unlink(filePath: string) { return promisify(cb => fs.unlink(filePath, cb)); } export function realpath(filePath: string) { return promisify(cb => fs.realpath(filePath, cb)); } function _symlink(src: string, dest: string, type: string) { return promisify(cb => fs.symlink(src, dest, type, cb)); } function stripExtension(filePath: string) { return path.join( path.dirname(filePath), path.basename(filePath, path.extname(filePath)) ); } async function cmdShim(src: string, dest: string) { // If not a symlink we default to the actual src file // https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L273 let relativeShimTarget = await readlink(src); let currentShimTarget = relativeShimTarget ? path.resolve(path.dirname(src), relativeShimTarget) : src; await promisify(cb => _cmdShim(currentShimTarget, stripExtension(dest), cb)); } async function createSymbolicLink(src, dest, type) { try { await lstat(dest); await rimraf(dest); } catch (err) { if (err.code === 'EPERM') throw err; } await _symlink(src, dest, type); } async function createPosixSymlink(origin, dest, type) { if (type === 'exec') { type = 'file'; } let src = path.relative(path.dirname(dest), origin); return await createSymbolicLink(src, dest, type); } async function createWindowsSymlink(src, dest, type) { if (type === 'exec') { return await cmdShim(src, dest); } else { return await createSymbolicLink(src, dest, type); } } export async function symlink( src: string, dest: string, type: 'exec' | 'junction' ) { if (dest.includes(path.sep)) { await mkdirp(path.dirname(dest)); } if (process.platform === 'win32') { return await createWindowsSymlink(src, dest, type); } else { return await createPosixSymlink(src, dest, type); } } export async function readdir(dir: string) { return promisify(cb => fs.readdir(dir, cb)); } // Return an empty array if a directory doesnt exist (but still throw if errof if dir is a file) export async function readdirSafe(dir: string) { return stat(dir) .catch(err => Promise.resolve([])) .then(statsOrArray => { if (statsOrArray instanceof Array) return statsOrArray; if (!statsOrArray.isDirectory()) throw new Error(dir + ' is not a directory'); return readdir(dir); }); } function readCmdShim(filePath: string) { return promisify(cb => _readCmdShim(filePath, cb)); } function _readlink(filePath: string) { return promisify(cb => fs.readlink(filePath, cb)); } // Copied from: // https://github.com/npm/npm/blob/d081cc6c8d73f2aa698aab36605377c95e916224/lib/utils/gently-rm.js#L280-L297 export async function readlink(filePath: string) { let stat = await lstat(filePath); let result = null; if (stat.isSymbolicLink()) { result = await _readlink(filePath); } else { try { result = await readCmdShim(filePath); } catch (err) { if (err.code !== 'ENOTASHIM' && err.code !== 'EISDIR') { throw err; } } } return result; } export async function dirExists(dir: string) { try { let _stat = await stat(dir); return _stat.isDirectory(); } catch (err) { return false; } } export async function symlinkExists(filePath: string) { try { let stat = await lstat(filePath); return stat.isSymbolicLink(); } catch (err) { return false; } }
boltpkg/bolt
src/utils/fs.js
JavaScript
mit
4,517
module.exports = IpfsUtil; var fs = require('fs'); var formstream = require('formstream'); var http = require('http'); var request = require('request'); function IpfsUtil() { } IpfsUtil.prototype.init = function (config) { this.__host = config.ipfs.host; this.__port = config.ipfs.port; }; IpfsUtil.prototype.getTar = function (key, toFile, callback) { var self = this; var uri = 'http://' + self.__host + ':' + self.__port + '/api/v0/tar/cat?arg=' + key; console.log(uri); request .get(uri) .on('end', function () { console.log('GET request ended....'); callback(); }).on('error', function (err) { console.log('ERROR: ', err); return callback(err); }) .pipe(fs.createWriteStream(toFile)); }; IpfsUtil.prototype.uploadTar = function (filePath, callback) { var self = this; var form = formstream(); form.file('file', filePath); var options = { method: 'POST', host: self.__host, port: self.__port, path: '/api/v0/tar/add', headers: form.headers() }; console.log(options); var req = http.request(options, function (res) { res.on('data', function (data) { console.log(data); callback(null, (JSON.parse(data)).Hash); }); //res.on('end', function () { // console.log('Request ended...'); // callback(); //}); res.on('error', function (err) { console.log(err); return callback(err); }) }); form.pipe(req); };
team-tenacious/tracey-job-modules
lib/utils/ipfs-util.js
JavaScript
mit
1,625
import {observable} from 'mobx'; export default class SessionDocumentModel { @observable id; @observable sessionID; @observable studentID; @observable filename; @observable CreatorId; @observable archived; constructor(value) { this.id = id; this.sessionID = sessionID; this.studentID = studentID; this.filename = filename; this.CreatorId = CreatorId; this.archived = archived; } }
JasonShin/HELP-yo
public/js/models/SessionDocumentModel.js
JavaScript
mit
445
'use babel'; //import reddit from './api/reddit'; import giphy from './api/giphy'; import ohMaGif from './api/oh-ma-gif'; import reactionGifs from './api/reaction-gifs'; const apis = [ //reddit, giphy, ohMaGif, reactionGifs ]; export default function getRndThumbnail() { const apiFn = apis[Math.floor(Math.random() * apis.length)]; return apiFn().catch(err => { // Show error notification atom.notifications.addError(err, { dismissable: true }); }); }
josex2r/atom-make-me-lol
lib/get-rnd-thumbnail.js
JavaScript
mit
520
var dropzoneOverlay = document.querySelector('.dropzone-overlay'); function getDataTransferFiles(event) { var dataTransferItemsList = []; if (event.dataTransfer) { var dt = event.dataTransfer; if (dt.files && dt.files.length) { dataTransferItemsList = dt.files; } else if (dt.items && dt.items.length) { // During the drag even the dataTransfer.files is null // but Chrome implements some drag store, which is accesible via dataTransfer.items dataTransferItemsList = dt.items; } } else if (event.target && event.target.files) { dataTransferItemsList = event.target.files; } if (dataTransferItemsList.length > 0) { dataTransferItemsList = [dataTransferItemsList[0]]; } // Convert from DataTransferItemsList to the native Array return Array.prototype.slice.call(dataTransferItemsList); } function showDragFocus() { dropzoneOverlay.className = 'dropzone-overlay active'; } function hideDragFocus() { dropzoneOverlay.className = 'dropzone-overlay'; } function onFileDragEnter(ev) { ev.preventDefault(); showDragFocus(); } function onFileDragOver(ev) { ev.preventDefault(); } function onFileDrop(ev) { ev.preventDefault(); hideDragFocus(); var fileList = getDataTransferFiles(ev); updateStickerImage(fileList[0]); return null; } function onFileDragLeave(ev) { ev.preventDefault(); console.log(ev.target) if (ev.target !== document.body) { return; } hideDragFocus(); } function drawImage(canvas, imageBitmap) { var ctx = canvas.getContext('2d'); ctx.drawImage(file, 0, 0); } function updateStickerImage(file) { var reader = new FileReader(); reader.onload = function(ev) { var dataURL = ev.target.result; document.querySelectorAll('.sticker-img').forEach(function(img) { img.style = 'background-image: url(' + dataURL + ')'; }); } reader.readAsDataURL(file); } document.body.ondragenter = onFileDragEnter; document.body.ondragover = onFileDragOver; document.body.ondragleave = onFileDragLeave; document.body.ondrop = onFileDrop;
vintlucky777/sticker-measure
static/scripts/main.js
JavaScript
mit
2,199
'use strict'; import React from 'react'; import { external_url_map } from "../components/globals"; /** * Method to display either mode of inheritance with adjective, * or just mode of inheritance if no adjective * @param {object} object - A GDM or Interpretation object */ export function renderSelectedModeInheritance(object) { let moi = '', moiAdjective = ''; if (object && object.modeInheritance) { moi = object.modeInheritance; if (object.modeInheritanceAdjective) { moiAdjective = object.modeInheritanceAdjective; } } return ( <span>{moi && moi.length ? renderModeInheritanceLink(moi, moiAdjective) : 'None'}</span> ); } /** * Method to construct mode of inheritance linkout */ function renderModeInheritanceLink(modeInheritance, modeInheritanceAdjective) { if (modeInheritance) { let start = modeInheritance.indexOf('('); let end = modeInheritance.indexOf(')'); let hpoNumber; let adjective = modeInheritanceAdjective && modeInheritanceAdjective.length ? ' (' + modeInheritanceAdjective.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1] + ')' : ''; if (start && end) { hpoNumber = modeInheritance.substring(start+1, end); } if (hpoNumber && hpoNumber.indexOf('HP:') > -1) { let hpoLink = external_url_map['HPO'] + hpoNumber; return ( <span><a href={hpoLink} target="_blank">{modeInheritance.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1]}</a>{adjective}</span> ); } else { return ( <span>{modeInheritance + adjective}</span> ); } } }
ClinGen/clincoded
src/clincoded/static/libs/render_mode_inheritance.js
JavaScript
mit
1,687
"use strict"; var echo = require('echo'), Authorization = require('./auth.js'), Packer = require('./packer.js'), Request = require('./request.js'), RequestOptions = require('./req-options.js'), portMatch = /:(\d+)$/, parse = function (host, port) { var out = { "host": "localhost", "port": 80 }, match = portMatch.exec(host); if (match) { if (isNaN(port)) { port = match[1]; } host = host.slice(0, match.index); } if (host) { out.host = host; } if (!isNaN(port)) { out.port = Number(port); } return out; }, secs = function (ms) { var secs = ms / 1000; return '(' + secs.toFixed(3) + ' sec)'; }; function Client() { this.host = undefined; this.port = undefined; this.auth = undefined; this.timeout = undefined; this.verbose = undefined; } Client.prototype = { "request": function (options, data, done, fail) { var self = this, auth = self.auth, verbose = self.verbose, target = self.toString(options), req, authStr; if (auth) { authStr = auth.toString(options); } req = Request.create(options, authStr); req.on('response', function (res, options) { var code = res.statusCode, failed = function (msg) { if (msg && verbose) { echo(msg); } if (fail) { fail(code, options, res); } else { res._dump(); } }; if (verbose) { echo(target, 'returned', code, secs(options.duration)); } if (code === 401) { if (auth) { if (authStr) { failed('Invalid credentials.'); } else { auth.parse(res.headers); res._dump(); self.request(options, data, done, fail); } } else { failed('Credentials required.'); } } else if (Math.floor(code / 100) === 2) { if (done) { done(res, options); } } else { failed(); } }); req.on('timeout', function (seconds) { var sec = '(' + seconds + ' seconds)'; if (verbose) { echo(target, 'timed out.', sec); } auth.clear(); if (fail) { fail('ETIMEDOUT', options); } }); req.on('error', function (code, options) { if (verbose) { echo(target, code); } if (fail) { fail(code, options); } }); if (verbose) { echo(target); } req.send(data, self.timeout); }, "get": function (path, done, fail) { var options = RequestOptions.createGET(this.host, this.port, path); this.request(options, undefined, done, fail); }, "postEmpty": function (path, done, fail) { var options = RequestOptions.createPOSTEmpty(this.host, this.port, path); this.request(options, undefined, done, fail); }, "post": function (path, mime, str, done, fail) { var options = RequestOptions.createPOSTAs(this.host, this.port, path, mime, str); this.request(options, str, done, fail); }, "postString": function (path, str, done, fail) { var options = RequestOptions.createPOSTString(this.host, this.port, path, str); this.request(options, str, done, fail); }, "postJSON": function (path, json, done, fail) { var data = JSON.stringify(json), options = RequestOptions.createPOSTJSON(this.host, this.port, path, data); this.request(options, data, done, fail); }, "postXML": function (path, xml, done, fail) { var data = Packer.packXML(xml), options = RequestOptions.createPOSTXML(this.host, this.port, path, data); this.request(options, data, done, fail); }, "toString": function (options) { var host = this.host + ':' + this.port, str = options.method + ' ' + host + options.path, max = 60; if (str.length > max) { return str.slice(0, max) + '...'; } return str; } }; module.exports = { "create": function (info) { var client = new Client(), parsed; if (!info) { info = {}; } parsed = parse(info.host, info.port); client.host = parsed.host; client.port = parsed.port; if (info.user) { client.auth = Authorization.create(info.user, info.pass); } client.timeout = info.timeout || 180; client.verbose = info.verbose; return client; } };
snsolutionuk/mydash
views/js/node-aux/hdc/client.js
JavaScript
mit
5,273
var searchData= [ ['database',['Database',['../namespace_pontikis_1_1_database.html',1,'Pontikis']]], ['pg_5fsequence_5fname_5fauto',['PG_SEQUENCE_NAME_AUTO',['../class_pontikis_1_1_database_1_1_dacapo.html#aef46219ed4c7133e99979e0d3aa5cd86',1,'Pontikis::Database::Dacapo']]], ['pontikis',['Pontikis',['../namespace_pontikis.html',1,'']]], ['prepared_5fstatements_5fnumbered',['PREPARED_STATEMENTS_NUMBERED',['../class_pontikis_1_1_database_1_1_dacapo.html#a963df8efcdd80ba37064e3cde0c8809a',1,'Pontikis::Database::Dacapo']]], ['prepared_5fstatements_5fquestion_5fmark',['PREPARED_STATEMENTS_QUESTION_MARK',['../class_pontikis_1_1_database_1_1_dacapo.html#a63dd2d4d612585c42c7e53e9b66caf24',1,'Pontikis::Database::Dacapo']]] ];
pontikis/dacapo
docs/doxygen/html/search/all_a.js
JavaScript
mit
738
import test from 'ava'; import debounce from 'lodash.debounce'; import webpack from 'webpack'; import 'babel-core/register'; import helper from './_helper'; import expected from './basic/expected.json'; test.beforeEach(t => { const config = helper.getSuiteConfig('basic'); t.context.config = config t.context.extractOpts = helper.getExtractOptions(config); t.end(); }) test('basic', t => { t.plan(1); const callback = (err, stats) => { err = err || (stats.hasErrors() ? new Error(stats.toString()) : null) if (err) { t.fail(err); t.end(); } setTimeout(() => { const output = require(t.context.extractOpts.outputFile); t.same(output, expected); t.end(); }, t.context.extractOpts.writeDebounceMs); } webpack(t.context.config, callback); }) test('basic (onOutput)', t => { t.plan(1); const onOutput = debounce((filename, blob, total) => { t.same(total, expected); t.end(); }, t.context.extractOpts.writeDebounceMs); const config = Object.assign({}, t.context.config, { extractCssModuleClassnames: { onOutput } }); const callback = (err, stats) => { err = err || (stats.hasErrors() ? new Error(stats.toString()) : null) if (err) { t.fail(err); t.end(); } } webpack(config, callback); });
mmrko/extract-css-module-classnames-loader
test/basic.js
JavaScript
mit
1,287
/** * 对Storage的封装 * Author : smohan * Website : https://smohan.net * Date: 2017/10/12 * 参数1:布尔值, true : sessionStorage, 无论get,delete,set都得申明 * 参数1:string key 名 * 参数2:null,用作删除,其他用作设置 * 参数3:string,用于设置键名前缀 * 如果是sessionStorage,即参数1是个布尔值,且为true, * 无论设置/删除/获取都应该指明,而localStorage无需指明 */ const MEMORY_CACHE = Object.create(null) export default function () { let isSession = false, name, value, prefix let args = arguments if (typeof args[0] === 'boolean') { isSession = args[0] args = [].slice.call(args, 1) } name = args[0] value = args[1] prefix = args[2] === undefined ? '_mo_data_' : args[2] const Storage = isSession ? window.sessionStorage : window.localStorage if (!name || typeof name !== 'string') { throw new Error('name must be a string') } let cacheKey = (prefix && typeof prefix === 'string') ? (prefix + name) : name if (value === null) { //remove delete MEMORY_CACHE[cacheKey] return Storage.removeItem(cacheKey) } else if (!value && value !== 0) { //get if (MEMORY_CACHE[cacheKey]) { return MEMORY_CACHE[cacheKey] } let _value = undefined try { _value = JSON.parse(Storage.getItem(cacheKey)) } catch (e) {} return _value } else { //set MEMORY_CACHE[cacheKey] = value return Storage.setItem(cacheKey, JSON.stringify(value)) } }
S-mohan/mblog
src/utils/store.js
JavaScript
mit
1,514
/* * * UI reducer * */ import { fromJS } from 'immutable'; import { SET_PRODUCT_QUANTITY_SELECTOR, } from './constants'; const initialState = fromJS({ product: { quantitySelected: 1, }, }); function uiReducer(state = initialState, action) { switch (action.type) { case SET_PRODUCT_QUANTITY_SELECTOR: return state.setIn(['product', 'quantitySelected'], action.quantity); default: return state; } } export default uiReducer;
outdooricon/my-retail-example
app/global/reducers/ui/index.js
JavaScript
mit
465
var async = require('async'); var settings = require('../settings/settings.js'); var Post = require('../models/post.js'); var List = require('../models/list.js'); module.exports = function(app){ app.get('/getArchive',function(req,res,next){ if(req.sessionID){ var list = new List({ pageIndex:1, pageSize:settings.pageSize, queryObj:{} }); list.getArchive(function(err,archiveArray){ if(!(err)&&archiveArray){ res.json(archiveArray); res.end(); }else{ res.json({status:404,message:''}); res.end(); } }); }else{ res.end(); } }); app.get('/getPageCount',function(req,res,next){ if(req.sessionID){ var list = new List({ pageIndex:1, pageSize:settings.pageSize, queryObj:{} }); list.getCount(function(err,count){ if(!(err)&&(count!=0)){ res.json(Math.ceil(count/settings.pageSize)); res.end(); }else{ res.json({status:404,message:''}); res.end(); } }); }else{ res.end(); } }); app.get('/',function(req,res,next){ if(req.sessionID){ var list = new List({ pageIndex:1, pageSize:settings.pageSize, queryObj:{} }); list.getList(function(err,docs){ if(!(err)&&docs){ res.json(docs); res.end(); }else{ res.json({status:404,message:''}); res.end(); } }); }else{ res.end(); } }); }
mywei1989/blog_angular
api/routes/list.js
JavaScript
mit
1,575
module('Item'); test('.setOptions()', function() { var item = new Item({ name: 'Name', category: 'Category', icon: 'Icon', value: 'Value', flavor: 'Flavor', rarity: 'Rare', }); item.code = 'Code'; equal(item.getName(),'Name'); equal(item.getCategory(),'Category'); equal(item.getIcon(),'Icon'); equal(item.getValue(),'Value'); equal(item.getFlavor(),'Flavor'); equal(item.getRarity(),'Rare'); equal(item.getCode(),'Code'); equal(item.isEquipment(),false); }); test('Rarity Classes', function() { var item = Factories.buildItem({}); equal(item.getRarity(),'Common'); equal(item.getClassName(),'highlight-item-common'); item.rarity = 'Uncommon'; equal(item.getClassName(),'highlight-item-uncommon'); item.rarity = 'Rare'; equal(item.getClassName(),'highlight-item-rare'); item.rarity = 'Epic'; equal(item.getClassName(),'highlight-item-epic'); });
maldrasen/archive
Mephidross/old/reliquary/test/ItemTest.js
JavaScript
mit
920
(function (angular) { // Create all modules and define dependencies to make sure they exist // and are loaded in the correct order to satisfy dependency injection // before all nested files are concatenated by Gulp // Config angular .module('jackalMqtt.config', []) .value('jackalMqtt.config', { debug: true }); // Modules angular .module('jackalMqtt.services', []); angular .module('jackalMqtt', [ 'jackalMqtt.config', 'jackalMqtt.services' ]); })(angular); angular .module('jackalMqtt.services') .factory('mqttService', MqttService) .factory('dataService', DataService); DataService.$inject = [ ]; function DataService () { var service = { data: { } }; return service; } MqttService.$inject = ['$rootScope', 'dataService']; function MqttService ($rootScope, dataService) { var mqttc; var Paho = Paho; var callbacks = { }; function addCallback(chanel, callbackName, dataName) { callbacks[chanel] = [callbackName, dataName]; } function deleteCallback(chanel){ delete callbacks[chanel]; } function chanelMatch(chanel, destination) { var reg = '^'; destination += '/'; var levels = chanel.split('/'); for (var ind = 0; ind < levels.length; ind++){ var lvl = levels[ind]; if(lvl === '+'){ reg = '([a-z]|[0-9])+/'; }else if(lvl === '#'){ reg += '(([a-z]|[0-9])|/)*'; }else{ reg += (lvl + '/'); } } reg += '$'; reg = new RegExp(reg); if(reg.test(destination)){ return true; } return false; } function onConnect() { $rootScope.$broadcast('connected'); } function onConnectionLost(responseObject) { if(responseObject.errorCode !== 0){ $rootScope.$broadcast('connectionLost'); } } function onMessageArrived(message) { var payload = message.payloadString; var destination = message.destinationName; for(var key in callbacks) { if(callbacks.hasOwnProperty(key)) { var match = chanelMatch(key, destination); if(match) { dataService.data[callbacks[key][1]] = payload; $rootScope.$broadcast(callbacks[key][0]); } } } } function connect(host, port, options) { mqttc = new Paho.MQTT.Client(host, Number(port), 'web_client_' + Math.round(Math.random() * 1000)); mqttc.onConnectionLost = onConnectionLost; mqttc.onMessageArrived = onMessageArrived; options['onSuccess'] = onConnect; mqttc.connect(options); } function disconnect() { mqttc.disconnect(); } function subscribe(chanel, callbackName, dataName) { mqttc.subscribe(chanel); addCallback(chanel, callbackName, dataName); } function unsubscribe(chanel) { mqttc.unsubscribe(chanel); deleteCallback(chanel); } function publish(chanel, message, retained) { var payload = JSON.stringify(message); var mqttMessage = new Paho.MQTT.Message(payload); mqttMessage.retained = retained; mqttMessage.detinationName = chanel; mqttc.send(mqttMessage); } return { connect: connect, disconnect: disconnect, subscribe: subscribe, unsubscribe: unsubscribe, publish: publish, /** TEST CODE **/ _addCallback: addCallback, _deleteCallback: deleteCallback, _chanelMatch: chanelMatch, _callbacks: callbacks /** TEST CODE **/ }; }
DarkDruiD/jackal-mqtt
dist/jackal-mqtt.js
JavaScript
mit
3,856
import TheWalletView from '@/views/TheWalletView'; import Dashboard from '@/views/layouts-wallet/TheDashboardLayout'; import Send from '@/views/layouts-wallet/TheSendTransactionLayout'; import NftManager from '@/views/layouts-wallet/TheNFTManagerLayout'; import Swap from '@/views/layouts-wallet/TheSwapLayout'; import InteractContract from '@/views/layouts-wallet/TheInteractContractLayout'; import DeployContract from '@/views/layouts-wallet/TheDeployContractLayout'; import SignMessage from '@/views/layouts-wallet/TheSignMessageLayout'; import VerifyMessage from '@/views/layouts-wallet/TheVerifyMessageLayout'; import Dapps from '@/views/layouts-wallet/TheDappCenterLayout.vue'; import DappRoutes from '@/dapps/routes-dapps.js'; import Settings from '@/modules/settings/ModuleSettings'; import NftManagerSend from '@/modules/nft-manager/components/NftManagerSend'; // import Notifications from '@/modules/notifications/ModuleNotifications'; import Network from '@/modules/network/ModuleNetwork'; import { swapProps, swapRouterGuard } from './helpers'; import { ROUTES_WALLET } from '../configs/configRoutes'; export default { path: '/wallet', component: TheWalletView, props: true, children: [ { path: ROUTES_WALLET.WALLETS.PATH, name: ROUTES_WALLET.WALLETS.NAME, component: Dashboard, meta: { noAuth: false } }, { path: ROUTES_WALLET.DASHBOARD.PATH, name: ROUTES_WALLET.DASHBOARD.NAME, component: Dashboard, meta: { noAuth: false } }, { path: ROUTES_WALLET.SETTINGS.PATH, name: ROUTES_WALLET.SETTINGS.NAME, component: Settings, meta: { noAuth: false } }, { path: ROUTES_WALLET.SEND_TX.PATH, name: ROUTES_WALLET.SEND_TX.NAME, component: Send, props: true, meta: { noAuth: false } }, { path: ROUTES_WALLET.NFT_MANAGER.PATH, name: ROUTES_WALLET.NFT_MANAGER.NAME, component: NftManager, children: [ { path: ROUTES_WALLET.NFT_MANAGER_SEND.PATH, name: ROUTES_WALLET.NFT_MANAGER_SEND.NAME, component: NftManagerSend, meta: { noAuth: false } } ], meta: { noAuth: false } }, // { // path: ROUTES_WALLET.NOTIFICATIONS.PATH, // name: ROUTES_WALLET.NOTIFICATIONS.NAME, // component: Notifications, // meta: { // noAuth: false // } // }, { path: ROUTES_WALLET.NETWORK.PATH, name: ROUTES_WALLET.NETWORK.NAME, component: Network, meta: { noAuth: false } }, { path: ROUTES_WALLET.SWAP.PATH, name: ROUTES_WALLET.SWAP.NAME, component: Swap, props: swapProps, beforeEnter: swapRouterGuard, meta: { noAuth: false } }, { path: ROUTES_WALLET.DAPPS.PATH, component: Dapps, children: DappRoutes, meta: { noAuth: false } }, { path: ROUTES_WALLET.DEPLOY_CONTRACT.PATH, name: ROUTES_WALLET.DEPLOY_CONTRACT.NAME, component: DeployContract, meta: { noAuth: false } }, { path: ROUTES_WALLET.INTERACT_WITH_CONTRACT.PATH, name: ROUTES_WALLET.INTERACT_WITH_CONTRACT.NAME, component: InteractContract, meta: { noAuth: false } }, { path: ROUTES_WALLET.SIGN_MESSAGE.PATH, name: ROUTES_WALLET.SIGN_MESSAGE.NAME, component: SignMessage, meta: { noAuth: false } }, { path: ROUTES_WALLET.VERIFY_MESSAGE.PATH, name: ROUTES_WALLET.VERIFY_MESSAGE.NAME, component: VerifyMessage, meta: { noAuth: false } } ] };
MyEtherWallet/MyEtherWallet
src/core/router/routes-wallet.js
JavaScript
mit
3,789
/** * Created by ozgur on 24.07.2017. */ var assert = require('assert'); var fs = require("fs"); var path = require("path"); var LineCounter = require("../lib/LineCounter"); var ExtensionsFactory = require("../lib/Extensions"); var Rules = require("../lib/Rules"); describe("LineCounter", function(){ before(function(){ var dir = __dirname; fs.mkdirSync(path.join(dir, "dir")); fs.mkdirSync(path.join(dir, "dir", "dir2")); fs.mkdirSync(path.join(dir, "dir", "dir3")); fs.writeFileSync(path.join(dir, "dir", "file1.java"), "line1\nline2"); fs.writeFileSync(path.join(dir, "dir", "file1.js"), "line1\nline2\nline3"); fs.writeFileSync(path.join(dir, "dir", "dir2", "file3.php"), "line1\nline2"); fs.writeFileSync(path.join(dir, "dir", "dir2", "file4.swift"), "line1\nline2"); fs.writeFileSync(path.join(dir, "dir", "dir3", "file5.java"), "line1\nline2"); fs.writeFileSync(path.join(dir, "dir", "dir3", "file6.js"), "line1\nline2"); }); describe("#resolveTargetFiles()", function(){ it("should return allowed extensions", function(){ var lc = new LineCounter(); lc.setPath(path.join(__dirname, "dir")); lc.setExtensions(ExtensionsFactory.from("js")); var result = lc.resolveTargetFiles(); var expected = [ path.join(__dirname, "dir", "dir3", "file6.js"), path.join(__dirname, "dir", "file1.js") ]; for( var i = 0; i < expected.length; i++ ){ assert.equal(expected[i], result[i].getPath()); } }); it("should return all except disallowed ones", function(){ var lc = new LineCounter(); lc.setPath(path.join(__dirname, "dir")); lc.setExtensions(ExtensionsFactory.except("java, swift, php")); var result = lc.resolveTargetFiles(); var expected = [ path.join(__dirname, "dir", "dir3", "file6.js"), path.join(__dirname, "dir", "file1.js") ]; for( var i = 0; i < expected.length; i++ ){ assert.equal(expected[i], result[i].getPath()); } }); it("should return all", function(){ var lc = new LineCounter(); lc.setPath(path.join(__dirname, "dir")); var result = lc.resolveTargetFiles(); var expected = [ path.join(__dirname, "dir", "dir2", "file3.php"), path.join(__dirname, "dir", "dir2", "file4.swift"), path.join(__dirname, "dir", "dir3", "file5.java"), path.join(__dirname, "dir", "dir3", "file6.js"), path.join(__dirname, "dir", "file1.java"), path.join(__dirname, "dir", "file1.js")]; for( var i = 0; i < expected.length; i++ ){ assert.equal(expected[i], result[i].getPath()); } }); }); describe("#getLines()", function(){ it("should count all files correctly", function(done){ var lc = new LineCounter(); lc.setPath(path.join(__dirname, "dir")); lc.getLines(function(result){ assert.equal(6, result.files); assert.equal(13, result.lines); done(); }); }); it("should count only js files", function(done){ var lc = new LineCounter(); lc.setPath(path.join(__dirname, "dir")); lc.setExtensions(ExtensionsFactory.from("js")); lc.getLines(function(result){ assert.equal(2, result.files); assert.equal(5, result.lines); done(); }); }); }); describe("#addRule()", function(){ it("should return only the files starts with file1", function(){ var lc = new LineCounter(); lc.setPath(path.join(__dirname, "dir")); lc.addRule(Rules.filePrefix, "file1"); var result = lc.resolveTargetFiles(); var expected = [ path.join(__dirname, "dir", "file1.java"), path.join(__dirname, "dir", "file1.js") ]; for( var i = 0; i < expected.length; i++ ){ assert.equal(expected[i], result[i].getPath()); } }); it("should ignore dir2 and dir3 directories", function(){ var lc = new LineCounter(); lc.setPath(path.join(__dirname, "dir")); lc.addRule(Rules.ignoreDir, "dir2"); lc.addRule(Rules.ignoreDir, "dir3"); var result = lc.resolveTargetFiles(); var expected = [ path.join(__dirname, "dir", "file1.java"), path.join(__dirname, "dir", "file1.js") ]; for( var i = 0; i < expected.length; i++ ){ assert.equal(expected[i], result[i].getPath()); } }); }); after(function(){ var dir = __dirname; fs.unlinkSync(path.join(dir, "dir", "dir3", "file6.js")); fs.unlinkSync(path.join(dir, "dir", "dir3", "file5.java")); fs.unlinkSync(path.join(dir, "dir", "dir2", "file4.swift")); fs.unlinkSync(path.join(dir, "dir", "dir2", "file3.php")); fs.unlinkSync(path.join(dir, "dir", "file1.js")); fs.unlinkSync(path.join(dir, "dir", "file1.java")); fs.rmdirSync(path.join(dir, "dir", "dir2")); fs.rmdirSync(path.join(dir, "dir", "dir3")); fs.rmdirSync(path.join(dir, "dir")); }); });
social13/line-counter-node
tests/lineCounterTest.js
JavaScript
mit
5,389
define(['./Suite','./SuiteView','./Spy', './Verify'],function (Suite,SuiteView,Spy,Verify) { var itchCork = { Suite: Suite, suiteView: new SuiteView(), Spy: Spy, Verify: Verify }; itchCork.Suite.prototype.linkView(itchCork.suiteView); window._bTestResults = {}; return itchCork; });
adamjmoon/itchcorkjs
itchcork/itchcork.js
JavaScript
mit
352
!function r(e,n,t){function i(u,f){if(!n[u]){if(!e[u]){var a="function"==typeof require&&require;if(!f&&a)return a(u,!0);if(o)return o(u,!0);var c=new Error("Cannot find module '"+u+"'");throw c.code="MODULE_NOT_FOUND",c}var s=n[u]={exports:{}};e[u][0].call(s.exports,function(r){var n=e[u][1][r];return i(n||r)},s,s.exports,r,e,n,t)}return n[u].exports}for(var o="function"==typeof require&&require,u=0;u<t.length;u++)i(t[u]);return i}({1:[function(r,e,n){!function(){"use strict";Object.rearmed.add({hasKey:function(r){var e=!1;for(var n in this)if(n===r){e=!0;break}return e}})}()},{}]},{},[1]);
westonganger/rearmed-js
dist/object/hasKey.min.js
JavaScript
mit
598
const sinon = require('sinon'); const sinonChai = require('sinon-chai'); const chai = require('chai'); const dirtyChai = require('dirty-chai'); const should = chai.Should; should(); chai.use(dirtyChai); chai.use(sinonChai); const index = require('./../src/index.js'); const error = new Error('should not be called'); describe('node-vault', () => { describe('module', () => { it('should export a function that returns a new client', () => { const v = index(); index.should.be.a('function'); v.should.be.an('object'); }); }); describe('client', () => { let request = null; let response = null; let vault = null; // helper function getURI(path) { return [vault.endpoint, vault.apiVersion, path].join('/'); } function assertRequest(thisRequest, params, done) { return () => { thisRequest.should.have.calledOnce(); thisRequest.calledWithMatch(params).should.be.ok(); return done(); }; } beforeEach(() => { // stub requests request = sinon.stub(); response = sinon.stub(); response.statusCode = 200; request.returns({ then(fn) { return fn(response); }, catch(fn) { return fn(); }, }); vault = index( { endpoint: 'http://localhost:8200', token: '123', 'request-promise': request, // dependency injection of stub } ); }); describe('help(path, options)', () => { it('should response help text for any path', done => { const path = 'sys/policy'; const params = { method: 'GET', uri: `${getURI(path)}?help=1`, }; vault.help(path) .then(assertRequest(request, params, done)) .catch(done); }); it('should handle undefined options', done => { const path = 'sys/policy'; const params = { method: 'GET', uri: `${getURI(path)}?help=1`, }; vault.help(path) .then(assertRequest(request, params, done)) .catch(done); }); }); describe('list(path, requestOptions)', () => { it('should list entries at the specific path', done => { const path = 'secret/hello'; const params = { method: 'LIST', uri: getURI(path), }; vault.list(path) .then(assertRequest(request, params, done)) .catch(done); }); }); describe('write(path, data, options)', () => { it('should write data to path', done => { const path = 'secret/hello'; const data = { value: 'world', }; const params = { method: 'PUT', uri: getURI(path), }; vault.write(path, data) .then(assertRequest(request, params, done)) .catch(done); }); it('should handle undefined options', done => { const path = 'secret/hello'; const data = { value: 'world', }; const params = { method: 'PUT', uri: getURI(path), }; vault.write(path, data) .then(assertRequest(request, params, done)) .catch(done); }); }); describe('read(path, options)', () => { it('should read data from path', done => { const path = 'secret/hello'; const params = { method: 'GET', uri: getURI(path), }; vault.read(path) .then(assertRequest(request, params, done)) .catch(done); }); it('should handle undefined options', done => { const path = 'secret/hello'; const params = { method: 'GET', uri: getURI(path), }; vault.read(path) .then(assertRequest(request, params, done)) .catch(done); }); }); describe('delete(path, options)', () => { it('should delete data from path', done => { const path = 'secret/hello'; const params = { method: 'DELETE', uri: getURI(path), }; vault.delete(path) .then(assertRequest(request, params, done)) .catch(done); }); it('should handle undefined options', done => { const path = 'secret/hello'; const params = { method: 'DELETE', uri: getURI(path), }; vault.delete(path) .then(assertRequest(request, params, done)) .catch(done); }); }); describe('handleVaultResponse(response)', () => { it('should return a function that handles errors from vault server', () => { const fn = vault.handleVaultResponse; fn.should.be.a('function'); }); it('should return a Promise with the body if successful', done => { const data = { hello: 1 }; response.body = data; const promise = vault.handleVaultResponse(response); promise.then(body => { body.should.equal(data); return done(); }); }); it('should return a Promise with the error if failed', done => { response.statusCode = 500; response.body = { errors: ['Something went wrong.'], }; response.request = { path: 'test', }; const promise = vault.handleVaultResponse(response); promise.catch(err => { err.message.should.equal(response.body.errors[0]); return done(); }); }); it('should return the status code if no error in the response', done => { response.statusCode = 500; response.request = { path: 'test', }; const promise = vault.handleVaultResponse(response); promise.catch(err => { err.message.should.equal(`Status ${response.statusCode}`); return done(); }); }); it('should not handle response from health route as error', done => { const data = { initialized: true, sealed: true, standby: true, server_time_utc: 1474301338, version: 'Vault v0.6.1', }; response.statusCode = 503; response.body = data; response.request = { path: '/v1/sys/health', }; const promise = vault.handleVaultResponse(response); promise.then(body => { body.should.equal(data); return done(); }); }); it('should return error if error on request path with health and not sys/health', done => { response.statusCode = 404; response.body = { errors: [], }; response.request = { path: '/v1/sys/policies/applications/im-not-sys-health/app', }; vault.handleVaultResponse(response) .then(() => done(error)) .catch(err => { err.message.should.equal(`Status ${response.statusCode}`); return done(); }); }); it('should return a Promise with the error if no response is passed', done => { const promise = vault.handleVaultResponse(); promise.catch((err) => { err.message.should.equal('No response passed'); return done(); }); }); }); describe('generateFunction(name, config)', () => { const config = { method: 'GET', path: '/myroute', }; const configWithSchema = { method: 'GET', path: '/myroute', schema: { req: { type: 'object', properties: { testProperty: { type: 'integer', minimum: 1, }, }, required: ['testProperty'], }, }, }; const configWithQuerySchema = { method: 'GET', path: '/myroute', schema: { query: { type: 'object', properties: { testParam1: { type: 'integer', minimum: 1, }, testParam2: { type: 'string', }, }, required: ['testParam1', 'testParam2'], }, }, }; it('should generate a function with name as defined in config', () => { const name = 'myGeneratedFunction'; vault.generateFunction(name, config); vault.should.have.property(name); const fn = vault[name]; fn.should.be.a('function'); }); describe('generated function', () => { it('should return a promise', done => { const name = 'myGeneratedFunction'; vault.generateFunction(name, config); const fn = vault[name]; const promise = fn(); request.calledOnce.should.be.ok(); /* eslint no-unused-expressions: 0*/ promise.should.be.promise; promise.then(done) .catch(done); }); it('should handle config with schema property', done => { const name = 'myGeneratedFunction'; vault.generateFunction(name, configWithSchema); const fn = vault[name]; const promise = fn({ testProperty: 3 }); promise.then(done).catch(done); }); it('should handle invalid arguments via schema property', done => { const name = 'myGeneratedFunction'; vault.generateFunction(name, configWithSchema); const fn = vault[name]; const promise = fn({ testProperty: 'wrong data type here' }); promise.catch(err => { err.message.should.equal('Invalid type: string (expected integer)'); return done(); }); }); it('should handle schema with query property', done => { const name = 'myGeneratedFunction'; vault.generateFunction(name, configWithQuerySchema); const fn = vault[name]; const promise = fn({ testParam1: 3, testParam2: 'hello' }); const options = { path: '/myroute?testParam1=3&testParam2=hello', }; promise .then(() => { request.calledWithMatch(options).should.be.ok(); done(); }) .catch(done); }); }); }); describe('request(options)', () => { it('should reject if options are undefined', done => { vault.request() .then(() => done(error)) .catch(() => done()); }); it('should handle undefined path in options', done => { const promise = vault.request({ method: 'GET', }); promise.catch(err => { err.message.should.equal('Missing required property: path'); return done(); }); }); it('should handle undefined method in options', done => { const promise = vault.request({ path: '/', }); promise.catch(err => { err.message.should.equal('Missing required property: method'); return done(); }); }); }); }); });
trevorr/node-vault
test/unit.js
JavaScript
mit
11,148
'use strict'; function A() { this._va = 0; console.log('A'); } A.prototype = { va: 1, fa: function() { console.log('A->fa()'); } }; function B() { this._vb = 0; console.log('B'); } B.prototype = { vb: 1, fb: function() { console.log('B->fb()'); } }; function C() { this._vc = 0; console.log('C'); } C.prototype = { vc: 1, fc: function() { console.log('C->fc()'); } }; function D(){ this._vd = 0; console.log('D'); } D.prototype = { vd: 1, fd: function() { this.fa(); this.fb(); this.fc(); console.log('D->fd()'); } }; var mixin = require('../mixin'); D = mixin(D, A); D = mixin(D, B); D = mixin(D, C); var d = new D(); console.log(d); console.log(d.constructor.name); d.fd(); var a = new A(); console.log(a); console.log(a.__proto__); console.log(a.va);
floatinghotpot/mixin-pro
test/testMixin.js
JavaScript
mit
825
export { default } from 'ember-transformer/transforms/array';
ChrisHonniball/ember-transformer
app/transforms/array.js
JavaScript
mit
61