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 |
|---|---|---|---|---|---|
/* Copyright 2021 Peppy Player peppy.player@gmail.com
This file is part of Peppy Player.
Peppy Player is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Peppy Player is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Peppy Player. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import Accordion from '@material-ui/core/Accordion';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionActions from '@material-ui/core/AccordionActions';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import Button from '@material-ui/core/Button';
import Factory from "../Factory";
export default class Nas extends React.Component {
setOptions = (name, value, index) => {
if (value === "cifs") {
this.props.updateState("mount.options", "uid=1000,gid=1000,dir_mode=0700,file_mode=0700", index);
}
this.props.updateState(name, value, index);
}
render() {
const { index, nas, classes, labels, mount, unmount, deleteNas, updateState } = this.props;
let style = { "width": "30rem", "marginBottom": "1.4rem" };
let last = { "width": "30rem", "marginBottom": "0rem" };
const TYPE_DEFAULT = "text";
const TYPE_PASSWORD = "password";
return (
<div style={{ width: "32rem", marginBottom: "0.5rem" }}>
<Accordion>
<AccordionSummary expandIcon={<ExpandMoreIcon />}>
<div style={{ width: "100%", display: "flex", flexDirection: "row", justifyContent: "space-between", alignItems: "center" }}>
<div style={{ fontWeight: "bold" }}>
<div>{nas.name}</div>
</div>
<div style={{ fontWeight: "bold", color: nas.mounted ? "green" : "red" }}>
<div>{nas.mounted ? labels.mounted : labels.unmounted}</div>
</div>
</div>
</AccordionSummary>
<AccordionDetails className={classes.details}>
<div>
{Factory.createTextField("name", nas, updateState, style, classes, labels, false, index, TYPE_DEFAULT, true)}
{Factory.createTextField("ip.address", nas, updateState, style, classes, labels, false, index, TYPE_DEFAULT, true)}
{Factory.createTextField("folder", nas, updateState, style, classes, labels, false, index, TYPE_DEFAULT, true)}
{Factory.createTextField("filesystem", nas, this.setOptions, style, classes, labels, false, index, TYPE_DEFAULT, true)}
{Factory.createTextField("username", nas, updateState, style, classes, labels, false, index, TYPE_DEFAULT, true)}
{Factory.createTextField("password", nas, updateState, style, classes, labels, false, index, TYPE_PASSWORD, true)}
{Factory.createTextField("mount.options", nas, updateState, last, classes, labels, false, index, TYPE_DEFAULT)}
</div>
</AccordionDetails>
<AccordionActions>
<Button variant="contained" disabled={nas.mounted} className={classes.button}
style={{ marginRight: "0.2rem", marginBottom: "1rem" }} onClick={() => { mount(index) }}>{labels["mount"]}
</Button>
<Button variant="contained" disabled={!nas.mounted} className={classes.button}
style={{ marginRight: "0.2rem", marginBottom: "1rem" }} onClick={() => { unmount(index) }}>{labels["unmount"]}
</Button>
<Button variant="contained" className={classes.button}
style={{ marginRight: "0.5rem", marginBottom: "1rem" }} onClick={() => { deleteNas(index) }}>{labels["delete"]}
</Button>
</AccordionActions>
</Accordion>
</div>
);
}
}
| project-owner/Peppy | web/client/configdev/src/components/Nas.js | JavaScript | gpl-3.0 | 4,176 |
import { ConstraintViolationListException } from '../constraint-violation-list.exception'
import json from '~/static/__mocks__/violations'
describe('Check constraint violation list exception.', () => {
it('can get violations list by property.', () => {
const constraint = new ConstraintViolationListException(JSON.parse(json))
expect(constraint.violations.length).toEqual(1)
expect(constraint.getViolationsBy('email')[0].message).toBe('baz message.')
expect(constraint.getViolationsBy('fake_field')).toEqual([])
})
})
| eerison/myprofile | client/exception/__tests__/constraint-violation-list.exception.unit.js | JavaScript | gpl-3.0 | 539 |
/*!
* Piwik - free/libre analytics platform
*
* @link http://piwik.org
* @license http://www.gnu.org/licenses/gpl-3.0.html GPL v3 or later
*/
/**
* Converts ngModel value to a number
*
* Example:
* <input type="number" string-to-number>...</div>
*/
(function () {
angular.module('piwikApp.directive').directive('stringToNumber', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$parsers.push(function(value) {
return '' + value;
});
ngModel.$formatters.push(function(value) {
return parseFloat(value);
});
}
};
});
})();
| piwik/piwik | plugins/CoreHome/angularjs/common/directives/string-to-number.js | JavaScript | gpl-3.0 | 746 |
var schedule = [
{
"id": "session-1",
"title": "Registration",
"tracks": [1, 2]
},
{
"id": "session-2",
"title": "Moving the Web forward with HTML5",
"tracks": [1, 2]
},
{
"id": "session-3",
"title": "Diving in at the deep end with Canvas",
"tracks": [1]
},
{
"id": "session-4",
"title": "New Technologies in Enterprise",
"tracks": [2]
},
{
"id": "session-5",
"title": "WebSockets and You",
"tracks": [1]
},
{
"id": "session-6",
"title": "Coffee and Cake Break",
"tracks": [1, 2]
},
{
"id": "session-7",
"title": "Building Responsive UIs",
"tracks": [1]
},
{
"id": "session-8",
"title": "Fun with Forms (no, really!)",
"tracks": [2]
},
{
"id": "session-9",
"title": "A Fresh Look at Layouts",
"tracks": [1]
},
{
"id": "session-10",
"title": "Real-world Applications of HTML5 APIs",
"tracks": [2]
},
{
"id": "session-11",
"title": "Lunch",
"tracks": [1, 2]
},
{
"id": "session-12",
"title": "Getting to Grips with JavaScript",
"tracks": [1]
},
{
"id": "session-13",
"title": "Transforms and Animations",
"tracks": [2]
},
{
"id": "session-14",
"title": "Web Design Adventures with CSS3",
"tracks": [1]
},
{
"id": "session-15",
"title": "Introducing Data Access and Caching",
"tracks": [2]
},
{
"id": "session-16",
"title": "Closing Thanks and Prizes",
"tracks": [1, 2]
}
];
// TODO: Task 2 - Get the "schedule" list element from the document
var list = document.getElementById("schedule");
function createSessionElement(session) {
// TODO: Task 3 - Create a <li> element for the session.
// Add the session title as the <li> text content
// Return the <li> element
var li = document.createElement("li");
li.textContent = session.title;
return li;
};
function clearList() {
while (list.firstChild) {
list.removeChild(list.firstChild);
}
}
function displaySchedule() {
clearList();
// TODO: Task 4 - Loop through the schedule array
// Create session elements
// Append the elements to the list
for (var i = 0; i < schedule.length; i++) {
var li = createSessionElement(schedule[i]);
list.appendChild(li);
}
}
displaySchedule();
// SIG // Begin signature block
// SIG // MIIaVgYJKoZIhvcNAQcCoIIaRzCCGkMCAQExCzAJBgUr
// SIG // DgMCGgUAMGcGCisGAQQBgjcCAQSgWTBXMDIGCisGAQQB
// SIG // gjcCAR4wJAIBAQQQEODJBs441BGiowAQS9NQkAIBAAIB
// SIG // AAIBAAIBAAIBADAhMAkGBSsOAwIaBQAEFBwI1Tpqf6h3
// SIG // 33yZ3Lo4Tcr+DaYxoIIVJjCCBJkwggOBoAMCAQICEzMA
// SIG // AACdHo0nrrjz2DgAAQAAAJ0wDQYJKoZIhvcNAQEFBQAw
// SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0
// SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
// SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj
// SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0EwHhcNMTIwOTA0
// SIG // MjE0MjA5WhcNMTMwMzA0MjE0MjA5WjCBgzELMAkGA1UE
// SIG // BhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAOBgNV
// SIG // BAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29mdCBD
// SIG // b3Jwb3JhdGlvbjENMAsGA1UECxMETU9QUjEeMBwGA1UE
// SIG // AxMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMIIBIjANBgkq
// SIG // hkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuqRJbBD7Ipxl
// SIG // ohaYO8thYvp0Ka2NBhnScVgZil5XDWlibjagTv0ieeAd
// SIG // xxphjvr8oxElFsjAWCwxioiuMh6I238+dFf3haQ2U8pB
// SIG // 72m4aZ5tVutu5LImTXPRZHG0H9ZhhIgAIe9oWINbSY+0
// SIG // 39M11svZMJ9T/HprmoQrtyFndNT2eLZhh5iUfCrPZ+kZ
// SIG // vtm6Y+08Tj59Auvzf6/PD7eBfvT76PeRSLuPPYzIB5Mc
// SIG // 87115PxjICmfOfNBVDgeVGRAtISqN67zAIziDfqhsg8i
// SIG // taeprtYXuTDwAiMgEPprWQ/grZ+eYIGTA0wNm2IZs7uW
// SIG // vJFapniGdptszUzsErU4RwIDAQABo4IBDTCCAQkwEwYD
// SIG // VR0lBAwwCgYIKwYBBQUHAwMwHQYDVR0OBBYEFN5R3Bvy
// SIG // HkoFPxIcwbzDs2UskQWYMB8GA1UdIwQYMBaAFMsR6MrS
// SIG // tBZYAck3LjMWFrlMmgofMFYGA1UdHwRPME0wS6BJoEeG
// SIG // RWh0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js
// SIG // L3Byb2R1Y3RzL01pY0NvZFNpZ1BDQV8wOC0zMS0yMDEw
// SIG // LmNybDBaBggrBgEFBQcBAQROMEwwSgYIKwYBBQUHMAKG
// SIG // Pmh0dHA6Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2Vy
// SIG // dHMvTWljQ29kU2lnUENBXzA4LTMxLTIwMTAuY3J0MA0G
// SIG // CSqGSIb3DQEBBQUAA4IBAQAqpPfuwMMmeoNiGnicW8X9
// SIG // 7BXEp3gT0RdTKAsMAEI/OA+J3GQZhDV/SLnP63qJoc1P
// SIG // qeC77UcQ/hfah4kQ0UwVoPAR/9qWz2TPgf0zp8N4k+R8
// SIG // 1W2HcdYcYeLMTmS3cz/5eyc09lI/R0PADoFwU8GWAaJL
// SIG // u78qA3d7bvvQRooXKDGlBeMWirjxSmkVXTP533+UPEdF
// SIG // Ha7Ki8f3iB7q/pEMn08HCe0mkm6zlBkB+F+B567aiY9/
// SIG // Wl6EX7W+fEblR6/+WCuRf4fcRh9RlczDYqG1x1/ryWlc
// SIG // cZGpjVYgLDpOk/2bBo+tivhofju6eUKTOUn10F7scI1C
// SIG // dcWCVZAbtVVhMIIEujCCA6KgAwIBAgIKYQKOQgAAAAAA
// SIG // HzANBgkqhkiG9w0BAQUFADB3MQswCQYDVQQGEwJVUzET
// SIG // MBEGA1UECBMKV2FzaGluZ3RvbjEQMA4GA1UEBxMHUmVk
// SIG // bW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0
// SIG // aW9uMSEwHwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFt
// SIG // cCBQQ0EwHhcNMTIwMTA5MjIyNTU4WhcNMTMwNDA5MjIy
// SIG // NTU4WjCBszELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldh
// SIG // c2hpbmd0b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNV
// SIG // BAoTFU1pY3Jvc29mdCBDb3Jwb3JhdGlvbjENMAsGA1UE
// SIG // CxMETU9QUjEnMCUGA1UECxMebkNpcGhlciBEU0UgRVNO
// SIG // OkY1MjgtMzc3Ny04QTc2MSUwIwYDVQQDExxNaWNyb3Nv
// SIG // ZnQgVGltZS1TdGFtcCBTZXJ2aWNlMIIBIjANBgkqhkiG
// SIG // 9w0BAQEFAAOCAQ8AMIIBCgKCAQEAluyOR01UwlyVgNdO
// SIG // Cz2/l0PDS+NgZxEvAU0M2NFGLxBA3gukUFISiAtDei0/
// SIG // 7khuZseR5gPKbux5qWojm81ins1qpD/no0P/YkehtLpE
// SIG // +t9AwYVUfuigpyxDI5tSHzI19P6aVp+NY3d7MJ4KM4Vy
// SIG // G8pKyMwlzdtdES7HsIzxj0NIRwW1eiAL5fPvwbr0s9jN
// SIG // OI/7Iao9Cm2FF9DK54YDwDODtSXEzFqcxMPaYiVNUyUU
// SIG // YY/7G+Ds90fGgEXmNVMjNnfKsN2YKznAdTUP3YFMIT12
// SIG // MMWysGVzKUgn2MLSsIRHu3i61XQD3tdLGfdT3njahvdh
// SIG // iCYztEfGoFSIFSssdQIDAQABo4IBCTCCAQUwHQYDVR0O
// SIG // BBYEFC/oRsho025PsiDQ3olO8UfuSMHyMB8GA1UdIwQY
// SIG // MBaAFCM0+NlSRnAK7UD7dvuzK7DDNbMPMFQGA1UdHwRN
// SIG // MEswSaBHoEWGQ2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNv
// SIG // bS9wa2kvY3JsL3Byb2R1Y3RzL01pY3Jvc29mdFRpbWVT
// SIG // dGFtcFBDQS5jcmwwWAYIKwYBBQUHAQEETDBKMEgGCCsG
// SIG // AQUFBzAChjxodHRwOi8vd3d3Lm1pY3Jvc29mdC5jb20v
// SIG // cGtpL2NlcnRzL01pY3Jvc29mdFRpbWVTdGFtcFBDQS5j
// SIG // cnQwEwYDVR0lBAwwCgYIKwYBBQUHAwgwDQYJKoZIhvcN
// SIG // AQEFBQADggEBAHP/fS6dzY2IK3x9414VceloYvAItkNW
// SIG // xFxKLWjY+UgRkfMRnIXsEtRUoHWpOKFZf3XuxvU02FSk
// SIG // 4tDMfJerk3UwlwcdBFMsNn9/8UAeDJuA4hIKIDoxwAd1
// SIG // Z+D6NJzsiPtXHOVYYiCQRS9dRanIjrN8cm0QJ8VL2G+i
// SIG // qBKzbTUjZ/os2yUtuV2xHgXnQyg+nAV2d/El3gVHGW3e
// SIG // SYWh2kpLCEYhNah1Nky3swiq37cr2b4qav3fNRfMPwzH
// SIG // 3QbPTpQkYyALLiSuX0NEEnpc3TfbpEWzkToSV33jR8Zm
// SIG // 08+cRlb0TAex4Ayq1fbVPKLgtdT4HH4EVRBrGPSRzVGn
// SIG // lWUwggW8MIIDpKADAgECAgphMyYaAAAAAAAxMA0GCSqG
// SIG // SIb3DQEBBQUAMF8xEzARBgoJkiaJk/IsZAEZFgNjb20x
// SIG // GTAXBgoJkiaJk/IsZAEZFgltaWNyb3NvZnQxLTArBgNV
// SIG // BAMTJE1pY3Jvc29mdCBSb290IENlcnRpZmljYXRlIEF1
// SIG // dGhvcml0eTAeFw0xMDA4MzEyMjE5MzJaFw0yMDA4MzEy
// SIG // MjI5MzJaMHkxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpX
// SIG // YXNoaW5ndG9uMRAwDgYDVQQHEwdSZWRtb25kMR4wHAYD
// SIG // VQQKExVNaWNyb3NvZnQgQ29ycG9yYXRpb24xIzAhBgNV
// SIG // BAMTGk1pY3Jvc29mdCBDb2RlIFNpZ25pbmcgUENBMIIB
// SIG // IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsnJZ
// SIG // XBkwZL8dmmAgIEKZdlNsPhvWb8zL8epr/pcWEODfOnSD
// SIG // GrcvoDLs/97CQk4j1XIA2zVXConKriBJ9PBorE1LjaW9
// SIG // eUtxm0cH2v0l3511iM+qc0R/14Hb873yNqTJXEXcr609
// SIG // 4CholxqnpXJzVvEXlOT9NZRyoNZ2Xx53RYOFOBbQc1sF
// SIG // umdSjaWyaS/aGQv+knQp4nYvVN0UMFn40o1i/cvJX0Yx
// SIG // ULknE+RAMM9yKRAoIsc3Tj2gMj2QzaE4BoVcTlaCKCoF
// SIG // MrdL109j59ItYvFFPeesCAD2RqGe0VuMJlPoeqpK8kbP
// SIG // Nzw4nrR3XKUXno3LEY9WPMGsCV8D0wIDAQABo4IBXjCC
// SIG // AVowDwYDVR0TAQH/BAUwAwEB/zAdBgNVHQ4EFgQUyxHo
// SIG // ytK0FlgByTcuMxYWuUyaCh8wCwYDVR0PBAQDAgGGMBIG
// SIG // CSsGAQQBgjcVAQQFAgMBAAEwIwYJKwYBBAGCNxUCBBYE
// SIG // FP3RMU7TJoqV4ZhgO6gxb6Y8vNgtMBkGCSsGAQQBgjcU
// SIG // AgQMHgoAUwB1AGIAQwBBMB8GA1UdIwQYMBaAFA6sgmBA
// SIG // VieX5SUT/CrhClOVWeSkMFAGA1UdHwRJMEcwRaBDoEGG
// SIG // P2h0dHA6Ly9jcmwubWljcm9zb2Z0LmNvbS9wa2kvY3Js
// SIG // L3Byb2R1Y3RzL21pY3Jvc29mdHJvb3RjZXJ0LmNybDBU
// SIG // BggrBgEFBQcBAQRIMEYwRAYIKwYBBQUHMAKGOGh0dHA6
// SIG // Ly93d3cubWljcm9zb2Z0LmNvbS9wa2kvY2VydHMvTWlj
// SIG // cm9zb2Z0Um9vdENlcnQuY3J0MA0GCSqGSIb3DQEBBQUA
// SIG // A4ICAQBZOT5/Jkav629AsTK1ausOL26oSffrX3XtTDst
// SIG // 10OtC/7L6S0xoyPMfFCYgCFdrD0vTLqiqFac43C7uLT4
// SIG // ebVJcvc+6kF/yuEMF2nLpZwgLfoLUMRWzS3jStK8cOeo
// SIG // DaIDpVbguIpLV/KVQpzx8+/u44YfNDy4VprwUyOFKqSC
// SIG // HJPilAcd8uJO+IyhyugTpZFOyBvSj3KVKnFtmxr4HPBT
// SIG // 1mfMIv9cHc2ijL0nsnljVkSiUc356aNYVt2bAkVEL1/0
// SIG // 2q7UgjJu/KSVE+Traeepoiy+yCsQDmWOmdv1ovoSJgll
// SIG // OJTxeh9Ku9HhVujQeJYYXMk1Fl/dkx1Jji2+rTREHO4Q
// SIG // FRoAXd01WyHOmMcJ7oUOjE9tDhNOPXwpSJxy0fNsysHs
// SIG // cKNXkld9lI2gG0gDWvfPo2cKdKU27S0vF8jmcjcS9G+x
// SIG // PGeC+VKyjTMWZR4Oit0Q3mT0b85G1NMX6XnEBLTT+yzf
// SIG // H4qerAr7EydAreT54al/RrsHYEdlYEBOsELsTu2zdnnY
// SIG // CjQJbRyAMR/iDlTd5aH75UcQrWSY/1AWLny/BSF64pVB
// SIG // J2nDk4+VyY3YmyGuDVyc8KKuhmiDDGotu3ZrAB2WrfIW
// SIG // e/YWgyS5iM9qqEcxL5rc43E91wB+YkfRzojJuBj6DnKN
// SIG // waM9rwJAav9pm5biEKgQtDdQCNbDPTCCBgcwggPvoAMC
// SIG // AQICCmEWaDQAAAAAABwwDQYJKoZIhvcNAQEFBQAwXzET
// SIG // MBEGCgmSJomT8ixkARkWA2NvbTEZMBcGCgmSJomT8ixk
// SIG // ARkWCW1pY3Jvc29mdDEtMCsGA1UEAxMkTWljcm9zb2Z0
// SIG // IFJvb3QgQ2VydGlmaWNhdGUgQXV0aG9yaXR5MB4XDTA3
// SIG // MDQwMzEyNTMwOVoXDTIxMDQwMzEzMDMwOVowdzELMAkG
// SIG // A1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0b24xEDAO
// SIG // BgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1pY3Jvc29m
// SIG // dCBDb3Jwb3JhdGlvbjEhMB8GA1UEAxMYTWljcm9zb2Z0
// SIG // IFRpbWUtU3RhbXAgUENBMIIBIjANBgkqhkiG9w0BAQEF
// SIG // AAOCAQ8AMIIBCgKCAQEAn6Fssd/bSJIqfGsuGeG94uPF
// SIG // mVEjUK3O3RhOJA/u0afRTK10MCAR6wfVVJUVSZQbQpKu
// SIG // mFwwJtoAa+h7veyJBw/3DgSY8InMH8szJIed8vRnHCz8
// SIG // e+eIHernTqOhwSNTyo36Rc8J0F6v0LBCBKL5pmyTZ9co
// SIG // 3EZTsIbQ5ShGLieshk9VUgzkAyz7apCQMG6H81kwnfp+
// SIG // 1pez6CGXfvjSE/MIt1NtUrRFkJ9IAEpHZhEnKWaol+TT
// SIG // BoFKovmEpxFHFAmCn4TtVXj+AZodUAiFABAwRu233iNG
// SIG // u8QtVJ+vHnhBMXfMm987g5OhYQK1HQ2x/PebsgHOIktU
// SIG // //kFw8IgCwIDAQABo4IBqzCCAacwDwYDVR0TAQH/BAUw
// SIG // AwEB/zAdBgNVHQ4EFgQUIzT42VJGcArtQPt2+7MrsMM1
// SIG // sw8wCwYDVR0PBAQDAgGGMBAGCSsGAQQBgjcVAQQDAgEA
// SIG // MIGYBgNVHSMEgZAwgY2AFA6sgmBAVieX5SUT/CrhClOV
// SIG // WeSkoWOkYTBfMRMwEQYKCZImiZPyLGQBGRYDY29tMRkw
// SIG // FwYKCZImiZPyLGQBGRYJbWljcm9zb2Z0MS0wKwYDVQQD
// SIG // EyRNaWNyb3NvZnQgUm9vdCBDZXJ0aWZpY2F0ZSBBdXRo
// SIG // b3JpdHmCEHmtFqFKoKWtTHNY9AcTLmUwUAYDVR0fBEkw
// SIG // RzBFoEOgQYY/aHR0cDovL2NybC5taWNyb3NvZnQuY29t
// SIG // L3BraS9jcmwvcHJvZHVjdHMvbWljcm9zb2Z0cm9vdGNl
// SIG // cnQuY3JsMFQGCCsGAQUFBwEBBEgwRjBEBggrBgEFBQcw
// SIG // AoY4aHR0cDovL3d3dy5taWNyb3NvZnQuY29tL3BraS9j
// SIG // ZXJ0cy9NaWNyb3NvZnRSb290Q2VydC5jcnQwEwYDVR0l
// SIG // BAwwCgYIKwYBBQUHAwgwDQYJKoZIhvcNAQEFBQADggIB
// SIG // ABCXisNcA0Q23em0rXfbznlRTQGxLnRxW20ME6vOvnuP
// SIG // uC7UEqKMbWK4VwLLTiATUJndekDiV7uvWJoc4R0Bhqy7
// SIG // ePKL0Ow7Ae7ivo8KBciNSOLwUxXdT6uS5OeNatWAweaU
// SIG // 8gYvhQPpkSokInD79vzkeJkuDfcH4nC8GE6djmsKcpW4
// SIG // oTmcZy3FUQ7qYlw/FpiLID/iBxoy+cwxSnYxPStyC8jq
// SIG // cD3/hQoT38IKYY7w17gX606Lf8U1K16jv+u8fQtCe9RT
// SIG // ciHuMMq7eGVcWwEXChQO0toUmPU8uWZYsy0v5/mFhsxR
// SIG // VuidcJRsrDlM1PZ5v6oYemIp76KbKTQGdxpiyT0ebR+C
// SIG // 8AvHLLvPQ7Pl+ex9teOkqHQ1uE7FcSMSJnYLPFKMcVpG
// SIG // QxS8s7OwTWfIn0L/gHkhgJ4VMGboQhJeGsieIiHQQ+kr
// SIG // 6bv0SMws1NgygEwmKkgkX1rqVu+m3pmdyjpvvYEndAYR
// SIG // 7nYhv5uCwSdUtrFqPYmhdmG0bqETpr+qR/ASb/2KMmyy
// SIG // /t9RyIwjyWa9nR2HEmQCPS2vWY+45CHltbDKY7R4VAXU
// SIG // QS5QrJSwpXirs6CWdRrZkocTdSIvMqgIbqBbjCW/oO+E
// SIG // yiHW6x5PyZruSeD3AWVviQt9yGnI5m7qp5fOMSn/DsVb
// SIG // XNhNG6HY+i+ePy5VFmvJE6P9MYIEnDCCBJgCAQEwgZAw
// SIG // eTELMAkGA1UEBhMCVVMxEzARBgNVBAgTCldhc2hpbmd0
// SIG // b24xEDAOBgNVBAcTB1JlZG1vbmQxHjAcBgNVBAoTFU1p
// SIG // Y3Jvc29mdCBDb3Jwb3JhdGlvbjEjMCEGA1UEAxMaTWlj
// SIG // cm9zb2Z0IENvZGUgU2lnbmluZyBQQ0ECEzMAAACdHo0n
// SIG // rrjz2DgAAQAAAJ0wCQYFKw4DAhoFAKCBvjAZBgkqhkiG
// SIG // 9w0BCQMxDAYKKwYBBAGCNwIBBDAcBgorBgEEAYI3AgEL
// SIG // MQ4wDAYKKwYBBAGCNwIBFTAjBgkqhkiG9w0BCQQxFgQU
// SIG // x1akBvkUDdGjlbnjWeKW/NwfC0swXgYKKwYBBAGCNwIB
// SIG // DDFQME6gJoAkAE0AaQBjAHIAbwBzAG8AZgB0ACAATABl
// SIG // AGEAcgBuAGkAbgBnoSSAImh0dHA6Ly93d3cubWljcm9z
// SIG // b2Z0LmNvbS9sZWFybmluZyAwDQYJKoZIhvcNAQEBBQAE
// SIG // ggEAgtmRbonl60J/3fHzPQhfYuVU+fvE8CMbudagvWru
// SIG // x5tdMOnZoMY1IywBpaEq4MFEhoHhDwxL5hKqAQofZ78H
// SIG // wBl+NzyPMaATauIP9DIWKb3eFL8qUYsIoKgMw0BwYlt9
// SIG // 2BgNnNnjiHkyQPCZr6QtI8WUmJkIu0YAOsNqTjrtFlA/
// SIG // UkkclTIWIVAmhrGSBzx+GYcaXY4W89clNzed1gInKuDt
// SIG // 43G8NngFLszvgAfAMfPVwKSb4k62yICcC111uPiylxCH
// SIG // pUTh0oqtvs2GUXfJDnmKgmLiTeVwMHYgEnq7UG4RoBwm
// SIG // nfO7ZsgBDrigBm2w5i9cVfiUU1AzyxS2OD8WJKGCAh8w
// SIG // ggIbBgkqhkiG9w0BCQYxggIMMIICCAIBATCBhTB3MQsw
// SIG // CQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQ
// SIG // MA4GA1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9z
// SIG // b2Z0IENvcnBvcmF0aW9uMSEwHwYDVQQDExhNaWNyb3Nv
// SIG // ZnQgVGltZS1TdGFtcCBQQ0ECCmECjkIAAAAAAB8wCQYF
// SIG // Kw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0B
// SIG // BwEwHAYJKoZIhvcNAQkFMQ8XDTEyMTExNDIzNDQ1M1ow
// SIG // IwYJKoZIhvcNAQkEMRYEFAAY0THR9ZJFHRz/LbIm5Rt2
// SIG // zWJIMA0GCSqGSIb3DQEBBQUABIIBABfscaw4pFq6driP
// SIG // JVYp3JkXaGOm/c5R1wEWO3t8EDIoA5wKR0jADAHM888H
// SIG // wJrHmdwshofLJEfpmzJrUzynfPxckiNqHGFlzzwAd29p
// SIG // gs9BBmYy4EG8My4fwTBeTPLzTA6BHMKD4j/DBOoNrnRN
// SIG // j/wngrK03iDU5jWXz9C3JKcZ9rynuPp4raArwpnE4vFR
// SIG // uqXpUwq1z7cnaOAbl/mv43oszAUcGGvYHPRM1yW4UYnN
// SIG // MSBGWcIc52bgo3OL1mB6PFA0W2FWf9hB6gWBqUiy+EzF
// SIG // PSDvLzhFY2MtSURzPruBj+9xk03i4q4cGBbXeAasjJ5d
// SIG // 2TjAQfrWQ3qu7LQUvuQ=
// SIG // End signature block
| theglue99/Interface480 | Classcontent/Mod03/Labfiles/Starter/Exercise 1/ContosoConf/scripts/pages/schedule.js | JavaScript | gpl-3.0 | 13,966 |
/**
* Address
*
* @namespace core
* @author Georgi Popov
* @version 1.0.0
* @license http://www.gnu.org/licenses/gpl-3.0.en.html GPLv3
* @requires com/magadanski/core/core.js
* @requires com/magadanski/core/EventDispatcher.js
*/
define('com.magadanski.core.Address', function () {
var that;
// private properties
/**
* Root-relative address to the homepage
*
* This variable holds the path to the root of the application. In case it's in the root of the domain the default value of '/' will be used.
*
* In case the application is, however, in some subdirectory you'll need to overwrite this by passing an `aRoot` argument to the class constructor.
*
* @access private
* @inner
* @memberOf Address
* @type {string}
* @default
* @see Address
*/
var addressRoot = '/';
/**
* Copy of deep-linked address
*
* The property is not to be mistaken with the `window.location.hash` object (although it can contain it).
* This will not always appear with "#" but can also be set as any path.
*
* If you use `setHath('#hash')` this will essentially match the `window.location.hash` yet you can ommit the "#" symbol
* when calling the method.
*
* It gets updated through the `updateHash()` private method each time a `setHash()` call occurs.
*
* There is a `getHash()` getter and a `setHath()` setter to allow you to control the property.
*
* @access private
* @inner
* @memberOf Address
* @type {string}
* @see {@link Address#getHash|getHash}
* @see {@link Address#setHash|setHash}
*/
var hash = '';
/**
* Holder of a state property for HTML5 `history.pushState()`
*
* This will be updated when the `setHash()` method is used.
*
* You cannot directly set the value of `state` without calling `setHash()` but you can retrieve it with the `getState()` getter.
*
* @access private
* @inner
* @readonly
* @memberOf Address
* @type {string}
* @see {@link Address#getState|getState}
*/
var state = '';
// private methods
/**
* Auto handler of the `window.popstate` event
*
* @access private
* @inner
* @memberOf Address
* @param {Event} e The `popstate` event
* @return {void}
*/
function popStateHandler(e) {
updateHash();
state = e.state;
}
/**
* Stores the current hash as a property each time `setHash()` is called.
*
* @access private
* @inner
* @memberOf Address
* @return {void}
* @see {@link Address~hash|hash}
* @see {@link Address#setHash|setHash}
*/
function updateHash() {
hash = '/' + window.location.pathname.replace(addressRoot, '').replace(/^\//, '');
}
/**
* A helper class for working with browser history and push state. This should be used for deep linking.
*
* @class Address
* @since 1.0.0
* @extends {EventDispatcher}
* @param {string} aRoot The path to the main script on the server. Defult value is root: '/'.
* @fires {@link Address#change|change}
*/
var Address = function (aRoot) {
that = this;
if (typeof(aRoot) === 'string') {
addressRoot = aRoot;
}
// priviledged properties
// priviledged methods
/**
* Getter for {@link Address~hash|hash}
*
* @access public
* @instance
* @method getHash
* @memberof Address
* @return {string} The URL hash
* @see {@link Address~hash|hash}
* @see {@link Address#setHash|setHash}
*/
that.getHash = function () {
return hash;
}
/**
* Sets the URL hash, the title and allows for a custom state to be saved.
*
* This is an alias for `history.pushState` that also performs some internal class handling and event triggering.
*
* @access public
* @instance
* @method setHash
* @memberof Address
* @param {string} hash The new value that would be set for the hash
* @param {string} title The title argument to be passed to the history.pushstate function. As of February 8th, 2016 this is still simply ignored by all browsers.
* @param {object} state An object storing additional information for the state itself
* @see {@link Address~hash|hash}
* @see {@link Address#getHash|getHash}
*/
that.setHash = function (hash, title, state) {
var old = { hash: that.getHash(), state: that.getState() };
if (old.hash != hash) {
history.pushState(title, state, hash);
updateHash();
window.dispatchEvent(new PopStateEvent('popstate', { state: state }));
/**
* Event dispatched when the URL of the page changes.
*
* This is accompanied by a native window.popstate event.
*
* @event Address#change
* @type {Object}
* @property {string} previousHash The previous page {@link Address~hash|hash}
* @property {Object} previousState The previous page {@link Address~state|state}
*/
that.dispatchEvent('change', { previousHash: old.hash, previousState: old.state });
}
}
/**
* Getter for {@link Address~state|state}
*
* @access public
* @instance
* @method getState
* @memberof Address
* @return {object} The state object
* @see {@link Address#state~state}
* @see {@link Address#setHash|setHash}
*/
that.getState = function () {
return state;
}
// constructor
window.addEventListener('popstate', popStateHandler);
}
Address.inherits(com.magadanski.core.EventDispatcher);
com.magadanski.core.Address = Address;
// public methods
}); | magadanskiuchen/com.magadanski.core | Address.js | JavaScript | gpl-3.0 | 5,406 |
var searchData=
[
['rstc_5fisr',['rstc_isr',['../group__CM3__nvic__isrprototypes__SAM3U.html#ga956fd7cee38c7b56aa95b9eb69a58c4b',1,'nvic.h']]],
['rtc_5fisr',['rtc_isr',['../group__CM3__nvic__isrprototypes__SAM3U.html#ga0aac539d8cd80c163b7d986d10e53ced',1,'nvic.h']]],
['rtt_5fisr',['rtt_isr',['../group__CM3__nvic__isrprototypes__SAM3U.html#gadb3798184c4c941134a1db7eb5571eb5',1,'nvic.h']]]
];
| Aghosh993/TARS_codebase | libopencm3/doc/sam3u/html/search/functions_6.js | JavaScript | gpl-3.0 | 400 |
/*
Copyright (C) 2016 PencilBlue, LLC
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
//dependencies
var url = require('url');
module.exports = function TrinketMediaRendererModule(pb) {
//pb dependencies
var util = pb.util;
var BaseMediaRenderer = pb.media.renderers.BaseMediaRenderer;
/**
*
* @class TrinketMediaRenderer
* @constructor
*/
function TrinketMediaRenderer(){}
/**
* The media type supported by the provider
* @private
* @static
* @property TYPE
* @type {String}
*/
var TYPE = 'trinket';
/**
* Provides the styles used by each type of view
* @private
* @static
* @property STYLES
* @type {Object}
*/
var STYLES = Object.freeze({
view: {
width: "100%"
},
editor: {
width: "600px",
height: "400px"
},
post: {
width: "600px",
height: "400px"
}
});
/**
* Retrieves the supported extension types for the renderer.
* @static
* @method getSupportedExtensions
* @return {Array}
*/
TrinketMediaRenderer.getSupportedExtensions = function() {
return [];
};
/**
* Retrieves the style for the specified type of view
* @static
* @method getStyle
* @param {String} viewType The view type calling for a styling
* @return {Object} a hash of style properties
*/
TrinketMediaRenderer.getStyle = function(viewType) {
return STYLES[viewType] || STYLES.view;
};
/**
* Retrieves the supported media types as a hash.
* @static
* @method getSupportedTypes
* @return {Object}
*/
TrinketMediaRenderer.getSupportedTypes = function() {
var types = {};
types[TYPE] = true;
return types;
};
/**
* Retrieves the name of the renderer.
* @static
* @method getName
* @return {String}
*/
TrinketMediaRenderer.getName = function() {
return 'TrinketMediaRenderer';
};
/**
* Determines if the URL to a media object is supported by this renderer
* @static
* @method isSupported
* @param {String} urlStr
* @return {Boolean} TRUE if the URL is supported by the renderer, FALSE if not
*/
TrinketMediaRenderer.isSupported = function(urlStr) {
var details = url.parse(urlStr, true, true);
return TrinketMediaRenderer.isFullSite(details);
};
/**
* Indicates if the passed URL to a media resource points to the main website
* that provides the media represented by this media renderer
* @static
* @method isFullSite
* @param {Object|String} parsedUrl The URL string or URL object
* @return {Boolean} TRUE if URL points to the main domain and media resource, FALSE if not
*/
TrinketMediaRenderer.isFullSite = function(parsedUrl) {
if (util.isString(parsedUrl)) {
parsedUrl = url.parse(urlStr, true, true);
}
return parsedUrl.host && parsedUrl.host.indexOf('trinket.io') >= 0 && (parsedUrl.pathname.indexOf('/python/') === 0 || parsedUrl.pathname.indexOf('/embed/') === 0 || parsedUrl.pathname.indexOf('/library/trinkets/') === 0);
};
/**
* Gets the specific type of the media resource represented by the provided URL
* @static
* @method getType
* @param {String} urlStr
* @return {String}
*/
TrinketMediaRenderer.getType = function(urlStr) {
return TrinketMediaRenderer.isSupported(urlStr) ? TYPE : null;
}
/**
* Retrieves the Font Awesome icon class. It is safe to assume that the type
* provided will be a supported type by the renderer.
* @static
* @method getIcon
* @param {String} type
* @return {String}
*/
TrinketMediaRenderer.getIcon = function(type) {
return 'key fa-flip-horizontal';
};
/**
* Renders the media resource via the raw URL to the resource
* @static
* @method renderByUrl
* @param {String} urlStr
* @param {Object} [options]
* @param {Object} [options.attrs] A hash of all attributes (excluding style)
* that will be applied to the element generated by the rendering
* @param {Object} [options.style] A hash of all attributes that will be
* applied to the style of the element generated by the rendering.
* @param {Function} cb A callback where the first parameter is an Error if
* occurred and the second is the rendering of the media resource as a HTML
* formatted string
*/
TrinketMediaRenderer.renderByUrl = function(urlStr, options, cb) {
TrinketMediaRenderer.getMediaId(urlStr, function(err, mediaId) {
if (util.isError(err)) {
return cb(err);
}
TrinketMediaRenderer.render({location: mediaId}, options, cb);
});
};
/**
* Renders the media resource via the media descriptor object. It is only
* guaranteed that the "location" property will be available at the time of
* rendering.
* @static
* @method render
* @param {Object} media
* @param {String} media.location The unique resource identifier (only to the
* media type) for the media resource
* @param {Object} [options]
* @param {Object} [options.attrs] A hash of all attributes (excluding style)
* that will be applied to the element generated by the rendering
* @param {Object} [options.style] A hash of all attributes that will be
* applied to the style of the element generated by the rendering.
* @param {Function} cb A callback where the first parameter is an Error if
* occurred and the second is the rendering of the media resource as a HTML
* formatted string
*/
TrinketMediaRenderer.render = function(media, options, cb) {
if (util.isFunction(options)) {
cb = options;
options = {};
}
var embedUrl = TrinketMediaRenderer.getEmbedUrl(media.location);
cb(null, BaseMediaRenderer.renderIFrameEmbed(embedUrl, options.attrs, options.style));
};
/**
* Retrieves the source URI that will be used when generating the rendering
* @static
* @method getEmbedUrl
* @param {String} mediaId The unique (only to the type) media identifier
* @return {String} A properly formatted URI string that points to the resource
* represented by the media Id
*/
TrinketMediaRenderer.getEmbedUrl = function(mediaId) {
return mediaId.indexOf('http') === 0 ? mediaId : 'https://trinket.io/embed/python/' + mediaId;
};
/**
* Retrieves the unique identifier from the URL provided. The value should
* distinguish the media resource from the others of this type and provide
* insight on how to generate the embed URL.
* @static
* @method getMediaId
*/
TrinketMediaRenderer.getMediaId = function(urlStr, cb) {
var details = url.parse(urlStr, true, true);
var parts = details.pathname.split('/');
cb(null, parts[3]);
};
/**
* Retrieves any meta data about the media represented by the URL.
* @static
* @method getMeta
* @param {String} urlStr
* @param {Boolean} isFile indicates if the URL points to a file that was
* uploaded to the PB server
* @param {Function} cb A callback that provides an Error if occurred and an
* Object if meta was collected. NULL if no meta was collected
*/
TrinketMediaRenderer.getMeta = function(urlStr, isFile, cb) {
var details = url.parse(urlStr, true, true);
var meta = details.query;
cb(null, meta);
};
/**
* Retrieves a URI to a thumbnail for the media resource
* @static
* @method getThumbnail
* @param {String} urlStr
* @param {Function} cb A callback where the first parameter is an Error if
* occurred and the second is the URI string to the thumbnail. Empty string or
* NULL if no thumbnail is available
*/
TrinketMediaRenderer.getThumbnail = function(urlStr, cb) {
cb(null, '');
};
/**
* Retrieves the native URL for the media resource. This can be the raw page
* where it was found or a direct link to the content.
* @static
* @method getNativeUrl
*/
TrinketMediaRenderer.getNativeUrl = function(media) {
return 'http://trinket.io/python/' + media.location;
};
//exports
return TrinketMediaRenderer;
};
| v3rt1go/respiro | include/service/media/renderers/trinket_media_renderer.js | JavaScript | gpl-3.0 | 9,227 |
var classfr_1_1iessa_1_1dao_1_1trafic_1_1_trafic_dao_test =
[
[ "testCharger", "d6/dba/classfr_1_1iessa_1_1dao_1_1trafic_1_1_trafic_dao_test.html#a9954930a0797b788a6efc98512043fc6", null ],
[ "testChargerVolArr", "d6/dba/classfr_1_1iessa_1_1dao_1_1trafic_1_1_trafic_dao_test.html#acb7b5fecbe3bbc42f7695ffc5ffe1ad6", null ],
[ "testChargerVolDep", "d6/dba/classfr_1_1iessa_1_1dao_1_1trafic_1_1_trafic_dao_test.html#a6b76e65b783b038cea55af49eb92e176", null ]
]; | avaret/simuroul | doxydoc/html/d6/dba/classfr_1_1iessa_1_1dao_1_1trafic_1_1_trafic_dao_test.js | JavaScript | gpl-3.0 | 471 |
/**
*
* The Touch Action API provides the basis of all gestures that can be automated in Appium.
* It is currently only available to native apps and can not be used to interact with webapps.
* At its core is the ability to chain together _ad hoc_ individual actions, which will then be
* applied to an element in the application on the device. The basic actions that can be used are:
*
* - press (pass selector or (x,y) or both)
* - longPress (pass selector or (x,y) or both)
* - tap (pass selector or (x,y) or both)
* - moveTo (pass selector or (x,y) or both)
* - wait (pass ms (as milliseconds))
* - release (no arguments)
*
* If you use the touchAction command with a selector you don't need to pass the selector to each
* action. It will be propagated by the internally (if no x or y parameters are given).
*
* <example>
:touchAction.js
it('should do a touch gesture', function () {
var screen = $('//UITextbox');
// simple touch action on element
screen.touchAction('tap');
// same as
browser.touchAction('//UITextbox', 'tap')
// simple touch action using x y variables
browser.touchAction({
action: 'tap', x: 300, y:200
})
// simple touch action using selector and x y variables
// tap location is 30px right and 20px down relative from the center of the element
browser.touchAction({
action: 'tap', x: 30, y:20, selector: '//UIAApplication[1]/UIAElement[2]'
})
// multi action on an element (drag&drop)
screen.touchAction([
'press',
{ action: 'moveTo', x: 200, y: 0 },
'release'
])
// same as
browser.touchAction('//UITextbox', [
'press',
{ action: 'moveTo', x: 200, y: 0},
'release'
])
// multi action using x y variables
// moveTo location is relative from the starting coordinate
browser.touchAction([
{ action: 'press', x: 20, y: 550 },
{ action: 'moveTo', x: 0, y: -500},
'release'
])
// drag&drop to element
screen.touchAction([
'press',
{ action: 'moveTo', selector: '//UIAApplication[1]/UIAElement[2]' },
'release'
])
});
:multiTouchAction.js
it('should do a multitouch gesture', function () {
// drag&drop with two fingers 200px down
browser.touchAction([
[{action: 'press', x: 10, y: 10}, { action: 'moveTo', x: 0, y: 200 }, 'release'],
[{action: 'press', x: 100, y: 10}, { action: 'moveTo', x: 0, y: 200 }, 'release']
])
})
* </example>
*
* @param {String} selector selector to execute the touchAction on
* @param {String} action action to execute
*
* @see https://saucelabs.com/blog/appium-sauce-labs-bootcamp-chapter-2-touch-actions
* @type mobile
* @for android, ios
* @uses mobile/performTouchAction, mobile/performMultiAction
*
*/
const TOUCH_ACTIONS = ['press', 'longPress', 'tap', 'moveTo', 'wait', 'release']
const POS_ACTIONS = TOUCH_ACTIONS.slice(0, -2)
const ACCEPTED_OPTIONS = ['x', 'y', 'selector', 'element']
export default function touchAction (selector, actions) {
if (typeof selector !== 'string' || TOUCH_ACTIONS.indexOf(selector) > -1) {
actions = selector
selector = this.lastResult
}
if (!Array.isArray(actions)) {
actions = [actions]
}
/**
* check if multiAction
*/
if (Array.isArray(actions[0])) {
actions = formatArgs(selector, actions)
return Promise.all(getSelectors.call(this, actions, true)).then((jsonElements) => {
actions = replaceSelectorsById(actions, jsonElements)
return this.performMultiAction({ actions })
})
}
actions = formatArgs(selector, actions)
return Promise.all(getSelectors.call(this, actions)).then((jsonElements) => {
actions = replaceSelectorsById(actions, jsonElements)
return this.performTouchAction({ actions })
})
}
/**
* helper to determine if action has proper option arguments
* ('press', 'longPress', 'tap', 'moveTo' need at least some kind of position information)
* @param {String} action name of action
* @param {Object} options action options
* @return {Boolean} True if don't need any options or has a position option
*/
let hasValidActionOptions = function (action, options) {
return POS_ACTIONS.indexOf(action) < 0 || (POS_ACTIONS.indexOf(action) > -1 && Object.keys(options).length > 0)
}
let formatArgs = function (selector, actions) {
return actions.map((action) => {
if (Array.isArray(action)) {
return formatArgs(selector, action)
}
const formattedAction = { action: action.action, options: {} }
/**
* propagate selector or element to options object
*/
if (
selector &&
// selector is given as string `e.g. browser.touchAction(selector, 'tap')`
typeof selector === 'string' &&
// don't propagate for actions that don't require element options
POS_ACTIONS.indexOf(typeof action === 'string' ? action : formattedAction.action) > -1 &&
// don't propagate if user has x and y set
!(isFinite(action.x) && isFinite(action.y))
) {
formattedAction.options.selector = selector
} else if (
selector &&
// selector is given by previous command
// e.g. $(selector).touchAction('tap')
selector.value &&
// don't propagate for actions that don't require element options
POS_ACTIONS.indexOf(typeof action === 'string' ? action : formattedAction.action) > -1 &&
// don't propagate if user has x and y set
!(isFinite(action.x) && isFinite(action.y))
) {
formattedAction.options.element = selector.value.ELEMENT
}
if (typeof action === 'string') {
if (!hasValidActionOptions(action, formattedAction.options)) {
throw new Error(
`Touch action "${action}" doesn't have proper options. Make sure certain actions like ` +
`${POS_ACTIONS.join(', ')} have position options like "selector", "x" or "y".`
)
}
formattedAction.action = action
/**
* remove options property if empty
*/
if (Object.keys(formattedAction.options).length === 0) {
delete formattedAction.options
}
return formattedAction
}
if (isFinite(action.x)) formattedAction.options.x = action.x
if (isFinite(action.y)) formattedAction.options.y = action.y
if (action.ms) formattedAction.options.ms = action.ms
if (action.selector && POS_ACTIONS.indexOf(formattedAction.action) > -1) {
formattedAction.options.selector = action.selector
}
if (action.element) {
formattedAction.options.element = action.element
delete formattedAction.options.selector
}
/**
* remove options property if empty
*/
if (Object.keys(formattedAction.options).length === 0) {
delete formattedAction.options
}
/**
* option check
* make sure action has proper options before sending command to Appium
*/
if (formattedAction.action === 'release' && formattedAction.options) {
throw new Error(
'action "release" doesn\'t accept any options ' +
`("${Object.keys(formattedAction.options).join('", "')}" found)`
)
} else if (
formattedAction.action === 'wait' &&
(Object.keys(formattedAction.options).indexOf('x') > -1 || Object.keys(formattedAction.options).indexOf('y') > -1)
) {
throw new Error('action "wait" doesn\'t accept x, y options')
} else if (POS_ACTIONS.indexOf(formattedAction.action) > -1) {
for (const option in formattedAction.options) {
if (ACCEPTED_OPTIONS.indexOf(option) === -1) {
throw new Error(`action "${formattedAction.action}" doesn't accept "${option}" as option`)
}
}
if (Object.keys(formattedAction.options || {}).length === 0) {
throw new Error(
`Touch actions like "${formattedAction.action}" need at least some kind of ` +
'position information like "selector", "x" or "y" options, you\'ve none given.'
)
}
}
return formattedAction
})
}
let getSelectors = function (actions, isMultiAction = false) {
let queriedSelectors = []
/**
* flatten actions array
*/
if (isMultiAction) {
actions = [].concat.apply([], actions)
}
return actions
/**
* map down to list of selectors
*/
.map((action) => action.options && action.options.selector)
/**
* filter actions without selector and unique selectors
*/
.filter((selector) => {
const res = Boolean(selector) && queriedSelectors.indexOf(selector) === -1
queriedSelectors.push(selector)
return res
})
/**
* call element command on selectors
*/
.map((selector) => this.element(selector))
}
/**
* replaces selector action properties with element ids after they got fetched
* @param {Object[]} actions list of actions
* @param {Object[]} elements list of fetched elements
* @return {Object[]} list of actions with proper element ids
*/
let replaceSelectorsById = function (actions, elements) {
return actions.map((action) => {
if (Array.isArray(action)) {
return replaceSelectorsById(action, elements)
}
if (!action.options || !action.options.selector) {
return action
}
elements.forEach((element) => {
if (action.options.selector === element.selector) {
action.options.element = element.value.ELEMENT
delete action.options.selector
}
})
return action
})
}
| Cy6erlion/wharica | node_modules/webdriverio/lib/commands/touchAction.js | JavaScript | gpl-3.0 | 10,452 |
/**
* Created by burnualive on 10/12/14.
*/
var sel = 0;
var act_id;
var k = 0;
var team = [];
function t_ch(id)
{
if(id < 127)
{
return 1;
}
else if(id < 253)
{
return 2;
}
else if(id < 369)
{
return 3;
}
else
{
return 4;
}
}
function rem(id)
{
if(sel === 1)
{
document.getElementById("box" + id).style.display = 'none';
if(act_id.length > 2)
{
set_team(act_id[1] + act_id[2], id);
}
else
{
set_team(act_id[1], id);
}
console.log(team);
k++;
disp(id);
}
else
{
alert("Please select a position first.")
}
}
function disp(id)
{
var a, b;
var radio = document.getElementById(act_id);
var style = radio.style;
var li = document.createElement('li');
var name = document.getElementById("cn" + id).value;
li.style.cssText = radio.style.cssText;
li.style.width = "16%";
if(li.style.marginTop.length == 0)
{
a = li.style.marginLeft;
if(a.length > 2)
{
b = parseInt(a[0] + a[1]);
}
else
{
b = parseInt(a[0]);
}
b = b - 15;
a = b + '%';
li.style.marginLeft = a;
}
else
{
a = li.style.marginTop;
b = parseInt(a[0] + a[1]);
if(b > 10)
{
b = b - 10;
}
a = b + '%';
li.style.marginTop = a;
}
li.innerHTML = "<a href='javascript:ret(" + id + "," + act_id + ");' id='set" + act_id[1] + "' style='float: right;color:rgba(0,0,0,0.7);z-index:1001;font-size:70%;width:100%;text-align:right;'>X</a>" + "<p>" + name + "</p>";
li.id = act_id;
radio.parentNode.replaceChild(li, radio);
sel = 0;
}
function ret(id, li)
{
// alert(div.id[1]);
rem_team(li.id[1]);
k--;
document.getElementById("box" + id).style.display = 'block';
var a, b;
var radio = document.createElement('input');
radio.style.cssText = li.style.cssText;
radio.style.width = "auto";
if(radio.style.marginTop.length == 0)
{
a = radio.style.marginLeft;
if(a.length > 2)
{
b = parseInt(a[0] + a[1]);
}
else
{
b = parseInt(a[0]);
}
b = b + 15;
a = b + '%';
radio.style.marginLeft = a;
}
else
{
a = radio.style.marginTop;
b = parseInt(a[0] + a[1]);
if(b != 10)
{
b = b + 10;
}
a = b + '%';
radio.style.marginTop = a;
}
radio.name = "f";
radio.type = 'radio';
radio.id = li.id;
radio.setAttribute('onClick', 'active(this.id)');
li.parentNode.replaceChild(radio, li);
}
function active(act)
{
sel = 1;
act_id = act;
}
function form_check()
{
if(act_id[0] === 'a')
{
return 1;
}
else if(act_id[0] === 'b')
{
return 2;
}
else if(act_id[0] === 'c')
{
return 3;
}
else if(act_id[0] === 'd')
{
return 4;
}
else if(act_id[0] === 'e')
{
return 5;
}
else if(act_id[0] === 'f')
{
return 6;
}
else if(act_id[0] === 'g')
{
return 7;
}
}
function subm()
{
if(k < 11)
{
alert("Team not full");
}
else
{
var id;
for(var j = 1; j < 12; j++)
{
id = 't' + j;
document.getElementById(id).value = team[j - 1];
}
var num = form_check();
id = 't' + 12;
document.getElementById(id).value = num;
document.getElementById('form').action = "/home/getsquad";
document.getElementById('form').method = "post";
//document.getElementById('form').submit();
}
}
function clear_all()
{
var id = "set";
for(var i = 0; i < 11; i++)
{
id = "set" + i;
if(document.getElementById(id))
{
document.getElementById(id).click();
}
}
k = 0;
// document.getElementsByClassName('set').fireEvent('onClick');
}
function set_team(pos, id)
{
team[pos] = id;
}
function rem_team(pos)
{
team[pos] = 0;
} | adirola/RPL | public/javascript/rpl_formation.js | JavaScript | gpl-3.0 | 4,288 |
var crypto = require('crypto');
var db = require('./database');
function md5 (data) {
return crypto.createHash('md5').update(data).digest('hex');
}
module.exports = function (email, password, cb) {
var users = db.handle.collection('users');
users.findOne(
{
email: email,
$or: [
{
password: password,
password_cipher: { $exists: false }
},
{
password: md5(password),
password_cipher: 'md5'
}
]
},
function (err, user) {
if (err) {
console.error('database error:', err);
cb(err);
return;
}
if (user) {
cb(null, user);
}
else {
var err = new Error('Authentication failure: invalid email or password.');
err.user_presentable = true;
cb(err);
}
}
);
};
module.exports.create = function (email, password, name, cb) {
if (name === '') {
var err = new Error('Name must not be empty.');
err.user_presentable = true;
cb(err);
return;
}
if (email === '') {
var err = new Error('Email must not be empty.');
err.user_presentable = true;
cb(err);
return;
}
if (password.length < 4) {
var err = new Error('Password must have at least 4 characters.');
err.user_presentable = true;
cb(err);
return;
}
var users = db.handle.collection('users');
users.findOne(
{ email: email },
function (err, existing_user) {
if (err) {
cb(err);
return;
}
if (existing_user) {
var err = new Error('A user with this email address already exists in the database.');
err.user_presentable = true;
cb(err);
return;
}
else {
users.insert(
{
name: name,
email: email,
password: md5(password),
password_cipher: 'md5'
},
function (err) {
if (err) {
cb(err);
return;
}
cb(null);
}
);
}
}
);
};
| n2liquid/expressive | src/auth.js | JavaScript | gpl-3.0 | 1,846 |
/*
Copyright 2008,
Matthias Ehmann,
Michael Gerhaeuser,
Carsten Miller,
Bianca Valentin,
Alfred Wassermann,
Peter Wilfahrt
This file is part of JSXGraph.
JSXGraph is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
JSXGraph is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with JSXGraph. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* The FileReader object bundles the file input capabilities of JSXGraph.
*/
JXG.FileReader = {
/**
* Opens a file using the given URL and passes the contents to {@link JXG.FileReader#parseString}
* @param {String} url
* @param {JXG.Board|function} board Either a board or in case <tt>format</tt> equals 'raw' this has to be a callback function.
* @param {String} format The expected file format. Possible values are <dl>
* <dt>raw</dt><dd>Raw text file. In this case <tt>board</tt> has to be a callback function.</dd>
* <dt>geonext</dt><dd>Geonext File <a href="http://www.geonext.de">http://www.geonext.de</a></dd>
* <dt>intergeo</dt><dd>Intergeo file format <a href="http://www.i2geo.net">http://www.i2geo.net</a></dd>
* <dt>tracenpoche</dt><dd>Tracenpoche construction <a href="http://www.tracenpoche.net">http://www.tracenpoche.net</a></dd>
* <dt>graph</dt><dd>Graph file</dd>
* <dt>digraph</dt><dd>DiGraph file</dd>
* <dt>geogebra</dt><dd>Geogebra File <a href="http://www.geogebra.org">http://www.geogebra.org</a></dd>
* <dl><dt>cdy or cinderella</dt><dd>Cinderella (<a href="http://www.cinderella.de/">http://www.cinderella.de</a></dd>
* </dl>
* @param {Boolean} async Call ajax asynchonously.
*/
parseFileContent: function (url, board, format, async) {
var request = false;
if(!JXG.exists(async)) {
async = true;
}
//this.request = false;
try {
request = new XMLHttpRequest();
if(format.toLowerCase()=='raw') {
request.overrideMimeType('text/plain; charset=iso-8859-1');
} else {
request.overrideMimeType('text/xml; charset=iso-8859-1');
}
} catch (e) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
request = false;
}
}
}
if (!request) {
alert("AJAX not activated!");
return;
}
request.open("GET", url, async);
if(format.toLowerCase() === 'raw') {
this.cbp = function() {
var req = request;
if (req.readyState == 4) {
board(req.responseText);
}
};
} else {
this.cbp = function() {
var req = request;
if (req.readyState == 4) {
var text = '';
if (typeof req.responseStream!='undefined' &&
(req.responseText.slice(0,2) == "PK" // ZIP -> Geogebra
|| JXG.Util.asciiCharCodeAt(req.responseText.slice(0,1),0)==31) // gzip -> Cinderella
) {
text = JXG.Util.Base64.decode(BinFileReader(req)); // After this, text contains the base64 encoded, zip-compressed string
} else {
text = req.responseText;
}
this.parseString(text, board, format, false);
}
};
}
this.cb = JXG.bind(this.cbp, this);
request.onreadystatechange = this.cb;
try {
request.send(null);
} catch (e) {
throw new Error("JSXGraph: A problem occurred while trying to read '" + url + "'.");
}
},
/**
* Cleans out unneccessary whitespaces in a chunk of xml.
* @param {XMLElement} el
*/
cleanWhitespace: function (el) {
var cur = el.firstChild;
while (cur != null) {
if (cur.nodeType == 3 && !/\S/.test(cur.nodeValue)) {
el.removeChild( cur );
} else if ( cur.nodeType == 1 ) {
this.cleanWhitespace( cur );
}
cur = cur.nextSibling;
}
},
/**
* Converts a given string into a XML tree.
* @param {String} str
* @returns {XMLElement} The xml tree represented by the root node.
*/
stringToXMLTree: function (str) {
// The string "str" is converted into a XML tree.
if(typeof DOMParser === 'undefined') {
// IE workaround, since there is no DOMParser
DOMParser = function () {};
DOMParser.prototype.parseFromString = function (str, contentType) {
if (typeof ActiveXObject !== 'undefined') {
var d = new ActiveXObject('MSXML.DomDocument');
d.loadXML(str);
return d;
}
};
}
var parser = new DOMParser(),
tree = parser.parseFromString(str, 'text/xml');
this.cleanWhitespace(tree);
return tree;
},
/**
* Parses a given string according to the file format given in format.
* @param {String} str Contents of the file.
* @param {JXG.Board} board The board the construction in the file should be loaded in.
* @param {String} format Possible values are <dl>
* <dt>raw</dt><dd>Raw text file. In this case <tt>board</tt> has to be a callback function.</dd>
* <dt>geonext</dt><dd>Geonext File <a href="http://www.geonext.de">http://www.geonext.de</a></dd>
* <dt>intergeo</dt><dd>Intergeo file format <a href="http://www.i2geo.net">http://www.i2geo.net</a></dd>
* <dt>tracenpoche</dt><dd>Tracenpoche construction <a href="http://www.tracenpoche.net">http://www.tracenpoche.net</a></dd>
* <dt>graph</dt><dd>Graph file</dd>
* <dt>digraph</dt><dd>DiGraph file</dd>
* <dt>geogebra</dt><dd>Geogebra File <a href="http://www.geogebra.org">http://www.geogebra.org</a></dd>
* <dl><dt>cdy or cinderella</dt><dd>Cinderella (<a href="http://www.cinderella.de/">http://www.cinderella.de</a></dd>
* </dl>
* @param {Boolean} isString Some file formats can be given as Base64 encoded strings or as plain xml, in both cases
* they are given as strings. This flag is used to distinguish those cases: <tt>true</tt> means, it is given as a string,
* no need to un-Base64 and unzip the file.
*/
parseString: function (str, board, format, isString) {
var tree, graph, xml;
format = format.toLowerCase();
switch (format) {
case 'cdy':
case 'cinderella':
// if isString is true, str is the base64 encoded zip file, otherwise it's just the zip file
if(isString) {
str = JXG.Util.Base64.decode(str);
}
str = JXG.CinderellaReader.readCinderella(str, board);
board.xmlString = str;
break;
case 'tracenpoche':
board.xmlString = JXG.TracenpocheReader.readTracenpoche(str, board);
break;
case 'graph':
str = JXG.GraphReader.readGraph(str, board, false);
break;
case 'digraph':
str = JXG.GraphReader.readGraph(str, updateboard, true);
break;
case 'geonext':
// str is a string containing the XML code of the construction
str = JXG.GeonextReader.prepareString(str);
xml = true;
break;
case 'geogebra':
isString = str.slice(0, 2) !== "PK";
// if isString is true, str is a base64 encoded string, otherwise it's the zipped file
str = JXG.GeogebraReader.prepareString(str, isString);
xml = true;
break;
case 'intergeo':
if(isString) {
str = JXG.Util.Base64.decode(str);
}
str = JXG.IntergeoReader.prepareString(str);
xml = true;
break;
}
if (xml) {
board.xmlString = str;
tree = this.stringToXMLTree(str);
// Now, we can walk through the tree
this.readElements(tree, board, format);
}
},
/**
* Reading the elements of a geonext or geogebra file
* @param {} tree expects the content of the parsed geonext file returned by function parseFromString
* @param {Object} board board object
*/
readElements: function (tree, board, format) {
if (format.toLowerCase()=='geonext') {
board.suspendUpdate();
if(tree.getElementsByTagName('GEONEXT').length != 0) {
JXG.GeonextReader.readGeonext(tree, board);
}
board.unsuspendUpdate();
}
else if(tree.getElementsByTagName('geogebra').length != 0) {
JXG.GeogebraReader.readGeogebra(tree, board);
}
else if(format.toLowerCase()=='intergeo') {
JXG.IntergeoReader.readIntergeo(tree, board);
}
}
};
// The following code is vbscript. This is a workaround to enable binary data downloads via AJAX in
// Microsoft Internet Explorer.
if(/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
document.write('<script type="text/vbscript">\n\
Function Base64Encode(inData)\n\
Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"\n\
Dim cOut, sOut, I\n\
For I = 1 To LenB(inData) Step 3\n\
Dim nGroup, pOut, sGroup\n\
nGroup = &H10000 * AscB(MidB(inData, I, 1)) + _\n\
&H100 * MyASC(MidB(inData, I + 1, 1)) + MyASC(MidB(inData, I + 2, 1))\n\
nGroup = Oct(nGroup)\n\
nGroup = String(8 - Len(nGroup), "0") & nGroup\n\
pOut = Mid(Base64, CLng("&o" & Mid(nGroup, 1, 2)) + 1, 1) + _\n\
Mid(Base64, CLng("&o" & Mid(nGroup, 3, 2)) + 1, 1) + _\n\
Mid(Base64, CLng("&o" & Mid(nGroup, 5, 2)) + 1, 1) + _\n\
Mid(Base64, CLng("&o" & Mid(nGroup, 7, 2)) + 1, 1)\n\
sOut = sOut + pOut\n\
Next\n\
Select Case LenB(inData) Mod 3\n\
Case 1: \'8 bit final\n\
sOut = Left(sOut, Len(sOut) - 2) + "=="\n\
Case 2: \'16 bit final\n\
sOut = Left(sOut, Len(sOut) - 1) + "="\n\
End Select\n\
Base64Encode = sOut\n\
End Function\n\
\n\
Function MyASC(OneChar)\n\
If OneChar = "" Then MyASC = 0 Else MyASC = AscB(OneChar)\n\
End Function\n\
\n\
Function BinFileReader(xhr)\n\
Dim byteString\n\
Dim b64String\n\
Dim i\n\
byteString = xhr.responseBody\n\
ReDim byteArray(LenB(byteString))\n\
For i = 1 To LenB(byteString)\n\
byteArray(i-1) = AscB(MidB(byteString, i, 1))\n\
Next\n\
b64String = Base64Encode(byteString)\n\
BinFileReader = b64String\n\
End Function\n\
</script>\n');
}
| ecastro/moodle23ulpgc | lib/jsxgraph/src/FileReader.js | JavaScript | gpl-3.0 | 11,679 |
var ChatServer = require('./src/chat-server.js');
var ChatClient = require('./src/chat-client.js');
new ChatServer().start();
var client = new ChatClient();
client.connect('http://localhost:6000');
| AvagArakelyan/chat-server | index.js | JavaScript | gpl-3.0 | 202 |
var SsdpClient = require("node-ssdp").Client;
var UpnpClient = require('upnp-device-client');
var util = require("util");
var Q = require('q');
var EventEmitter = require("events").EventEmitter;
var log = require('loglevel');
var RaumfeldRenderer = require("./RaumfeldRenderer");
var RaumfeldVirtualRenderer = require("./RaumfeldVirtualRenderer");
var RaumfeldMediaServer = require("./RaumfeldMediaServer");
var VIRTUAL_RENDERER = "Virtual Media Player";
function RaumfeldManager() {
EventEmitter.call(this);
this.ssdpClient = new SsdpClient();
this.rendererType = "all";
var self = this;
this.ssdpClient.on('response', function (headers, statusCode, rinfo) {
self.createDevice(headers.LOCATION);
});
}
util.inherits(RaumfeldManager, EventEmitter);
RaumfeldManager.prototype.createDevice = function (url) {
var client = new UpnpClient(url);
var self = this;
var deferred = Q.defer();
client.getDeviceDescription(function (err, description) {
if (err) return deferred.reject(err);
if (description.manufacturer != "Raumfeld GmbH") {
return deferred.resolve(null);
}
log.debug("Discovered Raumfeld device: " + description.friendlyName);
switch (description.deviceType) {
case 'urn:schemas-upnp-org:device:MediaServer:1':
device = self.createMediaServer(client);
deferred.resolve(device);
break;
case 'urn:schemas-upnp-org:device:MediaRenderer:1':
if (description.modelDescription == VIRTUAL_RENDERER) {
if(self.rendererType == "all" || self.rendererType == "virtual") {
device = self.createVirtualRenderer(client);
deferred.resolve(device);
}
} else {
if(self.rendererType == "all" || self.rendererType == "real") {
device = self.createRenderer(client);
deferred.resolve(device);
}
}
break;
default:
log.info(
"Device " + description.friendlyName + " with type " + description.modelDescription + " is not implemented"
);
deferred.resolve(null);
break;
}
})
return deferred.promise;
}
RaumfeldManager.prototype.createVirtualRenderer = function (client) {
var device = new RaumfeldVirtualRenderer(client);
this.emit("rendererFound", device);
log.debug("Created renderer " + device.name);
return device;
}
RaumfeldManager.prototype.createRenderer = function (client) {
var device = new RaumfeldRenderer(client);
this.emit("rendererFound", device);
log.debug("Created renderer " + device.name);
return device;
}
RaumfeldManager.prototype.createMediaServer = function (client) {
var device = new RaumfeldMediaServer(client);
this.emit("mediaServerFound", device);
log.debug("Created media server");
return device;
}
RaumfeldManager.prototype.discover = function (rendererType, updateInterval) {
var self = this;
if(!rendererType) {
rendererType = "all";
}
this.rendererType = rendererType;
var sendDiscover = function() {
log.info("Discovering Raumfeld devices");
self.ssdpClient.search('urn:schemas-upnp-org:device:MediaServer:1');
self.ssdpClient.search('urn:schemas-upnp-org:device:MediaRenderer:1');
if(updateInterval > 0) {
setTimeout(sendDiscover, updateInterval);
}
}
sendDiscover();
}
module.exports = RaumfeldManager;
| dennis-hh/node-raumfeld | lib/RaumfeldManager.js | JavaScript | gpl-3.0 | 3,697 |
var assert = require("assert");
var Deudnunda = require("../deudnunda.js");
var test = function(iter, test_set) {
this.test_set = test_set;
this.iter_cnt = parseInt(iter) - 1;
this.run = function() {
var self = this;
describe('TEST' + iter, function() {
it('CASE : ' + self.test_set, function(done) {
var deudnunda = new Deudnunda('/python_sources/malhandaNLP.py', self.test_set);
deudnunda.py_nlp.on('message', function(message) {
deudnunda.nlp_reslut = message;
});
deudnunda.py_nlp.end(function (err) {
if (err) throw err;
console.log('KoNLPy result : ' + deudnunda.nlp_reslut);
describe('Method test :: ', function() {
test_splitPythonList(deudnunda);
test_getKeyMorpheme(deudnunda);
test_makeCommand(deudnunda);
});
done();
});
}).timeout(5000);
});
};
var test_splitPythonList = function(deudnunda) {
it('splitPythonList() method', function() {
/*
// Mecab result
var expect = [
[ {"morpheme" : "티비","type" : "NNG"}, {"morpheme" : "켜","type" : "VV"},{"morpheme" : "줘","type" : "EC+VV+EC"} ],
[ {"morpheme" : "전등","type" : "NNG"}, {"morpheme" : "꺼주","type" : "VV"},{"morpheme" : "지","type" : "EC"},
{"morpheme" : "않","type" : "VX"}, {"morpheme" : "겠","type" : "EP"},{"morpheme" : "니","type" : "EC"} ],
[ {"morpheme" : "에어컨","type" : "NNG"}, {"morpheme" : "온도","type" : "NNG"},{"morpheme" : "낮춰","type" : "VV+EC"},
{"morpheme" : "줘","type" : "VX+EC"} ]
];
*/
// Twitter result
var expect = [
[ {"morpheme" : "티비","type" : "Noun"}, {"morpheme" : "켜","type" : "Verb"},{"morpheme" : "줘","type" : "Eomi"} ],
[ {"morpheme":"전등","type":"Noun"},{"morpheme":"꺼","type":"Verb"},{"morpheme":"주","type":"PreEomi"},{"morpheme":"지","type":"Eomi"},{"morpheme":"않겠","type":"Verb"},{"morpheme":"니","type":"Eomi"} ],
[ {"morpheme":"에어컨","type":"Noun"},{"morpheme":"온도","type":"Noun"},{"morpheme":"낮춰","type":"Verb"},{"morpheme":"줘","type":"Eomi"} ]
];
var actual = deudnunda.splitPythonList();
do_assert(actual, expect);
});
};
var test_getKeyMorpheme = function(deudnunda) {
it('getKeyMorpheme() method', function() {
// Mecab result
/*var expect = [
{"noun" : ["티비"],"verb" : "켜"},
{"noun" : ["전등"],"verb" : "꺼주"},
{"noun" : ["에어컨", "온도"],"verb" : "낮춰"}
];*/
var expect = [
{"noun" : ["티비"],"verb" : "켜"},
{"noun" : ["전등"],"verb" : "꺼"},
{"noun" : ["에어컨", "온도"],"verb" : "낮춰"}
];
var actual = deudnunda.getKeyMorpheme(deudnunda.splitPythonList());
do_assert(actual, expect);
});
};
var test_makeCommand = function(deudnunda) {
it('makeCommand() method', function() {
var expect = [
{"target" : "티비","operation" : "ON","motion":"POWER"},
{"target" : "전등","operation" : "OFF","motion":"POWER"},
{"target" : "에어컨","operation" : "DOWN","motion":""}
];
var key_mor = deudnunda.getKeyMorpheme(deudnunda.splitPythonList());
var actual = deudnunda.makeCommand(key_mor);
do_assert(actual, expect);
});
};
var do_assert = function(actual, expect) {
console.log(expect[iter - 1]);
assert.equal(
JSON.stringify(expect[iter - 1]),
JSON.stringify(actual)
);
};
};
var test_set = ["티비 켜줘", "전등 꺼주지 않겠니", "에어컨 온도 낮춰줘"];
for(var i in test_set) {
var t = new test(parseInt(i) + 1, test_set[i]);
t.run();
} | Ajou-masinda/RPi-Node | unit_test/deudnunda_test.js | JavaScript | gpl-3.0 | 3,706 |
/*
Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'forms', 'ja', {
button: {
title: 'ボタン プロパティ',
text: 'テキスト (値)',
type: 'タイプ',
typeBtn: 'ボタン',
typeSbm: '送信',
typeRst: 'リセット'
},
checkboxAndRadio: {
checkboxTitle: 'チェックボックス プロパティ',
radioTitle: 'ラジオボタン プロパティ',
value: '値',
selected: '選択済み'
},
form: {
title: 'フォーム プロパティ',
menu: 'フォーム プロパティ',
action: 'アクション',
method: 'メソッド',
encoding: 'エンコーディング'
},
hidden: {
title: '不可視フィールド プロパティ',
name: '名前',
value: '値'
},
select: {
title: '選択フィールド プロパティ',
selectInfo: '情報',
opAvail: '利用可能なオプション',
value: '選択項目値',
size: 'サイズ',
lines: '行',
chkMulti: '複数項目選択を許可',
opText: '選択項目名',
opValue: '値',
btnAdd: '追加',
btnModify: '編集',
btnUp: '上へ',
btnDown: '下へ',
btnSetValue: '選択した値を設定',
btnDelete: '削除'
},
textarea: {
title: 'テキストエリア プロパティ',
cols: '列',
rows: '行'
},
textfield: {
title: '1行テキスト プロパティ',
name: '名前',
value: '値',
charWidth: 'サイズ',
maxChars: '最大長',
type: 'タイプ',
typeText: 'テキスト',
typePass: 'パスワード入力'
}
});
| tsmaryka/hitc | public/javascripts/ckeditor/plugins/forms/lang/ja.js | JavaScript | gpl-3.0 | 1,607 |
import { dict } from './../../actions'
const {SET_ALL_FRAMES} = dict
const initialState = {
frameList: []
}
const setAllFrames = (state = initialState, action) => {
switch (action.type) {
case SET_ALL_FRAMES:
return Object.assign({}, state, {
frameList: action.payload
});
default:
return state;
}
}
export default setAllFrames | golemfactory/golem-electron | src/reducers/frame/all.js | JavaScript | gpl-3.0 | 389 |
"use strict";
/**
* Tag
* @description :: Model for storing Tag records
*/
var shortId = require('shortid');
var slug = require('slug');
module.exports = {
schema: true,
attributes: {
id: {
type: 'string',
unique: true,
index: true,
defaultsTo: shortId.generate,
primaryKey: true,
size: 15
},
name: {
type: 'string',
required: true,
unique: true,
size: 100,
minLength: 1
},
slug: {
unique: true,
type: 'string'
},
files: {
collection: 'file',
via: 'tags'
},
datasets: {
collection: 'dataset',
via: 'tags'
},
createdBy: {
model: 'user',
required: true
},
toJSON() {
return this.toObject();
}
},
searchables: ['name'],
beforeUpdate: (values, next) => {
if (values.name) {
values.slug = slug(values.name, {
lower: true
});
}
next()
},
beforeCreate: (values, next) => {
if (values.name) {
values.slug = slug(values.name, {
lower: true
});
}
next()
}
};
| gcba-odin/odin | api/models/Tag.js | JavaScript | gpl-3.0 | 1,371 |
"use strict";
const logger = require("../../logwrapper");
const twitchApi = require("../api");
/**
* @typedef TwitchCategory
* @property {string} id - The ID of this category
* @property {string} name - The name of this category
* @property {string} boxArtUrl - The box art or cover image url of this category
*/
/**
* @param {import("@twurple/api").HelixGame} category
* @param {string} size
* @returns {TwitchCategory}
* */
const mapTwitchCategory = (category, size) => {
const mappedCategory = {
id: category.id,
name: category.name,
boxArtUrl: ""
};
if (category.box_art_url) {
mappedCategory.boxArtUrl = category.box_art_url.replace("{width}x{height}", size);
} else {
mappedCategory.boxArtUrl = category.boxArtUrl.replace("{width}x{height}", size);
}
return mappedCategory;
};
/**
* @param {string} categoryId
* @param {string} [size]
* @returns {Promise.<TwitchCategory>}
*/
const getCategoryById = async (categoryId, size = "285x380") => {
const client = twitchApi.getClient();
try {
const category = await client.games.getGameById(categoryId);
if (category == null) return null;
return mapTwitchCategory(category, size);
} catch (error) {
logger.error("Failed to get twitch category", error);
return null;
}
};
/**
* @param {string} categoryName
* @returns {Promise.<TwitchCategory[]>}
*/
const searchCategories = async (categoryName) => {
const client = twitchApi.getClient();
let categories = [];
try {
const response = await client.search.searchCategories(categoryName);
if (response && response.data) {
categories = response.data;
}
} catch (err) {
logger.error("Failed to search twitch categories", err);
}
return categories.map(c => mapTwitchCategory(c));
};
exports.getCategoryById = getCategoryById;
exports.searchCategories = searchCategories; | Firebottle/Firebot | backend/twitch-api/resource/categories.js | JavaScript | gpl-3.0 | 1,974 |
const Command = require('./command');
const openWeather = require('openweather-apis');
const promisify = require('es6-promisify');
const googleMapsClient = require('@google/maps').createClient({
key: process.env.GOOGLE_MAPS_KEY
});
//Set up weather
openWeather.setLang('en');
openWeather.setUnits('imperial');
openWeather.setAPPID(process.env.WEATHER_KEY);
const simplifyWeather = (description, code) => {
const simple = description.replace(/\b\w/g, l => l.toUpperCase());
switch (code) {
case 800:
return simple + ' :sunny:';
break;
case 801:
case 802:
case 803:
case 804:
return simple + ' :white_sun_cloud:';
case 900:
return simple + ' :cloud_tornado:';
break;
case 901:
case 902:
return simple + ' :cyclone:';
break;
case 906:
return simple + ' :snowflake:';
default:
break;
}
if(code >= 700) {
return simple + ' :fog:';
} else if(code >= 600) {
return simple + ' :cloud_snow:';
} else if(code >= 500) {
return simple + ' :cloud_rain:';
} else if(code >= 300) {
return simple + ' :white_sun_rain_cloud:';
} else {
return simple + ' :thunder_cloud_rain:';
}
return simple;
};
class Weather extends Command {
constructor(cmd, params) {
super(cmd, params, '!fetch weather <address> Get current weather')
}
async runCommand() {
// Check if there are params
if(this.params.length <= 0)
return "I need an address, city, or zip code to get you the weather :sunny:"
// Geocode an address.
// Promisifying it
const geocode = promisify(googleMapsClient.geocode, googleMapsClient);
const response = await geocode({ address: this.params.join(' ') }).catch(err => {
return "It seems I can't find location"
});
if(response.json.status === 'ZERO_RESULTS')
return "It looks I can't find that particular location :dog:"
const lat = response.json.results[0].geometry.location.lat;
const lng = response.json.results[0].geometry.location.lng;
openWeather.setCoordinate(lat,lng);
const getSmartJSON = promisify(openWeather.getSmartJSON, openWeather);
const getWeatherForecastForDays = promisify(openWeather.getWeatherForecastForDays, openWeather);
const smartPromise = getSmartJSON();
const forecastPromise = getWeatherForecastForDays(2);
const [smart, forecast] = await Promise.all([smartPromise, forecastPromise]).catch(err => console.error(err));
const currentInfo = simplifyWeather(smart.description,smart.weathercode);
const todayForecast = simplifyWeather(forecast.list[0].weather[0].description, forecast.list[0].weather[0].id);
const tomorrowForecast = simplifyWeather(forecast.list[1].weather[0].description, forecast.list[1].weather[0].id);
return `**The current weather in *${forecast.city.name}*:** ${smart.temp}° F, ${currentInfo}\n\n**Today's forecast:**\n\t__High:__ ${forecast.list[0].temp.max}° F\n\t__Low:__ ${forecast.list[0].temp.min}\n\t__Weather:__ ${todayForecast}\n\n**Tomorrow's Forecast:**\n\t__High:__ ${forecast.list[1].temp.max}° F\n\t__Low:__ ${forecast.list[1].temp.min}\n\t__Weather:__ ${tomorrowForecast}`;
}
}
module.exports = Weather; | moondog94/fido-bot | commands/weather.js | JavaScript | gpl-3.0 | 3,096 |
angular
.module('myApp')
.config(function($stateProvider, $urlRouterProvider){
$stateProvider
.state('home', {
url: '/home',
templateUrl: 'views/home.html',
controller: 'MainCtrl'
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'AuthCtrl',
onEnter: function(Auth, $state){
Auth.currentUser().then(function(){
$state.go('home')
})
}
})
.state('register', {
url: '/register',
templateUrl: 'views/register.html',
controller: 'AuthCtrl',
onEnter: function(Auth, $state){
Auth.currentUser().then(function(){
$state.go('home')
})
}
})
.state('welcome', {
url: '/welcome',
templateUrl: 'views/new_profile.html',
controller: 'AccountCtrl'
})
.state('songs', {
url: '/songs',
templateUrl: 'views/songs.html',
controller: 'SongsCtrl'
})
//.state('songs.show', {
// url: '/:id',
// templateUrl: 'views/song.html',
// controller: 'SongsCtrl',
// resolve: {
// song: function ($stateParams, SongsService) {
// return SongsService.getSong($stateParams.id);
// }
// }
//})
.state('settings', {
url: '/settings',
templateUrl: 'views/settings.html',
controller: 'AccountCtrl'
})
.state('settings.profile', {
url: '/profile',
templateUrl: 'views/settings/profile.html',
controller: 'AccountCtrl'
})
.state('settings.deactivate', {
url: '/deactivate',
templateUrl: 'views/settings/deleteProfile.html',
controller: 'AccountCtrl'
})
$urlRouterProvider.otherwise('/home')
}) | ThisIsTyDell/sound-genie | app/assets/javascripts/routes.js | JavaScript | gpl-3.0 | 1,862 |
if (!String.prototype.format) {
String.prototype.format = function() {
var txt = this;
for (var i = 0; i < arguments.length; i++) {
var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
txt = txt.replace(exp, arguments[i]);
}
return txt;
};
}
if (!String.format) {
String.format = function() {
for (var i = 1; i < arguments.length; i++) {
var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
arguments[0] = arguments[0].replace(exp, arguments[i]);
}
return arguments[0];
};
}
| jweyrich/livemgr-webui | media/js/lib/string.format.js | JavaScript | gpl-3.0 | 502 |
var Sequelize = require('sequelize');
var sequelize = CONFIG.database;
var %%model_name%% = sequelize.define('%%model%%', {
%%model_attrs%%
}, {
freezeTableName: true // Model tableName will be the same as the model name
});
module.exports = %%model_name%%;
| nodeontrain/trainjs | template/scaffold/app/models/model.js | JavaScript | gpl-3.0 | 261 |
CKEDITOR.plugins.setLang("sourcearea","sr-latn",{toolbar:"Kôd"}); | babbling-brook/streambed | js/resources/ckeditor/release/plugins/sourcearea/lang/sr-latn.js | JavaScript | gpl-3.0 | 69 |
import React, { Component } from 'react';
export default class ErrorCC extends Component {
constructor(props) {
super(props);
}
render() {
var content;
if (this.state.submitted) {
content = (
<div className="col-md-12">
<h1>Zahlung erfolgreich abgeschlossen!</h1>
Vielen Dank für deine Spende!
</div>
);
} else {
content = '';
}
return (
<div className="container paddingTopBottom15">
<div className="row paymentPage">Ein Fehler ist aufgetreten</div>
</div>
);
}
}
/* vim: set softtabstop=2:shiftwidth=2:expandtab */
| Dica-Developer/weplantaforest | ui/src/js/payment/ErrorCC.js | JavaScript | gpl-3.0 | 632 |
var ENDPOINT = 'http://localhost:5000';
var editor;
function updateSuggestions(result) {
console.log('Update suggestions, sailor');
}
function pushToServer() {
$.ajax({
url: ENDPOINT + '/suggestions',
type: 'POST',
data: JSON.stringify({text: editor.getText()}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: updateSuggestions
});
}
$(document).ready(function () {
var pushToServerTimer;
editor = new Quill('#editor', {
theme: 'snow'
});
editor.addModule('toolbar', {
container: '#toolbar' // Selector for toolbar container
});
editor.on('text-change', function (){
console.log('tetchange');
if (typeof(pushToServerTimer) === 'undefined') {
pushToServerTimer = window.setTimeout(pushToServer, 1000);
} else {
window.clearTimeout(pushToServerTimer);
pushToServerTimer = window.setTimeout(pushToServer, 1000);
}
});
});
| davidlandry93/cs-games-longrun | client/js/scripts.js | JavaScript | gpl-3.0 | 1,033 |
import React, { Component } from 'react';
import Tools from './tools/Tools';
export default class ToolsPage extends Component {
constructor(props) {
super(props);
this.state = {
user: {},
pageCount: 0
};
}
render() {
var that = this;
var toolsPart;
var page = this.state.pageCount;
toolsPart = <Tools />;
return <div className="container paddingTopBottom15">{toolsPart}</div>;
}
}
| Dica-Developer/weplantaforest | ui/src/js/profile/ToolsPage.js | JavaScript | gpl-3.0 | 437 |
import { connect} from 'react-redux';
import { bindActionCreators } from 'redux';
import * as commerceActionCreators from '../actions/index.es6.js';
import CommercesFilter from '../components/CommercesFilter.es6.jsx';
const mapStateToProps = (state) => {
return {
commerces: state.commerces
}
};
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(Object.assign({}, commerceActionCreators), dispatch)
};
}
const CommercesFilterContainer = connect(
mapStateToProps,
mapDispatchToProps
)(CommercesFilter);
export default CommercesFilterContainer;
| manufarfaro/jebri-sample | app/assets/javascripts/containers/CommercesFilterContainer.js | JavaScript | gpl-3.0 | 614 |
import ServiceReducer from './ServiceReducer'
class GenericServiceReducer extends ServiceReducer {
/* **************************************************************************/
// Class
/* **************************************************************************/
static get name () { return 'GenericServiceReducer' }
/* **************************************************************************/
// Avatar
/* **************************************************************************/
/**
* Sets the page favicons as the avatar
* @param service: the service to update
* @param favicons: the list of favicons
* @param touchIcons: the list of touch icons
*/
static setPageFaviconAvatar (service, favicons, touchIcons) {
if ((favicons === undefined || favicons.length === 0) && (touchIcons === undefined || touchIcons.length === 0)) {
return service.changeData({ serviceAvatarURL: null })
} else {
// Use the touch icon over the favicon as it's normally larger
const validTouchIcons = (touchIcons || [])
.filter((f) => f.split('?')[0].endsWith('.png'))
if (validTouchIcons.length) {
return service.changeData({ serviceAvatarURL: validTouchIcons.slice(-1)[0] })
}
const validFavicons = (favicons || [])
.map((f) => f.endsWith('/') ? f.substr(0, f.length - 1) : f) // Electron sometimes gives a trailing slash :-/
.filter((f) => { // some websites send junk
const base = f.split('?')[0]
return base.endsWith('.png') || base.endsWith('.ico') || base.endsWith('.jpg') || base.endsWith('.gif')
})
if (validFavicons.length) {
const bestFavicon = validFavicons.find((f) => f.endsWith('.ico')) || favicons.slice(-1)[0]
return service.changeData({ serviceAvatarURL: bestFavicon })
} else {
return service.changeData({ serviceAvatarURL: null })
}
}
}
/* **************************************************************************/
// Settings
/* **************************************************************************/
/**
* Updates the url for the service
* @param service: the service to update
* @param url: the url to set
*/
static setUrl (service, url) {
return service.changeData({ url: url })
}
/**
* Updates the setting to show adaptor data
* @param service: the service to update
* @param supports: true to supports, false otherwise
*/
static setSupportsWBGAPI (service, supports) {
return service.changeData({ supportsWBGAPI: supports })
}
/**
* Sets whether to use the page title as the display name or not
* @param service: the service to update
* @param use: true to use, false otherwise
*/
static setUsePageTitleAsDisplayName (service, use) {
return service.changeData({ usePageTitleAsDisplayName: use })
}
/**
* Sets whether to use the page theme as the color or not
* @param service: the service to update
* @param use: true to use, false otherwise
*/
static setUsePageThemeAsColor (service, use) {
return service.changeData({ usePageThemeAsColor: use })
}
}
export default GenericServiceReducer
| wavebox/waveboxapp | classic/src/shared/AltStores/Account/ServiceReducers/GenericServiceReducer.js | JavaScript | mpl-2.0 | 3,173 |
/*global restyle */
/*global Draggabilly */
'use strict';
var utils = require('../lib/utils');
var selector = require('../lib/selector');
var tagName = 'z-block';
var htmlTemplate = `
<div class="ports-container inputs">
<content select="z-port.input"></content>
</div>
<div id="main">
<div class="content-container">
<content></content>
</div>
<span class="block-key">a</span>
</div>
<div class="ports-container outputs">
<content select="z-port.output"></content>
</div>
`;
var template = utils.dom.createFragment(htmlTemplate);
var cssAsJson = {
// The following will apply to the root DOM element of the custom
// element.
'': {
// By default custom elements are inline elements. Current element
// has its own height and width and can be insterted in a text
// flow. So we need a 'display: inline-block' style. Moreover, this
// is needed as a workaround for a bug in Draggabilly (which only
// works on block elements, not on inline ones).
'display': 'inline-block',
'position': 'absolute'
},
'#main': {
'background': 'rgba(1, 1, 1, 0)',
'border-left': '3px solid',
'border-left-color': 'rgba(1, 1, 1, 0)',
'border-right': '3px solid',
'border-right-color': 'rgba(1, 1, 1, 0)'
},
'.content-container': {
'background': 'white',
'border': '1px solid #e1e8ed',
'border-radius': 2,
'overflow': 'hidden'
},
'.content-container > script': {
'padding': '4px 8px 2px 8px'
},
'.content-container > span': {
'padding': '4px 8px 2px 8px'
},
'.content-container > div': {
'padding': '4px 8px 2px 8px'
},
'.ports-container': {
'padding': 0,
'minHeight': 2,
'overflow': 'visible'
},
'.ports-container z-port': {
'float': 'left',
'marginLeft': 8,
'marginRight': 8
},
'span.block-key': {
'font-size': 11,
'color': '#444',
'position': 'absolute',
'bottom': 3,
'right': 3,
'padding-right': 3,
'padding-left': 3,
'background': '#fff'
},
'z-port.input .port-key': {
'top': -3
},
'z-port.output .port-key': {
'bottom': -3
}
};
// Apply the css definition and prepending the custom element tag to all
// CSS selectors.
var style = restyle(tagName, cssAsJson);
var redraw = function (block) {
var ports = block.querySelectorAll('z-port');
[].forEach.call(ports, function (port) {
port.redraw();
});
};
var makeItDraggable = function (block) {
block.draggie = new Draggabilly(block, {
});
block.draggie.externalAnimate = function () {
redraw(block);
};
block.draggie.on('staticClick', function (event) {
// TODO depends on the port's DOM wich might change.
if (event.target.parentNode.tagName === 'Z-PORT') {
// In that case we have clicked on the "selector" of a port and the
// action is to select it and not to do something with the block.
return;
}
// TODO don't use globals
window.setCurrentBlock(block);
window.app.commands.editBlock(block);
});
};
var properties = {
createdCallback: {value: function() {
// At the beginning the light DOM is stored in the current element.
var lightDom = this;
// Start composed DOM with a copy of the template
var composedDom = template.cloneNode(true);
// Then progressively move elements from light to composed DOM based on
// selectors on light DOM and fill <content> tags in composed DOM with
// them.
['z-port.input', 'z-port.output', ''].forEach(function(selector) {
utils.dom.move({
from: lightDom, withSelector: selector,
to: composedDom, onTag: 'content'
});
});
// At this stage composed DOM is completed and light DOM is empty (i.e.
// 'this' has no children). Composed DOM is set as the content of the
// current element.
this.appendChild(composedDom);
this.hideKey();
var that = this;
var ports = that.querySelectorAll('z-port');
[].forEach.call(ports, function(port) {
port.block = that;
});
this.content = this.querySelector('.ze-content');
this.redraw = redraw.bind(null, this);
selector.setSelectable(this, true);
}},
attachedCallback: {value: function() {
// TODO bug in chrome or in webreflection polyfill. If makeItDraggable
// is called in createdCallback then Draggabily adds a
// 'position:relative' because the css style of block that set
// position to absolute has not been applied yet (with chrome). With
// WebReflection's polyfill the style is applied so Draggabilly doesn't
// change position. Why a different behaviour? Which is wrong ? Chrome,
// webreflection or the spec? Maybe we can try with polymer polyfill.
makeItDraggable(this);
}},
unplug: {value: function() {
var ports = this.querySelectorAll('z-port');
[].forEach.call(ports, function (port) {
port.unplug();
});
}},
addPort: {value: function (htmlString) {
var fragment = utils.dom.createFragment(htmlString);
var port = fragment.firstChild;
port.block = this;
if (port.classList.contains('input')) {
var portContainer = this.querySelector('.ports-container.inputs');
portContainer.appendChild(fragment);
} else if (port.classList.contains('output')) {
var portContainer = this.querySelector('.ports-container.outputs');
portContainer.appendChild(fragment);
}
return port;
}},
keyElement: {
get: function () {
return this.querySelector('span.block-key');
}
},
key: {
set: function (value) {
this.keyElement.innerHTML = value;
}
},
showKey: {value: function () {
this.keyElement.style.visibility = 'visible';
}},
hideKey: {value: function () {
this.keyElement.style.visibility = 'hidden';
}},
ports: {
get: function () {
return {
'out': this.querySelector('z-port.output'),
'inputs': this.querySelectorAll('z-port.input'),
'outputs': this.querySelectorAll('z-port.output')
};
}
},
draggable: {
set: function(value) {
if (value) {
this.draggie.enable();
} else {
this.draggie.disable();
}
}
},
contentInnerHTML: {
get: function () {
return this.querySelector('.content-container').innerHTML;
},
set: function (string) {
this.querySelector('.content-container').innerHTML = string;
this.content = this.querySelector('.ze-content');
}
}
};
var proto = Object.create(HTMLElement.prototype, properties);
proto.css = style;
document.registerElement(tagName, {prototype: proto});
// TODO clean globals
window.getElementBlock = function (element) {
// TODO do a search to find the first parent block for cases where
// element is down in the element hiearchy.
var maybeBlock = element.parentNode.parentNode.parentNode;
var block;
if (maybeBlock.tagName === 'Z-BLOCK') {
block = maybeBlock;
} else {
block = element.phantomedBy.parentNode.parentNode.parentNode;
}
return block;
};
| nnodot/zed | webcomponents/z-block.js | JavaScript | mpl-2.0 | 7,789 |
angular
.module('webmakerApp')
.controller('navigationController', ['$scope', '$location', '$routeParams', '$rootScope', 'weblit', 'wmNav', 'CONFIG',
function ($scope, $location, $routeParams, $rootScope, weblit, wmNav, config) {
// Nav data
$scope.nav = wmNav.nav;
// User urls
$scope.accountSettingsUrl = config.accountSettingsUrl;
$scope.eventsUrl = config.eventsUrl;
$scope.teachUrl = config.teachUrl;
// Start with collapsed state for navigation
$scope.primaryCollapse = true;
$scope.secondaryCollapse = true;
$scope.tertiaryCollapse = true;
$scope.mobileCollapse = true;
$scope.collapseToggle = function () {
$scope.primaryCollapse = !$scope.primaryCollapse;
$scope.secondaryCollapse = !$scope.secondaryCollapse;
$scope.tertiaryCollapse = !$scope.tertiaryCollapse;
};
$scope.weblitToggle = function () {
$scope.mobileCollapse = !$scope.mobileCollapse;
};
$rootScope.$on('$locationChangeSuccess', function (event) {
$scope.primaryCollapse = true;
$scope.secondaryCollapse = true;
$scope.tertiaryCollapse = true;
$scope.mobileCollapse = true;
});
$scope.clickedResource = false;
$scope.literacies = weblit.all();
$scope.page = wmNav.page;
$scope.section = wmNav.section;
$scope.isActivePage = function (page) {
return page === wmNav.page();
};
$scope.isActiveSection = function (section) {
return section === wmNav.section();
};
// Search
$scope.search = function (input) {
window.location = '/' + config.lang + '/search?type=all&q=' + input;
};
}
])
.controller('exploreController', ['$scope', 'CONFIG',
function ($scope, CONFIG) {
$scope.eventsUrl = CONFIG.eventsUrl;
$scope.contributeBoxes = [{
icon: 'book',
title: 'Teaching kits',
description: 'Teaching kits desc',
target: '/' + CONFIG.lang + '/make-your-own'
}, {
icon: 'map-marker',
title: 'Events',
description: 'Events desc',
target: 'https://events.webmaker.org/'
}, {
icon: 'globe',
title: 'Translate',
description: 'Translate desc',
target: 'https://support.mozilla.org/' + CONFIG.lang + '/kb/translate-webmaker'
}, {
icon: 'picture-o',
title: 'Design',
description: 'Design desc',
target: 'https://wiki.mozilla.org/Webmaker/Design'
}, {
icon: 'code',
title: 'Code',
description: 'Code desc',
target: 'https://support.mozilla.org/' + CONFIG.lang + '/kb/contribute-webmaker-code'
}, {
icon: 'rocket',
title: 'Partner',
description: 'Partner desc',
target: 'http://party.webmaker.org/' + CONFIG.lang + '/partners'
}];
}
])
.controller('homeController', ['$rootScope', '$scope', 'wmNav', '$routeParams', 'localize', 'CONFIG',
function ($rootScope, $scope, wmNav, $routeParams, localize, CONFIG) {
wmNav.page('home');
wmNav.section('');
$scope.userDel = $routeParams.userDel;
if ($routeParams.auth === 'login') {
$rootScope.wmTokenLogin();
} else if ($routeParams.auth === 'new-account') {
$rootScope.wmCreateUser();
}
function onboardingExperience() {
$('#home-start-form').on('submit', function () {
$rootScope.joinWebmaker($('.home-email-field').val(), '', $('#onboarding-checkbox').prop('checked'));
});
var input = $('.onboarding-input');
var inputText = localize.getLocalizedString('sharing');
var currentLength = 0;
var publishedText = $('.onboarding-published-text');
var timeout;
function setFontSize() {
publishedText.css('font-size', publishedText.height() + 'em');
}
$(window).resize(setFontSize);
$('.onboarding-next-button').click(function () {
var text = input.val();
$('.onboarding-step-1').addClass('hidden');
$('.onboarding-step-2').removeClass('hidden');
$('.home-panel').addClass('home-blue');
$('.home-panel').removeClass('home-green');
if (text) {
setFontSize();
publishedText.text(text);
}
});
function cancelAutoInput() {
clearTimeout(timeout);
$('.onboarding-tooltip-container').removeClass('fade-in');
}
function inputTextCharacter() {
input.val(input.val() + inputText[currentLength++]);
if (currentLength < inputText.length) {
timeout = setTimeout(inputTextCharacter, 200);
}
}
input.click(function () {
input[0].setSelectionRange(0, input.val().length);
cancelAutoInput();
});
input.on('input', cancelAutoInput);
input.on('blur', function () {
$('.onboarding-tooltip-container').addClass('fade-in');
});
input.focus();
timeout = setTimeout(inputTextCharacter, 2000);
}
if ($routeParams.variant === '6') {
if (localize.resourceFileLoaded) {
onboardingExperience();
} else {
$rootScope.$on('localizeResourcesUpdated', onboardingExperience);
}
} else {
$('#home-start-form').on('submit', function () {
$rootScope.joinWebmaker($('.home-email-field').val());
});
}
}
])
.controller('competencyController', ['$rootScope', '$scope', '$routeParams',
'weblit', 'CONFIG', '$timeout', 'wmNav',
function ($rootScope, $scope, $routeParams, weblit, CONFIG, $timeout, wmNav) {
wmNav.page($routeParams.id);
wmNav.section('resources');
$scope.tag = $routeParams.id;
$scope.skill = weblit.all().filter(function (item) {
return item.tag === $scope.tag;
})[0];
if ($rootScope.contentReady) {
$scope.content = $rootScope.allContent[$scope.tag];
} else {
$timeout(function () {
$scope.content = $rootScope.allContent[$scope.tag];
}, 500);
}
$scope.weblit = weblit;
$scope.wlcPoints = CONFIG.wlcPoints;
}
])
.controller('competencyMediaGenController', ['$scope', '$sce',
function ($scope, $sce) {
function safeUrl(media) {
// jscs:disable maximumLineLength
var youtubeQueryStringParams = 'enablejsapi=1&wmode=transparent&autohide=1&autoplay=0&rel=0&fs=1&hd=1&rel=0&showinfo=0&start=&theme=dark';
// jscs:enable maximumLineLength
var vimeoQueryStringParams = 'title=0&byline=0&portrait=0&color=eb6933';
var sources = {
'youtube': 'https://www.youtube-nocookie.com/embed/' + media.content + '?' + youtubeQueryStringParams,
'vimeo': 'https://player.vimeo.com/video/' + media.content + '?' + vimeoQueryStringParams,
'ted': 'https://embed-ssl.ted.com/talks/' + media.content + '.html',
'popcorn': media.content
};
var source = sources[media.type];
if (source) {
return $sce.trustAsResourceUrl(source);
} else {
return media.content;
}
}
$scope.safeUrl = safeUrl;
}
])
.controller('resourceFormController', ['$scope', '$http', 'wmAnalytics',
function ($scope, $http, analytics) {
$scope.formData = {};
$scope.submit = function (form) {
var data = $scope.formData;
data.username = $scope._user.username;
data.email = $scope._user.email;
data.webliteracy = $scope.skill.term;
$http
.post('/api/submit-resource', data)
.success(function (ok) {
if (ok) {
$scope.success = true;
$scope.formData = {};
analytics.event('Suggested Web Literacy Resource');
}
})
.error(function (err) {
console.log(err);
});
};
}
])
.controller('resourcesHomeController', ['$scope', 'weblit', 'wmNav',
function ($scope, weblit, wmNav) {
wmNav.page('resources');
wmNav.section('teach');
$scope.literacies = weblit.all();
}
])
.controller('literacyController', ['$scope', 'weblit', 'wmNav', 'CONFIG',
function ($scope, weblit, wmNav, CONFIG) {
wmNav.section('resources');
wmNav.page('literacy');
$scope.litMapTitle = weblit.title() + ' - ' + weblit.version;
$scope.strands = weblit.strands();
$scope.litMap = weblit.allByStrand();
$scope.wlcPoints = CONFIG.wlcPoints;
}
])
.controller('toolsController', ['$scope', 'wmNav',
function ($scope, wmNav) {
wmNav.page('tools');
wmNav.section('tools');
}
])
.controller('makeYourOwnController', ['$rootScope', '$scope', '$timeout', 'wmNav', 'CONFIG',
function ($rootScope, $scope, $timeout, wmNav, CONFIG) {
wmNav.section('resources');
wmNav.page('make-your-own');
function init() {
$scope.userId = $rootScope._user.id;
$scope.direction = CONFIG.direction;
}
// Don't fire controller until after $rootScope is ready
if ($rootScope._user) {
init();
} else {
$timeout(function () {
init();
}, 500);
}
}
])
.controller('mwcController', ['$rootScope', '$scope', '$routeParams', '$timeout', 'wmNav',
function ($rootScope, $scope, $routeParams, $timeout, wmNav) {
wmNav.section('resources');
wmNav.page('');
$scope.page = $routeParams.mwc;
// Keeps controller operations in one function to be fired when $rootScope is ready
function init() {
$scope.madewithcode = $rootScope.madewithcode[$scope.page];
$scope.userId = $rootScope._user.id;
}
// Don't fire controller until after $rootScope is ready
if ($rootScope._user) {
init();
} else {
$timeout(function () {
init();
}, 500);
}
}
])
.controller('badgesAdminController', ['$rootScope', '$scope', '$http', 'wmNav',
function ($rootScope, $scope, $http, wmNav) {
wmNav.page('badges-admin');
wmNav.section('explore');
$scope.badges = [];
$scope.reverse = false;
$scope.predicate = 'created';
$scope.hasPermissions = function (badge) {
return window.badgesPermissionsModel({
badge: badge,
user: $rootScope._user,
action: 'applications'
});
};
$http
.get('/api/badges')
.success(function (badges) {
$scope.badges = badges;
});
}
])
.controller('createUpdateBadgeController', [
'$rootScope',
'$scope',
'$http',
'$routeParams',
'$location',
'wmNav',
'CONFIG',
function ($rootScope, $scope, $http, $routeParams, $location, wmNav, config) {
wmNav.page('create-badge');
wmNav.section('explore');
// Update or create?
$scope.view = $routeParams.badge ? 'update' : 'create';
$scope.title = $routeParams.badge ? 'Update Badge' : 'Create a New Badge';
if ($scope.view === 'update') {
$http
.get('/api/badges/' + $routeParams.badge)
.success(function (data) {
data.tags = data.tags.map(function (obj) {
return obj.value;
}).join(', ');
$scope.badge = data;
})
.error(function (err) {
console.log(err);
});
} else {
// This holds all the values for the new badge
$scope.badge = {
criteria: [{
description: '# This is an example\n* point 1\n* point 2\n* point 3'
}]
};
}
$scope.hasError = function (formEl) {
return {
'has-error': ($scope.submitAttempt || formEl.$dirty) && formEl.$invalid
};
};
$scope.criteriaPreview = function () {
if (!$scope.badge || !$scope.badge.criteria) {
return '';
}
var result = $scope.badge.criteria.map(function (item) {
return item.description;
}).join('\n\n');
return result;
};
$scope.addCriterion = function () {
$scope.badge.criteria.push({
description: ''
});
};
$scope.removeCriterion = function (index) {
$scope.badge.criteria.splice(index, 1);
};
function prepareBadge(data) {
var badge = angular.copy(data);
// Badgekit api requires both, but we want them to be the same.
badge.consumerDescription = data.earnerDescription;
badge.criteriaUrl = 'https://webmaker.org/badges/' + badge.slug;
badge.unique = 0;
badge.type = 'Skill';
// Tags
if (badge.tags) {
badge.tags = data.tags.split(/[\s,]+/).filter(function (item) {
return item;
});
} else {
delete badge.tags;
}
// Criteria
badge.criteria = data.criteria.map(function (criterion) {
criterion.required = 1;
return criterion;
});
return badge;
}
$scope.submit = function (isValid, badge) {
$scope.submitAttempt = true;
if (!isValid) {
return;
}
var url = '/api/badges/' + ($routeParams.badge ? $routeParams.badge + '/' + $scope.view : 'create');
badge = prepareBadge(badge);
console.log('Sending...', badge);
$http
.post(url, badge)
.success(function (data) {
console.log('Success!', data);
window.location = '/' + config.lang + '/badges/' + data.slug;
})
.error(function (err) {
console.log(err);
});
};
}
])
.controller('badgesAdminBadgeController', ['$scope', '$http', '$window', '$routeParams', '$modal', 'wmNav',
function ($scope, $http, $window, $routeParams, $modal, wmNav) {
wmNav.page('badges-admin');
wmNav.section('explore');
var currentBadge = $routeParams.badge;
$scope.badge = {};
$scope.instances = [];
$scope.badgesError = false;
// Error handling
function onError(err) {
$scope.badgesError = err.error;
console.log(err);
}
// This issues a new badge
$scope.issueBadges = function (emailString, comment) {
var emails = emailString.split(/[,;\n ]+/);
$http
.post('/api/badges/' + currentBadge + '/issue', {
emails: emails,
comment: comment
})
.success(function (data) {
$scope.badgesError = false;
$scope.instances = data.concat($scope.instances);
$scope.issueComment = '';
$scope.issueEmails = '';
})
.error(onError);
};
// This revokes badges
$scope.revokeBadge = function (email) {
var ok = $window.confirm('Are you sure you want to delete ' + email + '\'s badge?');
if (ok) {
$http
.delete('/api/badges/' + currentBadge + '/instance/email/' + email)
.success(function () {
for (var i = 0; i < $scope.instances.length; i++) {
if ($scope.instances[i].email === email) {
$scope.instances.splice(i, 1);
}
}
})
.error(onError);
}
};
// This opens the review application dialog
$scope.reviewApplication = function reviewApplication(application) {
$modal.open({
templateUrl: '/views/partials/review-application-modal.html',
resolve: {
application: function () {
return application;
}
},
controller: ReviewApplicationController
}).result.then(function (review) {
$http
.post('/api/badges/' + currentBadge + '/applications/' + review.id + '/review', {
comment: review.comment,
reviewItems: createReviewItems(review.decision)
})
.success(function () {
for (var i = 0; i < $scope.applications.length; i++) {
if ($scope.applications[i].slug === review.id) {
$scope.applications.splice(i, 1);
}
}
})
.error(onError);
});
};
// Allows all criteria to be satisfied/not satisfied based on single decision
function createReviewItems(decision) {
var criteria = $scope.badge.criteria;
var reviewItems = [];
// true not allowed due to bug 1021186
var satisfied = decision === 'yes';
criteria.forEach(function (item) {
reviewItems.push({
criterionId: item.id,
satisfied: satisfied,
comment: ''
});
});
return reviewItems;
}
var ReviewApplicationController = function ($scope, $modalInstance, application) {
$scope.review = {
id: application.slug,
email: application.learner
};
$scope.application = application;
$scope.ok = function () {
$modalInstance.close($scope.review);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
};
// On load, Get all instances
$http
.get('/api/badges/' + currentBadge + '/instances')
.success(function (data) {
$scope.instances = data.instances;
$scope.badge = data.badge;
})
.error(onError);
// Also get applications
$http
.get('/api/badges/' + currentBadge + '/applications')
.success(function (data) {
$scope.applications = data;
})
.error(onError);
}
])
.controller('appmakerController', ['$scope', '$rootScope', '$timeout',
function ($scope, $rootScope, $timeout) {
$scope.audiences = [{
title: 'students',
image: '/img/appmaker/appmaker-hero-blue.svg'
}, {
title: 'business',
image: '/img/appmaker/appmaker-hero-red.svg'
}, {
title: 'friends',
image: '/img/appmaker/appmaker-hero-yellow.svg'
}];
$scope.makes = [{
title: 'Music App',
image: '/img/appmaker/music-app.jpg',
remixUrl: '//apps.webmaker.org/' + $scope.lang + '/designer?remix=http://magical-profit-510.webmak.es/app',
installUrl: '//magical-profit-510.webmak.es/install',
appUrl: '//magical-profit-510.webmak.es/app'
}, {
title: 'Chat App',
image: '/img/appmaker/chat-app.jpg',
remixUrl: '//apps.webmaker.org/' + $scope.lang + '/designer?remix=http://scattered-reading-531.webmak.es/app',
installUrl: '//scattered-reading-531.webmak.es/install',
appUrl: '//scattered-reading-531.webmak.es/app'
}, {
title: 'Fireworks App',
image: '/img/appmaker/fireworks-app.jpg',
remixUrl: '//apps.webmaker.org/' + $scope.lang + '/designer?remix=http://neat-rate-866.webmak.es/app',
installUrl: '//neat-rate-866.webmak.es/install',
appUrl: '//neat-rate-866.webmak.es/app'
}];
// Properties the view needs to see
$scope.showAudienceTitle = $scope.audiences[0].title;
$scope.currentSlideIndex = 0;
// Group of timeout promises used to transition the selected audience
var transitionPromises = [];
// Reference to the slide that's actually coming up
var currentSlideIndex = 0;
$scope.setActiveSlide = function (active, index) {
// If the slide that called this function is active...
if (active) {
// ... and it's not already the slide we're headed to...
if (currentSlideIndex !== index) {
currentSlideIndex = index;
// Destroy any existing promises
if (transitionPromises.length) {
transitionPromises.forEach($timeout.cancel);
}
// Hide the audience text
$scope.showAudienceTitle = false;
// Wait until audience text is faded out; then change view's currentSlideIndex
transitionPromises.push($timeout(function () {
$scope.currentSlideIndex = currentSlideIndex;
}, 400));
// Show audience text again once fade has happened and text has changed
transitionPromises.push($timeout(function () {
$scope.showAudienceTitle = $scope.audiences[currentSlideIndex].title;
}, 800));
}
}
};
}
])
.controller('feedbackController', ['$scope', 'wmNav',
function ($scope, wmNav) {
wmNav.section('info');
wmNav.page('feedback');
}
])
.controller('getinvolvedController', ['$scope', 'wmNav',
function ($scope, wmNav) {
wmNav.section('teach');
wmNav.page('getinvolved');
}
])
.controller('mentorController', ['$scope', 'wmNav',
function ($scope, wmNav) {
wmNav.section('teach');
wmNav.page('mentor');
}
])
.controller('localebannerController', ['$scope', 'CONFIG', '$http', '$location',
function ($scope, config, $http, $location) {
$http.get('/localeInfo').success(function (localeInfo) {
$scope.listLang = [];
$scope.langmap = config.langmap;
localeInfo.otherLangPrefs.map(function (item) {
if (config.supportLang.indexOf(item) !== -1 &&
$scope.listLang.indexOf(item) !== 1 && $scope.listLang.length < 1 &&
item.match(/^[a-z]{2}/) && config.lang.match(/^[a-z]{2}/) &&
item.match(/^[a-z]{2}/)[0] !== config.lang.match(/^[a-z]{2}/)[0]) {
$scope.listLang.push(item);
}
});
var el = document.getElementById('locale-banner');
if (!$scope.listLang.length) {
$scope.bannerBool = true;
el.remove();
}
$scope.removeBanner = function removeBanner() {
localStorage.setItem('localeBanner', true);
$scope.bannerBool = true;
el.remove();
};
$scope.acceptRedirect = function acceptRedirect() {
var href = $location.path();
var lang = config.lang;
var supportedLanguages = config.supportLang;
// Remove banner and set cookie session.
$scope.removeBanner();
// matches any of these:
// `en`, `en-us`, `en-US` or `ady`
var matchesLang;
var matches = href.match(/([a-z]{2,3})([-]([a-zA-Z]{2}))?/);
if (matches) {
if (matches[1] && matches[2]) {
matchesLang = matches[1].toLowerCase() + matches[2].toUpperCase();
} else {
matchesLang = matches[1].toLowerCase();
}
}
// if the selected language is match to the language in the header
if ($scope.listLang[0] === lang) {
return;
// check if we have any matches and they are exist in the array we have
} else if ((matches && matches[0]) && supportedLanguages.indexOf(matchesLang) !== -1) {
href = href.replace(matches[0], $scope.listLang[0]);
window.location = href;
} else if (href === '/') {
window.location = '/' + $scope.listLang[0];
} else {
window.location = '/' + $scope.listLang[0] + href;
}
};
$scope.didYouKnowLocale = localeInfo.didYouKnowLocale[$scope.listLang[0]];
$scope.bannerBool = localStorage.getItem('localeBanner');
});
}
]);
| mozilla/webmaker.org | public/js/angular/controllers.js | JavaScript | mpl-2.0 | 23,808 |
/**
* ServiceProfessionalServices
*
* @module activities/service-professional-services
*
* FIXME: Complete jsdocs, description
* TODO: Quick460 Must complete refactoring
*/
import * as activities from '../index';
import * as clients from '../../data/clients';
import { Route, RouteMatcher } from '../../utils/Router';
import $ from 'jquery';
import Activity from '../../components/Activity';
import Client from '../../models/Client';
import ServiceProfessionalServiceViewModel from '../../viewmodels/ServiceProfessionalService';
import UserJobProfile from '../../viewmodels/UserJobProfile';
import UserType from '../../enums/UserType';
import { item as getUserListing } from '../../data/userListings';
import ko from 'knockout';
import onboarding from '../../data/onboarding';
import serviceListGroupFactories from '../../viewmodels/ServiceListGroupFactories';
import serviceProfessionalServices from '../../data/serviceProfessionalServices';
import shell from '../../app.shell';
import { show as showError } from '../../modals/error';
import style from './style.styl';
import template from './template.html';
const ROUTE_NAME = 'service-professional-services';
const DEFAULT_BACK_LINK = '/listing-editor';
export default class ServiceProfessionalServices extends Activity {
static get template() { return template; }
static get style() { return style; }
constructor($activity, app) {
super($activity, app);
// MIXIM with ServiceProfessionalServiceViewModel (it includes all its properties)
// TODO: Refactor to not depend on mixims, expected to get to that by declouping
// logic as components
ServiceProfessionalServiceViewModel.call(this, app);
this.accessLevel = UserType.serviceProfessional;
this.helpLink = '/help/relatedArticles/201967166-listing-and-pricing-your-services';
this.navBar = Activity.createSubsectionNavBar('Job Title', {
backLink: DEFAULT_BACK_LINK,
helpLink: this.helpLink
});
// Save defaults to restore on updateNavBarState when needed:
this.defaultLeftAction = this.navBar.leftAction().model.toPlainObject(true);
this.title = ko.pureComputed(() => {
if (this.isInOnboarding() && this.listingTitle()) {
return 'Add your first ' + this.listingTitle() + ' offering';
}
else if (this.listingTitle() && !this.isSelectionMode()) {
return this.listingTitle() + ' offerings';
}
else if (this.listingTitle() && this.isSelectionMode()) {
return "What's included in " + this.clientName() + "'s " + this.listingTitle() + ' appointment?';
}
else {
return 'Select a job title';
}
});
this.__defViewMethods();
this.__defViewProperties();
this.__defHandlers();
}
__defViewProperties() {
this.clientID = ko.observable(null);
this.client = ko.observable(null);
this.serviceEditorCancelLink = ko.observable(null);
this.isInOnboarding = onboarding.inProgress;
this.isLocked = this.isLoading;
this.jobTitles = new UserJobProfile(this.app);
this.jobTitles.baseUrl('/service-professional-services');
this.clientName = ko.pureComputed(() => (this.client() && this.client().firstName()) || '');
this.clientFullName = ko.pureComputed(() => (this.client() && this.client().fullName()) || '');
this.clientManagerLink = ko.pureComputed(() => {
if (this.client() || this.isSelectionMode() || onboarding.inProgress()) {
return null;
}
else {
return '#!/clients';
}
});
this.listingTitle = ko.observable('Job Title');
this.submitText = ko.pureComputed(() => this.isLoading() && 'loading...' || 'Save and continue');
this.onboardingNextReady = ko.computed(() => {
var isin = onboarding.inProgress();
var hasPricing = this.list().length > 0;
return isin && hasPricing;
});
}
__defViewMethods() {
// Go back with the selected pricing when triggered in the form/view
this.returnSelected = (pricing, jobTitleID) => {
// Pass the selected client in the info
this.requestData.selectedServices = pricing;
this.requestData.selectedJobTitleID = jobTitleID;
// And go back
shell.goBack(this.requestData);
};
this.returnRequest = () => {
shell.goBack(this.requestData);
};
this.loadServicesData = () => {
var clientID = this.clientID();
var jobTitleID = this.jobTitleID();
var services = null;
if(this.isSelectionMode()) {
services = serviceProfessionalServices.getServicesBookableByProvider(clientID, jobTitleID);
}
else if (clientID) {
services = serviceProfessionalServices.getClientSpecificServicesForJobTitle(clientID, jobTitleID);
}
else {
services = serviceProfessionalServices.getList(jobTitleID);
}
return this.loadData(null, jobTitleID, services);
};
this.serviceListGroupsFactory = (services, pricingTypes) => {
var factories = serviceListGroupFactories;
var listGroupsFactory = this.isSelectionMode() ?
factories.providerBookedServices :
factories.providerManagedServices;
var isClientSpecific = !!this.clientID();
services = this.isAdditionMode() ? [] : services;
return listGroupsFactory(services, pricingTypes, this.clientName(), isClientSpecific);
};
this.editServiceRequest = () => $.extend({ cancelLink: this.serviceEditorCancelLink() }, this.requestData);
this.newServiceRequest = () => $.extend({ cancelLink: this.serviceEditorCancelLink() }, this.requestData);
// Replace and reuse method inherit from ServiceProfessionalService mixim
// (cannot define as a method and use `super` since comes from mixim constructor)
var baseNewServiceURL = this.newServiceURL.bind(this);
this.newServiceURL = (jobTitleID, pricingTypeID, isClientSpecific) => {
if(isClientSpecific) {
return `#!service-professional-service-editor/${jobTitleID}/pricingType/${pricingTypeID}/client/${this.clientID()}/new`;
}
else {
return baseNewServiceURL(jobTitleID, pricingTypeID);
}
};
/**
Ends the selection process, ready to collect selection
and passing it to the requester activity.
Works too to pass to the next onboarding step
**/
this.endSelection = (data, event) => {
if (onboarding.inProgress()) {
// Ensure we keep the same jobTitleID in next steps as here:
onboarding.selectedJobTitleID(this.jobTitleID());
onboarding.goNext();
}
else {
this.returnSelected(
this.selectedServices().map((pricing) => pricing.model.toPlainObject(true)),
this.jobTitleID()
);
}
event.preventDefault();
event.stopImmediatePropagation();
};
this.selectedServiceRequest = (pricing) => pricing.model.toPlainObject(true);
}
/**
* TODO: Replace registerHandler calls with subscribeTo/observeChanges
*/
__defHandlers() {
this.registerHandler({
target: this.clientID,
handler: (clientID) => {
this.client(null);
if(clientID) {
clients
.item(clientID)
.onceLoaded()
.then((client) => {
this.client(new Client(client));
})
.catch((error) => {
showError({
title: 'Unable to load client.',
error
});
});
}
}
});
this.registerHandler({
target: this.client,
// Update navbar (may include the client name)
handler: this.updateNavBarState.bind(this)
});
}
applyOwnNavbarRules() {
this.navBar.title(this.requestData.title || '');
if (this.requestData.cancelLink) {
this.convertToCancelAction(this.navBar.leftAction(), this.requestData.cancelLink, this.requestData);
}
else {
this.navBar.leftAction().model.updateWith(this.defaultLeftAction, true);
this.navBar.leftAction().model.updateWith(this.newLeftAction(), true);
}
}
newLeftAction() {
var leftAction = {};
var jid = this.jobTitleID();
var url = this.mustReturnTo || (DEFAULT_BACK_LINK + (jid ? '/' + jid : ''));
var handler = this.isSelectionMode() ? this.returnRequest : null;
leftAction.link = url;
leftAction.text = this.leftActionText();
leftAction.handler = handler;
return leftAction;
}
leftActionText() {
var clientName = this.client() && this.clientFullName();
var jobTitle = this.listingTitle();
return this.requestData.navTitle || clientName || jobTitle || 'Back';
}
updateNavBarState() {
// Perform updates that apply this request:
return onboarding.updateNavBar(this.navBar) || this.applyOwnNavbarRules();
}
referrerURL() {
return (shell.referrerRoute && shell.referrerRoute.url) || '/';
}
getServiceEditorCancelLink(isAdditionMode) {
if (isAdditionMode) {
// Sets referrer as cancel link
return this.referrerURL();
}
else {
return '/service-professional-services' + this.requestData.route.path;
}
}
buildRoute(jobTitleID, clientID, isAdditionMode) {
var base = '/service-professional-services';
var jobTitle = '/' + jobTitleID;
var client = clientID > 0 ? ('/client/' + clientID) : '';
var newParam = isAdditionMode ? '/new' : '';
return base + jobTitle + client + newParam;
}
parseRoute(url) {
var paramsDefaults = { jobTitleID: 0, isNew: false, clientID: null };
var matcher = new RouteMatcher([
new Route('/:jobTitleID/new', { isNew: true }),
new Route('/:jobTitleID/client/:clientID/new', { isNew: true }),
new Route('/:jobTitleID/client/:clientID'),
new Route('/new', { isNew: true }),
new Route('/:jobTitleID')
], paramsDefaults);
return matcher.match(url) || paramsDefaults;
}
useJobTitle(jobTitleID) {
this.jobTitleID(jobTitleID);
if (jobTitleID === 0) {
this.clearData();
this.jobTitles.sync();
}
else {
// Load the data
this.loadServicesData();
// Load informational listing title
const listingDataProvider = getUserListing(jobTitleID);
this.subscribeTo(listingDataProvider.onData, (listing) => {
this.listingTitle(listing.title);
// Update navbar (may indicate the listing title)
this.updateNavBarState();
// May depend on current URL, will change with job title
this.serviceEditorCancelLink(this.getServiceEditorCancelLink(this.isAdditionMode()));
});
this.subscribeTo(listingDataProvider.onDataError, (error) => {
showError({
title: 'There was an error while loading.',
error
});
});
}
}
show(state) {
super.show(state);
// Reset: avoiding errors because persisted data for different ID on loading
// or outdated info forcing update
this.reset();
// Use data provided through state for internal communication between
// activities (hidden state, not available at url/query).
this.preSelectedServices(state.selectedServices || []);
this.isSelectionMode(state.selectPricing === true);
const selectedJobTitleID = state.selectedJobTitleID;
// Query parameters
// Remember route to go back, from a request of 'mustReturn' or last requested
this.mustReturnTo = state.route.query.mustReturn || this.mustReturnTo;
// URL segments parameters (path)
const params = this.parseRoute(state.route.path);
this.clientID(params.clientID | 0);
// Choose job title from URL or fallback to selected in state
let jobTitleID = params.jobTitleID | 0;
if (jobTitleID === 0 && selectedJobTitleID > 0) {
jobTitleID = selectedJobTitleID |0;
}
// Addition Mode
const isAdditionMode = params.isNew;
this.serviceEditorCancelLink(this.getServiceEditorCancelLink(isAdditionMode));
if (isAdditionMode) {
state.cancelLink = this.referrerURL();
}
this.isAdditionMode(isAdditionMode);
this.updateNavBarState();
this.useJobTitle(jobTitleID);
}
}
activities.register(ROUTE_NAME, ServiceProfessionalServices);
| loconomics/loconomics | app/source/js/activities/service-professional-services/index.js | JavaScript | mpl-2.0 | 13,591 |
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/FileUtils.jsm");
var randomIsOn;
var mainWindow = window.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIWebNavigation)
.QueryInterface(Components.interfaces.nsIDocShellTreeItem)
.rootTreeItem
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
function createSidebarItem(aType) {
const XUL_NS = "http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul";
var item = document.createElementNS(XUL_NS, aType); // create a new XUL menuitem
//item.setAttribute("label", aLabel);
//dump("created item \n");
return item;
}
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/array/shuffle [v1.0]
function shuffle(o){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
function unavail(){
alert("This feature is currently unavailable");
}
function scanPage(){
mainWindow.netflixRandomizer.scanPage();
}
function selectAll() {
var sidebarPlaylist = document.getElementById("listbox2");
var listItems = sidebarPlaylist.getElementsByTagName("listitem");
for (var i = 0, num = listItems.length; i < num; i++){
listItems[i].setAttribute('selected',true);
}
}
function clearSidebar() {
var sidebarOnPage = document.getElementById("listbox1");
var listItems = sidebarOnPage.getElementsByTagName("listitem");
for (var i = 0, num = listItems.length; i < num; i++){
listItems[0].parentNode.removeChild(listItems[0]);
}
var sidebarPlaylist = document.getElementById("listbox2");
var listItems = sidebarPlaylist.getElementsByTagName("listitem");
for (var i = 0, num = listItems.length; i < num; i++){
listItems[0].parentNode.removeChild(listItems[0]);
}
}
function updatePlaylist() {
clearSidebar();
//dump("START playlist update \n");
var sidebarOnPage = document.getElementById("listbox1");
var sidebarPlaylist = document.getElementById("listbox2");
var file = FileUtils.getFile("ProfD", ["netflixrandomizer.sqlite"]);
var mDBConn = Services.storage.openDatabase(file);
var statement = mDBConn.createStatement("SELECT * FROM onpage");
//dump("got vbox1 \n");
var i = 1;
try{
while(statement.executeStep()){
var name = statement.getString(5);
name = name.replace(/\\/g, "");
var li = createSidebarItem("listitem");
li.setAttribute("id",statement.getString(0));
li.setAttribute("class",statement.getString(1));
li.setAttribute("url",statement.getString(6));
// li.setAttribute("ep",statement.getString(4));
// li.setAttribute("name",statement.getString(name));
// li.setAttribute("title",statement.getString(2));
// li.setAttribute("season",statement.getString(3));
var l1 = createSidebarItem("listcell");
l1.setAttribute("label",statement.getString(4));
li.appendChild(l1);
var l2 = createSidebarItem("listcell");
l2.setAttribute("label",name);
li.appendChild(l2);
var l3 = createSidebarItem("listcell");
l3.setAttribute("label",statement.getString(2));
li.appendChild(l3);
var l4 = createSidebarItem("listcell");
l4.setAttribute("label",statement.getString(3));
li.appendChild(l4);
sidebarOnPage.appendChild(li);
i++;
}
}finally{
statement.reset();
}
var statement2 = mDBConn.createStatement("SELECT * FROM playlist");
var statement3 = mDBConn.createStatement("SELECT cvid FROM status");
statement3.executeStep();
var cvid = statement3.getString(0);
statement3.reset();
//dump("got vbox1 \n");
var i = 1;
try{
while(statement2.executeStep()){
var name = statement2.getString(5);
name = name.replace(/\\/g, "");
var li = createSidebarItem("listitem");
li.setAttribute("id",statement2.getString(0));
li.setAttribute("vid",statement2.getString(1));
//for styling
if (statement2.getString(1) == cvid){
li.setAttribute("class","currently-playing");
}
li.setAttribute("url",statement2.getString(6));
var l1 = createSidebarItem("listcell");
l1.setAttribute("label",statement2.getString(4));
li.appendChild(l1);
var l2 = createSidebarItem("listcell");
l2.setAttribute("label",name);
li.appendChild(l2);
var l3 = createSidebarItem("listcell");
l3.setAttribute("label",statement2.getString(2));
li.appendChild(l3);
var l4 = createSidebarItem("listcell");
l4.setAttribute("label",statement2.getString(3));
li.appendChild(l4);
sidebarPlaylist.appendChild(li);
i++;
}
}finally{
statement2.reset();
}
//dump("END playlist update \n");
mDBConn.close();
}
function addToPlaylist() {
//dump("adding to playlist \n");
var sidebarOnPage = document.getElementById("listbox1");
var listItems = sidebarOnPage.getElementsByTagName("listitem");
//dump("got vars \n");
var file = FileUtils.getFile("ProfD", ["netflixrandomizer.sqlite"]);
var mDBConn = Services.storage.openDatabase(file);
try{
for (var i = 0; i < listItems.length; i++){
if (listItems[i].getAttribute('selected')){
//dump(listItems[i].getAttribute('id')+"\n");
var listCells = listItems[i].getElementsByTagName("listcell");
mDBConn.executeSimpleSQL("DELETE FROM onpage WHERE pid="+listItems[i].getAttribute('id'));
//dump("deleted from onpage table \n");
//dump(listItems[i].getAttribute('class')+"\n");
mDBConn.executeSimpleSQL('INSERT INTO playlist(pid,vid,title,season,ep,name,url,watched) VALUES(' + null + ',' + listItems[i].getAttribute('class') + ',"' + listCells[2].getAttribute('label') + '",' + listCells[3].getAttribute('label') + ',' + listCells[0].getAttribute('label') + ',"' + listCells[1].getAttribute('label') + '","' + listItems[i].getAttribute('url') + '",0)');
//dump("adding to playlist table \n");
}
}
//dump("done adding to playlist \n");
mDBConn.close();
}catch(err){
dump("add to playlist error: "+err+"\n");
}
updatePlaylist();
}
function removeFromPlaylist() {
var sidebarPlaylist = document.getElementById("listbox2");
var listItems = sidebarPlaylist.getElementsByTagName("listitem");
var file = FileUtils.getFile("ProfD", ["netflixrandomizer.sqlite"]);
var mDBConn = Services.storage.openDatabase(file);
for (var i = 0; i < listItems.length; i++){
if (listItems[i].getAttribute('selected')){
//dump(listItems[i].getAttribute('id')+"\n");
mDBConn.executeSimpleSQL("DELETE FROM playlist WHERE pid="+listItems[i].getAttribute('id'));
}
}
mDBConn.close();
updatePlaylist();
}
function playVid() {
var sidebarPlaylist = document.getElementById("listbox2");
var selectedVids = sidebarPlaylist.getElementsByTagName("listitem");
//REDIRECT
//dump(selectedVids[0].getAttribute('url') + "\n");
var file = FileUtils.getFile("ProfD", ["netflixrandomizer.sqlite"]);
var mDBConn = Services.storage.openDatabase(file);
var counter = 0;
for (var i = 0; i < selectedVids.length; i++){
if (selectedVids[i].getAttribute('selected')){
mDBConn.executeSimpleSQL("UPDATE status SET playing=1, cvid="+ selectedVids[i].getAttribute('vid') +" WHERE id=1");
mDBConn.close();
counter++;
mainWindow.openUILinkIn(selectedVids[i].getAttribute('url'), "current", false);
}
}
if (counter == 0){
alert("Please select a video from playlist");
}
}
function randomizer() {
if (!randomIsOn){
var file = FileUtils.getFile("ProfD", ["netflixrandomizer.sqlite"]);
var mDBConn = Services.storage.openDatabase(file);
var playlistVids = shuffle(document.getElementsByTagName('listitem'));
for (var i=0, il=playlistVids.length; i<il; i++) {
mDBConn.executeSimpleSQL('INSERT INTO current_playlist(cpid,pid) VALUES(' + null + ',' + playlistVids[i].getAttribute('id') + ')');
}
mDBConn.close();
randomIsOn = true;
//mainWindow.openUILinkIn("http://www.randomon.com", "current", false);
}else{
randomIsOn = false;
//mainWindow.openUILinkIn("randomOFF", "current", false);
}
}
function resetOnPage() {
var file = FileUtils.getFile("ProfD", ["netflixrandomizer.sqlite"]);
var mDBConn = Services.storage.openDatabase(file);
mDBConn.executeSimpleSQL("DROP TABLE IF EXISTS onpage");
mDBConn.executeSimpleSQL("CREATE TABLE IF NOT EXISTS onpage (pid INTEGER PRIMARY KEY AUTOINCREMENT, vid INTEGER, title TEXT, season INTEGER, ep INTEGER, name TEXT, url TEXT)");
mDBConn.close();
updatePlaylist();
}
function resetPlaylist() {
var file = FileUtils.getFile("ProfD", ["netflixrandomizer.sqlite"]);
var mDBConn = Services.storage.openDatabase(file);
mDBConn.executeSimpleSQL("DROP TABLE IF EXISTS playlist");
mDBConn.executeSimpleSQL("CREATE TABLE IF NOT EXISTS playlist (pid INTEGER PRIMARY KEY AUTOINCREMENT, vid INTEGER, title TEXT, season INTEGER, ep INTEGER, name TEXT, url TEXT, watched INTEGER)");
mDBConn.close();
updatePlaylist();
}
var playlist = {
onLoad: function(e) {
window.top.document.getElementById("netflix-randomizer-toolbar-button").id = "netflix-randomizer-toolbar-button-on";
//alert('load');
var sidebarOnPage = document.getElementById("listbox1");
sidebarOnPage.addEventListener("dblclick", function(event)
{
var target = event.target;
while (target && target.localName != "listitem")
target = target.parentNode;
if (!target)
return; // Event target isn't a list item
addToPlaylist();
}, false);
var sidebarPlaylist = document.getElementById("listbox2");
sidebarPlaylist.addEventListener("dblclick", function(event)
{
var target = event.target;
while (target && target.localName != "listitem")
target = target.parentNode;
if (!target)
return; // Event target isn't a list item
playVid();
}, false);
updatePlaylist();
},
onFocus: function(e) {
//alert('got focus');
updatePlaylist();
},
onUnload: function(e) {
//alert('close');
window.top.document.getElementById("netflix-randomizer-toolbar-button-on").id = "netflix-randomizer-toolbar-button";
}
}
window.addEventListener("load", function(e) { playlist.onLoad(e); }, false);
window.addEventListener("focus", function(e) { playlist.onFocus(e); }, false);
window.addEventListener("unload", function(e) { playlist.onUnload(e); }, false); | J0shK/NetflixPlaylist | chrome/content/sidebar.js | JavaScript | mpl-2.0 | 10,554 |
/* jshint expr: true, mocha:true */
(function () {
'use strict';
const fs = require('fs');
const assert = require('assert');
const fb = require('../lib');
const options = {
host: 'rf-server',
port: '3050',
database: 'd:/bases/test/node_firebird.fdb',
user: 'SYSDBA',
password: 'masterkey'
};
describe('connection', () => {
it('reconnection test', (done) => {
fb.attach(options, (err, db) => {
if (err) {
throw err;
}
db.on('reconnect', () => {
done();
});
db.connection._socket.end();
});
});
it('write blob (stream)', (done) => {
fb.attach(options, function (err, db) {
assert.ifError(err);
db.query('INSERT INTO blob_table (blob_field) VALUES(?) RETURNING (id)', [fs.createReadStream('test/image.png')], (err, result) => {
assert.ifError(err);
assert.notEqual(result, null);
assert.equal(typeof result, 'object');
assert(result.id > 0);
db.query('DELETE FROM blob_table WHERE id = ?', [result.id], (err, result) => {
assert.ifError(err);
done();
});
});
});
});
it('write blob (buffer)', (done) => {
fb.attach(options, function (err, db) {
assert.ifError(err);
db.query('INSERT INTO blob_table (blob_field) VALUES(?) RETURNING (id)', [fs.readFileSync('test/image.png')], (err, result) => {
assert.ifError(err);
assert.notEqual(result, null);
assert.equal(typeof result, 'object');
assert(result.id > 0);
db.query('DELETE FROM blob_table WHERE id = ?', [result.id], (err, result) => {
assert.ifError(err);
done();
});
});
});
});
it('read blob', function (done) {
var sql = "SELECT FIRST(1) blob_field FROM blob_table";
fb.attach(options, function (err, db) {
assert.ifError(err);
db.transaction(fb.ISOLATION_READ, function (err, transaction) {
assert.ifError(err);
transaction.query(sql, function (err, result) {
assert.equal(err, null);
assert.notEqual(result, null);
assert.equal(result.length, 1);
assert.equal(typeof result[0].blob_field, 'function');
result[0].blob_field(function (err, name, content) {
assert.ifError(err);
content.on('error', function (err) {
assert.ifError(err);
});
content.on('data', function (chunk) {
//
});
content.on('end', function () {
transaction.commit(function (err) {
assert.ifError(err);
db.detach(function (err) {
assert.ifError(err);
done();
});
});
});
});
});
});
});
});
it('read blob from procedure', function (done) {
var sql = "SELECT p.data FROM p_get_blob p ";
fb.attach(options, function (err, db) {
assert.ifError(err);
db.transaction(fb.ISOLATION_READ, function (err, transaction) {
assert.ifError(err);
transaction.query(sql, function (err, result) {
assert.equal(err, null);
assert.notEqual(result, null);
assert.equal(result.length, 1);
assert.equal(typeof result[0].data, 'function');
result[0].data(function (err, name, content) {
assert.ifError(err);
content.on('error', function (err) {
assert.ifError(err);
});
content.on('data', function (chunk) {
//
});
content.on('end', function () {
transaction.commit(function (err) {
assert.ifError(err);
db.detach(function (err) {
assert.ifError(err);
done();
});
});
});
});
});
});
});
});
it('partial simple packets', (done) => {
const sql = `
SELECT * FROM columns_table
`;
fb.attach(options, (err, db) => {
assert.ifError(err);
db.query(sql, (err, result, columns) => {
assert.equal(err, null);
assert.notEqual(result, null);
assert.notEqual(columns, null);
assert.equal(columns.length, 69);
db.detach(function (err) {
assert.ifError(err);
done();
});
});
});
});
it('partial fetch packets', (done) => {
const sql = `
SELECT FIRST(10000) * FROM big_table
`;
fb.attach(options, (err, db) => {
assert.ifError(err);
db.query(sql, (err, result) => {
assert.equal(err, null);
assert.notEqual(result, null);
assert.equal(result.length, 10000);
db.detach(function (err) {
assert.ifError(err);
done();
});
});
});
});
});
})(); | restfront/node-firebird | test/connection.test.js | JavaScript | mpl-2.0 | 6,720 |
var searchData=
[
['unit_20testing_20api',['Unit Testing API',['../c_test.html',1,'c_APIs']]],
['utf_2d8_20string_20handling_20api',['UTF-8 String Handling API',['../c_utf8.html',1,'c_APIs']]],
['use_20ipc',['Use IPC',['../componenthello_i_p_c.html',1,'componentWriting']]],
['uninstall_20legato',['Uninstall Legato',['../getstarted_uninstall.html',1,'getstartedRestore']]],
['use_20legato',['Use Legato',['../index.html',1,'']]],
['upgrade_20notes',['Upgrade Notes',['../legato_upgrade_beta.html',1,'getstartedMain']]],
['usec',['usec',['../structle__clk___time__t.html#a8324bdde9199a09a47489a3f246f184c',1,'le_clk_Time_t']]]
];
| legatoproject/legato-docs | 14_10/search/all_12.js | JavaScript | mpl-2.0 | 644 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict';
define([
'cocktail',
'underscore',
'views/confirm',
'views/base',
'stache!templates/confirm_reset_password',
'lib/promise',
'lib/session',
'lib/auth-errors',
'views/mixins/resend-mixin',
'views/mixins/service-mixin'
],
function (Cocktail, _, ConfirmView, BaseView, Template, p, Session, AuthErrors,
ResendMixin, ServiceMixin) {
var t = BaseView.t;
var SESSION_UPDATE_TIMEOUT_MS = 10000;
var View = ConfirmView.extend({
template: Template,
className: 'confirm-reset-password',
initialize: function (options) {
options = options || {};
this._interTabChannel = options.interTabChannel;
this._sessionUpdateTimeoutMS = options.sessionUpdateTimeoutMS ||
SESSION_UPDATE_TIMEOUT_MS;
var data = this.ephemeralData();
this._email = data.email;
this._passwordForgotToken = data.passwordForgotToken;
},
events: {
'click #resend': BaseView.preventDefaultThen('validateAndSubmit')
},
context: function () {
return {
email: this._email,
encodedEmail: encodeURIComponent(this._email),
forceAuth: this.broker.isForceAuth()
};
},
beforeRender: function () {
// user cannot confirm if they have not initiated a reset password
if (! this._passwordForgotToken) {
this.navigate('reset_password');
return false;
}
},
_getSignInRoute: function () {
if (this.relier.isOAuth()) {
return 'oauth/signin';
}
return 'signin';
},
afterRender: function () {
var bounceGraphic = this.$el.find('.graphic');
bounceGraphic.addClass('pulse');
var self = this;
if (self.relier.isOAuth()) {
this.transformLinks();
}
// this sequence is a bit tricky and needs to be explained.
//
// For OAuth and Sync, we are trying to make it so users who complete
// the password reset flow in another tab of the same browser are
// able to finish signing in if the original tab is still open.
// After requesting the password reset, the original tab sits and polls
// the server querying whether the password reset is complete.
//
// This crypto stuff needs to occur in the original tab because OAuth
// reliers and sync may only have the appropriate state in the original
// tab. This means, for password reset, we have to ship information like
// the unwrapBKey and keyFetchToken from tab 2 to tab 1. We have a plan,
// albeit a complex one.
//
// In tab 2, two auth server calls are made after the user
// fills out the new passwords and submits the form:
//
// 1. /account/reset
// 2. /account/login
//
// The first call resets the password, the second signs the user in
// so that Sync/OAuth key/code generation can occur.
//
// tab 1 will be notified that the password reset is complete
// after step 1. The problem is, tab 1 can only do its crypto
// business after step 2 and after the information has been shipped from
// tab 2 to tab 1.
//
// To communicate between tabs, a special channel is set up that makes
// use of localStorage as the comms medium. When tab 1 starts its poll,
// it also starts listening for messages on localStorage. This is in
// case the tab 2 finishes both #1 and #2 before the poll completes.
// If a message is received by time the poll completes, take the
// information from the message and sign the user in.
//
// If a message has not been received by time the poll completes,
// assume we are either in a second browser or in between steps #1 and
// #2. Start a timeout in case the user verifies in a second browser
// and the message is never received. If the timeout is reached,
// force a manual signin of the user.
//
// If a message is received before the timeout hits, HOORAY!
return self.broker.persist()
.then(function () {
self._waitForConfirmation()
.then(function (sessionInfo) {
self.logScreenEvent('verification.success');
// The original window should finish the flow if the user
// completes verification in the same browser and has sessionInfo
// passed over from tab 2.
if (sessionInfo) {
return self._finishPasswordResetSameBrowser(sessionInfo);
}
return self._finishPasswordResetDifferentBrowser();
})
.then(null, function (err) {
self.displayError(err);
});
});
},
_waitForConfirmation: function () {
var self = this;
return p.all([
self._waitForSessionUpdate(),
self._waitForServerConfirmationNotice()
.then(function () {
if (! self._isWaitForSessionUpdateComplete) {
self._startSessionUpdateWaitTimeout();
}
})
]).spread(function (sessionInfo) {
return sessionInfo;
});
},
_finishPasswordResetSameBrowser: function (sessionInfo) {
var self = this;
var account = self.user.initAccount(sessionInfo);
// The OAuth flow needs the sessionToken to finish the flow.
return self.user.setSignedInAccount(account)
.then(function () {
self.displaySuccess(t('Password reset'));
return self.broker.afterResetPasswordConfirmationPoll(account)
.then(function (result) {
if (result && result.halt) {
return;
}
if (self.relier.isDirectAccess()) {
// user is most definitely signed in since sessionInfo
// was passed in. Just ship direct access users to /settings
self.navigate('settings', {
success: t('Account verified successfully')
});
} else {
self.navigate('reset_password_complete');
}
});
});
},
_finishPasswordResetDifferentBrowser: function () {
var self = this;
// user verified in a different browser, make them sign in. OAuth
// users will be redirected back to the RP, Sync users will be
// taken to the Sync controlled completion page.
Session.clear();
self.navigate(self._getSignInRoute(), {
success: t('Password reset successfully. Sign in to continue.')
});
},
_waitForServerConfirmationNotice: function () {
var self = this;
return self.fxaClient.isPasswordResetComplete(self._passwordForgotToken)
.then(function (isComplete) {
if (isComplete) {
return true;
}
var deferred = p.defer();
self.setTimeout(function () {
// _waitForServerConfirmationNotice will return a promise and the
// promise chain remains unbroken.
deferred.resolve(self._waitForServerConfirmationNotice());
}, self.VERIFICATION_POLL_IN_MS);
return deferred.promise;
});
},
_waitForSessionUpdate: function () {
var deferred = p.defer();
var self = this;
self._deferred = deferred;
self._sessionUpdateNotificationHandler = _.bind(self._sessionUpdateWaitComplete, self);
self._interTabChannel.on('login', self._sessionUpdateNotificationHandler);
return deferred.promise;
},
_startSessionUpdateWaitTimeout: function () {
var self = this;
self._sessionUpdateWaitTimeoutHandler =
_.bind(self._sessionUpdateWaitComplete, self, null);
self._sessionUpdateWaitTimeout =
self.setTimeout(self._sessionUpdateWaitTimeoutHandler,
self._sessionUpdateTimeoutMS);
},
_sessionUpdateWaitComplete: function (event) {
var self = this;
var data = event && event.data;
self._isWaitForSessionUpdateComplete = true;
self.clearTimeout(self._sessionUpdateWaitTimeout);
self._interTabChannel.off('login', self._sessionUpdateNotificationHandler);
// Sensitive data is passed between tabs using localStorage.
// Delete the data from storage as soon as possible.
self._interTabChannel.clearMessages();
self._deferred.resolve(data);
},
submit: function () {
var self = this;
self.logScreenEvent('resend');
return self.fxaClient.passwordResetResend(self._email,
self._passwordForgotToken, self.relier)
.then(function () {
self.displaySuccess();
}, function (err) {
if (AuthErrors.is(err, 'INVALID_TOKEN')) {
return self.navigate('reset_password', {
error: err
});
}
// unexpected error, rethrow for display.
throw err;
});
},
// The ResendMixin overrides beforeSubmit. Unless set to undefined,
// Cocktail runs both the original version and the overridden version.
beforeSubmit: undefined
});
Cocktail.mixin(
View,
ResendMixin,
ServiceMixin
);
return View;
});
| chilts/fxa-content-server | app/scripts/views/confirm_reset_password.js | JavaScript | mpl-2.0 | 9,460 |
import { routing } from '../../app/routes'
import { FETCH_DETAIL_SUCCESS } from '../../shared/ducks/detail/constants'
import titleActionMapping from '../../shared/services/document-title/document-title'
const TITLE_SUFFIX = 'Data en informatie - Amsterdam'
const TITLE_DEFAULT = 'Data en informatie - Amsterdam'
const getDefaultDocumentTitle = (page) => () => routing?.[page]?.title ?? TITLE_DEFAULT
const documentHead = () => (next) => (action) => {
// The change of the route and some actions should change the document title
const shouldChangeTitle =
Object.keys(routing)
.map((key) => routing[key].type)
.includes(action.type) || action.type === FETCH_DETAIL_SUCCESS
if (shouldChangeTitle) {
const page = Object.keys(routing).find((key) => routing[key].type === action.type)
const titleResolver = titleActionMapping.find((item) => item.actionType === action.type)
const getTitle = titleResolver?.getTitle ?? getDefaultDocumentTitle(page)
const pageTitle = getTitle(action, getDefaultDocumentTitle(page)())
if (typeof document !== 'undefined') {
document.title = `${pageTitle} - ${TITLE_SUFFIX}`
}
}
return next(action)
}
export default documentHead
| DatapuntAmsterdam/atlas_prototype | src/store/middleware/documentHead.js | JavaScript | mpl-2.0 | 1,215 |
cb.define({
xtype: 'view',
name: 'music',
renderTo: '#body-col2',
items: [{
xtype: 'panel',
type: 'info',
id: 'panel-add-music',
reload: false,
items: [{
xtype: 'head',
items: [{
xtype: 'form',
name: 'music-send',
items: [{
xtype: 'input',
type: 'hidden',
name: 'action',
value: 'send'
},{
xtype: 'row',
items: [{
xtype: 'col',
size: 12,
items: [{
xtype: 'div',
text: 'Compartir música',
id: 'share-music-button',
css: {'font-size': '23px', cursor: 'pointer'},
listeners: {
click: function(){
$(this).css({position: 'relative', 'border-bottom': '1px solid white'}).animate({top: '-10px'},'fast');
$('#form-music-box').animate({height: '100%'}, 'fast', function(){
$(this).css({height: 'auto', overflow: 'initial'});
});
$('#panel-add-music').find('.panel-heading').css('padding-bottom', '0px');
}
}
},{
xtype: 'div',
id: 'form-music-box',
css: {overflow:'hidden', height: '0px'},
items: [{
xtype: 'label',
text: 'Título',
margin: '0 0 5px 5px'
},{
xtype: 'input',
type: 'text',
name: 'titulo'
},{
xtype: 'label',
text: 'Descripción y enlaces',
margin: '15px 0 5px 5px'
},{
xtype: 'textarea',
name: 'enlace',
cls: 'form-control',
height: '140px'
},{
xtype: 'row',
items: [{
xtype: 'col',
size: {
xs: 12
},
id: 'add-music-tag',
css: {'padding-top': 0}
},{
xtype: 'col',
size: {
xs: 6,
sm: 4
},
padding: '5px 5px 0 0',
items: [{
xtype: 'button',
cls: 'pull-left',
text: 'Cancelar',
size: 'small',
listeners: {
click: function(){
$("textarea[name='enlace']").val('');
$("input[name='titulo']").val('');
$("#add-music-tag").find('.glyphicon-remove').click();
$('#form-music-box').css({overflow: 'hidden', height: '0px'});
$('#panel-add-music').find('.panel-heading').css('padding-bottom', '10px');
$('#share-music-button').css({'border-bottom': 'none'}).animate({top: '0px'},'fast');
}
}
}]
},{
xtype: 'col',
size: {
xs: 6,
sm: 4
},
items: [{
xtype: 'dropup',
group: {
cls: 'pull-right'
},
glyphicon: 'music',
caret: false,
css: {'margin-top': '6px'},
text: ' Añadir tag ',
size: 'small',
id: 'add-tag',
items: {
store: 'tags',
field: 'music',
xtype: 'a',
attr: {
'data-id': '{id}'
},
text: '{name}',
listeners: {
click: function(){
cb.ctr('gotorave', 'add_tag', this);
}
}
}
}]
},{
xtype: 'col',
size: {
xs: 12,
sm: 4
},
padding: '5px 0 0 0',
items: [{
xtype: 'button',
type: 'primary',
cls: 'pull-center',
text: 'Compartir',
width: '100%',
listeners: {
click: function(){
cb.ctr('gotorave', 'sharemusic');
}
}
}]
}]
}]
}]
}]
}]
}]
},{
xtype: 'body',
id: 'music-progress',
css: { display: 'none', padding: '0px' }
}]
},{
xtype: 'div',
id: 'music-content',
items: {
store: 'music',
field: 'msc',
css: { 'margin-top': '10px'},
xtype: 'panel',
type: 'info',
attr: {'data-id': '{id}'},
items: [{
xtype: 'head',
items: [{
xtype: 'review',
attr: {data: 'music'},
float: 'right',
css: {'margin-right': '-5px'}
},{
xtype: 'div',
cls: 'text-left',
css: {'font-size': '17px'},
field: 'titulo'
}]
},{
xtype: 'body',
items: [{
xtype: 'div',
css: {'text-align': 'center'},
html: '{enlace}'
}]
},{
xtype: 'footer',
css: {'overflow': 'auto'},
items: {
field: 'tags',
xtype: 'div',
cls: 'label label-default',
css: {
'margin-right': '10px',
'font-size': '17px'
},
text: '{name}'
}
}]
}
}]
}); | ci-bus/ci-bus | module/gotorave/view/musicView.js | JavaScript | mpl-2.0 | 4,602 |
/*
***** BEGIN LICENSE BLOCK *****
Version: MPL 1.1/GPL 2.0/LGPL 2.1
The contents of this source code are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this source code except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
for the specific language governing rights and limitations under the
License.
The Original Code is the FireGPG extension.
The Initial Developer of the Original Code is Maximilien Cuony.
Portions created by the Initial Developer are Copyright (C) 2007
the Initial Developer. All Rights Reserved.
Contributor(s): Asher256
Alternatively, the contents of this source code may be used under the terms of
either the GNU General Public License Version 2 or later (the "GPL"), or
the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
in which case the provisions of the GPL or the LGPL are applicable instead
of those above. If you wish to allow use of your version of this source code
only under the terms of either the GPL or the LGPL, and not to allow others to
use your version of this source code under the terms of the MPL, indicate your
decision by deleting the provisions above and replace them with the notice
and other provisions required by the GPL or the LGPL. If you do not delete
the provisions above, a recipient may use your version of this source code
under the terms of any one of the MPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****
*/
if (typeof(FireGPG)=='undefined') { FireGPG = {}; }
if (typeof(FireGPG.Const)=='undefined') { FireGPG.Const = {}; }
/* Constant: FireGPG.Const.Version
The current version of FireGPG */
FireGPG.Const.Version = '0.8';
/* Constant: FireGPG.Const.VersionA
The current verion of FireGPG without dots */
FireGPG.Const.VersionA = '08';
/* Constant: FireGPG.Const.Status
The status of the FireGPG's code. Can be _DEVEL_ or _RELASE_. Use _RELASE_ only for.. relases ;). */
FireGPG.Const.Status = 'RELASE';
/* Constant: FireGPG.Const.Svn
The current subversion's revision number, for this file ! */
FireGPG.Const.Svn = "$Rev: 663 $";
/*
Function: FireGPG.debug
Check if debuggin is enabled and if yes show up messages in console
Paramters:
message - The message
debugCode - The position in the code
fatal - True if it's a fatal error.
*/
FireGPG.debug = function(message, debugCode, fatal) {
if (FireGPG.Const.Status == "RELASE" && !fatal)
return;
if (message && message.lineNumber)
message = message.fileName + '@' + message.lineNumber + ' ' + message.message;
if (fatal)
Components.utils.reportError("FireGPG-debug: [" + debugCode + "]" + message);
else {
var consoleService = Components.classes["@mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
consoleService.logStringMessage("FireGPG-debug: [" + debugCode + "] " + message);
}
}
FireGPG.Misc = {
/*
Constants: Id for components.
NS_LOCALEFILE_CONTRACTID - Id for the component @mozilla.org/file/local;1
NS_DIRECTORYSERVICE_CONTRACTID - Id for the component @mozilla.org/file/directory_service;1
NS_NETWORKOUTPUT_CONTRACTID - Id for the component @mozilla.org/network/file-output-stream;1
NS_NETWORKINPUT_CONTRACTID - Id for the @mozilla.org/network/file-input-stream;1
NS_NETWORKINPUTS_CONTRACTID - Id for the component @mozilla.org/scriptableinputstream;1
NS_PROCESSUTIL_CONTRACTID - Id for the component @mozilla.org/process/util;1
*/
NS_LOCALEFILE_CONTRACTID: "@mozilla.org/file/local;1",
NS_DIRECTORYSERVICE_CONTRACTID: "@mozilla.org/file/directory_service;1",
NS_NETWORKOUTPUT_CONTRACTID: "@mozilla.org/network/file-output-stream;1",
NS_NETWORKINPUT_CONTRACTID: "@mozilla.org/network/file-input-stream;1",
NS_NETWORKINPUTS_CONTRACTID: "@mozilla.org/scriptableinputstream;1",
NS_PROCESSUTIL_CONTRACTID: "@mozilla.org/process/util;1",
/*
Constants: Tempory files
TMP_DIRECTORY - The base name for files (doesn't same to be a directory)
TMP_FILES - The file name for common files.
TMP_RFILES - The file name for executable scripts.
TMP_EFILES - The file name for executables..
*/
TMP_DIRECTORY: "TmpD",
TMP_FILES: "fgpg_tmpFile",
/*
Constants: Write modes for files.
WRITE_MODE - The default mode for files.
WRITE_PERMISSION - The default permission for files
WRITE_PERMISSION_R - The default permission for executable files
*/
WRITE_MODE: 0x02 | 0x08 | 0x20,
WRITE_PERMISSION: 0600,
WRITE_PERMISSION_R: 0777,
/*
Variable: savedPassword
The password of the private key, saved for later actions.
*/
savedPassword: null, /* the private key password */
/*
Variable: oldKeyID
The previous key selected.
*/
oldKeyID: '',
/*
Variable: updateAvailable
True if an update of FireGPG is available
*/
updateAvailable: false,
/*
Function: choosePublicKey
Show a dialog (list.xul) to choose a list of public keys (array).
null is returned if the public key is not choosed
Paramters:
preSelect - _Optional_. And array of keys to preselect.
*/
choosePublicKey: function(preSelect)
{
if(preSelect == undefined)
preSelect = {};
var params = {title: '', description: '', list: {}, selected_items: {}, preSelect: {}};
var i18n = document.getElementById("firegpg-strings");
params.title = i18n.getString('choosePublicKeyTitle');
params.description = i18n.getString('choosePublicKeyDescription');
keylistcall = FireGPG.Core.listKeys();
if (keylistcall.result == FireGPG.Const.Results.SUCCESS)
params.list = keylistcall.keylist;
else
return;
params.preSelect = preSelect;
var dlg = window.openDialog('chrome://firegpg/content/Dialogs/list.xul',
'', 'chrome, dialog, modal, resizable=yes',
params);
dlg.focus();
if(params.selected_items.length == 0 || params.selected_items.length == undefined)
{
return null;
} //If we have to, add the private key too.
else {
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.firegpg.");
try {
var to_my_self = prefs.getBoolPref("allvays_to_myself",false);
} catch (e) {
to_my_self = false;
}
if (to_my_self == true)
{
var selfKeyId = FireGPG.Misc.getSelfKey();
if (selfKeyId != null)
{
params.selected_items.push(selfKeyId);
}
}
}
return params.selected_items;
},
/*
Function: choosePrivateKey
Show a dialog (list.xul) to choose a private key.
null is returned if no keys are chosen.
Parameters:
preSelect - _Optional_. A list of key to preselect
*/
choosePrivateKey:function (preSelect)
{
if(preSelect == undefined)
preSelect = {};
var params = {title: '', description: '', list: {}, selected_item: null, preSelect: {}};
var i18n = document.getElementById("firegpg-strings");
params.title = i18n.getString('choosePrivateKeyTitle');
params.description = i18n.getString('choosePrivateKeyDescription');
keylistcall = FireGPG.Core.listKeys(true);
if (keylistcall.result == FireGPG.Const.Results.SUCCESS)
params.list = keylistcall.keylist;
else
return;
params.preSelect = preSelect;
var dlg = window.openDialog('chrome://firegpg/content/Dialogs/list.xul',
'', 'chrome, dialog, modal, resizable=yes',
params);
dlg.focus();
if(params.selected_items.length == 0)
{
params.selected_items = null;
return null;
}
return params.selected_items[0];
},
/*
Function: showText
Show 'text' in a dialog (the editor)
Parameters:
text - The text to show display
description - _Optional_. The message to show. If not set, use the default.
title - _Optional_. The title of the window. If not set, use the default.
doShowButtons - _Optional_. If we have to show buttons to encrypt and so. Default to false.
validSign - _Optional_. The message for the validSign field.
*/
showText:function (text, description, title, doShowButtons, validSign) {
/* default description and title values */
var i18n = document.getElementById("firegpg-strings");
/* setting params */
var params = {text: text, title: title, description: description, doShowButtons: doShowButtons, validSign: validSign};
if(title == undefined)
params.title = i18n.getString('showTextDefaultTitle');
if(description == undefined)
params.description = i18n.getString('showTextDefaultDescription');
if(doShowButtons == undefined)
params.doShowButtons = false;
if(validSign == undefined)
params.validSign = null;
/* open the dialog */
window.openDialog('chrome://firegpg/content/Dialogs/showtext.xul',
'', 'chrome, dialog, resizable=yes',
params).focus();
},
/*
Function: showEditor
Open the editor (the showtext.xul dialog)
*/
showEditor:function () {
var i18n = document.getElementById("firegpg-strings");
var title = i18n.getString('editorTitle');
var description = i18n.getString('editorDescription');
FireGPG.Misc.showText('',description,title);
},
/*
Function: getPassword
Show the generic dialog to get a password.
An object is returned :
{password: "password", save_password: true/false}$
null is returned if cancel button is clicked.
Parameters:
question - The text to show for the prompt.
save_password - _Optional_. The default value for the save password checkbox. If not set, value set in the options by the user is used.
domain - _Optional_. Say the password is asked form this page and disable the savepassword checkbox.
nosavecheckbox - _Optional_. Disable the save password feature
*/
getPassword:function (question, save_password, domain, nosavecheckbox) {
if(save_password == undefined) {
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.firegpg.");
try {
save_password = prefs.getBoolPref("default_memory");
} catch (e) {
save_password = false;
}
}
if (domain == undefined)
domain = false;
if (nosavecheckbox == undefined)
nosavecheckbox = false;
var params = {password: '',
save_password: save_password,
result: false, question: question, domain: domain, nosavecheckbox: nosavecheckbox};
var dlg = window.openDialog('chrome://firegpg/content/Dialogs/password.xul',
'', 'chrome, dialog, modal, resizable=yes', params);
dlg.focus();
if(params.result) {
if (domain == false && nosavecheckbox == false)
prefs.setBoolPref("default_memory",params.save_password);
return params;
}
return null;
},
/*
Function: savePassword
* TODO !*
Save a password in the password manager of Firefox
Parameters:
password - The password
*/
savePassword:function (password) {
},
/*
Function: getSavedPassword
* TODO !*
Get the password saved in the password manager of Firefox
*/
getSavedPassword:function () {
},
/*
Function: getPrivateKeyPassword
This uses getPassword:function () to get a password for a private key.
It's the user request for it, it's save the password for later.
If useSavedPassword = false, the password is asked each time,
even if it's already saved in the global variable savedPassword.
null is returned on error.
Parameters:
useSavedPassword - _Optional_. Set this to false to disable the use of a saved password
domain - _Optional_. The domain to pass to <getPassword>.
message - _Optional_. The message to ask the user.
nosavecheckbox - _Optional_. Disable the save password feature
*/
getPrivateKeyPassword:function (useSavedPassword /* default = true */, domain /* default = false*/, message /* default = false*/, nosavecheckbox) {
/* the default value of the optional variable */
if(useSavedPassword == undefined)
useSavedPassword = true;
if(domain == undefined)
domain = false;
if (nosavecheckbox == undefined)
nosavecheckbox = false;
/* return password if it's saved in savePassword */
if(useSavedPassword && FireGPG.Misc.savedPassword != null)
return FireGPG.Misc.savedPassword;
/* show the dialog ! */
if (message == undefined)
var question = document.getElementById('firegpg-strings').
getString('passwordDialogEnterPrivateKey');
else
var question = message;
var result = FireGPG.Misc.getPassword(question,undefined,domain, nosavecheckbox);
if(result == null)
return null;
if(result.save_password && domain == false && nosavecheckbox != true) {
FireGPG.Misc.savedPassword = result.password;
try {
document.getElementById('firegpg-menu-memo-pop').style.display = '';
document.getElementById('firegpg-menu-memo-menu').style.display = '';
//document.getElementById('firegpg-menu-memo-tool').style.display = '';
}
catch(e) { FireGPG.debug(e,'misc.getPrivateKeyPassword',true); }
}
return result.password;
},
/*
Function: getsavedPassword
Return the saved password
*/
getsavedPassword:function () {
return FireGPG.Misc.savedPassword;
},
/*
Function: eraseSavedPassword
This erase the saved password :function (it's for exemple when a sign failled)
*/
eraseSavedPassword:function () {
FireGPG.Misc.savedPassword = null;
try {
if (document.getElementById('firegpg-menu-memo-pop'))
document.getElementById('firegpg-menu-memo-pop').style.display = 'none';
if (document.getElementById('firegpg-menu-memo-menu'))
document.getElementById('firegpg-menu-memo-menu').style.display = 'none';
if (document.getElementById('firegpg-menu-memo-tool'))
document.getElementById('firegpg-menu-memo-tool').style.display = 'none';
}
catch (e) { }
},
/*
Function: getSelfKey
who return a private key for the user :function (the default or the one selected in the list)
null is returned if no key is selected.
Parameters:
autoSelectPrivate - _Optional_. A list of key to autoselect
*/
getSelfKey:function (autoSelectPrivate) {
var keyID;
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.firegpg.");
keyID = prefs.getCharPref("default_private_key");
/* we must ask for private key ? */
if(keyID == '')
keyID = FireGPG.Misc.choosePrivateKey(autoSelectPrivate);
/* request password if key id is changed */
if(keyID.toString() != FireGPG.Misc.oldKeyID.toString()) {
FireGPG.Misc.eraseSavedPassword();
}
FireGPG.Misc.oldKeyID = keyID;
return keyID;
},
/*
Function: getTmpDir
Get the path of a tmp file.
The path is returned.
*/
getTmpDir:function () {
return Components.classes[FireGPG.Misc.NS_DIRECTORYSERVICE_CONTRACTID].
getService(Components.interfaces.nsIProperties).
get(FireGPG.Misc.TMP_DIRECTORY, Components.interfaces.nsIFile);
},
/*
Function: getTmpFile
Get an unique temporary file name.
The path + filename is returned.
Parameters:
permission - _Optional_. The permission of the file. See <Write modes for files>
suffix_file - _Optional_. A suffix to add to the default file name.
*/
getTmpFile:function (permission /* optional */, suffix_file) {
if(permission == undefined)
permission = FireGPG.Misc.WRITE_PERMISSION;
var fileobj = FireGPG.Misc.getTmpDir();
if (permission == FireGPG.Misc.WRITE_PERMISSION_R)
var fileName = FireGPG.Misc.TMP_RFILES;
else
var fileName = FireGPG.Misc.TMP_FILES;
if(suffix_file != undefined)
fileName += '_S_' + suffix_file; //To be sure to be unique.
var date = new Date();
fileobj.append( Math.floor(Math.random() * 9999) + date.getTime() + Math.floor(Math.random() * 9999) + Math.floor(Math.random() * 9999) + fileName);
fileobj.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, permission);
fileobj.permissions = permission;
return fileobj.path;
},
/*
Function: removeFile
Delete a file.
Parameters:
path - The file to delete.
*/
removeFile:function (path) {
var fileobj = Components.classes[FireGPG.Misc.NS_LOCALEFILE_CONTRACTID].
createInstance(Components.interfaces.nsILocalFile);
fileobj.initWithPath(path);
try {
fileobj.remove(path);
}
catch (e) {
/* If file doesn't exist */
}
},
/*
Function: fileExist
Return true if a file exist
Parameters:
path - The file to delete.
*/
fileExist:function (path) {
var fileobj = Components.classes[FireGPG.Misc.NS_LOCALEFILE_CONTRACTID].
createInstance(Components.interfaces.nsILocalFile);
fileobj.initWithPath(path);
try {
return fileobj.exists();
}
catch (e) {
return false;
}
},
/*
Function: putIntoFile
Save data to a file. File saved in UTF-8 charset.
Parameters:
filename - The name of the file
data - The data to save
*/
putIntoFile:function (filename, data)
{
var fileobj = Components.classes[FireGPG.Misc.NS_LOCALEFILE_CONTRACTID].
createInstance(Components.interfaces.nsILocalFile);
fileobj.initWithPath(filename);
var foStream = Components.classes[FireGPG.Misc.NS_NETWORKOUTPUT_CONTRACTID].
createInstance(Components.interfaces.nsIFileOutputStream);
foStream.init(fileobj, FireGPG.Misc.WRITE_MODE, FireGPG.Misc.WRITE_PERMISSION, 0);
//foStream.write(data, data.length);
var charset = "UTF-8"; // Can be any character encoding name that Mozilla supports
var os = Components.classes["@mozilla.org/intl/converter-output-stream;1"]
.createInstance(Components.interfaces.nsIConverterOutputStream);
// This assumes that fos is the nsIOutputStream you want to write to
os.init(foStream, charset, 0, 0x0000);
os.writeString(data);
os.close();
foStream.close();
},
/*
Function: getFromFile
Get the content of a file
Parameters:
filename - The location of the file.
charset - _Optional_. The charset of the file. Default to UTF-8
*/
getFromFile:function (filename,charset) {
if (charset == undefined)
charset = "UTF-8";
try {
var fileobj = Components.classes[FireGPG.Misc.NS_LOCALEFILE_CONTRACTID].
createInstance(Components.interfaces.nsILocalFile);
fileobj.initWithPath(filename);
var data = "";
var fstream = Components.classes[FireGPG.Misc.NS_NETWORKINPUT_CONTRACTID].createInstance(Components.interfaces.nsIFileInputStream);
//var sstream2 = Components.classes[FireGPG.Misc.NS_NETWORKINPUTS_CONTRACTID].
// createInstance(Components.interfaces.nsIScriptableInputStream);
const replacementChar = Components.interfaces.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER;
// var charset = /* Need to find out what the character encoding is. Using UTF-8 for this example: */ "UTF-8";
var sstream = Components.classes["@mozilla.org/intl/converter-input-stream;1"].createInstance(Components.interfaces.nsIConverterInputStream);
fstream.init(fileobj, -1, 0, 0);
//sstream2.init(fstream);
// This assumes that fis is the nsIInputStream you want to read from
sstream.init(fstream, charset, 1024, 0xFFFD);
var str = {};
var lengtth = sstream.readString(4096, str);
while (lengtth > 0) {
data += str.value;
lengtth = sstream.readString(4096, str);
}
sstream.close();
fstream.close();
return data;
}
catch (e) { FireGPG.debug(e,'misc.getFromFile',true) }
return '';
},
/*
Function: putIntoBinFile
Save data to a file, in binary mode.
Parameters:
filename - The name of the file
data - The data to save
*/
putIntoBinFile:function (filename, data) {
// pngBinary already exists
var aFile = Components.classes["@mozilla.org/file/local;1"]
.createInstance(Components.interfaces.nsILocalFile);
aFile.initWithPath(filename);
var stream = Components.classes["@mozilla.org/network/safe-file-output-stream;1"]
.createInstance(Components.interfaces.nsIFileOutputStream);
stream.init(aFile, FireGPG.Misc.WRITE_MODE, FireGPG.Misc.WRITE_PERMISSION, 0); // write, create, truncate
stream.write(data, data.length);
if (stream instanceof Components.interfaces.nsISafeOutputStream) {
stream.finish();
} else {
stream.close();
}
},
/*
Function: getBinContent
Get the content of a binary file
Parameters:
aURL - The location of the file.
maxData - _Optional_. The max length of data to get. {MAX} is returned if there is too data
*/
getBinContent:function (aURL, maxData) {
var ioService = Components.classes["@mozilla.org/network/io-service;1"].
getService(Components.interfaces.nsIIOService);
var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
var channel = ioService.newChannel(aURL, null, null);
var input = channel.open();
//istream.init(input, -1, -1, false);
var bstream = Components.classes["@mozilla.org/binaryinputstream;1"]
.createInstance(Components.interfaces.nsIBinaryInputStream);
bstream.setInputStream(input);
//var bytes = bstream.readBytes(bstream.available());
var bytes = "";
while (bstream.available() != 0) {
if (maxData != undefined && (bytes.length + bstream.available()) > maxData) {
bstream.close();istream.close();
return "{MAX}";
}
bytes += bstream.readBytes(bstream.available());
}
return bytes;
},
/*
Function: getContent
Get the content of a resource form anywhere (like chrome://)
Parameters:
aURL - The location of the resource.
*/
getContent:function (aURL){
var ioService = Components.classes["@mozilla.org/network/io-service;1"].
getService(Components.interfaces.nsIIOService);
var scriptableStream = Components.classes["@mozilla.org/scriptableinputstream;1"].
getService(Components.interfaces.nsIScriptableInputStream);
var channel = ioService.newChannel(aURL, null, null);
var input = channel.open();
scriptableStream.init(input);
var str = scriptableStream.read(input.available());
scriptableStream.close();
input.close();
return str;
},
/*
Function: getContentXtttp
Get the content of a web resource by using a xmlhttprequest.
Parameters:
url - The url of the resource
*/
getContentXHttp:function (url)
{
p = new XMLHttpRequest();
p.onload = null;
p.open("GET", url, false);
p.send(null);
if ( p.status != "200" )
{
return null;
}
else
{
contenu = p.responseText;
return contenu;
}
},
/*
Function: testIfSomethingsIsNew
Test if user update FireGPG or if he have to update, and show the What is new page send a ping or propose to update FireGPG if relevant.
*/
testIfSomethingsIsNew:function () {
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.firegpg.");
/* Should we show the assistant ? */
var assistant = "";
try {
assistant = prefs.getBoolPref("assisant_has_already_been_executed");
} catch (e) { assistant = false}
if (!assistant) {
window.openDialog('chrome://firegpg/content/Dialogs/Assistant/1-welcome.xul','', 'chrome, dialog, resizable=false').focus();
prefs.setBoolPref("assisant_has_already_been_executed",true)
}
//Check des versions
var version = "";
try {
version = prefs.getCharPref("gpg_version");
} catch (e) { }
var em = Components.classes["@mozilla.org/extensions/manager;1"]
.getService(Components.interfaces.nsIExtensionManager);
var addon = em.getItemForID("firegpg@firegpg.team");
var versionAct = addon.version;
versionAct = FireGPG.Const.Version;
var i18n = document.getElementById("firegpg-strings");
if (version != versionAct)
{
prefs.setCharPref("gpg_version",versionAct)
/*var title = "FireGPG - What is new ?";
var description = "What is new in FireGPG ? (An anonymous ping has been send to FireGPG's team for stats.)";
try {
title = i18n.getString('whatIsNewTitle');
description = i18n.getString('whatIsNewDescription');
} catch (e) { }
//FireGPG.Misc.showText(FireGPG.Misc.getContent("chrome://firegpg/content/whatisnew.txt"),description,title,true);*/
//Show the page
gBrowser.selectedTab = gBrowser.addTab("http://getfiregpg.org/s/justupdated/" + versionAct);
//Send the ping
if (version == "")
var mode = "New";
else
var mode = version;
var misc = FireGPG.Misc.getContent("http://getfiregpg.org/stable/stats.php?version=" + versionAct + "&oldversion=" + mode);
} else {
//DESACTIVED FOR ADDON.MOZILLA.ORG/*
//Try to find an update, if it's needed.
var noUpdates = false;
try {
noUpdates = prefs.getBoolPref("no_updates");
} catch (e) { }
if (!noUpdates)
{
if (FireGPG.Misc.updateAvailable) {
if (document.getElementById('firegpg-statusbar-update'))
document.getElementById('firegpg-statusbar-update').style.display = '';
} else {
var Stamp = new Date();
var nbMs = Stamp.getTime();
var lastUpdate = 0;
try {
lastUpdate = parseInt(prefs.getCharPref("lastUpdateCheck"));
} catch (e) { }
//Not A Number
if (isNaN(lastUpdate))
lastUpdate = 0;
//One day
if (lastUpdate < (nbMs - (24 * 60 * 60 * 1000)))
{
prefs.setCharPref("lastUpdateCheck",nbMs);
//Get the last version
var updateData = FireGPG.Misc.getContent("http://getfiregpg.org/stable/update.rdf");
var toDetect = "NS1:version=\"" + versionAct + "\"";
if (updateData.indexOf('ec8030f7-c20a-464f-9b0e-13a3a9e97384') != -1 && updateData.indexOf(toDetect) == -1)
{
if (document.getElementById('firegpg-statusbar-update') != null) {
document.getElementById('firegpg-statusbar-update').style.display = '';
FireGPG.Misc.updateAvailable = true;
} else {
FireGPG.Misc.showUpdateDialog();
}
}
}
}
}
//*/
}
},
/*
Function: showUpdateDialog
Show the update dialog to let user update FireGPG
*/
showUpdateDialog:function () {
var i18n = document.getElementById("firegpg-strings");
var newVersion = "A new version of FireGPG is available, would you like to update now?";
try {
newVersion = i18n.getString('newVersionAlert');
} catch (e) { }
if (confirm(newVersion))
{
openUILink("http://getfiregpg.org/stable/firegpg.xpi");
}
FireGPG.Misc.updateAvailable = false;
if (document.getElementById('firegpg-statusbar-update') != null)
document.getElementById('firegpg-statusbar-update').style.display = 'none';
},
/*
Function: htmlEncode
Encode special chars (&, <, > et ") to they html values.
Parameters:
s - The text.
*/
htmlEncode:function (s) {
var str = new String(s);
str = str.replace(/&/g, "&");
str = str.replace(/</g, "<");
str = str.replace(/>/g, ">");
str = str.replace(/"/g, """);
return str;
},
/*
Function: gmailWrapping
This fuction approximates gmail's line-wrapping rules, so that
a message can be wrapped before it's signed, instead of after,
which would break the signature.
Parameters:
text - The text.
*/
gmailWrapping:function (text)
{
var lines = text.split("\n");
var result = "";
// Wrap each line
for (var i = 0; i < lines.length; i++)
{
// gmail doesn't wrap lines with less than 81 characters
// or lines that have been quoted from previous messages
// in the usual way, so we don't bother either.
if (lines[i].length <= 80 || lines[i].substring(0,2) == "> ")
result = result + lines[i] + "\n";
else
// If we're wrapping a line, each of the resulting
// lines shouldn't be longer than 70 characters
// unless it has to be.
result = result + FireGPG.Misc.wrap(lines[i], 70) + "\n";
}
return result;
},
/*
Function: wrap
This function wraps a single line of text into multiple lines,
each no longer than limit, unless a single word is too long.
Parameters:
text - The text.
limit - The maximum characters for one line.
*/
wrap:function (text, limit)
{
var result = "";
// Keep wrapping until the remainder is short enough.
while (text.length > limit)
{
var index = text.lastIndexOf(" ", limit);
// If the first word is too long, look for the first space
if (index == -1)
index = text.indexOf(" ");
// If there are no more spaces at all, give up.
if (index == -1)
{
break;
}
else
{
result = result + text.substring(0, index) + "\n";
text = text.substring(index + 1);
}
}
return result + text;
},
/*
Function: genreate_api_key
Generate and random string between 64 and 128 charactes, probably unique.
This is usefull for the api.
*/
genreate_api_key:function () {
var validchars = "";
var startvalid = "";
var minsize, maxsize, count, actualsize, random_value;
minsize = parseInt( 64 );
maxsize = parseInt( 128 );
startvalid = "";
validchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
actualsize = Math.floor( Math.random() * ( maxsize - minsize + 1 ) ) + minsize;
random_value = startvalid.charAt( Math.floor( Math.random() * startvalid.length ) );
for (count = 1; count < actualsize; count++){
random_value += validchars.charAt( Math.floor( Math.random() * validchars.length ) );
}
return random_value;
},
/*
Function: trim
Remove extra space at the end and the begging of the string.
Parameters:
str - The string
*/
trim :function (str){
return str.replace(/^\s+/, "").replace(/\s+$/, "");
},
/*
Function: TrimAndWash
Remove extra space at the end and the begging of the string, and remove \n
Parameters:
str - The string
*/
TrimAndWash:function (str) {
return FireGPG.Misc.trim(str).replace(/\n/, "");
},
/*
Function: EnigConvertGpgToUnicode
Convert the gpg --with-collums text (who are strangly encoded) into a uniform Unicode string.
This function is from Enigmail, same license as FireGPG.Core.
Parameters:
text - The text to convert
*/
EnigConvertGpgToUnicode:function (text) {
try {
if (typeof(text)=="string") {
text = text.replace(/\\x3a/ig, "\\e3A");
a=text.search(/\\x[0-9a-fA-F]{2}/);
while (a>=0) {
ch=unescape('%'+text.substr(a+2,2));
r= new RegExp("\\"+text.substr(a,4));
text=text.replace(r, ch);
a=text.search(/\\x[0-9a-fA-F]{2}/);
}
}
text = FireGPG.Misc.EnigConvertToUnicode(text, "utf-8");
} catch (ex) { FireGPG.debug(ex,'misc.EnigConvertGpgToUnicode',true); }
return text;
},
/*
Function: EnigConvertToUnicode
Convert the text, in the specified chaset, into an Unicode string.
This function is from Enigmail, same license as FireGPG.Core.
Parameters:
text - The text to convert
charset - The charset of the text.
*/
EnigConvertToUnicode:function (text, charset) {
if (!text || !charset || (charset.toLowerCase() == "iso-8859-1"))
return text;
// Encode plaintext
try {
var unicodeConv = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].getService(Components.interfaces.nsIScriptableUnicodeConverter);
unicodeConv.charset = charset;
return unicodeConv.ConvertToUnicode(text);
} catch (ex) {
FireGPG.debug(ex,'misc.EnigConvertToUnicode',true);
return text;
}
},
/*
Function: EnigConvertFromUnicode
Convert the text, in unicode, into an string in the specified chaset.
This function is from Enigmail, same license as FireGPG.Core.
Parameters:
text - The text to convert
charset - The charset of the text.
*/
EnigConvertFromUnicode:function (text, charset) {
if (!text || !charset || (charset.toLowerCase() == "iso-8859-1"))
return text;
// Encode plaintext
try {
var unicodeConv = Components.classes["@mozilla.org/intl/scriptableunicodeconverter"].getService(Components.interfaces.nsIScriptableUnicodeConverter);
unicodeConv.charset = charset;
return unicodeConv.ConvertFromUnicode(text);
} catch (ex) {
FireGPG.debug(ex,'misc.EnigConvertFromUnicode',true);
return text;
}
},
/*
Function: CreateTreeItemKey
Return a Treeitem for the key in parameter
Parameters:
key - The key
document - The current document.
forceId - If we have to force the id of the key
*/
CreateTreeItemKey:function (key, document, forceId) {
var item = document.createElement('treeitem');
var row = document.createElement('treerow');
var child1 = document.createElement('treecell');
child1.setAttribute('label', key.keyName);
row.appendChild(child1);
var child2 = document.createElement('treecell');
child2.setAttribute('label', key.keyId);
row.appendChild(child2);
var child3 = document.createElement('treecell');
child3.setAttribute('label', key.keyDate);
row.appendChild(child3);
var child4 = document.createElement('treecell');
child4.setAttribute('label', key.keyExpi);
row.appendChild(child4);
var id = key.keyId;
if (forceId != undefined)
id = forceId;
row.setAttribute('gpg-id', id);
item.appendChild(row);
return item;
},
/*
Function: CreateTreeItemKey2
Return a Treeitem for the key in parameter
Parameters:
key - The key
document - The current document.
forceId - If we have to force the id of the key
privateKey - True if it's a private key
subkey - True if it's a subkey
*/
CreateTreeItemKey2:function (key, document, forceId, privateKey, subkey) {
var turstList = new Array();
turstList['-'] = 'trustUndef';
turstList['q'] = 'trustUndef';
turstList['n'] = 'trustDont';
turstList['m'] = 'trustMargi';
turstList['f'] = 'trustFull';
turstList['u'] = 'trustUltimate';
turstList['e'] = 'trustExpired';
turstList['r'] = 'trustRevoqued';
var item = document.createElement('treeitem');
var row = document.createElement('treerow');
var child1 = document.createElement('treecell');
child1.setAttribute('label', key.keyName);
child1 = FireGPG.Misc.setSkinForKey(key, child1, privateKey);
row.appendChild(child1);
var child2 = document.createElement('treecell');
child2.setAttribute('label', key.keyId);
child2 = FireGPG.Misc.setSkinForKey(key, child2, privateKey);
row.appendChild(child2);
var child3 = document.createElement('treecell');
child3.setAttribute('label', key.keyDate);
child3 = FireGPG.Misc.setSkinForKey(key, child3, privateKey);
row.appendChild(child3);
var child4 = document.createElement('treecell');
child4.setAttribute('label', key.keyExpi);
child4 = FireGPG.Misc.setSkinForKey(key, child4, privateKey);
row.appendChild(child4);
var child5 = document.createElement('treecell');
child5.setAttribute('label', document.getElementById('firegpg-strings').
getString(turstList[key.keyTrust]));
child5 = FireGPG.Misc.setSkinForKey(key, child5, privateKey);
if (key.revoked) {
child5.setAttribute('label', document.getElementById('firegpg-strings').
getString(turstList['r']));
}
row.appendChild(child5);
var id = key.keyId;
if (forceId != undefined)
id = forceId;
row.setAttribute('gpg-id', id);
row.setAttribute('gpg-rid', key.keyId);
row.setAttribute('gpg-fingerprint', key.fingerPrint);
if (privateKey == true)
row.setAttribute('gpg-privatekey', 'privatekey');
if (key.revoked)
row.setAttribute('gpg-revokedkey', 'revokedkey');
if (subkey)
row.setAttribute('gpg-subkey', 'subkey');
item.appendChild(row);
return item;
},
/*
Function: setSkinForKey
Set the correct class of a key, using his status (private, revoked)
Parameters:
key - The key
child - The element
privateKEy - True if it's a private key
*/
setSkinForKey:function (key, child, privateKey) {
if (privateKey == true)
child.setAttribute('properties', 'privatekey');
if (key.revoked)
child.setAttribute('properties', 'revokedkey');
if (key.revoked && privateKey)
child.setAttribute('properties', 'revokedprivatekey');
return child;
},
/*
Function: CreateTreeItemKey3
Return a Treeitem for the key in parameter
Parameters:
key - The key
document - The current document.
mainKey - The partent key of the key
sign - The sign of the key
havePrivate - If the user have the private key
*/
CreateTreeItemKey3:function (key, document, mainKey, sign, havePrivate) {
var item = document.createElement('treeitem');
var row = document.createElement('treerow');
var child1 = document.createElement('treecell');
child1.setAttribute('label', key.keyName);
child1 = FireGPG.Misc.setSkinForKey2(key, child1, mainKey, sign, havePrivate);
row.appendChild(child1);
var child2 = document.createElement('treecell');
child2.setAttribute('label', key.keyId);
child2 = FireGPG.Misc.setSkinForKey2(key, child2, mainKey, sign, havePrivate);
row.appendChild(child2);
var child3 = document.createElement('treecell');
child3.setAttribute('label', key.keyDate);
child3 = FireGPG.Misc.setSkinForKey2(key, child3, mainKey, sign, havePrivate);
row.appendChild(child3);
var id = key.keyId;
row.setAttribute('gpg-id', id);
if (sign && havePrivate)
row.setAttribute('gpg-haveprivate', 'haveprivate');
item.appendChild(row);
return item;
},
/*
Function: setSkinForKey2
Set class for a node with the key attribute
Parameters:
key - The key
child - The node
mainKey - The partent key of the key
sign - The sign of the key
havePrivate - If the user have the private key
*/
setSkinForKey2:function (key, child, mainKey, sign, havePrivate) {
if (mainKey == true)
child.setAttribute('properties', 'mainkey');
if (mainKey == false && sign == false)
child.setAttribute('properties', 'subkey');
if (sign == true)
child.setAttribute('properties', 'sign');
if (sign && havePrivate)
child.setAttribute('properties', 'signwithprivatekey');
return child;
},
/*
Function: getKeyServer
Return the current key server
*/
getKeyServer:function () {
var prefs = Components.classes["@mozilla.org/preferences-service;1"].
getService(Components.interfaces.nsIPrefService);
prefs = prefs.getBranch("extensions.firegpg.");
try {
keyserver = prefs.getCharPref("keyserver");
} catch (e) {
keyserver = "";
}
if (keyserver == "") {
keyserver = "pgp.mit.edu";
prefs.setCharPref("keyserver", "pgp.mit.edu");
}
return keyserver;
},
/*
Function: showSearchBox
Show the dialog box to search key
Paramters:
autoSearch - Preset the search field
*/
showSearchBox:function (autoSearch) {
window.openDialog("chrome://firegpg/content/Dialogs/Keymanager/searchkey.xul", "searchBox", "chrome,centerscreen", {autoSearch: autoSearch}).focus();
},
/*
Function: convertCRLFToStandarts
Convert CR to CRLF, LF to CRLF and keep CRLF
Parameters:
text - The text
*/
convertCRLFToStandarts:function (text) {
//Standarts say: \r\n, stoo.
text = text.replace(/\r\n/ig, "\n"); // \r\n -> \n
text = text.replace(/\r/ig, "\n"); // \r -> \n
text = text.replace(/\n/ig, "\r\n"); // \n -> \r\n
return text;
},
/*
Function: dumper
This function was inspired by the print_r function of PHP.
This will accept some data as the argument and return a
text that will be a more readable version of the
array/hash/object that is given.
Paramters:
arr - The object
level - The current level of the dump
*/
dumper:function (arr,level) {
var dumped_text = "";
if(!level) level = 0;
//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += " ";
if(typeof(arr) == 'object') { //Array/Hashes/Objects
for(var item in arr) {
var value = arr[item];
if(typeof(value) == 'object') { //If it is an array,
dumped_text += level_padding + "'" + item + "' ...\n";
dumped_text += FireGPG.Misc.dumper(value,level+1);
} else {
dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
}
}
} else { //Stings/Chars/Numbers etc.
dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
},
/*
Function: dump2
Show an array or an object in a console
Parameters:
o - The object
*/
dump2:function (o) {
for (i in o) {
if (o[i])
FireGPG.debug(o[i], i, true);
if (o.i)
FireGPG.debug(o.i, '~' + i, true);
}
},
/*
Class: UTF8
Class to handle UTF8 tests.
http://snippets.dzone.com/posts/show/5294
*/
UTF8: {
/*
Function: encode
Encode a text to utf8
Parameters:
s - The text
*/
encode: function(s){
for(var c, i = -1, l = (s = s.split("")).length, o = String.fromCharCode; ++i < l;
s[i] = (c = s[i].charCodeAt(0)) >= 127 ? o(0xc0 | (c >>> 6)) + o(0x80 | (c & 0x3f)) : s[i]
);
return s.join("");
},
/*
Function: decode
Decode a utf8 text
Parameters:
s - The text
*/
decode: function(s){
for(var a, b, i = -1, l = (s = s.split("")).length, o = String.fromCharCode, c = "charCodeAt"; ++i < l;
((a = s[i][c](0)) & 0x80) &&
(s[i] = (a & 0xfc) == 0xc0 && ((b = s[i + 1][c](0)) & 0xc0) == 0x80 ?
o(((a & 0x03) << 6) + (b & 0x3f)) : o(128), s[++i] = "")
);
return s.join("");
}
},
/*
Class: Base64
Class to handle base64 encoding
http://www.webtoolkit.info/
*/
Base64:{
/*
Variable: _keyStr
Valid base64 chars
*/
_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
/*
Function: encode
Encode to base6
Parameters:
input - The text
bMode - Convert to utf8
*/
encode: function (input,bMode) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
if (bMode != true)
input = FireGPG.Misc.Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
}
return output;
},
/*
Function: decode
Decode a base64 string
Paramters:
input - The text
bMode - Decode from utf8
*/
decode : function (input,bMode) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = this._keyStr.indexOf(input.charAt(i++));
enc2 = this._keyStr.indexOf(input.charAt(i++));
enc3 = this._keyStr.indexOf(input.charAt(i++));
enc4 = this._keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
if (bMode != true)
output = FireGPG.Misc.Base64._utf8_decode(output);
return output;
},
/*
Function: _utf8_encode
Encode a string to utf8
Parameters:
string - The string
*/
_utf8_encode:function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
/*
Function: _utf8_decode
Decode string from utf8
Parameters:
utftext - The text
*/
_utf8_decode :function (utftext) {
var string = "";
var i = 0;
var c = 0;
var c1 = 0;
var c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
},
/*
Function: pgpencode
Useless function who do nothing
Parameters:
texte - A variable. Cool.
*/
pgpencode: function(texte) {
}
},
/*
Function: getFileExtention
Return the extention of a file
Parameters:
filename - The file name
*/
getFileExtention:function (filename) {
return filename.substring(filename.length - 3,filename.length).toLowerCase();
}
}
| Asher256/firegpg | content/Core/misc.js | JavaScript | mpl-2.0 | 54,690 |
'use strict';
export const Counts = new Mongo.Collection('counts');
| algorithm-ninja/shuriken | shuriken-web/imports/api/counts.js | JavaScript | agpl-3.0 | 69 |
'use strict';
var CONSTANTS = require('../constants');
var denormalize = require('./denormalize');
module.exports = function(dependencies) {
var listeners = dependencies('elasticsearch').listeners;
function getOptions() {
return {
events: {
add: CONSTANTS.NOTIFICATIONS.EVENT_ADDED,
update: CONSTANTS.NOTIFICATIONS.EVENT_UPDATED,
remove: CONSTANTS.NOTIFICATIONS.EVENT_DELETED
},
denormalize: denormalize.denormalize,
getId: denormalize.getId,
type: CONSTANTS.SEARCH.TYPE_NAME,
index: CONSTANTS.SEARCH.INDEX_NAME
};
}
function register() {
return listeners.addListener(getOptions());
}
return {
register: register,
getOptions: getOptions
};
};
| heroandtn3/openpaas-esn | modules/linagora.esn.calendar/backend/lib/search/searchHandler.js | JavaScript | agpl-3.0 | 743 |
/**
* @class Ext.JSON
* Modified version of Douglas Crockford's JSON.js that doesn't
* mess with the Object prototype
* http://www.json.org/js.html
* @singleton
*/
Ext.JSON = new(function() {
var me = this,
encodingFunction,
decodingFunction,
useNative = null,
useHasOwn = !! {}.hasOwnProperty,
isNative = function() {
if (useNative === null) {
useNative = Ext.USE_NATIVE_JSON && window.JSON && JSON.toString() == '[object JSON]';
}
return useNative;
},
pad = function(n) {
return n < 10 ? "0" + n : n;
},
doDecode = function(json) {
return eval("(" + json + ')');
},
doEncode = function(o, newline) {
// http://jsperf.com/is-undefined
if (o === null || o === undefined) {
return "null";
} else if (Ext.isDate(o)) {
return Ext.JSON.encodeDate(o);
} else if (Ext.isString(o)) {
return encodeString(o);
}
// Allow custom zerialization by adding a toJSON method to any object type.
// Date/String have a toJSON in some environments, so check these first.
else if (o.toJSON) {
return o.toJSON();
} else if (Ext.isArray(o)) {
return encodeArray(o, newline);
} else if (typeof o == "number") {
//don't use isNumber here, since finite checks happen inside isNumber
return isFinite(o) ? String(o) : "null";
} else if (Ext.isBoolean(o)) {
return String(o);
} else if (Ext.isObject(o)) {
return encodeObject(o, newline);
} else if (typeof o === "function") {
return "null";
}
return 'undefined';
},
m = {
"\b": '\\b',
"\t": '\\t',
"\n": '\\n',
"\f": '\\f',
"\r": '\\r',
'"': '\\"',
"\\": '\\\\',
'\x0b': '\\u000b' //ie doesn't handle \v
},
charToReplace = /[\\\"\x00-\x1f\x7f-\uffff]/g,
encodeString = function(s) {
return '"' + s.replace(charToReplace, function(a) {
var c = m[a];
return typeof c === 'string' ? c : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
}) + '"';
},
//<debug>
encodeArrayPretty = function(o, newline) {
var len = o.length,
cnewline = newline + ' ',
sep = ',' + cnewline,
a = ["[", cnewline], // Note newline in case there are no members
i;
for (i = 0; i < len; i += 1) {
a.push(doEncode(o[i], cnewline), sep);
}
// Overwrite trailing comma (or empty string)
a[a.length - 1] = newline + ']';
return a.join('');
},
encodeObjectPretty = function(o, newline) {
var cnewline = newline + ' ',
sep = ',' + cnewline,
a = ["{", cnewline], // Note newline in case there are no members
i;
for (i in o) {
if (!useHasOwn || o.hasOwnProperty(i)) {
a.push(doEncode(i) + ': ' + doEncode(o[i], cnewline), sep);
}
}
// Overwrite trailing comma (or empty string)
a[a.length - 1] = newline + '}';
return a.join('');
},
//</debug>
encodeArray = function(o, newline) {
//<debug>
if (newline) {
return encodeArrayPretty(o, newline);
}
//</debug>
var a = ["[", ""], // Note empty string in case there are no serializable members.
len = o.length,
i;
for (i = 0; i < len; i += 1) {
a.push(doEncode(o[i]), ',');
}
// Overwrite trailing comma (or empty string)
a[a.length - 1] = ']';
return a.join("");
},
encodeObject = function(o, newline) {
//<debug>
if (newline) {
return encodeObjectPretty(o, newline);
}
//</debug>
var a = ["{", ""], // Note empty string in case there are no serializable members.
i;
for (i in o) {
if (!useHasOwn || o.hasOwnProperty(i)) {
a.push(doEncode(i), ":", doEncode(o[i]), ',');
}
}
// Overwrite trailing comma (or empty string)
a[a.length - 1] = '}';
return a.join("");
};
/**
* The function which {@link #encode} uses to encode all javascript values to their JSON representations
* when {@link Ext#USE_NATIVE_JSON} is `false`.
*
* This is made public so that it can be replaced with a custom implementation.
*
* @param {Object} o Any javascript value to be converted to its JSON representation
* @return {String} The JSON representation of the passed value.
* @method
*/
me.encodeValue = doEncode;
/**
* Encodes a Date. This returns the actual string which is inserted into the JSON string as the literal expression.
* **The returned value includes enclosing double quotation marks.**
*
* The default return format is "yyyy-mm-ddThh:mm:ss".
*
* To override this:
* Ext.JSON.encodeDate = function(d) {
* return Ext.Date.format(d, '"Y-m-d"');
* };
*
* @param {Date} d The Date to encode
* @return {String} The string literal to use in a JSON string.
*/
me.encodeDate = function(o) {
return '"' + o.getFullYear() + "-"
+ pad(o.getMonth() + 1) + "-"
+ pad(o.getDate()) + "T"
+ pad(o.getHours()) + ":"
+ pad(o.getMinutes()) + ":"
+ pad(o.getSeconds()) + '"';
};
/**
* Encodes an Object, Array or other value.
*
* If the environment's native JSON encoding is not being used ({@link Ext#USE_NATIVE_JSON} is not set, or the environment does not support it), then
* ExtJS's encoding will be used. This allows the developer to add a `toJSON` method to their classes which need serializing to return a valid
* JSON representation of the object.
*
* @param {Object} o The variable to encode
* @return {String} The JSON string
*/
me.encode = function(o) {
if (!encodingFunction) {
// setup encoding function on first access
encodingFunction = isNative() ? JSON.stringify : me.encodeValue;
}
return encodingFunction(o);
};
/**
* Decodes (parses) a JSON string to an object. If the JSON is invalid, this function throws a SyntaxError unless the safe option is set.
* @param {String} json The JSON string
* @param {Boolean} safe (optional) Whether to return null or throw an exception if the JSON is invalid.
* @return {Object} The resulting object
*/
me.decode = function(json, safe) {
if (!decodingFunction) {
// setup decoding function on first access
decodingFunction = isNative() ? JSON.parse : doDecode;
}
try {
return decodingFunction(json);
} catch (e) {
if (safe === true) {
return null;
}
Ext.Error.raise({
sourceClass: "Ext.JSON",
sourceMethod: "decode",
msg: "You're trying to decode an invalid JSON String: " + json
});
}
};
})();
/**
* Shorthand for {@link Ext.JSON#encode}
* @member Ext
* @method encode
* @inheritdoc Ext.JSON#encode
*/
Ext.encode = Ext.JSON.encode;
/**
* Shorthand for {@link Ext.JSON#decode}
* @member Ext
* @method decode
* @inheritdoc Ext.JSON#decode
*/
Ext.decode = Ext.JSON.decode;
/**
* @class Ext
*
* The Ext namespace (global object) encapsulates all classes, singletons, and
* utility methods provided by Sencha's libraries.
*
* Most user interface Components are at a lower level of nesting in the namespace,
* but many common utility functions are provided as direct properties of the Ext namespace.
*
* Also many frequently used methods from other classes are provided as shortcuts
* within the Ext namespace. For example {@link Ext#getCmp Ext.getCmp} aliases
* {@link Ext.ComponentManager#get Ext.ComponentManager.get}.
*
* Many applications are initiated with {@link Ext#onReady Ext.onReady} which is
* called once the DOM is ready. This ensures all scripts have been loaded,
* preventing dependency issues. For example:
*
* Ext.onReady(function(){
* new Ext.Component({
* renderTo: document.body,
* html: 'DOM ready!'
* });
* });
*
* For more information about how to use the Ext classes, see:
*
* - <a href="http://www.sencha.com/learn/">The Learning Center</a>
* - <a href="http://www.sencha.com/learn/Ext_FAQ">The FAQ</a>
* - <a href="http://www.sencha.com/forum/">The forums</a>
*
* @singleton
*/
Ext.apply(Ext, {
userAgent: navigator.userAgent.toLowerCase(),
cache: {},
idSeed: 1000,
windowId: 'ext-window',
documentId: 'ext-document',
/**
* True when the document is fully initialized and ready for action
*/
isReady: false,
/**
* True to automatically uncache orphaned Ext.Elements periodically
*/
enableGarbageCollector: true,
/**
* True to automatically purge event listeners during garbageCollection.
*/
enableListenerCollection: true,
/**
* Generates unique ids. If the element already has an id, it is unchanged
* @param {HTMLElement/Ext.Element} [el] The element to generate an id for
* @param {String} prefix (optional) Id prefix (defaults "ext-gen")
* @return {String} The generated Id.
*/
id: function(el, prefix) {
var me = this,
sandboxPrefix = '';
el = Ext.getDom(el, true) || {};
if (el === document) {
el.id = me.documentId;
}
else if (el === window) {
el.id = me.windowId;
}
if (!el.id) {
if (me.isSandboxed) {
sandboxPrefix = Ext.sandboxName.toLowerCase() + '-';
}
el.id = sandboxPrefix + (prefix || "ext-gen") + (++Ext.idSeed);
}
return el.id;
},
/**
* Returns the current document body as an {@link Ext.Element}.
* @return Ext.Element The document body
*/
getBody: function() {
var body;
return function() {
return body || (body = Ext.get(document.body));
};
}(),
/**
* Returns the current document head as an {@link Ext.Element}.
* @return Ext.Element The document head
* @method
*/
getHead: function() {
var head;
return function() {
return head || (head = Ext.get(document.getElementsByTagName("head")[0]));
};
}(),
/**
* Returns the current HTML document object as an {@link Ext.Element}.
* @return Ext.Element The document
*/
getDoc: function() {
var doc;
return function() {
return doc || (doc = Ext.get(document));
};
}(),
/**
* This is shorthand reference to {@link Ext.ComponentManager#get}.
* Looks up an existing {@link Ext.Component Component} by {@link Ext.Component#id id}
*
* @param {String} id The component {@link Ext.Component#id id}
* @return Ext.Component The Component, `undefined` if not found, or `null` if a
* Class was found.
*/
getCmp: function(id) {
return Ext.ComponentManager.get(id);
},
/**
* Returns the current orientation of the mobile device
* @return {String} Either 'portrait' or 'landscape'
*/
getOrientation: function() {
return window.innerHeight > window.innerWidth ? 'portrait' : 'landscape';
},
/**
* Attempts to destroy any objects passed to it by removing all event listeners, removing them from the
* DOM (if applicable) and calling their destroy functions (if available). This method is primarily
* intended for arguments of type {@link Ext.Element} and {@link Ext.Component}, but any subclass of
* {@link Ext.util.Observable} can be passed in. Any number of elements and/or components can be
* passed into this function in a single call as separate arguments.
*
* @param {Ext.Element/Ext.Component/Ext.Element[]/Ext.Component[]...} args
* An {@link Ext.Element}, {@link Ext.Component}, or an Array of either of these to destroy
*/
destroy: function() {
var ln = arguments.length,
i, arg;
for (i = 0; i < ln; i++) {
arg = arguments[i];
if (arg) {
if (Ext.isArray(arg)) {
this.destroy.apply(this, arg);
}
else if (Ext.isFunction(arg.destroy)) {
arg.destroy();
}
else if (arg.dom) {
arg.remove();
}
}
}
},
/**
* Execute a callback function in a particular scope. If no function is passed the call is ignored.
*
* For example, these lines are equivalent:
*
* Ext.callback(myFunc, this, [arg1, arg2]);
* Ext.isFunction(myFunc) && myFunc.apply(this, [arg1, arg2]);
*
* @param {Function} callback The callback to execute
* @param {Object} [scope] The scope to execute in
* @param {Array} [args] The arguments to pass to the function
* @param {Number} [delay] Pass a number to delay the call by a number of milliseconds.
*/
callback: function(callback, scope, args, delay){
if(Ext.isFunction(callback)){
args = args || [];
scope = scope || window;
if (delay) {
Ext.defer(callback, delay, scope, args);
} else {
callback.apply(scope, args);
}
}
},
/**
* Alias for {@link Ext.String#htmlEncode}.
* @inheritdoc Ext.String#htmlEncode
*/
htmlEncode : function(value) {
return Ext.String.htmlEncode(value);
},
/**
* Alias for {@link Ext.String#htmlDecode}.
* @inheritdoc Ext.String#htmlDecode
*/
htmlDecode : function(value) {
return Ext.String.htmlDecode(value);
},
/**
* Alias for {@link Ext.String#urlAppend}.
* @inheritdoc Ext.String#urlAppend
*/
urlAppend : function(url, s) {
return Ext.String.urlAppend(url, s);
}
});
Ext.ns = Ext.namespace;
// for old browsers
window.undefined = window.undefined;
/**
* @class Ext
*/
(function(){
/*
FF 3.6 - Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.17) Gecko/20110420 Firefox/3.6.17
FF 4.0.1 - Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1
FF 5.0 - Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0
IE6 - Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1;)
IE7 - Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; SV1;)
IE8 - Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)
IE9 - Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
Chrome 11 - Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.60 Safari/534.24
Safari 5 - Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1
Opera 11.11 - Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11
*/
var check = function(regex){
return regex.test(Ext.userAgent);
},
isStrict = document.compatMode == "CSS1Compat",
version = function (is, regex) {
var m;
return (is && (m = regex.exec(Ext.userAgent))) ? parseFloat(m[1]) : 0;
},
docMode = document.documentMode,
isOpera = check(/opera/),
isOpera10_5 = isOpera && check(/version\/10\.5/),
isChrome = check(/\bchrome\b/),
isWebKit = check(/webkit/),
isSafari = !isChrome && check(/safari/),
isSafari2 = isSafari && check(/applewebkit\/4/), // unique to Safari 2
isSafari3 = isSafari && check(/version\/3/),
isSafari4 = isSafari && check(/version\/4/),
isSafari5 = isSafari && check(/version\/5/),
isIE = !isOpera && check(/msie/),
isIE7 = isIE && ((check(/msie 7/) && docMode != 8 && docMode != 9) || docMode == 7),
isIE8 = isIE && ((check(/msie 8/) && docMode != 7 && docMode != 9) || docMode == 8),
isIE9 = isIE && ((check(/msie 9/) && docMode != 7 && docMode != 8) || docMode == 9),
isIE6 = isIE && check(/msie 6/),
isGecko = !isWebKit && check(/gecko/),
isGecko3 = isGecko && check(/rv:1\.9/),
isGecko4 = isGecko && check(/rv:2\.0/),
isGecko5 = isGecko && check(/rv:5\./),
isGecko10 = isGecko && check(/rv:10\./),
isFF3_0 = isGecko3 && check(/rv:1\.9\.0/),
isFF3_5 = isGecko3 && check(/rv:1\.9\.1/),
isFF3_6 = isGecko3 && check(/rv:1\.9\.2/),
isWindows = check(/windows|win32/),
isMac = check(/macintosh|mac os x/),
isLinux = check(/linux/),
scrollbarSize = null,
chromeVersion = version(true, /\bchrome\/(\d+\.\d+)/),
firefoxVersion = version(true, /\bfirefox\/(\d+\.\d+)/),
ieVersion = version(isIE, /msie (\d+\.\d+)/),
operaVersion = version(isOpera, /version\/(\d+\.\d+)/),
safariVersion = version(isSafari, /version\/(\d+\.\d+)/),
webKitVersion = version(isWebKit, /webkit\/(\d+\.\d+)/),
isSecure = /^https/i.test(window.location.protocol);
// remove css image flicker
try {
document.execCommand("BackgroundImageCache", false, true);
} catch(e) {}
//<debug>
var primitiveRe = /string|number|boolean/;
function dumpObject (object) {
var member, type, value, name,
members = [];
// Cannot use Ext.encode since it can recurse endlessly (if we're lucky)
// ...and the data could be prettier!
for (name in object) {
if (object.hasOwnProperty(name)) {
value = object[name];
type = typeof value;
if (type == "function") {
continue;
}
if (type == 'undefined') {
member = type;
} else if (value === null || primitiveRe.test(type) || Ext.isDate(value)) {
member = Ext.encode(value);
} else if (Ext.isArray(value)) {
member = '[ ]';
} else if (Ext.isObject(value)) {
member = '{ }';
} else {
member = type;
}
members.push(Ext.encode(name) + ': ' + member);
}
}
if (members.length) {
return ' \nData: {\n ' + members.join(',\n ') + '\n}';
}
return '';
}
function log (message) {
var options, dump,
con = Ext.global.console,
level = 'log',
indent = log.indent || 0,
stack;
log.indent = indent;
if (typeof message != 'string') {
options = message;
message = options.msg || '';
level = options.level || level;
dump = options.dump;
stack = options.stack;
if (options.indent) {
++log.indent;
} else if (options.outdent) {
log.indent = indent = Math.max(indent - 1, 0);
}
if (dump && !(con && con.dir)) {
message += dumpObject(dump);
dump = null;
}
}
if (arguments.length > 1) {
message += Array.prototype.slice.call(arguments, 1).join('');
}
message = indent ? Ext.String.repeat(' ', log.indentSize * indent) + message : message;
// w/o console, all messages are equal, so munge the level into the message:
if (level != 'log') {
message = '[' + level.charAt(0).toUpperCase() + '] ' + message;
}
// Not obvious, but 'console' comes and goes when Firebug is turned on/off, so
// an early test may fail either direction if Firebug is toggled.
//
if (con) { // if (Firebug-like console)
if (con[level]) {
con[level](message);
} else {
con.log(message);
}
if (dump) {
con.dir(dump);
}
if (stack && con.trace) {
// Firebug's console.error() includes a trace already...
if (!con.firebug || level != 'error') {
con.trace();
}
}
} else {
if (Ext.isOpera) {
opera.postError(message);
} else {
var out = log.out,
max = log.max;
if (out.length >= max) {
// this formula allows out.max to change (via debugger), where the
// more obvious "max/4" would not quite be the same
Ext.Array.erase(out, 0, out.length - 3 * Math.floor(max / 4)); // keep newest 75%
}
out.push(message);
}
}
// Mostly informational, but the Ext.Error notifier uses them:
++log.count;
++log.counters[level];
}
function logx (level, args) {
if (typeof args[0] == 'string') {
args.unshift({});
}
args[0].level = level;
log.apply(this, args);
}
log.error = function () {
logx('error', Array.prototype.slice.call(arguments));
}
log.info = function () {
logx('info', Array.prototype.slice.call(arguments));
}
log.warn = function () {
logx('warn', Array.prototype.slice.call(arguments));
}
log.count = 0;
log.counters = { error: 0, warn: 0, info: 0, log: 0 };
log.indentSize = 2;
log.out = [];
log.max = 750;
log.show = function () {
window.open('','extlog').document.write([
'<html><head><script type="text/javascript">',
'var lastCount = 0;',
'function update () {',
'var ext = window.opener.Ext,',
'extlog = ext && ext.log;',
'if (extlog && extlog.out && lastCount != extlog.count) {',
'lastCount = extlog.count;',
'var s = "<tt>" + extlog.out.join("~~~").replace(/[&]/g, "&").replace(/[<]/g, "<").replace(/[ ]/g, " ").replace(/\\~\\~\\~/g, "<br>") + "</tt>";',
'document.body.innerHTML = s;',
'}',
'setTimeout(update, 1000);',
'}',
'setTimeout(update, 1000);',
'</script></head><body></body></html>'].join(''));
};
//</debug>
var nullLog = function () {};
nullLog.info = nullLog.warn = nullLog.error = Ext.emptyFn;
Ext.setVersion('extjs', '4.1.0');
Ext.apply(Ext, {
/**
* @property {String} SSL_SECURE_URL
* URL to a blank file used by Ext when in secure mode for iframe src and onReady src
* to prevent the IE insecure content warning (`'about:blank'`, except for IE
* in secure mode, which is `'javascript:""'`).
*/
SSL_SECURE_URL : isSecure && isIE ? 'javascript:\'\'' : 'about:blank',
/**
* @property {Boolean} enableFx
* True if the {@link Ext.fx.Anim} Class is available.
*/
/**
* @property {Boolean} scopeResetCSS
* True to scope the reset CSS to be just applied to Ext components. Note that this
* wraps root containers with an additional element. Also remember that when you turn
* on this option, you have to use ext-all-scoped (unless you use the bootstrap.js to
* load your javascript, in which case it will be handled for you).
*/
scopeResetCSS : Ext.buildSettings.scopeResetCSS,
/**
* @property {String} resetCls
* The css class used to wrap Ext components when the {@link #scopeResetCSS} option
* is used.
*/
resetCls: Ext.buildSettings.baseCSSPrefix + 'reset',
/**
* @property {Boolean} enableNestedListenerRemoval
* **Experimental.** True to cascade listener removal to child elements when an element
* is removed. Currently not optimized for performance.
*/
enableNestedListenerRemoval : false,
/**
* @property {Boolean} USE_NATIVE_JSON
* Indicates whether to use native browser parsing for JSON methods.
* This option is ignored if the browser does not support native JSON methods.
*
* **Note:** Native JSON methods will not work with objects that have functions.
* Also, property names must be quoted, otherwise the data will not parse.
*/
USE_NATIVE_JSON : false,
/**
* Returns the dom node for the passed String (id), dom node, or Ext.Element.
* Optional 'strict' flag is needed for IE since it can return 'name' and
* 'id' elements by using getElementById.
*
* Here are some examples:
*
* // gets dom node based on id
* var elDom = Ext.getDom('elId');
* // gets dom node based on the dom node
* var elDom1 = Ext.getDom(elDom);
*
* // If we don't know if we are working with an
* // Ext.Element or a dom node use Ext.getDom
* function(el){
* var dom = Ext.getDom(el);
* // do something with the dom node
* }
*
* **Note:** the dom node to be found actually needs to exist (be rendered, etc)
* when this method is called to be successful.
*
* @param {String/HTMLElement/Ext.Element} el
* @return HTMLElement
*/
getDom : function(el, strict) {
if (!el || !document) {
return null;
}
if (el.dom) {
return el.dom;
} else {
if (typeof el == 'string') {
var e = Ext.getElementById(el);
// IE returns elements with the 'name' and 'id' attribute.
// we do a strict check to return the element with only the id attribute
if (e && isIE && strict) {
if (el == e.getAttribute('id')) {
return e;
} else {
return null;
}
}
return e;
} else {
return el;
}
}
},
/**
* Removes a DOM node from the document.
*
* Removes this element from the document, removes all DOM event listeners, and
* deletes the cache reference. All DOM event listeners are removed from this element.
* If {@link Ext#enableNestedListenerRemoval Ext.enableNestedListenerRemoval} is
* `true`, then DOM event listeners are also removed from all child nodes.
* The body node will be ignored if passed in.
*
* @param {HTMLElement} node The node to remove
* @method
*/
removeNode : isIE6 || isIE7 ? function() {
var d;
return function(n){
if(n && n.tagName != 'BODY'){
(Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
d = d || document.createElement('div');
d.appendChild(n);
d.innerHTML = '';
delete Ext.cache[n.id];
}
};
}() : function(n) {
if (n && n.parentNode && n.tagName != 'BODY') {
(Ext.enableNestedListenerRemoval) ? Ext.EventManager.purgeElement(n) : Ext.EventManager.removeAll(n);
n.parentNode.removeChild(n);
delete Ext.cache[n.id];
}
},
isStrict: isStrict,
isIEQuirks: isIE && !isStrict,
/**
* True if the detected browser is Opera.
* @type Boolean
*/
isOpera : isOpera,
/**
* True if the detected browser is Opera 10.5x.
* @type Boolean
*/
isOpera10_5 : isOpera10_5,
/**
* True if the detected browser uses WebKit.
* @type Boolean
*/
isWebKit : isWebKit,
/**
* True if the detected browser is Chrome.
* @type Boolean
*/
isChrome : isChrome,
/**
* True if the detected browser is Safari.
* @type Boolean
*/
isSafari : isSafari,
/**
* True if the detected browser is Safari 3.x.
* @type Boolean
*/
isSafari3 : isSafari3,
/**
* True if the detected browser is Safari 4.x.
* @type Boolean
*/
isSafari4 : isSafari4,
/**
* True if the detected browser is Safari 5.x.
* @type Boolean
*/
isSafari5 : isSafari5,
/**
* True if the detected browser is Safari 2.x.
* @type Boolean
*/
isSafari2 : isSafari2,
/**
* True if the detected browser is Internet Explorer.
* @type Boolean
*/
isIE : isIE,
/**
* True if the detected browser is Internet Explorer 6.x.
* @type Boolean
*/
isIE6 : isIE6,
/**
* True if the detected browser is Internet Explorer 7.x.
* @type Boolean
*/
isIE7 : isIE7,
/**
* True if the detected browser is Internet Explorer 8.x.
* @type Boolean
*/
isIE8 : isIE8,
/**
* True if the detected browser is Internet Explorer 9.x.
* @type Boolean
*/
isIE9 : isIE9,
/**
* True if the detected browser uses the Gecko layout engine (e.g. Mozilla, Firefox).
* @type Boolean
*/
isGecko : isGecko,
/**
* True if the detected browser uses a Gecko 1.9+ layout engine (e.g. Firefox 3.x).
* @type Boolean
*/
isGecko3 : isGecko3,
/**
* True if the detected browser uses a Gecko 2.0+ layout engine (e.g. Firefox 4.x).
* @type Boolean
*/
isGecko4 : isGecko4,
/**
* True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
* @type Boolean
*/
isGecko5 : isGecko5,
/**
* True if the detected browser uses a Gecko 5.0+ layout engine (e.g. Firefox 5.x).
* @type Boolean
*/
isGecko10 : isGecko10,
/**
* True if the detected browser uses FireFox 3.0
* @type Boolean
*/
isFF3_0 : isFF3_0,
/**
* True if the detected browser uses FireFox 3.5
* @type Boolean
*/
isFF3_5 : isFF3_5,
/**
* True if the detected browser uses FireFox 3.6
* @type Boolean
*/
isFF3_6 : isFF3_6,
/**
* True if the detected browser uses FireFox 4
* @type Boolean
*/
isFF4 : 4 <= firefoxVersion && firefoxVersion < 5,
/**
* True if the detected browser uses FireFox 5
* @type Boolean
*/
isFF5 : 5 <= firefoxVersion && firefoxVersion < 6,
/**
* True if the detected browser uses FireFox 10
* @type Boolean
*/
isFF10 : 10 <= firefoxVersion && firefoxVersion < 11,
/**
* True if the detected platform is Linux.
* @type Boolean
*/
isLinux : isLinux,
/**
* True if the detected platform is Windows.
* @type Boolean
*/
isWindows : isWindows,
/**
* True if the detected platform is Mac OS.
* @type Boolean
*/
isMac : isMac,
/**
* The current version of Chrome (0 if the browser is not Chrome).
* @type Number
*/
chromeVersion: chromeVersion,
/**
* The current version of Firefox (0 if the browser is not Firefox).
* @type Number
*/
firefoxVersion: firefoxVersion,
/**
* The current version of IE (0 if the browser is not IE). This does not account
* for the documentMode of the current page, which is factored into {@link #isIE7},
* {@link #isIE8} and {@link #isIE9}. Thus this is not always true:
*
* Ext.isIE8 == (Ext.ieVersion == 8)
*
* @type Number
*/
ieVersion: ieVersion,
/**
* The current version of Opera (0 if the browser is not Opera).
* @type Number
*/
operaVersion: operaVersion,
/**
* The current version of Safari (0 if the browser is not Safari).
* @type Number
*/
safariVersion: safariVersion,
/**
* The current version of WebKit (0 if the browser does not use WebKit).
* @type Number
*/
webKitVersion: webKitVersion,
/**
* True if the page is running over SSL
* @type Boolean
*/
isSecure: isSecure,
/**
* URL to a 1x1 transparent gif image used by Ext to create inline icons with
* CSS background images. In older versions of IE, this defaults to
* "http://sencha.com/s.gif" and you should change this to a URL on your server.
* For other browsers it uses an inline data URL.
* @type String
*/
BLANK_IMAGE_URL : (isIE6 || isIE7) ? '/' + '/www.sencha.com/s.gif' : 'data:image/gif;base64,R0lGODlhAQABAID/AMDAwAAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==',
/**
* Utility method for returning a default value if the passed value is empty.
*
* The value is deemed to be empty if it is:
*
* - null
* - undefined
* - an empty array
* - a zero length string (Unless the `allowBlank` parameter is `true`)
*
* @param {Object} value The value to test
* @param {Object} defaultValue The value to return if the original value is empty
* @param {Boolean} [allowBlank=false] true to allow zero length strings to qualify as non-empty.
* @return {Object} value, if non-empty, else defaultValue
* @deprecated 4.0.0 Use {@link Ext#valueFrom} instead
*/
value : function(v, defaultValue, allowBlank){
return Ext.isEmpty(v, allowBlank) ? defaultValue : v;
},
/**
* Escapes the passed string for use in a regular expression.
* @param {String} str
* @return {String}
* @deprecated 4.0.0 Use {@link Ext.String#escapeRegex} instead
*/
escapeRe : function(s) {
return s.replace(/([-.*+?^${}()|[\]\/\\])/g, "\\$1");
},
/**
* Applies event listeners to elements by selectors when the document is ready.
* The event name is specified with an `@` suffix.
*
* Ext.addBehaviors({
* // add a listener for click on all anchors in element with id foo
* '#foo a@click' : function(e, t){
* // do something
* },
*
* // add the same listener to multiple selectors (separated by comma BEFORE the @)
* '#foo a, #bar span.some-class@mouseover' : function(){
* // do something
* }
* });
*
* @param {Object} obj The list of behaviors to apply
*/
addBehaviors : function(o){
if(!Ext.isReady){
Ext.onReady(function(){
Ext.addBehaviors(o);
});
} else {
var cache = {}, // simple cache for applying multiple behaviors to same selector does query multiple times
parts,
b,
s;
for (b in o) {
if ((parts = b.split('@'))[1]) { // for Object prototype breakers
s = parts[0];
if(!cache[s]){
cache[s] = Ext.select(s);
}
cache[s].on(parts[1], o[b]);
}
}
cache = null;
}
},
/**
* Returns the size of the browser scrollbars. This can differ depending on
* operating system settings, such as the theme or font size.
* @param {Boolean} [force] true to force a recalculation of the value.
* @return {Object} An object containing scrollbar sizes.
* @return.width {Number} The width of the vertical scrollbar.
* @return.height {Number} The height of the horizontal scrollbar.
*/
getScrollbarSize: function (force) {
if (!Ext.isReady) {
return {};
}
if (force || !scrollbarSize) {
var db = document.body,
div = document.createElement('div');
div.style.width = div.style.height = '100px';
div.style.overflow = 'scroll';
div.style.position = 'absolute';
db.appendChild(div); // now we can measure the div...
// at least in iE9 the div is not 100px - the scrollbar size is removed!
scrollbarSize = {
width: div.offsetWidth - div.clientWidth,
height: div.offsetHeight - div.clientHeight
};
db.removeChild(div);
}
return scrollbarSize;
},
/**
* Utility method for getting the width of the browser's vertical scrollbar. This
* can differ depending on operating system settings, such as the theme or font size.
*
* This method is deprected in favor of {@link #getScrollbarSize}.
*
* @param {Boolean} [force] true to force a recalculation of the value.
* @return {Number} The width of a vertical scrollbar.
* @deprecated
*/
getScrollBarWidth: function(force){
var size = Ext.getScrollbarSize(force);
return size.width + 2; // legacy fudge factor
},
/**
* Copies a set of named properties fom the source object to the destination object.
*
* Example:
*
* ImageComponent = Ext.extend(Ext.Component, {
* initComponent: function() {
* this.autoEl = { tag: 'img' };
* MyComponent.superclass.initComponent.apply(this, arguments);
* this.initialBox = Ext.copyTo({}, this.initialConfig, 'x,y,width,height');
* }
* });
*
* Important note: To borrow class prototype methods, use {@link Ext.Base#borrow} instead.
*
* @param {Object} dest The destination object.
* @param {Object} source The source object.
* @param {String/String[]} names Either an Array of property names, or a comma-delimited list
* of property names to copy.
* @param {Boolean} [usePrototypeKeys] Defaults to false. Pass true to copy keys off of the
* prototype as well as the instance.
* @return {Object} The modified object.
*/
copyTo : function(dest, source, names, usePrototypeKeys){
if(typeof names == 'string'){
names = names.split(/[,;\s]/);
}
var n,
nLen = names.length,
name;
for(n = 0; n < nLen; n++) {
name = names[n];
if(usePrototypeKeys || source.hasOwnProperty(name)){
dest[name] = source[name];
}
}
return dest;
},
/**
* Attempts to destroy and then remove a set of named properties of the passed object.
* @param {Object} o The object (most likely a Component) who's properties you wish to destroy.
* @param {String...} args One or more names of the properties to destroy and remove from the object.
*/
destroyMembers : function(o){
for (var i = 1, a = arguments, len = a.length; i < len; i++) {
Ext.destroy(o[a[i]]);
delete o[a[i]];
}
},
/**
* Logs a message. If a console is present it will be used. On Opera, the method
* "opera.postError" is called. In other cases, the message is logged to an array
* "Ext.log.out". An attached debugger can watch this array and view the log. The
* log buffer is limited to a maximum of "Ext.log.max" entries (defaults to 250).
* The `Ext.log.out` array can also be written to a popup window by entering the
* following in the URL bar (a "bookmarklet"):
*
* javascript:void(Ext.log.show());
*
* If additional parameters are passed, they are joined and appended to the message.
* A technique for tracing entry and exit of a function is this:
*
* function foo () {
* Ext.log({ indent: 1 }, '>> foo');
*
* // log statements in here or methods called from here will be indented
* // by one step
*
* Ext.log({ outdent: 1 }, '<< foo');
* }
*
* This method does nothing in a release build.
*
* @param {String/Object} message The message to log or an options object with any
* of the following properties:
*
* - `msg`: The message to log (required).
* - `level`: One of: "error", "warn", "info" or "log" (the default is "log").
* - `dump`: An object to dump to the log as part of the message.
* - `stack`: True to include a stack trace in the log.
* - `indent`: Cause subsequent log statements to be indented one step.
* - `outdent`: Cause this and following statements to be one step less indented.
*
* @method
*/
log :
//<debug>
log ||
//</debug>
nullLog,
/**
* Partitions the set into two sets: a true set and a false set.
*
* Example 1:
*
* Ext.partition([true, false, true, true, false]);
* // returns [[true, true, true], [false, false]]
*
* Example 2:
*
* Ext.partition(
* Ext.query("p"),
* function(val){
* return val.className == "class1"
* }
* );
* // true are those paragraph elements with a className of "class1",
* // false set are those that do not have that className.
*
* @param {Array/NodeList} arr The array to partition
* @param {Function} truth (optional) a function to determine truth.
* If this is omitted the element itself must be able to be evaluated for its truthfulness.
* @return {Array} [array of truish values, array of falsy values]
* @deprecated 4.0.0 Will be removed in the next major version
*/
partition : function(arr, truth){
var ret = [[],[]],
a, v,
aLen = arr.length;
for (a = 0; a < aLen; a++) {
v = arr[a];
ret[ (truth && truth(v, a, arr)) || (!truth && v) ? 0 : 1].push(v);
}
return ret;
},
/**
* Invokes a method on each item in an Array.
*
* Example:
*
* Ext.invoke(Ext.query("p"), "getAttribute", "id");
* // [el1.getAttribute("id"), el2.getAttribute("id"), ..., elN.getAttribute("id")]
*
* @param {Array/NodeList} arr The Array of items to invoke the method on.
* @param {String} methodName The method name to invoke.
* @param {Object...} args Arguments to send into the method invocation.
* @return {Array} The results of invoking the method on each item in the array.
* @deprecated 4.0.0 Will be removed in the next major version
*/
invoke : function(arr, methodName){
var ret = [],
args = Array.prototype.slice.call(arguments, 2),
a, v,
aLen = arr.length;
for (a = 0; a < aLen; a++) {
v = arr[a];
if (v && typeof v[methodName] == 'function') {
ret.push(v[methodName].apply(v, args));
} else {
ret.push(undefined);
}
}
return ret;
},
/**
* Zips N sets together.
*
* Example 1:
*
* Ext.zip([1,2,3],[4,5,6]); // [[1,4],[2,5],[3,6]]
*
* Example 2:
*
* Ext.zip(
* [ "+", "-", "+"],
* [ 12, 10, 22],
* [ 43, 15, 96],
* function(a, b, c){
* return "$" + a + "" + b + "." + c
* }
* ); // ["$+12.43", "$-10.15", "$+22.96"]
*
* @param {Array/NodeList...} arr This argument may be repeated. Array(s)
* to contribute values.
* @param {Function} zipper (optional) The last item in the argument list.
* This will drive how the items are zipped together.
* @return {Array} The zipped set.
* @deprecated 4.0.0 Will be removed in the next major version
*/
zip : function(){
var parts = Ext.partition(arguments, function( val ){ return typeof val != 'function'; }),
arrs = parts[0],
fn = parts[1][0],
len = Ext.max(Ext.pluck(arrs, "length")),
ret = [];
for (var i = 0; i < len; i++) {
ret[i] = [];
if(fn){
ret[i] = fn.apply(fn, Ext.pluck(arrs, i));
}else{
for (var j = 0, aLen = arrs.length; j < aLen; j++){
ret[i].push( arrs[j][i] );
}
}
}
return ret;
},
/**
* Turns an array into a sentence, joined by a specified connector - e.g.:
*
* Ext.toSentence(['Adama', 'Tigh', 'Roslin']); //'Adama, Tigh and Roslin'
* Ext.toSentence(['Adama', 'Tigh', 'Roslin'], 'or'); //'Adama, Tigh or Roslin'
*
* @param {String[]} items The array to create a sentence from
* @param {String} connector The string to use to connect the last two words.
* Usually 'and' or 'or' - defaults to 'and'.
* @return {String} The sentence string
* @deprecated 4.0.0 Will be removed in the next major version
*/
toSentence: function(items, connector) {
var length = items.length;
if (length <= 1) {
return items[0];
} else {
var head = items.slice(0, length - 1),
tail = items[length - 1];
return Ext.util.Format.format("{0} {1} {2}", head.join(", "), connector || 'and', tail);
}
},
/**
* @property {Boolean} useShims
* By default, Ext intelligently decides whether floating elements should be shimmed.
* If you are using flash, you may want to set this to true.
*/
useShims: isIE6
});
})();
/**
* Loads Ext.app.Application class and starts it up with given configuration after the page is ready.
*
* See Ext.app.Application for details.
*
* @param {Object} config
*/
Ext.application = function(config) {
Ext.require('Ext.app.Application');
Ext.onReady(function() {
new Ext.app.Application(config);
});
};
//<localeInfo useApply="true" />
/**
* @class Ext.util.Format
This class is a centralized place for formatting functions. It includes
functions to format various different types of data, such as text, dates and numeric values.
__Localization__
This class contains several options for localization. These can be set once the library has loaded,
all calls to the functions from that point will use the locale settings that were specified.
Options include:
- thousandSeparator
- decimalSeparator
- currenyPrecision
- currencySign
- currencyAtEnd
This class also uses the default date format defined here: {@link Ext.Date#defaultFormat}.
__Using with renderers__
There are two helper functions that return a new function that can be used in conjunction with
grid renderers:
columns: [{
dataIndex: 'date',
renderer: Ext.util.Format.dateRenderer('Y-m-d')
}, {
dataIndex: 'time',
renderer: Ext.util.Format.numberRenderer('0.000')
}]
Functions that only take a single argument can also be passed directly:
columns: [{
dataIndex: 'cost',
renderer: Ext.util.Format.usMoney
}, {
dataIndex: 'productCode',
renderer: Ext.util.Format.uppercase
}]
__Using with XTemplates__
XTemplates can also directly use Ext.util.Format functions:
new Ext.XTemplate([
'Date: {startDate:date("Y-m-d")}',
'Cost: {cost:usMoney}'
]);
* @markdown
* @singleton
*/
(function() {
Ext.ns('Ext.util');
Ext.util.Format = {};
var UtilFormat = Ext.util.Format,
stripTagsRE = /<\/?[^>]+>/gi,
stripScriptsRe = /(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)/ig,
nl2brRe = /\r?\n/g,
// A RegExp to remove from a number format string, all characters except digits and '.'
formatCleanRe = /[^\d\.]/g,
// A RegExp to remove from a number format string, all characters except digits and the local decimal separator.
// Created on first use. The local decimal separator character must be initialized for this to be created.
I18NFormatCleanRe;
Ext.apply(UtilFormat, {
/**
* @property {String} thousandSeparator
* <p>The character that the {@link #number} function uses as a thousand separator.</p>
* <p>This may be overridden in a locale file.</p>
*/
//<locale>
thousandSeparator: ',',
//</locale>
/**
* @property {String} decimalSeparator
* <p>The character that the {@link #number} function uses as a decimal point.</p>
* <p>This may be overridden in a locale file.</p>
*/
//<locale>
decimalSeparator: '.',
//</locale>
/**
* @property {Number} currencyPrecision
* <p>The number of decimal places that the {@link #currency} function displays.</p>
* <p>This may be overridden in a locale file.</p>
*/
//<locale>
currencyPrecision: 2,
//</locale>
/**
* @property {String} currencySign
* <p>The currency sign that the {@link #currency} function displays.</p>
* <p>This may be overridden in a locale file.</p>
*/
//<locale>
currencySign: '$',
//</locale>
/**
* @property {Boolean} currencyAtEnd
* <p>This may be set to <code>true</code> to make the {@link #currency} function
* append the currency sign to the formatted value.</p>
* <p>This may be overridden in a locale file.</p>
*/
//<locale>
currencyAtEnd: false,
//</locale>
/**
* Checks a reference and converts it to empty string if it is undefined
* @param {Object} value Reference to check
* @return {Object} Empty string if converted, otherwise the original value
*/
undef : function(value) {
return value !== undefined ? value : "";
},
/**
* Checks a reference and converts it to the default value if it's empty
* @param {Object} value Reference to check
* @param {String} defaultValue The value to insert of it's undefined (defaults to "")
* @return {String}
*/
defaultValue : function(value, defaultValue) {
return value !== undefined && value !== '' ? value : defaultValue;
},
/**
* Returns a substring from within an original string
* @param {String} value The original text
* @param {Number} start The start index of the substring
* @param {Number} length The length of the substring
* @return {String} The substring
*/
substr : function(value, start, length) {
return String(value).substr(start, length);
},
/**
* Converts a string to all lower case letters
* @param {String} value The text to convert
* @return {String} The converted text
*/
lowercase : function(value) {
return String(value).toLowerCase();
},
/**
* Converts a string to all upper case letters
* @param {String} value The text to convert
* @return {String} The converted text
*/
uppercase : function(value) {
return String(value).toUpperCase();
},
/**
* Format a number as US currency
* @param {Number/String} value The numeric value to format
* @return {String} The formatted currency string
*/
usMoney : function(v) {
return UtilFormat.currency(v, '$', 2);
},
/**
* Format a number as a currency
* @param {Number/String} value The numeric value to format
* @param {String} sign The currency sign to use (defaults to {@link #currencySign})
* @param {Number} decimals The number of decimals to use for the currency (defaults to {@link #currencyPrecision})
* @param {Boolean} end True if the currency sign should be at the end of the string (defaults to {@link #currencyAtEnd})
* @return {String} The formatted currency string
*/
currency: function(v, currencySign, decimals, end) {
var negativeSign = '',
format = ",0",
i = 0;
v = v - 0;
if (v < 0) {
v = -v;
negativeSign = '-';
}
decimals = Ext.isDefined(decimals) ? decimals : UtilFormat.currencyPrecision;
format += format + (decimals > 0 ? '.' : '');
for (; i < decimals; i++) {
format += '0';
}
v = UtilFormat.number(v, format);
if ((end || UtilFormat.currencyAtEnd) === true) {
return Ext.String.format("{0}{1}{2}", negativeSign, v, currencySign || UtilFormat.currencySign);
} else {
return Ext.String.format("{0}{1}{2}", negativeSign, currencySign || UtilFormat.currencySign, v);
}
},
/**
* Formats the passed date using the specified format pattern.
* @param {String/Date} value The value to format. If a string is passed, it is converted to a Date by the Javascript
* Date object's <a href="http://www.w3schools.com/jsref/jsref_parse.asp">parse()</a> method.
* @param {String} format (Optional) Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
* @return {String} The formatted date string.
*/
date: function(v, format) {
if (!v) {
return "";
}
if (!Ext.isDate(v)) {
v = new Date(Date.parse(v));
}
return Ext.Date.dateFormat(v, format || Ext.Date.defaultFormat);
},
/**
* Returns a date rendering function that can be reused to apply a date format multiple times efficiently
* @param {String} format Any valid date format string. Defaults to {@link Ext.Date#defaultFormat}.
* @return {Function} The date formatting function
*/
dateRenderer : function(format) {
return function(v) {
return UtilFormat.date(v, format);
};
},
/**
* Strips all HTML tags
* @param {Object} value The text from which to strip tags
* @return {String} The stripped text
*/
stripTags : function(v) {
return !v ? v : String(v).replace(stripTagsRE, "");
},
/**
* Strips all script tags
* @param {Object} value The text from which to strip script tags
* @return {String} The stripped text
*/
stripScripts : function(v) {
return !v ? v : String(v).replace(stripScriptsRe, "");
},
/**
* Simple format for a file size (xxx bytes, xxx KB, xxx MB)
* @param {Number/String} size The numeric value to format
* @return {String} The formatted file size
*/
fileSize : function(size) {
if (size < 1024) {
return size + " bytes";
} else if (size < 1048576) {
return (Math.round(((size*10) / 1024))/10) + " KB";
} else {
return (Math.round(((size*10) / 1048576))/10) + " MB";
}
},
/**
* It does simple math for use in a template, for example:<pre><code>
* var tpl = new Ext.Template('{value} * 10 = {value:math("* 10")}');
* </code></pre>
* @return {Function} A function that operates on the passed value.
* @method
*/
math : function(){
var fns = {};
return function(v, a){
if (!fns[a]) {
fns[a] = Ext.functionFactory('v', 'return v ' + a + ';');
}
return fns[a](v);
};
}(),
/**
* Rounds the passed number to the required decimal precision.
* @param {Number/String} value The numeric value to round.
* @param {Number} precision The number of decimal places to which to round the first parameter's value.
* @return {Number} The rounded value.
*/
round : function(value, precision) {
var result = Number(value);
if (typeof precision == 'number') {
precision = Math.pow(10, precision);
result = Math.round(value * precision) / precision;
}
return result;
},
/**
* <p>Formats the passed number according to the passed format string.</p>
* <p>The number of digits after the decimal separator character specifies the number of
* decimal places in the resulting string. The <u>local-specific</u> decimal character is used in the result.</p>
* <p>The <i>presence</i> of a thousand separator character in the format string specifies that
* the <u>locale-specific</u> thousand separator (if any) is inserted separating thousand groups.</p>
* <p>By default, "," is expected as the thousand separator, and "." is expected as the decimal separator.</p>
* <p><b>New to Ext JS 4</b></p>
* <p>Locale-specific characters are always used in the formatted output when inserting
* thousand and decimal separators.</p>
* <p>The format string must specify separator characters according to US/UK conventions ("," as the
* thousand separator, and "." as the decimal separator)</p>
* <p>To allow specification of format strings according to local conventions for separator characters, add
* the string <code>/i</code> to the end of the format string.</p>
* <div style="margin-left:40px">examples (123456.789):
* <div style="margin-left:10px">
* 0 - (123456) show only digits, no precision<br>
* 0.00 - (123456.78) show only digits, 2 precision<br>
* 0.0000 - (123456.7890) show only digits, 4 precision<br>
* 0,000 - (123,456) show comma and digits, no precision<br>
* 0,000.00 - (123,456.78) show comma and digits, 2 precision<br>
* 0,0.00 - (123,456.78) shortcut method, show comma and digits, 2 precision<br>
* To allow specification of the formatting string using UK/US grouping characters (,) and decimal (.) for international numbers, add /i to the end.
* For example: 0.000,00/i
* </div></div>
* @param {Number} v The number to format.
* @param {String} format The way you would like to format this text.
* @return {String} The formatted number.
*/
number : function(v, formatString) {
if (!formatString) {
return v;
}
v = Ext.Number.from(v, NaN);
if (isNaN(v)) {
return '';
}
var comma = UtilFormat.thousandSeparator,
dec = UtilFormat.decimalSeparator,
i18n = false,
neg = v < 0,
hasComma,
psplit;
v = Math.abs(v);
// The "/i" suffix allows caller to use a locale-specific formatting string.
// Clean the format string by removing all but numerals and the decimal separator.
// Then split the format string into pre and post decimal segments according to *what* the
// decimal separator is. If they are specifying "/i", they are using the local convention in the format string.
if (formatString.substr(formatString.length - 2) == '/i') {
if (!I18NFormatCleanRe) {
I18NFormatCleanRe = new RegExp('[^\\d\\' + UtilFormat.decimalSeparator + ']','g');
}
formatString = formatString.substr(0, formatString.length - 2);
i18n = true;
hasComma = formatString.indexOf(comma) != -1;
psplit = formatString.replace(I18NFormatCleanRe, '').split(dec);
} else {
hasComma = formatString.indexOf(',') != -1;
psplit = formatString.replace(formatCleanRe, '').split('.');
}
if (psplit.length > 2) {
//<debug>
Ext.Error.raise({
sourceClass: "Ext.util.Format",
sourceMethod: "number",
value: v,
formatString: formatString,
msg: "Invalid number format, should have no more than 1 decimal"
});
//</debug>
} else if (psplit.length > 1) {
v = Ext.Number.toFixed(v, psplit[1].length);
} else {
v = Ext.Number.toFixed(v, 0);
}
var fnum = v.toString();
psplit = fnum.split('.');
if (hasComma) {
var cnum = psplit[0],
parr = [],
j = cnum.length,
m = Math.floor(j / 3),
n = cnum.length % 3 || 3,
i;
for (i = 0; i < j; i += n) {
if (i !== 0) {
n = 3;
}
parr[parr.length] = cnum.substr(i, n);
m -= 1;
}
fnum = parr.join(comma);
if (psplit[1]) {
fnum += dec + psplit[1];
}
} else {
if (psplit[1]) {
fnum = psplit[0] + dec + psplit[1];
}
}
if (neg) {
/*
* Edge case. If we have a very small negative number it will get rounded to 0,
* however the initial check at the top will still report as negative. Replace
* everything but 1-9 and check if the string is empty to determine a 0 value.
*/
neg = fnum.replace(/[^1-9]/g, '') !== '';
}
return (neg ? '-' : '') + formatString.replace(/[\d,?\.?]+/, fnum);
},
/**
* Returns a number rendering function that can be reused to apply a number format multiple times efficiently
* @param {String} format Any valid number format string for {@link #number}
* @return {Function} The number formatting function
*/
numberRenderer : function(format) {
return function(v) {
return UtilFormat.number(v, format);
};
},
/**
* Selectively do a plural form of a word based on a numeric value. For example, in a template,
* {commentCount:plural("Comment")} would result in "1 Comment" if commentCount was 1 or would be "x Comments"
* if the value is 0 or greater than 1.
* @param {Number} value The value to compare against
* @param {String} singular The singular form of the word
* @param {String} plural (optional) The plural form of the word (defaults to the singular with an "s")
*/
plural : function(v, s, p) {
return v +' ' + (v == 1 ? s : (p ? p : s+'s'));
},
/**
* Converts newline characters to the HTML tag <br/>
* @param {String} The string value to format.
* @return {String} The string with embedded <br/> tags in place of newlines.
*/
nl2br : function(v) {
return Ext.isEmpty(v) ? '' : v.replace(nl2brRe, '<br/>');
},
/**
* Alias for {@link Ext.String#capitalize}.
* @method
* @inheritdoc Ext.String#capitalize
*/
capitalize: Ext.String.capitalize,
/**
* Alias for {@link Ext.String#ellipsis}.
* @method
* @inheritdoc Ext.String#ellipsis
*/
ellipsis: Ext.String.ellipsis,
/**
* Alias for {@link Ext.String#format}.
* @method
* @inheritdoc Ext.String#format
*/
format: Ext.String.format,
/**
* Alias for {@link Ext.String#htmlDecode}.
* @method
* @inheritdoc Ext.String#htmlDecode
*/
htmlDecode: Ext.String.htmlDecode,
/**
* Alias for {@link Ext.String#htmlEncode}.
* @method
* @inheritdoc Ext.String#htmlEncode
*/
htmlEncode: Ext.String.htmlEncode,
/**
* Alias for {@link Ext.String#leftPad}.
* @method
* @inheritdoc Ext.String#leftPad
*/
leftPad: Ext.String.leftPad,
/**
* Alias for {@link Ext.String#trim}.
* @method
* @inheritdoc Ext.String#trim
*/
trim : Ext.String.trim,
/**
* Parses a number or string representing margin sizes into an object. Supports CSS-style margin declarations
* (e.g. 10, "10", "10 10", "10 10 10" and "10 10 10 10" are all valid options and would return the same result)
* @param {Number/String} v The encoded margins
* @return {Object} An object with margin sizes for top, right, bottom and left
*/
parseBox : function(box) {
box = Ext.isEmpty(box) ? '' : box;
if (Ext.isNumber(box)) {
box = box.toString();
}
var parts = box.split(' '),
ln = parts.length;
if (ln == 1) {
parts[1] = parts[2] = parts[3] = parts[0];
}
else if (ln == 2) {
parts[2] = parts[0];
parts[3] = parts[1];
}
else if (ln == 3) {
parts[3] = parts[1];
}
return {
top :parseInt(parts[0], 10) || 0,
right :parseInt(parts[1], 10) || 0,
bottom:parseInt(parts[2], 10) || 0,
left :parseInt(parts[3], 10) || 0
};
},
/**
* Escapes the passed string for use in a regular expression
* @param {String} str
* @return {String}
*/
escapeRegex : function(s) {
return s.replace(/([\-.*+?\^${}()|\[\]\/\\])/g, "\\$1");
}
});
})();
/**
* Provides the ability to execute one or more arbitrary tasks in a asynchronous manner.
* Generally, you can use the singleton {@link Ext.TaskManager} instead, but if needed,
* you can create separate instances of TaskRunner. Any number of separate tasks can be
* started at any time and will run independently of each other.
*
* Example usage:
*
* // Start a simple clock task that updates a div once per second
* var updateClock = function () {
* Ext.fly('clock').update(new Date().format('g:i:s A'));
* }
*
* var runner = new Ext.util.TaskRunner();
* var task = runner.start({
* run: updateClock,
* interval: 1000
* }
*
* The equivalent using TaskManager:
*
* var task = Ext.TaskManager.start({
* run: updateClock,
* interval: 1000
* });
*
* To end a running task:
*
* task.destroy();
*
* If a task needs to be started and stopped repeated over time, you can create a
* {@link Ext.util.TaskRunner.Task Task} instance.
*
* var task = runner.newTask({
* run: function () {
* // useful code
* },
* interval: 1000
* });
*
* task.start();
*
* // ...
*
* task.stop();
*
* // ...
*
* task.start();
*
* A re-usable, one-shot task can be managed similar to the above:
*
* var task = runner.newTask({
* run: function () {
* // useful code to run once
* },
* repeat: 1
* });
*
* task.start();
*
* // ...
*
* task.start();
*
* See the {@link #start} method for details about how to configure a task object.
*
* Also see {@link Ext.util.DelayedTask}.
*
* @constructor
* @param {Number/Object} [interval=10] The minimum precision in milliseconds supported by this
* TaskRunner instance. Alternatively, a config object to apply to the new instance.
*/
Ext.define('Ext.util.TaskRunner', {
/**
* @cfg interval
* The timer resolution.
*/
interval: 10,
/**
* @property timerId
* The id of the current timer.
* @private
*/
timerId: null,
constructor: function (interval) {
var me = this;
if (typeof interval == 'number') {
me.interval = interval;
} else if (interval) {
Ext.apply(me, interval);
}
me.tasks = [];
me.timerFn = Ext.Function.bind(me.onTick, me);
},
/**
* Creates a new {@link Ext.util.TaskRunner.Task Task} instance. These instances can
* be easily started and stopped.
* @param {Object} config The config object. For details on the supported properties,
* see {@link #start}.
*/
newTask: function (config) {
var task = new Ext.util.TaskRunner.Task(config);
task.manager = this;
return task;
},
/**
* Starts a new task.
*
* Before each invocation, Ext injects the property `taskRunCount` into the task object
* so that calculations based on the repeat count can be performed.
*
* The returned task will contain a `destroy` method that can be used to destroy the
* task and cancel further calls. This is equivalent to the {@link #stop} method.
*
* @param {Object} task A config object that supports the following properties:
* @param {Function} task.run The function to execute each time the task is invoked. The
* function will be called at each interval and passed the `args` argument if specified,
* and the current invocation count if not.
*
* If a particular scope (`this` reference) is required, be sure to specify it using
* the `scope` argument.
*
* @param {Boolean} task.run.return `false` from this function to terminate the task.
*
* @param {Number} task.interval The frequency in milliseconds with which the task
* should be invoked.
*
* @param {Object[]} task.args An array of arguments to be passed to the function
* specified by `run`. If not specified, the current invocation count is passed.
*
* @param {Object} task.scope The scope (`this` reference) in which to execute the
* `run` function. Defaults to the task config object.
*
* @param {Number} task.duration The length of time in milliseconds to invoke the task
* before stopping automatically (defaults to indefinite).
*
* @param {Number} task.repeat The number of times to invoke the task before stopping
* automatically (defaults to indefinite).
* @return {Object} The task
*/
start: function(task) {
var me = this,
now = new Date().getTime();
if (!task.pending) {
me.tasks.push(task);
task.pending = true; // don't allow the task to be added to me.tasks again
}
task.stopped = false; // might have been previously stopped...
task.taskRunTime = task.taskStartTime = now;
task.taskRunCount = 0;
if (!me.firing) {
me.startTimer(task.interval, now);
}
return task;
},
/**
* Stops an existing running task.
* @param {Object} task The task to stop
* @return {Object} The task
*/
stop: function(task) {
// NOTE: we don't attempt to remove the task from me.tasks at this point because
// this could be called from inside a task which would then corrupt the state of
// the loop in onTick
if (!task.stopped) {
task.stopped = true;
if (task.onStop) {
task.onStop.call(task.scope || task);
}
}
return task;
},
/**
* Stops all tasks that are currently running.
*/
stopAll: function() {
// onTick will take care of cleaning up the mess after this point...
Ext.each(this.tasks, this.stop, this);
},
//-------------------------------------------------------------------------
firing: false,
nextExpires: 1e99,
// private
onTick: function () {
var me = this,
tasks = me.tasks,
now = new Date().getTime(),
nextExpires = 1e99,
len = tasks.length,
expires, newTasks, i, task, rt, remove;
me.timerId = null;
me.firing = true; // ensure we don't startTimer during this loop...
// tasks.length can be > len if start is called during a task.run call... so we
// first check len to avoid tasks.length reference but eventually we need to also
// check tasks.length. we avoid repeating use of tasks.length by setting len at
// that time (to help the next loop)
for (i = 0; i < len || i < (len = tasks.length); ++i) {
task = tasks[i];
if (!(remove = task.stopped)) {
expires = task.taskRunTime + task.interval;
if (expires <= now) {
rt = task.run.apply(task.scope || task, task.args || [++task.taskRunCount]);
task.taskRunTime = now;
if (rt === false || task.taskRunCount === task.repeat) {
me.stop(task);
remove = true;
} else {
remove = task.stopped; // in case stop was called by run
expires = now + task.interval;
}
}
if (!remove && task.duration && task.duration <= (now - task.taskStartTime)) {
me.stop(task);
remove = true;
}
}
if (remove) {
task.pending = false; // allow the task to be added to me.tasks again
// once we detect that a task needs to be removed, we copy the tasks that
// will carry forward into newTasks... this way we avoid O(N*N) to remove
// each task from the tasks array (and ripple the array down) and also the
// potentially wasted effort of making a new tasks[] even if all tasks are
// going into the next wave.
if (!newTasks) {
newTasks = tasks.slice(0, i);
// we don't set me.tasks here because callbacks can also start tasks,
// which get added to me.tasks... so we will visit them in this loop
// and account for their expirations in nextExpires...
}
} else {
if (newTasks) {
newTasks.push(task); // we've cloned the tasks[], so keep this one...
}
if (nextExpires > expires) {
nextExpires = expires; // track the nearest expiration time
}
}
}
if (newTasks) {
// only now can we copy the newTasks to me.tasks since no user callbacks can
// take place
me.tasks = newTasks;
}
me.firing = false; // we're done, so allow startTimer afterwards
if (me.tasks.length) {
// we create a new Date here because all the callbacks could have taken a long
// time... we want to base the next timeout on the current time (after the
// callback storm):
me.startTimer(nextExpires - now, new Date().getTime());
}
},
// private
startTimer: function (timeout, now) {
var me = this,
expires = now + timeout,
timerId = me.timerId;
// Check to see if this request is enough in advance of the current timer. If so,
// we reschedule the timer based on this new expiration.
if (timerId && me.nextExpires - expires > me.interval) {
clearTimeout(timerId);
timerId = null;
}
if (!timerId) {
if (timeout < me.interval) {
timeout = me.interval;
}
me.timerId = setTimeout(me.timerFn, timeout);
me.nextExpires = expires;
}
}
},
function () {
var me = this,
proto = me.prototype;
/**
* Destroys this instance, stopping all tasks that are currently running.
* @method destroy
*/
proto.destroy = proto.stopAll;
/**
* @class Ext.TaskManager
* @extends Ext.util.TaskRunner
* @singleton
*
* A static {@link Ext.util.TaskRunner} instance that can be used to start and stop
* arbitrary tasks. See {@link Ext.util.TaskRunner} for supported methods and task
* config properties.
*
* // Start a simple clock task that updates a div once per second
* var task = {
* run: function(){
* Ext.fly('clock').update(new Date().format('g:i:s A'));
* },
* interval: 1000 //1 second
* }
*
* Ext.TaskManager.start(task);
*
* See the {@link #start} method for details about how to configure a task object.
*/
Ext.util.TaskManager = Ext.TaskManager = new me();
/**
* Instances of this class are created by {@link Ext.util.TaskRunner#newTask} method.
*
* For details on config properties, see {@link Ext.util.TaskRunner#start}.
* @class Ext.util.TaskRunner.Task
*/
me.Task = new Ext.Class({
isTask: true,
/**
* This flag is set to `true` by {@link #stop}.
* @private
*/
stopped: true, // this avoids the odd combination of !stopped && !pending
constructor: function (config) {
Ext.apply(this, config);
},
/**
* Restarts this task, clearing it duration, expiration and run count.
* @param {Number} [interval] Optionally reset this task's interval.
*/
restart: function (interval) {
if (interval !== undefined) {
this.interval = interval;
}
this.manager.start(this);
},
/**
* Starts this task if it is not already started.
* @param {Number} [interval] Optionally reset this task's interval.
*/
start: function (interval) {
if (this.stopped) {
this.restart(interval);
}
},
/**
* Stops this task.
*/
stop: function () {
this.manager.stop(this);
}
});
proto = me.Task.prototype;
/**
* Destroys this instance, stopping this task's execution.
* @method destroy
*/
proto.destroy = proto.stop;
});
/**
* @class Ext.perf.Accumulator
* @private
*/
Ext.define('Ext.perf.Accumulator', function () {
var currentFrame = null,
khrome = Ext.global['chrome'],
formatTpl,
// lazy init on first request for timestamp (avoids infobar in IE until needed)
// Also avoids kicking off Chrome's microsecond timer until first needed
getTimestamp = function () {
getTimestamp = function () {
return new Date().getTime();
}
// If Chrome is started with the --enable-benchmarking switch
if (Ext.isChrome && khrome && khrome.Interval) {
var interval = new khrome.Interval();
interval.start();
getTimestamp = function () {
return interval.microseconds() / 1000;
}
}
else if (window.ActiveXObject) {
try {
// the above technique is not very accurate for small intervals...
var toolbox = new ActiveXObject('SenchaToolbox.Toolbox');
getTimestamp = function () {
return toolbox.milliseconds;
};
} catch (e) {
// ignore
}
} else if (Date.now) {
getTimestamp = Date.now;
}
Ext.perf.getTimestamp = Ext.perf.Accumulator.getTimestamp = getTimestamp;
return getTimestamp();
};
function adjustSet (set, time) {
set.sum += time;
set.min = Math.min(set.min, time);
set.max = Math.max(set.max, time);
}
function leaveFrame (time) {
var totalTime = time ? time : (getTimestamp() - this.time), // do this first
me = this, // me = frame
accum = me.accum;
++accum.count;
if (! --accum.depth) {
adjustSet(accum.total, totalTime);
}
adjustSet(accum.pure, totalTime - me.childTime);
currentFrame = me.parent;
if (currentFrame) {
++currentFrame.accum.childCount;
currentFrame.childTime += totalTime;
}
}
function makeSet () {
return {
min: Number.MAX_VALUE,
max: 0,
sum: 0
}
}
function makeTap (me, fn) {
return function () {
var frame = me.enter(),
ret = fn.apply(this, arguments);
frame.leave();
return ret;
};
}
function round (x) {
return Math.round(x * 100) / 100;
}
function setToJSON (count, childCount, calibration, set) {
var data = {
avg: 0,
min: set.min,
max: set.max,
sum: 0
};
if (count) {
calibration = calibration || 0;
data.sum = set.sum - childCount * calibration;
data.avg = data.sum / count;
// min and max cannot be easily corrected since we don't know the number of
// child calls for them.
}
return data;
}
return {
constructor: function (name) {
var me = this;
me.count = me.childCount = me.depth = me.maxDepth = 0;
me.pure = makeSet();
me.total = makeSet();
me.name = name;
},
statics: {
getTimestamp: getTimestamp
},
format: function (calibration) {
if (!formatTpl) {
formatTpl = new Ext.XTemplate([
'{name} - {count} call(s)',
'<tpl if="count">',
'<tpl if="childCount">',
' ({childCount} children)',
'</tpl>',
'<tpl if="depth - 1">',
' ({depth} deep)',
'</tpl>',
'<tpl for="times">',
', {type}: {[this.time(values.sum)]} msec (',
//'min={[this.time(values.min)]}, ',
'avg={[this.time(values.sum / parent.count)]}',
//', max={[this.time(values.max)]}',
')',
'</tpl>',
'</tpl>'
].join(''), {
time: function (t) {
return Math.round(t * 100) / 100;
}
});
}
var data = this.getData(calibration);
data.name = this.name;
data.pure.type = 'Pure';
data.total.type = 'Total';
data.times = [data.pure, data.total];
return formatTpl.apply(data);
},
getData: function (calibration) {
var me = this;
return {
count: me.count,
childCount: me.childCount,
depth: me.maxDepth,
pure: setToJSON(me.count, me.childCount, calibration, me.pure),
total: setToJSON(me.count, me.childCount, calibration, me.total)
};
},
enter: function () {
var me = this,
frame = {
accum: me,
leave: leaveFrame,
childTime: 0,
parent: currentFrame
};
++me.depth;
if (me.maxDepth < me.depth) {
me.maxDepth = me.depth;
}
currentFrame = frame;
frame.time = getTimestamp(); // do this last
return frame;
},
monitor: function (fn, scope, args) {
var frame = this.enter();
if (args) {
fn.apply(scope, args);
} else {
fn.call(scope);
}
frame.leave();
},
report: function () {
Ext.log(this.format());
},
tap: function (className, methodName) {
var me = this,
methods = typeof methodName == 'string' ? [methodName] : methodName,
klass, statik, i, parts, length, name, src;
var tapFunc = function(){
if (typeof className == 'string') {
klass = Ext.global;
parts = className.split('.');
for (i = 0, length = parts.length; i < length; ++i) {
klass = klass[parts[i]];
}
} else {
klass = className;
}
for (i = 0, length = methods.length; i < length; ++i) {
name = methods[i];
statik = name.charAt(0) == '!';
if (statik) {
name = name.substring(1);
} else {
statik = !(name in klass.prototype);
}
src = statik ? klass : klass.prototype;
src[name] = makeTap(me, src[name]);
}
};
Ext.ClassManager.onCreated(tapFunc, me, className);
return me;
}
};
}(),
function () {
Ext.perf.getTimestamp = this.getTimestamp;
});
/**
* @class Ext.perf.Monitor
* @singleton
* @private
*/
Ext.define('Ext.perf.Monitor', {
singleton: true,
alternateClassName: 'Ext.Perf',
requires: [
'Ext.perf.Accumulator'
],
constructor: function () {
this.accumulators = [];
this.accumulatorsByName = {};
},
calibrate: function () {
var accum = new Ext.perf.Accumulator('$'),
total = accum.total,
getTimestamp = Ext.perf.Accumulator.getTimestamp,
count = 0,
frame,
endTime,
startTime;
startTime = getTimestamp();
do {
frame = accum.enter();
frame.leave();
++count;
} while (total.sum < 100);
endTime = getTimestamp();
return (endTime - startTime) / count;
},
get: function (name) {
var me = this,
accum = me.accumulatorsByName[name];
if (!accum) {
me.accumulatorsByName[name] = accum = new Ext.perf.Accumulator(name);
me.accumulators.push(accum);
}
return accum;
},
enter: function (name) {
return this.get(name).enter();
},
monitor: function (name, fn, scope) {
this.get(name).monitor(fn, scope);
},
report: function () {
var me = this,
accumulators = me.accumulators,
calibration = me.calibrate(),
report = ['Calibration: ' + Math.round(calibration * 100) / 100 + ' msec/sample'];
accumulators.sort(function (a, b) {
return (a.name < b.name) ? -1 : ((b.name < a.name) ? 1 : 0);
});
Ext.each(accumulators, function (accum) {
report.push(accum.format(calibration));
});
Ext.log(report.join('\n'));
},
getData: function (all) {
var ret = {},
accumulators = this.accumulators;
Ext.each(accumulators, function (accum) {
if (all || accum.count) {
ret[accum.name] = accum.getData();
}
});
return ret;
},
setup: function (config) {
if (!config) {
config = {
/*insertHtml: {
'Ext.dom.Helper': 'insertHtml'
},*/
/*xtplCompile: {
'Ext.XTemplateCompiler': 'compile'
},*/
// doInsert: {
// 'Ext.Template': 'doInsert'
// },
// applyOut: {
// 'Ext.XTemplate': 'applyOut'
// },
render: {
'Ext.AbstractComponent': 'render'
},
// fnishRender: {
// 'Ext.AbstractComponent': 'finishRender'
// },
// renderSelectors: {
// 'Ext.AbstractComponent': 'applyRenderSelectors'
// },
// compAddCls: {
// 'Ext.AbstractComponent': 'addCls'
// },
// compRemoveCls: {
// 'Ext.AbstractComponent': 'removeCls'
// },
// getStyle: {
// 'Ext.core.Element': 'getStyle'
// },
// setStyle: {
// 'Ext.core.Element': 'setStyle'
// },
// addCls: {
// 'Ext.core.Element': 'addCls'
// },
// removeCls: {
// 'Ext.core.Element': 'removeCls'
// },
// measure: {
// 'Ext.layout.component.Component': 'measureAutoDimensions'
// },
// moveItem: {
// 'Ext.layout.Layout': 'moveItem'
// },
// layoutFlush: {
// 'Ext.layout.Context': 'flush'
// },
layout: {
'Ext.layout.Context': 'run'
}
};
}
this.currentConfig = config;
var key, prop;
for (key in config) {
if (config.hasOwnProperty(key)) {
prop = config[key];
var accum = Ext.Perf.get(key),
className, methods;
for (className in prop) {
if (prop.hasOwnProperty(className)) {
methods = prop[className];
accum.tap(className, methods);
}
}
}
}
}
});
/**
* @class Ext.is
*
* Determines information about the current platform the application is running on.
*
* @singleton
*/
Ext.is = {
init : function(navigator) {
var platforms = this.platforms,
ln = platforms.length,
i, platform;
navigator = navigator || window.navigator;
for (i = 0; i < ln; i++) {
platform = platforms[i];
this[platform.identity] = platform.regex.test(navigator[platform.property]);
}
/**
* @property Desktop True if the browser is running on a desktop machine
* @type {Boolean}
*/
this.Desktop = this.Mac || this.Windows || (this.Linux && !this.Android);
/**
* @property Tablet True if the browser is running on a tablet (iPad)
*/
this.Tablet = this.iPad;
/**
* @property Phone True if the browser is running on a phone.
* @type {Boolean}
*/
this.Phone = !this.Desktop && !this.Tablet;
/**
* @property iOS True if the browser is running on iOS
* @type {Boolean}
*/
this.iOS = this.iPhone || this.iPad || this.iPod;
/**
* @property Standalone Detects when application has been saved to homescreen.
* @type {Boolean}
*/
this.Standalone = !!window.navigator.standalone;
},
/**
* @property iPhone True when the browser is running on a iPhone
* @type {Boolean}
*/
platforms: [{
property: 'platform',
regex: /iPhone/i,
identity: 'iPhone'
},
/**
* @property iPod True when the browser is running on a iPod
* @type {Boolean}
*/
{
property: 'platform',
regex: /iPod/i,
identity: 'iPod'
},
/**
* @property iPad True when the browser is running on a iPad
* @type {Boolean}
*/
{
property: 'userAgent',
regex: /iPad/i,
identity: 'iPad'
},
/**
* @property Blackberry True when the browser is running on a Blackberry
* @type {Boolean}
*/
{
property: 'userAgent',
regex: /Blackberry/i,
identity: 'Blackberry'
},
/**
* @property Android True when the browser is running on an Android device
* @type {Boolean}
*/
{
property: 'userAgent',
regex: /Android/i,
identity: 'Android'
},
/**
* @property Mac True when the browser is running on a Mac
* @type {Boolean}
*/
{
property: 'platform',
regex: /Mac/i,
identity: 'Mac'
},
/**
* @property Windows True when the browser is running on Windows
* @type {Boolean}
*/
{
property: 'platform',
regex: /Win/i,
identity: 'Windows'
},
/**
* @property Linux True when the browser is running on Linux
* @type {Boolean}
*/
{
property: 'platform',
regex: /Linux/i,
identity: 'Linux'
}]
};
Ext.is.init();
/**
* @class Ext.supports
*
* Determines information about features are supported in the current environment
*
* @singleton
*/
Ext.supports = {
/**
* Runs feature detection routines and sets the various flags. This is called when
* the scripts loads (very early) and again at {@link Ext#onReady}. Some detections
* are flagged as `early` and run immediately. Others that require the document body
* will not run until ready.
*
* Each test is run only once, so calling this method from an onReady function is safe
* and ensures that all flags have been set.
* @markdown
* @private
*/
init : function() {
var me = this,
doc = document,
tests = me.tests,
n = tests.length,
div = n && Ext.isReady && doc.createElement('div'),
test, notRun = [];
if (div) {
div.innerHTML = [
'<div style="height:30px;width:50px;">',
'<div style="height:20px;width:20px;"></div>',
'</div>',
'<div style="width: 200px; height: 200px; position: relative; padding: 5px;">',
'<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"></div>',
'</div>',
'<div style="position: absolute; left: 10%; top: 10%;"></div>',
'<div style="float:left; background-color:transparent;"></div>'
].join('');
doc.body.appendChild(div);
}
while (n--) {
test = tests[n];
if (div || test.early) {
me[test.identity] = test.fn.call(me, doc, div);
} else {
notRun.push(test);
}
}
if (div) {
doc.body.removeChild(div);
}
me.tests = notRun;
},
/**
* @property PointerEvents True if document environment supports the CSS3 pointer-events style.
* @type {Boolean}
*/
PointerEvents: 'pointerEvents' in document.documentElement.style,
/**
* @property CSS3BoxShadow True if document environment supports the CSS3 box-shadow style.
* @type {Boolean}
*/
CSS3BoxShadow: 'boxShadow' in document.documentElement.style,
/**
* @property ClassList True if document environment supports the HTML5 classList API.
* @type {Boolean}
*/
ClassList: !!document.documentElement.classList,
/**
* @property OrientationChange True if the device supports orientation change
* @type {Boolean}
*/
OrientationChange: ((typeof window.orientation != 'undefined') && ('onorientationchange' in window)),
/**
* @property DeviceMotion True if the device supports device motion (acceleration and rotation rate)
* @type {Boolean}
*/
DeviceMotion: ('ondevicemotion' in window),
/**
* @property Touch True if the device supports touch
* @type {Boolean}
*/
// is.Desktop is needed due to the bug in Chrome 5.0.375, Safari 3.1.2
// and Safari 4.0 (they all have 'ontouchstart' in the window object).
Touch: ('ontouchstart' in window) && (!Ext.is.Desktop),
tests: [
/**
* @property Transitions True if the device supports CSS3 Transitions
* @type {Boolean}
*/
{
identity: 'Transitions',
fn: function(doc, div) {
var prefix = [
'webkit',
'Moz',
'o',
'ms',
'khtml'
],
TE = 'TransitionEnd',
transitionEndName = [
prefix[0] + TE,
'transitionend', //Moz bucks the prefixing convention
prefix[2] + TE,
prefix[3] + TE,
prefix[4] + TE
],
ln = prefix.length,
i = 0,
out = false;
div = Ext.get(div);
for (; i < ln; i++) {
if (div.getStyle(prefix[i] + "TransitionProperty")) {
Ext.supports.CSS3Prefix = prefix[i];
Ext.supports.CSS3TransitionEnd = transitionEndName[i];
out = true;
break;
}
}
return out;
}
},
/**
* @property RightMargin True if the device supports right margin.
* See https://bugs.webkit.org/show_bug.cgi?id=13343 for why this is needed.
* @type {Boolean}
*/
{
identity: 'RightMargin',
fn: function(doc, div) {
var view = doc.defaultView;
return !(view && view.getComputedStyle(div.firstChild.firstChild, null).marginRight != '0px');
}
},
/**
* @property DisplayChangeInputSelectionBug True if INPUT elements lose their
* selection when their display style is changed. Essentially, if a text input
* has focus and its display style is changed, the I-beam disappears.
*
* This bug is encountered due to the work around in place for the {@link #RightMargin}
* bug. This has been observed in Safari 4.0.4 and older, and appears to be fixed
* in Safari 5. It's not clear if Safari 4.1 has the bug, but it has the same WebKit
* version number as Safari 5 (according to http://unixpapa.com/js/gecko.html).
*/
{
identity: 'DisplayChangeInputSelectionBug',
early: true,
fn: function() {
var webKitVersion = Ext.webKitVersion;
// WebKit but older than Safari 5 or Chrome 6:
return 0 < webKitVersion && webKitVersion < 533;
}
},
/**
* @property DisplayChangeTextAreaSelectionBug True if TEXTAREA elements lose their
* selection when their display style is changed. Essentially, if a text area has
* focus and its display style is changed, the I-beam disappears.
*
* This bug is encountered due to the work around in place for the {@link #RightMargin}
* bug. This has been observed in Chrome 10 and Safari 5 and older, and appears to
* be fixed in Chrome 11.
*/
{
identity: 'DisplayChangeTextAreaSelectionBug',
early: true,
fn: function() {
var webKitVersion = Ext.webKitVersion;
/*
Has bug w/textarea:
(Chrome) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-US)
AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.127
Safari/534.16
(Safari) Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us)
AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5
Safari/533.21.1
No bug:
(Chrome) Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_7)
AppleWebKit/534.24 (KHTML, like Gecko) Chrome/11.0.696.57
Safari/534.24
*/
return 0 < webKitVersion && webKitVersion < 534.24;
}
},
/**
* @property TransparentColor True if the device supports transparent color
* @type {Boolean}
*/
{
identity: 'TransparentColor',
fn: function(doc, div, view) {
view = doc.defaultView;
return !(view && view.getComputedStyle(div.lastChild, null).backgroundColor != 'transparent');
}
},
/**
* @property ComputedStyle True if the browser supports document.defaultView.getComputedStyle()
* @type {Boolean}
*/
{
identity: 'ComputedStyle',
fn: function(doc, div, view) {
view = doc.defaultView;
return view && view.getComputedStyle;
}
},
/**
* @property SVG True if the device supports SVG
* @type {Boolean}
*/
{
identity: 'Svg',
fn: function(doc) {
return !!doc.createElementNS && !!doc.createElementNS( "http:/" + "/www.w3.org/2000/svg", "svg").createSVGRect;
}
},
/**
* @property Canvas True if the device supports Canvas
* @type {Boolean}
*/
{
identity: 'Canvas',
fn: function(doc) {
return !!doc.createElement('canvas').getContext;
}
},
/**
* @property VML True if the device supports VML
* @type {Boolean}
*/
{
identity: 'Vml',
fn: function(doc) {
var d = doc.createElement("div");
d.innerHTML = "<!--[if vml]><br><br><![endif]-->";
return (d.childNodes.length == 2);
}
},
/**
* @property Float True if the device supports CSS float
* @type {Boolean}
*/
{
identity: 'Float',
fn: function(doc, div) {
return !!div.lastChild.style.cssFloat;
}
},
/**
* @property AudioTag True if the device supports the HTML5 audio tag
* @type {Boolean}
*/
{
identity: 'AudioTag',
fn: function(doc) {
return !!doc.createElement('audio').canPlayType;
}
},
/**
* @property History True if the device supports HTML5 history
* @type {Boolean}
*/
{
identity: 'History',
fn: function() {
var history = window.history;
return !!(history && history.pushState);
}
},
/**
* @property CSS3DTransform True if the device supports CSS3DTransform
* @type {Boolean}
*/
{
identity: 'CSS3DTransform',
fn: function() {
return (typeof WebKitCSSMatrix != 'undefined' && new WebKitCSSMatrix().hasOwnProperty('m41'));
}
},
/**
* @property CSS3LinearGradient True if the device supports CSS3 linear gradients
* @type {Boolean}
*/
{
identity: 'CSS3LinearGradient',
fn: function(doc, div) {
var property = 'background-image:',
webkit = '-webkit-gradient(linear, left top, right bottom, from(black), to(white))',
w3c = 'linear-gradient(left top, black, white)',
moz = '-moz-' + w3c,
opera = '-o-' + w3c,
options = [property + webkit, property + w3c, property + moz, property + opera];
div.style.cssText = options.join(';');
return ("" + div.style.backgroundImage).indexOf('gradient') !== -1;
}
},
/**
* @property CSS3BorderRadius True if the device supports CSS3 border radius
* @type {Boolean}
*/
{
identity: 'CSS3BorderRadius',
fn: function(doc, div) {
var domPrefixes = ['borderRadius', 'BorderRadius', 'MozBorderRadius', 'WebkitBorderRadius', 'OBorderRadius', 'KhtmlBorderRadius'],
pass = false,
i;
for (i = 0; i < domPrefixes.length; i++) {
if (document.body.style[domPrefixes[i]] !== undefined) {
return true;
}
}
return pass;
}
},
/**
* @property GeoLocation True if the device supports GeoLocation
* @type {Boolean}
*/
{
identity: 'GeoLocation',
fn: function() {
return (typeof navigator != 'undefined' && typeof navigator.geolocation != 'undefined') || (typeof google != 'undefined' && typeof google.gears != 'undefined');
}
},
/**
* @property MouseEnterLeave True if the browser supports mouseenter and mouseleave events
* @type {Boolean}
*/
{
identity: 'MouseEnterLeave',
fn: function(doc, div){
return ('onmouseenter' in div && 'onmouseleave' in div);
}
},
/**
* @property MouseWheel True if the browser supports the mousewheel event
* @type {Boolean}
*/
{
identity: 'MouseWheel',
fn: function(doc, div) {
return ('onmousewheel' in div);
}
},
/**
* @property Opacity True if the browser supports normal css opacity
* @type {Boolean}
*/
{
identity: 'Opacity',
fn: function(doc, div){
// Not a strict equal comparison in case opacity can be converted to a number.
if (Ext.isIE6 || Ext.isIE7 || Ext.isIE8) {
return false;
}
div.firstChild.style.cssText = 'opacity:0.73';
return div.firstChild.style.opacity == '0.73';
}
},
/**
* @property Placeholder True if the browser supports the HTML5 placeholder attribute on inputs
* @type {Boolean}
*/
{
identity: 'Placeholder',
fn: function(doc) {
return 'placeholder' in doc.createElement('input');
}
},
/**
* @property Direct2DBug True if when asking for an element's dimension via offsetWidth or offsetHeight,
* getBoundingClientRect, etc. the browser returns the subpixel width rounded to the nearest pixel.
* @type {Boolean}
*/
{
identity: 'Direct2DBug',
fn: function() {
return Ext.isString(document.body.style.msTransformOrigin);
}
},
/**
* @property BoundingClientRect True if the browser supports the getBoundingClientRect method on elements
* @type {Boolean}
*/
{
identity: 'BoundingClientRect',
fn: function(doc, div) {
return Ext.isFunction(div.getBoundingClientRect);
}
},
{
identity: 'IncludePaddingInWidthCalculation',
fn: function(doc, div){
var el = Ext.get(div.childNodes[1].firstChild);
return el.getWidth() == 210;
}
},
{
identity: 'IncludePaddingInHeightCalculation',
fn: function(doc, div){
var el = Ext.get(div.childNodes[1].firstChild);
return el.getHeight() == 210;
}
},
/**
* @property ArraySort True if the Array sort native method isn't bugged.
* @type {Boolean}
*/
{
identity: 'ArraySort',
fn: function() {
var a = [1,2,3,4,5].sort(function(){ return 0; });
return a[0] === 1 && a[1] === 2 && a[2] === 3 && a[3] === 4 && a[4] === 5;
}
},
/**
* @property Range True if browser support document.createRange native method.
* @type {Boolean}
*/
{
identity: 'Range',
fn: function() {
return !!document.createRange;
}
},
/**
* @property CreateContextualFragment True if browser support CreateContextualFragment range native methods.
* @type {Boolean}
*/
{
identity: 'CreateContextualFragment',
fn: function() {
var range = Ext.supports.Range ? document.createRange() : false;
return range && !!range.createContextualFragment;
}
},
/**
* @property WindowOnError True if browser supports window.onerror.
* @type {Boolean}
*/
{
identity: 'WindowOnError',
fn: function () {
// sadly, we cannot feature detect this...
return Ext.isIE || Ext.isGecko || Ext.webKitVersion >= 534.16; // Chrome 10+
}
},
/**
* @property TextAreaMaxLength True if the browser supports maxlength on textareas.
* @type {Boolean}
*/
{
identity: 'TextAreaMaxLength',
fn: function(){
var el = document.createElement('textarea');
return ('maxlength' in el);
}
},
/**
* @property GetPositionPercentage True if the browser will return the left/top/right/bottom
* position as a percentage when explicitly set as a percentage value.
* @type {Boolean}
*/
// Related bug: https://bugzilla.mozilla.org/show_bug.cgi?id=707691#c7
{
identity: 'GetPositionPercentage',
fn: function(doc, div){
return Ext.get(div.childNodes[2]).getStyle('left') == '10%';
}
}
]
};
Ext.supports.init(); // run the "early" detections now
| codeyu/Ext.NET.Community | Ext.Net/Build/Ext.Net/extjs/pkgs/extras.js | JavaScript | agpl-3.0 | 115,187 |
// Copyright (c) 2019 Uber Technologies, 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.
import React from 'react';
import { shallow } from 'enzyme';
import * as copy from 'copy-to-clipboard';
import { Button, Tooltip } from '@grafana/ui';
import CopyIcon from './CopyIcon';
jest.mock('copy-to-clipboard');
describe('<CopyIcon />', () => {
const props = {
className: 'classNameValue',
copyText: 'copyTextValue',
tooltipTitle: 'tooltipTitleValue',
};
let copySpy;
let wrapper;
beforeAll(() => {
copySpy = jest.spyOn(copy, 'default');
});
beforeEach(() => {
copySpy.mockReset();
wrapper = shallow(<CopyIcon {...props} />);
});
it('renders as expected', () => {
expect(wrapper).toMatchSnapshot();
});
it('updates state and copies when clicked', () => {
expect(wrapper.state().hasCopied).toBe(false);
expect(copySpy).not.toHaveBeenCalled();
wrapper.find(Button).simulate('click');
expect(wrapper.state().hasCopied).toBe(true);
expect(copySpy).toHaveBeenCalledWith(props.copyText);
});
it('persists state when tooltip opens', () => {
wrapper.setState({ hasCopied: true });
expect(wrapper.state().hasCopied).toBe(true);
});
});
| grafana/grafana | packages/jaeger-ui-components/src/common/CopyIcon.test.js | JavaScript | agpl-3.0 | 1,726 |
// menu view
import Vue from 'vuejs';
export default function (template) {
return new Vue({
el: '.menu',
template,
});
};
| arrchat/webclient | views/nav/menu/index.js | JavaScript | agpl-3.0 | 135 |
module.exports = {
name: 'ping',
type: 'core',
usage: 'ping',
permission: 1,
help: 'Tests the bot\'s ping time.',
main: function(bot, msg) {
var start = new Date(msg.createdAt).getTime();
msg.channel.send('Pong!')
.then(msg2 => msg2.edit("Pong! You're on the **" + msg.channel.guild.name + '** server.\nTook ' + (msg2.createdAt.getTime() - start) + ' ms to respond.'))
.catch(console.error);
},
};
| FRCDiscord/RoBot | modules/ping.js | JavaScript | agpl-3.0 | 479 |
/*
* This program was produced for the U.S. Agency for International Development. It was prepared by the USAID | DELIVER PROJECT, Task Order 4. It is part of a project which utilizes code originally licensed under the terms of the Mozilla Public License (MPL) v2 and therefore is licensed under MPL v2 or later.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the Mozilla Public License as published by the Mozilla Foundation, either version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Mozilla Public License for more details.
*
* You should have received a copy of the Mozilla Public License along with this program. If not, see http://www.mozilla.org/MPL/
*/
function ViewVaccineReportDetailController($scope, $location, $filter, report, discardingReasons) {
// initial state of the display
$scope.report = report;
$scope.discardingReasons = discardingReasons;
// populate scope with tab visibility info
$scope.tabVisibility = {};
_.chain(report.tabVisibilitySettings).groupBy('tab').map(function(key, value){
$scope.tabVisibility[value] = key[0].visible;
});
$scope.cancel = function () {
$location.path('/');
};
$scope.showAdverseEffect = function (effect, editMode) {
effect.date = $filter('date')(new Date(effect.date), 'yyyy-MM-dd');
effect.expiry = $filter('date')(new Date(effect.expiry), 'yyyy-MM-dd');
$scope.currentEffect = effect;
$scope.currentEffectMode = editMode;
$scope.adverseEffectModal = true;
};
$scope.closeAdverseEffectsModal = function () {
$scope.adverseEffectModal = false;
};
$scope.showCampaignForm = function (campaign, editMode) {
campaign.startDate = $filter('date')(new Date(campaign.startDate), 'yyyy-MM-dd');
campaign.endDate = $filter('date')(new Date(campaign.endDate), 'yyyy-MM-dd');
$scope.currentCampaign = campaign;
$scope.currentCampaignMode = editMode;
$scope.campaignsModal = true;
};
$scope.closeCampaign = function () {
$scope.campaignsModal = false;
};
$scope.toNumber = function (val) {
if (angular.isDefined(val) && val !== null) {
return parseInt(val, 10);
}
return 0;
};
$scope.rowRequiresExplanation = function (product) {
if (!isUndefined(product.discardingReasonId)) {
var reason = _.findWhere($scope.discardingReasons, {id: parseInt(product.discardingReasonId, 10)});
return reason.requiresExplanation;
}
return false;
};
}
ViewVaccineReportDetailController.resolve = {
report: function ($q, $timeout, $route, VaccineReport) {
var deferred = $q.defer();
$timeout(function () {
VaccineReport.get({id: $route.current.params.id}, function (data) {
data.report.coverageLineItemViews = _.groupBy(data.report.coverageLineItems, 'productId');
deferred.resolve(data.report);
});
}, 100);
return deferred.promise;
},
discardingReasons: function ($q, $timeout, $route, VaccineDiscardingReasons) {
var deferred = $q.defer();
$timeout(function () {
VaccineDiscardingReasons.get(function (data) {
deferred.resolve(data.reasons);
});
}, 100);
return deferred.promise;
}
}; | kelvinmbwilo/vims | modules/openlmis-web/src/main/webapp/public/js/vaccine/report/controller/vaccine-report-view-detail-controller.js | JavaScript | agpl-3.0 | 3,541 |
MWF.xApplication.MinderEditor.History = new Class({
initialize : function( minder ){
this.minder = minder;
this.MAX_HISTORY = 100;
this.lastSnap;
this.patchLock;
this.undoDiffs = [];
this.redoDiffs = [];
this.reset();
minder.on('contentchange', this.changed.bind(this));
minder.on('import', this.reset.bind(this));
minder.on('patch', this.updateSelection.bind(this));
},
reset: function () {
this.undoDiffs = [];
this.redoDiffs = [];
this.lastSnap = this.minder.exportJson();
},
makeUndoDiff: function() {
var headSnap = this.minder.exportJson();
var diff = MWF.xApplication.MinderEditor.JsonDiff(headSnap, this.lastSnap);
if (diff.length) {
this.undoDiffs.push(diff);
while (this.undoDiffs.length > this.MAX_HISTORY) {
this.undoDiffs.shift();
}
this.lastSnap = headSnap;
return true;
}
},
makeRedoDiff:function() {
var revertSnap = this.minder.exportJson();
this.redoDiffs.push(MWF.xApplication.MinderEditor.JsonDiff(revertSnap, this.lastSnap));
this.lastSnap = revertSnap;
},
undo: function() {
this.patchLock = true;
var undoDiff = this.undoDiffs.pop();
if (undoDiff) {
this.minder.applyPatches(undoDiff);
this.makeRedoDiff();
}
this.patchLock = false;
},
redo: function() {
this.patchLock = true;
var redoDiff = this.redoDiffs.pop();
if (redoDiff) {
this.minder.applyPatches(redoDiff);
this.makeUndoDiff();
}
this.patchLock = false;
},
changed: function() {
if (this.patchLock) return;
if (this.makeUndoDiff()) this.redoDiffs = [];
},
hasUndo: function() {
return !!this.undoDiffs.length;
},
hasRedo: function() {
return !!this.redoDiffs.length;
},
updateSelection: function(e) {
if (!this.patchLock) return;
var patch = e.patch;
switch (patch.express) {
case 'node.add':
this.minder.select(patch.node.getChild(patch.index), true);
break;
case 'node.remove':
case 'data.replace':
case 'data.remove':
case 'data.add':
this.minder.select(patch.node, true);
break;
}
}
})
/**
* @Desc: 新增一个用于处理系统ctrl+c ctrl+v等方式导入导出节点的MIMETYPE处理,如系统不支持clipboardEvent或者是FF则不初始化改class
* @Editor: Naixor
* @Date: 2015.9.21
*/
MWF.xApplication.MinderEditor.ClipboardMimeType = new Class({
initialize : function(){
this.SPLITOR = '\uFEFF';
this.MIMETYPE = {
'application/km': '\uFFFF'
};
this.SIGN = {
'\uFEFF': 'SPLITOR',
'\uFFFF': 'application/km'
};
},
/**
* 用于将一段纯文本封装成符合其数据格式的文本
* @method process private
* @param {MIMETYPE} mimetype 数据格式
* @param {String} text 原始文本
* @return {String} 符合该数据格式下的文本
* @example
* var str = "123";
* str = process('application/km', str); // 返回的内容再经过MimeType判断会读取出其数据格式为application/km
* process('text/plain', str); // 若接受到一个非纯文本信息,则会将其转换为新的数据格式
*/
process: function(mimetype, text) {
text = text || "";
if (!this.isPureText(text)) {
var _mimetype = this.whichMimeType(text);
if (!_mimetype) {
throw new Error('unknow mimetype!');
}
text = this.getPureText(text);
}
if (mimetype === false) {
return text;
}
return mimetype + this.SPLITOR + text;
},
/**
* 注册数据类型的标识
* @method registMimeTypeProtocol public
* @param {String} type 数据类型
* @param {String} sign 标识
*/
registMimeTypeProtocol : function(type, sign) {
if (sign && this.SIGN[sign]) {
throw new Error('sing has registed!');
}
if (type && !!this.MIMETYPE[type]) {
throw new Error('mimetype has registed!');
}
this.SIGN[sign] = type;
this.MIMETYPE[type] = sign;
},
/**
* 获取已注册数据类型的协议
* @method getMimeTypeProtocol public
* @param {String} type 数据类型
* @param {String} text|undefiend 文本内容或不传入
* @return {String|Function}
* @example
* text若不传入则直接返回对应数据格式的处理(process)方法
* 若传入文本则直接调用对应的process方法进行处理,此时返回处理后的内容
* var m = new MimeType();
* var kmprocess = m.getMimeTypeProtocol('application/km');
* kmprocess("123") === m.getMimeTypeProtocol('application/km', "123");
*
*/
getMimeTypeProtocol : function(type, text) {
var mimetype = this.MIMETYPE[type] || false;
if (text === undefined) {
return this.process(mimetype);
};
return this.process(mimetype, text);
},
getSpitor : function() {
return this.SPLITOR;
},
getMimeType : function(sign) {
if (sign !== undefined) {
return this.SIGN[sign] || null;
}
return this.MIMETYPE;
},
isPureText : function(text) {
if( !text )return true;
return !(~text.indexOf(this.getSpitor()));
},
getPureText : function(text) {
if (this.isPureText(text)) {
return text;
};
return text.split(this.getSpitor())[1];
},
whichMimeType : function(text) {
if (this.isPureText(text)) {
return null;
};
return this.getMimeType(text.split(this.getSpitor())[0]);
}
})
MWF.xApplication.MinderEditor.Clipboard = new Class({
initialize : function( editor ){
this.editor = editor;
this.minder = editor.minder;
this.Data = window.kityminder.data;
if (!this.minder.supportClipboardEvent || kity.Browser.gecko) {
return;
}
this.fsm = this.editor.fsm;
this.receiver = this.editor.receiver;
this.MimeType = this.editor.MimeType;
this.kmencode = this.MimeType.getMimeTypeProtocol('application/km');
this.decode = this.Data.getRegisterProtocol('json').decode;
this._selectedNodes = [];
/**
* 由editor的receiver统一处理全部事件,包括clipboard事件
* @Editor: Naixor
* @Date: 2015.9.24
*/
document.addEventListener('copy', this.beforeCopy.bind(this));
document.addEventListener('cut', this.beforeCut.bind(this));
document.addEventListener('paste', this.beforePaste.bind(this));
},
/*
* 增加对多节点赋值粘贴的处理
*/
encode: function (nodes) {
var _nodes = [];
for (var i = 0, l = nodes.length; i < l; i++) {
_nodes.push( this.minder.exportNode(nodes[i]));
}
return kmencode( this.Data.getRegisterProtocol('json').encode(_nodes));
},
beforeCopy : function (e) {
if (document.activeElement == this.receiver.element) {
var clipBoardEvent = e;
var state = this.fsm.state();
switch (state) {
case 'input': {
break;
}
case 'normal': {
var nodes = [].concat(this.minder.getSelectedNodes());
if (nodes.length) {
// 这里由于被粘贴复制的节点的id信息也都一样,故做此算法
// 这里有个疑问,使用node.getParent()或者node.parent会离奇导致出现非选中节点被渲染成选中节点,因此使用isAncestorOf,而没有使用自行回溯的方式
if (nodes.length > 1) {
var targetLevel;
nodes.sort(function(a, b) {
return a.getLevel() - b.getLevel();
});
targetLevel = nodes[0].getLevel();
if (targetLevel !== nodes[nodes.length-1].getLevel()) {
var plevel, pnode,
idx = 0, l = nodes.length, pidx = l-1;
pnode = nodes[pidx];
while (pnode.getLevel() !== targetLevel) {
idx = 0;
while (idx < l && nodes[idx].getLevel() === targetLevel) {
if (nodes[idx].isAncestorOf(pnode)) {
nodes.splice(pidx, 1);
break;
}
idx++;
}
pidx--;
pnode = nodes[pidx];
}
};
};
var str = encode(nodes);
clipBoardEvent.clipboardData.setData('text/plain', str);
}
e.preventDefault();
break;
}
}
}
},
beforeCut : function (e) {
if (document.activeElement == this.receiver.element) {
if (this.minder.getStatus() !== 'normal') {
e.preventDefault();
return;
};
var clipBoardEvent = e;
var state = this.fsm.state();
switch (this.state) {
case 'input': {
break;
}
case 'normal': {
var nodes = this.minder.getSelectedNodes();
if (nodes.length) {
clipBoardEvent.clipboardData.setData('text/plain', encode(nodes));
this.minder.execCommand('removenode');
}
e.preventDefault();
break;
}
}
}
},
beforePaste : function(e) {
if (document.activeElement == this.receiver.element) {
if (this.minder.getStatus() !== 'normal') {
e.preventDefault();
return;
};
var clipBoardEvent = e;
var state = this.fsm.state();
var textData = clipBoardEvent.clipboardData.getData('text/plain');
switch (state) {
case 'input': {
// input状态下如果格式为application/km则不进行paste操作
if (!this.MimeType.isPureText(textData)) {
e.preventDefault();
return;
};
break;
}
case 'normal': {
/*
* 针对normal状态下通过对选中节点粘贴导入子节点文本进行单独处理
*/
var sNodes = this.minder.getSelectedNodes();
if (this.MimeType.whichMimeType(textData) === 'application/km') {
var nodes = this.decode(this.MimeType.getPureText(textData));
var _node;
sNodes.forEach(function(node) {
// 由于粘贴逻辑中为了排除子节点重新排序导致逆序,因此复制的时候倒过来
for (var i = nodes.length-1; i >= 0; i--) {
_node = this.minder.createNode(null, node);
this.minder.importNode(_node, nodes[i]);
this._selectedNodes.push(_node);
node.appendChild(_node);
}
});
this.minder.select(this._selectedNodes, true);
this._selectedNodes = [];
this.minder.refresh();
}else if (clipBoardEvent.clipboardData && clipBoardEvent.clipboardData.items[0].type.indexOf('image') > -1) {
//var imageFile = clipBoardEvent.clipboardData.items[0].getAsFile();
//var serverService = angular.element(document.body).injector().get('server');
//
//return serverService.uploadImage(imageFile).then(function (json) {
// var resp = json.data;
// if (resp.errno === 0) {
// this.minder.execCommand('image', resp.data.url);
// }
//});
}
else {
sNodes.forEach(function(node) {
this.minder.Text2Children(node, textData);
});
}
e.preventDefault();
break;
}
}
}
}
})
MWF.xApplication.MinderEditor.Input = new Class({
initialize : function( editor ){
this.editor = editor;
this.fsm = editor.fsm;
this.minder = editor.minder;
//var hotbox = this.hotbox;
this.receiver = editor.receiver;
this.receiverElement = this.receiver.element;
this.isGecko = window.kity.Browser.gecko;
this.debug = this.editor.debug;
this.setupReciverElement();
this.setupFsm();
//this.setupHotbox();
},
setupFsm: function () {
// when jumped to input mode, enter
this.fsm.when('* -> input', this.enterInputMode.bind(this));
// when exited, commit or exit depends on the exit reason
this.fsm.when('input -> *', function(exit, enter, reason) {
switch (reason) {
case 'input-cancel':
return this.exitInputMode();
case 'input-commit':
default:
return this.commitInputResult();
}
}.bind(this));
// lost focus to commit
this.receiver.onblur(function (e) {
if (this.fsm.state() == 'input') {
this.fsm.jump('normal', 'input-commit');
}
}.bind(this));
this.minder.on('beforemousedown', function () {
if (this.fsm.state() == 'input') {
this.fsm.jump('normal', 'input-commit');
}
}.bind(this));
this.minder.on('dblclick', function() {
if (this.minder.getSelectedNode() && this.minder._status !== 'readonly') {
this.editText();
}
}.bind(this));
},
// let the receiver follow the current selected node position
setupReciverElement: function () {
if (this.debug.flaged) {
this.receiverElement.classList.add('debug');
}
this.receiverElement.onmousedown = function(e) {
e.stopPropagation();
};
this.minder.on('layoutallfinish viewchange viewchanged selectionchange', function(e) {
// viewchange event is too frequenced, lazy it
if (e.type == 'viewchange' && this.fsm.state() != 'input') return;
this.updatePosition();
}.bind(this));
this.updatePosition();
},
// edit entrance in hotbox
setupHotbox: function () {
hotbox.state('main').button({
position: 'center',
label: '编辑',
key: 'F2',
enable: function() {
return minder.queryCommandState('text') != -1;
},
action: editText
});
},
/**
* 增加对字体的鉴别,以保证用户在编辑状态ctrl/cmd + b/i所触发的加粗斜体与显示一致
* @editor Naixor
* @Date 2015-12-2
*/
// edit for the selected node
editText: function() {
var node = this.minder.getSelectedNode();
if (!node) {
return;
}
var textContainer = this.receiverElement;
this.receiverElement.innerText = "";
if (node.getData('font-weight') === 'bold') {
var b = document.createElement('b');
textContainer.appendChild(b);
textContainer = b;
}
if (node.getData('font-style') === 'italic') {
var i = document.createElement('i');
textContainer.appendChild(i);
textContainer = i;
}
textContainer.innerText = this.minder.queryCommandValue('text') || "";
if (this.isGecko) {
this.receiver.fixFFCaretDisappeared();
}
this.fsm.jump('input', 'input-request');
this.receiver.selectAll();
},
/**
* 增加对字体的鉴别,以保证用户在编辑状态ctrl/cmd + b/i所触发的加粗斜体与显示一致
* @editor Naixor
* @Date 2015-12-2
*/
enterInputMode: function() {
var node = this.minder.getSelectedNode();
var receiverElement = this.receiverElement;
if (node) {
var fontSize = node.getData('font-size') || node.getStyle('font-size');
receiverElement.style.fontSize = fontSize + 'px';
receiverElement.style.minWidth = 0;
receiverElement.style.minWidth = receiverElement.clientWidth + 'px';
receiverElement.style.fontWeight = node.getData('font-weight') || '';
receiverElement.style.fontStyle = node.getData('font-style') || '';
receiverElement.classList.add('input');
receiverElement.focus();
}
},
/**
* 按照文本提交操作处理
* @Desc: 从其他节点复制文字到另一个节点时部分浏览器(chrome)会自动包裹一个span标签,这样试用一下逻辑出来的就不是text节点二是span节点因此导致undefined的情况发生
* @Warning: 下方代码使用[].slice.call来将HTMLDomCollection处理成为Array,ie8及以下会有问题
* @Editor: Naixor
* @Date: 2015.9.16
*/
commitInputText: function(textNodes) {
var text = '';
var TAB_CHAR = '\t',
ENTER_CHAR = '\n',
STR_CHECK = /\S/,
SPACE_CHAR = '\u0020',
// 针对FF,SG,BD,LB,IE等浏览器下SPACE的charCode存在为32和160的情况做处理
SPACE_CHAR_REGEXP = new RegExp('(\u0020|' + String.fromCharCode(160) + ')'),
BR = document.createElement('br');
var isBold = false,
isItalic = false;
for (var str,
_divChildNodes,
space_l, space_num, tab_num,
i = 0, l = textNodes.length; i < l; i++) {
str = textNodes[i];
switch (Object.prototype.toString.call(str)) {
// 正常情况处理
case '[object HTMLBRElement]': {
text += ENTER_CHAR;
break;
}
case '[object Text]': {
// SG下会莫名其妙的加上 影响后续判断,干掉!
/**
* FF下的wholeText会导致如下问题:
* |123| -> 在一个节点中输入一段字符,此时TextNode为[#Text 123]
* 提交并重新编辑,在后面追加几个字符
* |123abc| -> 此时123为一个TextNode为[#Text 123, #Text abc],但是对这两个任意取值wholeText均为全部内容123abc
* 上述BUG仅存在在FF中,故将wholeText更改为textContent
*/
str = str.textContent.replace(" ", " ");
if (!STR_CHECK.test(str)) {
space_l = str.length;
while (space_l--) {
if (SPACE_CHAR_REGEXP.test(str[space_l])) {
text += SPACE_CHAR;
} else if (str[space_l] === TAB_CHAR) {
text += TAB_CHAR;
}
}
} else {
text += str;
}
break;
}
// ctrl + b/i 会给字体加上<b>/<i>标签来实现黑体和斜体
case '[object HTMLElement]': {
switch (str.nodeName) {
case "B": {
isBold = true;
break;
}
case "I": {
isItalic = true;
break;
}
default: {}
}
[].splice.apply(textNodes, [i, 1].concat([].slice.call(str.childNodes)));
l = textNodes.length;
i--;
break;
}
// 被增加span标签的情况会被处理成正常情况并会推交给上面处理
case '[object HTMLSpanElement]': {
[].splice.apply(textNodes, [i, 1].concat([].slice.call(str.childNodes)));
l = textNodes.length;
i--;
break;
}
// 若标签为image标签,则判断是否为合法url,是将其加载进来
case '[object HTMLImageElement]': {
if (str.src) {
if (/http(|s):\/\//.test(str.src)) {
minder.execCommand("Image", str.src, str.alt);
} else {
// data:image协议情况
}
};
break;
}
// 被增加div标签的情况会被处理成正常情况并会推交给上面处理
case '[object HTMLDivElement]': {
_divChildNodes = [];
for (var di = 0, l = str.childNodes.length; di < l; di++) {
_divChildNodes.push(str.childNodes[di]);
}
_divChildNodes.push(BR);
[].splice.apply(textNodes, [i, 1].concat(_divChildNodes));
l = textNodes.length;
i--;
break;
}
default: {
if (str && str.childNodes.length) {
_divChildNodes = [];
for (var di = 0, l = str.childNodes.length; di < l; di++) {
_divChildNodes.push(str.childNodes[di]);
}
_divChildNodes.push(BR);
[].splice.apply(textNodes, [i, 1].concat(_divChildNodes));
l = textNodes.length;
i--;
} else {
if (str && str.textContent !== undefined) {
text += str.textContent;
} else {
text += "";
}
}
// // 其他带有样式的节点被粘贴进来,则直接取textContent,若取不出来则置空
}
}
};
text = text.replace(/^\n*|\n*$/g, '');
text = text.replace(new RegExp('(\n|\r|\n\r)(\u0020|' + String.fromCharCode(160) + '){4}', 'g'), '$1\t');
this.minder.getSelectedNode().setText(text);
if (isBold) {
this.minder.queryCommandState('bold') || this.minder.execCommand('bold');
} else {
this.minder.queryCommandState('bold') && this.minder.execCommand('bold');
}
if (isItalic) {
this.minder.queryCommandState('italic') || this.minder.execCommand('italic');
} else {
this.minder.queryCommandState('italic') && this.minder.execCommand('italic');
}
this.exitInputMode();
return text;
},
/**
* 判断节点的文本信息是否是
* @Desc: 从其他节点复制文字到另一个节点时部分浏览器(chrome)会自动包裹一个span标签,这样使用以下逻辑出来的就不是text节点二是span节点因此导致undefined的情况发生
* @Notice: 此处逻辑应该拆分到 kityminder-core/core/data中去,单独增加一个对某个节点importJson的事件
* @Editor: Naixor
* @Date: 2015.9.16
*/
commitInputNode: function (node, text) {
try {
this. minder.decodeData('text', text).then(function(json) {
function importText(node, json, minder) {
var data = json.data;
node.setText(data.text || '');
var childrenTreeData = json.children || [];
for (var i = 0; i < childrenTreeData.length; i++) {
var childNode = minder.createNode(null, node);
importText(childNode, childrenTreeData[i], minder);
}
return node;
}
importText(node, json, this.minder);
this.minder.fire("contentchange");
this.minder.getRoot().renderTree();
this.minder.layout(300);
}.bind(this));
} catch (e) {
this.minder.fire("contentchange");
this.minder.getRoot().renderTree();
// 无法被转换成脑图节点则不处理
if (e.toString() !== 'Error: Invalid local format') {
throw e;
}
}
},
commitInputResult: function() {
/**
* @Desc: 进行如下处理:
* 根据用户的输入判断是否生成新的节点
* fix #83 https://github.com/fex-team/kityminder-editor/issues/83
* @Editor: Naixor
* @Date: 2015.9.16
*/
var textNodes = [].slice.call(this.receiverElement.childNodes);
/**
* @Desc: 增加setTimeout的原因:ie下receiverElement.innerHTML=""会导致后
* 面commitInputText中使用textContent报错,不要问我什么原因!
* @Editor: Naixor
* @Date: 2015.12.14
*/
setTimeout(function () {
// 解决过大内容导致SVG窜位问题
this.receiverElement.innerHTML = "";
}.bind(this), 0);
var node = this.minder.getSelectedNode();
textNodes = this.commitInputText(textNodes);
this.commitInputNode(node, textNodes);
if (node.type == 'root') {
var rootText = this.minder.getRoot().getText();
this.minder.fire('initChangeRoot', {text: rootText});
}
},
exitInputMode: function () {
this.receiverElement.classList.remove('input');
this.receiver.selectAll();
},
updatePosition: function() {
var focusNode = this.minder.getSelectedNode();
if (!focusNode) return;
if (!this.timer) {
this.timer = setTimeout(function() {
var box = focusNode.getRenderBox('TextRenderer');
this.receiverElement.style.left = Math.round(box.x) + 'px';
this.receiverElement.style.top = (this.debug.flaged ? Math.round(box.bottom + 30) : Math.round(box.y)) + 'px';
//receiverElement.focus();
this.timer = 0;
}.bind(this));
}
}
})
// 用于拖拽节点时屏蔽键盘事件
MWF.xApplication.MinderEditor.Drag = new Class({
initialize : function( editor ){
this.editor = editor;
this.fsm = editor.fsm;
this.minder = editor.minder;
//var hotbox = this.hotbox;
this.receiver = editor.receiver;
this.receiverElement = this.receiver.element;
this.setupFsm();
var downX, downY;
var MOUSE_HAS_DOWN = 0;
var MOUSE_HAS_UP = 1;
var BOUND_CHECK = 20;
var flag = MOUSE_HAS_UP;
var maxX, maxY, osx, osy, containerY;
var freeHorizen = this.freeHorizen = false;
var freeVirtical = this.freeVirtical = false;
this.frame = null;
this.minder.on('mousedown', function(e) {
flag = MOUSE_HAS_DOWN;
var rect = this.minder.getPaper().container.getBoundingClientRect();
downX = e.originEvent.clientX;
downY = e.originEvent.clientY;
containerY = rect.top;
maxX = rect.width;
maxY = rect.height;
}.bind(this));
this.minder.on('mousemove', function(e) {
if ( this.fsm.state() === 'drag' && flag == MOUSE_HAS_DOWN && this.minder.getSelectedNode()
&& (Math.abs(downX - e.originEvent.clientX) > BOUND_CHECK
|| Math.abs(downY - e.originEvent.clientY) > BOUND_CHECK)) {
osx = e.originEvent.clientX;
osy = e.originEvent.clientY - containerY;
if (osx < BOUND_CHECK) {
this.move('right', BOUND_CHECK - osx);
} else if (osx > maxX - BOUND_CHECK) {
this.move('left', BOUND_CHECK + osx - maxX);
} else {
freeHorizen = true;
}
if (osy < BOUND_CHECK) {
this.move('bottom', osy);
} else if (osy > maxY - BOUND_CHECK) {
this.move('top', BOUND_CHECK + osy - maxY);
} else {
freeVirtical = true;
}
if (freeHorizen && freeVirtical) {
this.move(false);
}
}
if (this.fsm.state() !== 'drag'
&& flag === MOUSE_HAS_DOWN
&& this.minder.getSelectedNode()
&& (Math.abs(downX - e.originEvent.clientX) > BOUND_CHECK
|| Math.abs(downY - e.originEvent.clientY) > BOUND_CHECK)) {
if (this.fsm.state() === 'hotbox') {
//hotbox.active(Hotbox.STATE_IDLE);
}
return this.fsm.jump('drag', 'user-drag');
}
}.bind(this));
window.addEventListener('mouseup', function () {
flag = MOUSE_HAS_UP;
if (this.fsm.state() === 'drag') {
this.move(false);
return this.fsm.jump('normal', 'drag-finish');
}
}.bind(this), false);
},
setupFsm: function(){
// when jumped to drag mode, enter
this.fsm.when('* -> drag', function() {
// now is drag mode
});
this.fsm.when('drag -> *', function(exit, enter, reason) {
if (reason == 'drag-finish') {
// now exit drag mode
}
});
},
move: function(direction, speed) {
if (!direction) {
this.freeHorizen = this.freeVirtical = false;
this.frame && kity.releaseFrame(this.frame);
this.frame = null;
return;
}
if (!this.frame) {
this.frame = kity.requestFrame((function (direction, speed, minder) {
return function (frame) {
switch (direction) {
case 'left':
minder._viewDragger.move({x: -speed, y: 0}, 0);
break;
case 'top':
minder._viewDragger.move({x: 0, y: -speed}, 0);
break;
case 'right':
minder._viewDragger.move({x: speed, y: 0}, 0);
break;
case 'bottom':
minder._viewDragger.move({x: 0, y: speed}, 0);
break;
default:
return;
}
frame.next();
};
})(direction, speed, this.minder));
}
}
})
MWF.xApplication.MinderEditor.FSM = new Class({
initialize: function( defaultState ){
this.currentState = defaultState;
this.BEFORE_ARROW = ' - ';
this.AFTER_ARROW = ' -> ';
this.handlers = [];
this.debug = new MWF.xApplication.MinderEditor.Debug('fsm');
},
/**
* 状态跳转
*
* 会通知所有的状态跳转监视器
*
* @param {string} newState 新状态名称
* @param {any} reason 跳转的原因,可以作为参数传递给跳转监视器
*/
jump: function(newState, reason) {
if (!reason) throw new Error('Please tell fsm the reason to jump');
var oldState = this.currentState;
var notify = [oldState, newState].concat([].slice.call(arguments, 1));
var i, handler;
// 跳转前
for (i = 0; i < this.handlers.length; i++) {
handler = this.handlers[i];
if (this.handlerConditionMatch(handler.condition, 'before', oldState, newState)) {
if (handler.apply(null, notify)) return;
}
}
this.currentState = newState;
this.debug.log('[{0}] {1} -> {2}', reason, oldState, newState);
// 跳转后
for (i = 0; i < this.handlers.length; i++) {
handler = this.handlers[i];
if (this.handlerConditionMatch(handler.condition, 'after', oldState, newState)) {
handler.apply(null, notify);
}
}
return this.currentState;
},
/**
* 返回当前状态
* @return {string}
*/
state : function() {
return this.currentState;
},
/**
* 添加状态跳转监视器
*
* @param {string} condition
* 监视的时机
* "* => *" (默认)
*
* @param {Function} handler
* 监视函数,当状态跳转的时候,会接收三个参数
* * from - 跳转前的状态
* * to - 跳转后的状态
* * reason - 跳转的原因
*/
when : function(condition, handler) {
if (arguments.length == 1) {
handler = condition;
condition = '* -> *';
}
var when, resolved, exit, enter;
resolved = condition.split(this.BEFORE_ARROW);
if (resolved.length == 2) {
when = 'before';
} else {
resolved = condition.split(this.AFTER_ARROW);
if (resolved.length == 2) {
when = 'after';
}
}
if (!when) throw new Error('Illegal fsm condition: ' + condition);
exit = resolved[0];
enter = resolved[1];
handler.condition = {
when: when,
exit: exit,
enter: enter
};
this.handlers.push(handler);
},
handlerConditionMatch: function (condition, when, exit, enter) {
if (condition.when != when) return false;
if (condition.enter != '*' && condition.enter != enter) return false;
if (condition.exit != '*' && condition.exit != exit) return;
return true;
}
})
//根据按键控制状态机的跳转
MWF.xApplication.MinderEditor.Jumping = function() {
/**
* @Desc: 下方使用receiver.enable()和receiver.disable()通过
* 修改div contenteditable属性的hack来解决开启热核后依然无法屏蔽浏览器输入的bug;
* 特别: win下FF对于此种情况必须要先blur在focus才能解决,但是由于这样做会导致用户
* 输入法状态丢失,因此对FF暂不做处理
* @Editor: Naixor
* @Date: 2015.09.14
*/
var fsm = this.fsm;
var minder = this.minder;
var receiver = this.receiver;
var container = this.container;
var receiverElement = receiver.element;
var hotbox = this.hotbox;
// Nice: http://unixpapa.com/js/key.html
function isIntendToInput(e) {
if (e.ctrlKey || e.metaKey || e.altKey) return false;
// a-zA-Z
if (e.keyCode >= 65 && e.keyCode <= 90) return true;
// 0-9 以及其上面的符号
if (e.keyCode >= 48 && e.keyCode <= 57) return true;
// 小键盘区域 (除回车外)
if (e.keyCode != 108 && e.keyCode >= 96 && e.keyCode <= 111) return true;
// 小键盘区域 (除回车外)
// @yinheli from pull request
if (e.keyCode != 108 && e.keyCode >= 96 && e.keyCode <= 111) return true;
// 输入法
if (e.keyCode == 229 || e.keyCode === 0) return true;
return false;
}
// normal -> *
receiver.listen('normal', function(e) {
// 为了防止处理进入edit模式而丢失处理的首字母,此时receiver必须为enable
receiver.enable();
// normal -> hotbox
if (e.is('Space')) {
e.preventDefault();
// safari下Space触发hotbox,然而这时Space已在receiver上留下作案痕迹,因此抹掉
if (kity.Browser.safari) {
receiverElement.innerHTML = '';
}
return fsm.jump('hotbox', 'space-trigger');
}
/**
* check
* @editor Naixor
* @Date 2015-12-2
*/
switch (e.type) {
case 'keydown': {
if (minder.getSelectedNode()) {
if (isIntendToInput(e)) {
return fsm.jump('input', 'user-input');
};
} else {
receiverElement.innerHTML = '';
}
// normal -> normal shortcut
fsm.jump('normal', 'shortcut-handle', e);
break;
}
case 'keyup': {
break;
}
default: {}
}
});
// hotbox -> normal
receiver.listen('hotbox', function(e) {
receiver.disable();
e.preventDefault();
var handleResult = hotbox.dispatch(e);
if (hotbox.state() == Hotbox.STATE_IDLE && fsm.state() == 'hotbox') {
return fsm.jump('normal', 'hotbox-idle');
}
});
// input => normal
receiver.listen('input', function(e) {
receiver.enable();
if (e.type == 'keydown') {
if (e.is('Enter')) {
e.preventDefault();
return fsm.jump('normal', 'input-commit');
}
if (e.is('Esc')) {
e.preventDefault();
return fsm.jump('normal', 'input-cancel');
}
if (e.is('Tab') || e.is('Shift + Tab')) {
e.preventDefault();
}
} else if (e.type == 'keyup' && e.is('Esc')) {
e.preventDefault();
return fsm.jump('normal', 'input-cancel');
}
});
//////////////////////////////////////////////
/// 右键呼出热盒
/// 判断的标准是:按下的位置和结束的位置一致
//////////////////////////////////////////////
var downX, downY;
var MOUSE_RB = 2; // 右键
container.addEventListener('mousedown', function(e) {
if (e.button == MOUSE_RB) {
e.preventDefault();
}
if (fsm.state() == 'hotbox') {
hotbox.active(Hotbox.STATE_IDLE);
fsm.jump('normal', 'blur');
} else if (fsm.state() == 'normal' && e.button == MOUSE_RB) {
downX = e.clientX;
downY = e.clientY;
}
}, false);
container.addEventListener('mousewheel', function(e) {
if (fsm.state() == 'hotbox') {
hotbox.active(Hotbox.STATE_IDLE);
fsm.jump('normal', 'mousemove-blur');
}
}, false);
container.addEventListener('contextmenu', function(e) {
e.preventDefault();
});
container.addEventListener('mouseup', function(e) {
if (fsm.state() != 'normal') {
return;
}
if (e.button != MOUSE_RB || e.clientX != downX || e.clientY != downY) {
return;
}
if (!minder.getSelectedNode()) {
return;
}
fsm.jump('hotbox', 'content-menu');
}, false);
// 阻止热盒事件冒泡,在热盒正确执行前导致热盒关闭
hotbox.$element.addEventListener('mousedown', function(e) {
e.stopPropagation();
});
}
//键盘事件接收/分发器
MWF.xApplication.MinderEditor.Receiver = new Class({
initialize: function( editor ){
this.editor = editor;
this.minder = editor.minder;
this.fsm = editor.fsm;
// 接收事件的 div
var element = this.element = document.createElement('div');
element.contentEditable = true;
/**
* @Desc: 增加tabindex属性使得element的contenteditable不管是trur还是false都能有focus和blur事件
* @Editor: Naixor
* @Date: 2015.09.14
*/
element.setAttribute("tabindex", -1);
element.classList.add('receiver');
element.onkeydown = element.onkeypress = element.onkeyup = this.dispatchKeyEvent.bind(this);
this.editor.contentNode.appendChild(element);
this.selectAll();
this.minder.on('beforemousedown', this.selectAll.bind(this));
this.minder.on('receiverfocus', this.selectAll.bind(this));
this.minder.on('readonly', function() {
// 屏蔽minder的事件接受,删除receiver和hotbox
this.minder.disable();
this.element.parentElement.removeChild(this.element);
//this.editor.hotbox.$container.removeChild(editor.hotbox.$element);
}.bind(this));
// 侦听器,接收到的事件会派发给所有侦听器
this.listeners = [];
},
selectAll: function() {
// 保证有被选中的
if (!this.element.innerHTML) this.element.innerHTML = ' ';
var range = document.createRange();
var selection = window.getSelection();
range.selectNodeContents(this.element);
selection.removeAllRanges();
selection.addRange(range);
this.element.focus();
},
/**
* @Desc: 增加enable和disable方法用于解决热核态的输入法屏蔽问题
* @Editor: Naixor
* @Date: 2015.09.14
*/
enable: function() {
this.element.setAttribute("contenteditable", true);
},
disable: function() {
this.element.setAttribute("contenteditable", false);
},
/**
* @Desc: hack FF下div contenteditable的光标丢失BUG
* @Editor: Naixor
* @Date: 2015.10.15
*/
fixFFCaretDisappeared: function() {
this.element.removeAttribute("contenteditable");
this.element.setAttribute("contenteditable", "true");
this.element.blur();
this.element.focus();
},
/**
* 以此事件代替通过mouse事件来判断receiver丢失焦点的事件
* @editor Naixor
* @Date 2015-12-2
*/
onblur: function (handler) {
this.element.onblur = handler;
},
// 侦听指定状态下的事件,如果不传 state,侦听所有状态
listen : function(state, listener) {
if (arguments.length == 1) {
listener = state;
state = '*';
}
listener.notifyState = state;
listeners.push(listener);
},
dispatchKeyEvent: function (e) {
e.is = function(keyExpression) {
var subs = keyExpression.split('|');
for (var i = 0; i < subs.length; i++) {
if (key.is(this, subs[i])) return true;
}
return false;
};
var listener, jumpState;
for (var i = 0; i < this.listeners.length; i++) {
listener = listeners[i];
// 忽略不在侦听状态的侦听器
if (listener.notifyState != '*' && listener.notifyState != fsm.state()) {
continue;
}
/**
*
* 对于所有的侦听器,只允许一种处理方式:跳转状态。
* 如果侦听器确定要跳转,则返回要跳转的状态。
* 每个事件只允许一个侦听器进行状态跳转
* 跳转动作由侦听器自行完成(因为可能需要在跳转时传递 reason),返回跳转结果即可。
* 比如:
*
* ```js
* receiver.listen('normal', function(e) {
* if (isSomeReasonForJumpState(e)) {
* return fsm.jump('newstate', e);
* }
* });
* ```
*/
if (this.listener.call(null, e)) {
return;
}
}
}
})
| o2oa/o2oa | o2web/source/x_component_MinderEditor/Rumtime.js | JavaScript | agpl-3.0 | 45,592 |
OC.L10N.register(
"theming",
{
"Loading preview…" : "Läser in förhandsvisning...",
"Saved" : "Sparat",
"Admin" : "Admin",
"a safe home for all your data" : "ett säkert hem för alla dina data",
"Name cannot be empty" : "Namn kan inte vara tom",
"The given name is too long" : "Det angivna namnet är för långt",
"The given web address is too long" : "Den angivna adressen är för lång",
"The given web address is not a valid URL" : "Den angivna webbadressen är inte en giltig webbadress",
"The given legal notice address is too long" : "Den angivna juridiska notisadressen är för lång",
"The given legal notice address is not a valid URL" : "Den angivna juridiska notisadressen är inte en giltig webbadress",
"The given privacy policy address is too long" : "Den angivna sekretesspolicyadressen är för lång",
"The given privacy policy address is not a valid URL" : "Den angivna sekretesspolicyadressen är inte en giltig webbadress",
"The given slogan is too long" : "Den angivna slogan är för lång",
"The given color is invalid" : "Den angivna färgen är inte tillgänglig",
"The file was uploaded" : "Filen laddades upp",
"The uploaded file exceeds the upload_max_filesize directive in php.ini" : "Uppladdningsfilen är för stor (upload_max_filesize i php.ini)",
"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" : "Den uppladdade filen överstiger MAX_FILE_SIZE-instruktionen specificerad i HTML-form",
"The file was only partially uploaded" : "Filen var endast delvis uppladdad",
"No file was uploaded" : "Ingen fil laddades upp",
"Missing a temporary folder" : "Saknar en temporär mapp",
"Could not write file to disk" : "Kunde inte skriva fil till disk",
"A PHP extension stopped the file upload" : "Ett PHP-tillägg stoppade filuppladdning",
"No file uploaded" : "Ingen fil uppladdad",
"You are already using a custom theme. Theming app settings might be overwritten by that." : "Du använder redan ett anpassat tema. Dessa appinställningar kan skrivas över.",
"Theming" : "Teman",
"Legal notice" : "Rättsligt meddelande",
"Privacy policy" : "Integritetspolicy",
"Adjust the Nextcloud theme" : "Justera Nextcloud-tema",
"Open documentation" : "Öppna dokumentationen",
"Theming makes it possible to easily customize the look and feel of your instance and supported clients. This will be visible for all users." : "Teman gör det möjligt att enkelt skräddarsy utseendet på ditt moln. Detta kommer att synas för alla användare.",
"Name" : "Namn",
"Reset to default" : "Återställ till grundinställningar",
"Web link" : "Webblänk",
"https://…" : "https://…",
"Slogan" : "Slogan",
"Color" : "Färg",
"Logo" : "Logotyp",
"Upload new logo" : "Ladda upp ny logotyp",
"Login image" : "Inloggningsbild",
"Upload new login background" : "Ladda upp ny bakgrundsbild",
"Remove background image" : "Ta bort bakgrundsbild",
"Advanced options" : "Avancerade inställningar",
"Legal notice link" : "Länk rättsligt meddelande",
"Privacy policy link" : "Länk integritetspolicy",
"Header logo" : "Huvud-logga",
"Upload new header logo" : "Ladda upp ny huvud-logga",
"Favicon" : "Favicon",
"Upload new favicon" : "Ladda upp nya favicon",
"Install the Imagemagick PHP extension with support for SVG images to automatically generate favicons based on the uploaded logo and color." : "Installera Imagemagick PHP-tillägget med stöd för SVG-bilder för att automatiskt generera favicons baserat på den uppladdade logotypen och färgen.",
"Unsupported image type" : "Filtyp stöds inte"
},
"nplurals=2; plural=(n != 1);");
| andreas-p/nextcloud-server | apps/theming/l10n/sv.js | JavaScript | agpl-3.0 | 3,799 |
/**
* Nome del file: settings.client.controller.test.js
* Percorso: /public/modules/users/tests/settings.client.controller.test.js
* Autore: InfiniTech
* Data creazione: 2015-09-02
* E-mail: info.infinitech@gmail.com
*
* Questo file è proprietà del gruppo InfiniTech e viene rilasciato sotto
* licenza GNU AGPLv3.
*
* Diario delle modifiche:
* 2015-09-02 - Aggiunti tests su metodi updateUserProfile(),
* changeUserPassword() - Alex Ruzzante
*/
'use strict';
(function() {
describe('SettingsController', function() {
//Initialize global variables
var scope;
var $httpBackend;
var $location;
var SettingsController;
var Users;
var Authentication;
var $stateParams;
beforeEach(module(ApplicationConfiguration.applicationModuleName));
beforeEach(inject(function($controller, $rootScope, _$httpBackend_,
_Authentication_, _Users_,
_$location_, _$stateParams_) {
scope = $rootScope.$new();
$httpBackend = _$httpBackend_;
Users = _Users_;
$location = _$location_;
Authentication = _Authentication_;
$stateParams = _$stateParams_;
SettingsController = $controller('SettingsController', {
$scope: scope
});
}));
it('$scope.updateUserProfile(isValid) should update user\'s profile if' +
' isValid is true', function() {
Authentication.user = {};
scope.success = false;
scope.error = undefined;
scope.user = {firstName: 'A sample', lastName: 'User'};
var mockUser = {firstName: 'A sample', lastName: 'User'};
$httpBackend.expectPUT('users').respond(mockUser);
scope.updateUserProfile(true);
$httpBackend.flush();
// Test scope value
expect(scope.success).toBeTruthy();
expect(Authentication.user.firstName).toBe('A sample');
expect(Authentication.user.lastName).toBe('User');
expect(scope.error).toBe(null);
});
it('$scope.updateUserProfile(isValid) should set scope.submitted if' +
' isValid is false', function() {
scope.submitted = false;
scope.updateUserProfile(false);
// Test scope value
expect(scope.submitted).toBeTruthy();
});
it('$scope.changeUserPassword() should set scope.success if it has' +
' changed the password', function() {
scope.passwordDetails = '*******';
scope.success = false;
scope.error = undefined;
$httpBackend.expectPOST('/users/password' , scope.passwordDetails).
respond(200);
scope.changeUserPassword();
$httpBackend.flush();
// Test scope value
expect(scope.success).toBeTruthy();
expect(scope.error).toBe(null);
expect(scope.passwordDetails).toBe(null);
});
it('$scope.changeUserPassword() should set scope.error if there is a' +
' change password error', function() {
scope.passwordDetails = '*******';
$httpBackend.expectPOST('/users/password' , scope.passwordDetails).
respond(400, {
'message': 'password error'
});
scope.changeUserPassword();
$httpBackend.flush();
// Test scope value
expect(scope.error).toBe('password error');
});
});
})();
| infinitech-unipd/Premi | public/modules/users/tests/settings.client.controller.test.js | JavaScript | agpl-3.0 | 3,247 |
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
{% include 'setup/doctype/contact_control/contact_control.js' %};
cur_frm.cscript.onload = function(doc,dt,dn){
}
cur_frm.cscript.refresh = function(doc,dt,dn){
if(doc.__islocal){
hide_field(['address_html', 'contact_html']);
}
else{
unhide_field(['address_html', 'contact_html']);
// make lists
cur_frm.cscript.make_address(doc,dt,dn);
cur_frm.cscript.make_contact(doc,dt,dn);
if (doc.show_in_website) {
cur_frm.set_intro(__("Published on website at: {0}",
[repl('<a href="/%(website_route)s" target="_blank">/%(website_route)s</a>', doc.__onload)]));
}
}
}
cur_frm.cscript.make_address = function() {
if(!cur_frm.address_list) {
cur_frm.address_list = new frappe.ui.Listing({
parent: cur_frm.fields_dict['address_html'].wrapper,
page_length: 2,
new_doctype: "Address",
custom_new_doc: function(doctype) {
var address = frappe.model.make_new_doc_and_get_name('Address');
address = locals['Address'][address];
address.sales_partner = cur_frm.doc.name;
address.address_title = cur_frm.doc.name;
address.address_type = "Office";
frappe.set_route("Form", "Address", address.name);
},
get_query: function() {
return "select name, address_type, address_line1, address_line2, city, state, country, pincode, fax, email_id, phone, is_primary_address, is_shipping_address from tabAddress where sales_partner='" +
cur_frm.doc.name.replace("'", "\\'") + "' and docstatus != 2 order by is_primary_address desc"
},
as_dict: 1,
no_results_message: __('No addresses created'),
render_row: cur_frm.cscript.render_address_row,
});
}
cur_frm.address_list.run();
}
cur_frm.cscript.make_contact = function() {
if(!cur_frm.contact_list) {
cur_frm.contact_list = new frappe.ui.Listing({
parent: cur_frm.fields_dict['contact_html'].wrapper,
page_length: 2,
new_doctype: "Contact",
custom_new_doc: function(doctype) {
var contact = frappe.model.make_new_doc_and_get_name('Contact');
contact = locals['Contact'][contact];
contact.sales_partner = cur_frm.doc.name;
frappe.set_route("Form", "Contact", contact.name);
},
get_query: function() {
return "select name, first_name, last_name, email_id, phone, mobile_no, department, designation, is_primary_contact from tabContact where sales_partner='" +
cur_frm.doc.name.replace("'", "\\'") + "' and docstatus != 2 order by is_primary_contact desc"
},
as_dict: 1,
no_results_message: __('No contacts created'),
render_row: cur_frm.cscript.render_contact_row,
});
}
cur_frm.contact_list.run();
}
cur_frm.fields_dict['partner_target_details'].grid.get_field("item_group").get_query = function(doc, dt, dn) {
return{
filters:{ 'is_group': "No" }
}
}
| gangadharkadam/office_erp | erpnext/setup/doctype/sales_partner/sales_partner.js | JavaScript | agpl-3.0 | 2,875 |
import React from 'react';
import PropTypes from 'prop-types';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import ResourceBreakdown from 'parser/shared/modules/resourcetracker/ResourceBreakdown';
//Need to extend this class to change how passive rune regeneration is displayed.
//The only new lines are 44, 49-54 and 78.
class RuneBreakdown extends ResourceBreakdown {
static propTypes = {
tracker: PropTypes.object.isRequired,
showSpenders: PropTypes.bool,
};
render() {
const { tracker, showSpenders } = this.props;
const resourceName = tracker.resource.name;
const generated = this.prepareGenerated(tracker.buildersObj);
const spent = this.prepareSpent(tracker.spendersObj);
let totalGenerated = tracker.generated;
let totalWasted = tracker.wasted;
let totalSpent = tracker.spent;
let totalCasts = tracker.spendersCasts;
// looks wrong but totals are only for the purpose of percentage, and if nothing was wasted, then 0/1 gives correct result 0% wasted, if it's not 0 it retains its original value
totalGenerated = (totalGenerated === 0) ? 1 : totalGenerated;
totalWasted = (totalWasted === 0) ? 1 : totalWasted;
totalSpent = (totalSpent === 0) ? 1 : totalSpent;
totalCasts = (totalCasts === 0) ? 1 : totalCasts;
return (
<div>
<table className="data-table">
<thead>
<tr>
<th>Ability</th>
<th colSpan="2"><dfn data-tip="Runes generated from passive regeneration and abilities that accelerate it are estimates.">{resourceName} generated</dfn></th>
<th colSpan="2"><dfn data-tip="This is the amount of resources that were generated while you were already at cap.">{resourceName} wasted</dfn></th>
</tr>
</thead>
<tbody>
{generated && generated
.filter(ability => ability.abilityId === SPELLS.RUNE_1.id)
.map(ability => (
<tr>
<td style={{ width: '30%' }}>
<SpellIcon id={ability.abilityId} noLink />{' '}
Passive Rune regeneration
</td>
<td style={{ width: 50, paddingRight: 5, textAlign: 'center' }}>
<dfn data-tip={`${formatPercentage(ability.generated / totalGenerated)} %`}>{ability.generated}</dfn>
</td>
<td style={{ width: '40%' }}>
<div
className="performance-bar"
style={{ width: `${(ability.generated / totalGenerated) * 100}%` }}
/>
</td>
<td style={{ width: 50, paddingRight: 5, textAlign: 'center' }}>
<dfn data-tip={`${formatPercentage(ability.wasted / totalWasted)} %`}>{ability.wasted}</dfn>
</td>
<td style={{ width: '30%' }}>
<div
className="performance-bar"
style={{ width: `${(ability.wasted / totalWasted) * 100}%` }}
/>
</td>
</tr>
))}
{generated && generated
.filter(ability => ability.abilityId !== SPELLS.RUNE_1.id)
.map(ability => (
<tr>
<td style={{ width: '30%' }}>
<SpellLink id={ability.abilityId} />
</td>
<td style={{ width: 50, paddingRight: 5, textAlign: 'center' }}>
<dfn data-tip={`${formatPercentage(ability.generated / totalGenerated)} %`}>{ability.generated}</dfn>
</td>
<td style={{ width: '40%' }}>
<div
className="performance-bar"
style={{ width: `${(ability.generated / totalGenerated) * 100}%` }}
/>
</td>
<td style={{ width: 50, paddingRight: 5, textAlign: 'center' }}>
<dfn data-tip={`${formatPercentage(ability.wasted / totalWasted)} %`}>{ability.wasted}</dfn>
</td>
<td style={{ width: '30%' }}>
<div
className="performance-bar"
style={{ width: `${(ability.wasted / totalWasted) * 100}%` }}
/>
</td>
</tr>
))}
</tbody>
</table>
{showSpenders && (
<table className="data-table">
<thead>
<tr>
<th>Ability</th>
<th colSpan="2">{resourceName} spent</th>
<th colSpan="2">Casts</th>
</tr>
</thead>
<tbody>
{spent && spent
.map(ability => (
<tr>
<td style={{ width: '30%' }}>
<SpellLink id={ability.abilityId} />
</td>
<td style={{ width: 50, paddingRight: 5, textAlign: 'center' }}>
<dfn data-tip={`${formatPercentage(ability.spent / totalSpent)} %`}>{ability.spent}</dfn>
</td>
<td style={{ width: '40%' }}>
<div
className="performance-bar"
style={{ width: `${(ability.spent / totalSpent) * 100}%` }}
/>
</td>
<td style={{ width: 50, paddingRight: 5, textAlign: 'center' }}>
<dfn data-tip={`${formatPercentage(ability.casts / totalCasts)} %`}>{ability.casts}</dfn>
</td>
<td style={{ width: '30%' }}>
<div
className="performance-bar"
style={{ width: `${(ability.casts / totalCasts) * 100}%` }}
/>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}
}
export default RuneBreakdown;
| FaideWW/WoWAnalyzer | src/parser/deathknight/shared/RuneBreakdown.js | JavaScript | agpl-3.0 | 6,269 |
// Component
class Polygon {
constructor(height, width) { //class constructor
this.name = "Polygon";
this.height = height;
this.width = width;
}
sayName() {
console.log("Name:", this.name);
}
}
// Exports
module.exports = Polygon;
| kasargeant/warhorse | test/data/client_src/js/Polygon.js | JavaScript | agpl-3.0 | 282 |
define(function(require) {
'use strict';
var PIXI = require('pixi');
var PixiView = require('common/v3/pixi/view');
var ArrowView = require('common/v3/pixi/view/arrow');
var Colors = require('common/colors/colors');
//var Vector2 = require('common/math/vector2');
var defineInputUpdateLocks = require('common/locks/define-locks');
var Constants = require('constants');
var silent = { silent: true };
var BodyView = PixiView.extend({
events: {
'touchstart .body': 'dragStart',
'mousedown .body': 'dragStart',
'touchmove .body': 'drag',
'mousemove .body': 'drag',
'touchend .body': 'dragEnd',
'mouseup .body': 'dragEnd',
'touchendoutside .body': 'dragEnd',
'mouseupoutside .body': 'dragEnd',
'touchstart .velocityMarker': 'dragVelocityStart',
'mousedown .velocityMarker': 'dragVelocityStart',
'touchmove .velocityMarker': 'dragVelocity',
'mousemove .velocityMarker': 'dragVelocity',
'touchend .velocityMarker': 'dragVelocityEnd',
'mouseup .velocityMarker': 'dragVelocityEnd',
'touchendoutside .velocityMarker': 'dragVelocityEnd',
'mouseupoutside .velocityMarker': 'dragVelocityEnd'
},
initialize: function(options) {
options = _.extend({
color: '#ddd',
interactionEnabled: true
}, options);
this.color = Colors.parseHex(options.color);
this.interactionEnabled = options.interactionEnabled;
this.mvt = options.mvt;
this.arrowViewModel = new ArrowView.ArrowViewModel({
originX: 0,
originY: 0
});
this._dragOffset = new PIXI.Point();
this._dragLocation = new PIXI.Point();
this.initGraphics();
this.listenTo(this.model, 'change:x', this.updateX);
this.listenTo(this.model, 'change:y', this.updateY);
this.listenTo(this.model, 'change:mass', this.drawBody);
this.listenTo(this.model, 'change:destroyedInCollision', this.updateDestroyedState);
this.listenTo(this.model, 'change:initVX', this.updateVelocity);
this.listenTo(this.model, 'change:initVY', this.updateVelocity);
this.listenTo(this.arrowViewModel, 'change:targetX change:targetY', this.changeVelocity);
},
initGraphics: function() {
this.body = new PIXI.Graphics();
this.body.buttonMode = true;
this.body.defaultCursor = 'move';
this.arrowView = new ArrowView({
model: this.arrowViewModel,
tailWidth: BodyView.ARROW_TAIL_WIDTH,
headWidth: BodyView.ARROW_HEAD_WIDTH,
headLength: BodyView.ARROW_HEAD_LENGTH,
fillColor: BodyView.ARROW_COLOR,
fillAlpha: BodyView.ARROW_ALPHA
});
this.initVelocityMarker();
this.displayObject.addChild(this.velocityMarker);
this.displayObject.addChild(this.arrowView.displayObject);
this.displayObject.addChild(this.body);
this.updateMVT(this.mvt);
},
initVelocityMarker: function() {
this.velocityMarker = new PIXI.Container();
this.velocityMarker.hitArea = new PIXI.Circle(0, 0, BodyView.VELOCITY_MARKER_RADIUS);
this.velocityMarker.buttonMode = true;
var color = Colors.parseHex(BodyView.VELOCITY_MARKER_COLOR);
var circle = new PIXI.Graphics();
circle.lineStyle(BodyView.VELOCITY_MARKER_THICKNESS, color, BodyView.VELOCITY_MARKER_ALPHA);
circle.drawCircle(0, 0, BodyView.VELOCITY_MARKER_RADIUS);
var label = new PIXI.Text('V', {
font: BodyView.VELOCITY_MARKER_FONT,
fill: BodyView.VELOCITY_MARKER_COLOR
});
label.resolution = this.getResolution();
label.anchor.x = 0.5
label.anchor.y = 0.4;
label.alpha = BodyView.VELOCITY_MARKER_ALPHA;
this.velocityMarker.addChild(circle);
this.velocityMarker.addChild(label);
},
drawBody: function() {
var diameter = 2.5 * Math.pow(this.model.get('mass'), 1/3) + 6;
var radius = this.mvt.modelToViewDeltaX(diameter) / 2;
this.body.clear();
this.body.beginFill(this.color, 1);
this.body.drawCircle(0, 0, radius);
this.body.endFill();
},
dragStart: function(event) {
if (!this.interactionEnabled)
return;
this.dragOffset = event.data.getLocalPosition(this.displayObject, this._dragOffset);
this.dragging = true;
},
drag: function(event) {
if (this.dragging) {
var dx = event.data.global.x - this.displayObject.x - this.dragOffset.x;
var dy = event.data.global.y - this.displayObject.y - this.dragOffset.y;
this.displayObject.x += dx;
this.displayObject.y += dy;
var x = Math.round(this.mvt.viewToModelX(this.displayObject.x));
var y = Math.round(this.mvt.viewToModelY(this.displayObject.y));
this.inputLock(function() {
this.model.set('initX', x);
this.model.set('initY', y);
});
}
},
dragEnd: function(event) {
this.dragging = false;
},
dragVelocityStart: function(event) {
if (!this.interactionEnabled)
return;
this.dragOffset = event.data.getLocalPosition(this.velocityMarker, this._dragOffset);
this.draggingVelocity = true;
},
dragVelocity: function(event) {
if (this.draggingVelocity) {
var local = event.data.getLocalPosition(this.displayObject, this._dragLocation);
var x = local.x - this.dragOffset.x;
var y = local.y - this.dragOffset.y;
this.velocityMarker.x = x;
this.velocityMarker.y = y;
this.arrowViewModel.set('targetX', this.velocityMarker.x);
this.arrowViewModel.set('targetY', this.velocityMarker.y);
}
},
dragVelocityEnd: function(event) {
this.draggingVelocity = false;
},
updateVelocity: function() {
this.updateLock(function() {
var x = this.mvt.modelToViewDeltaX(this.model.get('initVX'));
var y = this.mvt.modelToViewDeltaY(this.model.get('initVY'));
this.velocityMarker.x = x;
this.velocityMarker.y = y;
// We don't want it to draw twice, so make the first silent
this.arrowViewModel.set('targetX', x);
this.arrowViewModel.set('targetY', y);
});
},
changeVelocity: function() {
this.inputLock(function() {
this.model.set('initVX', Math.round(this.mvt.viewToModelDeltaX(this.arrowViewModel.get('targetX'))));
this.model.set('initVY', Math.round(this.mvt.viewToModelDeltaY(this.arrowViewModel.get('targetY'))));
});
},
updateX: function(model, x) {
this.updateLock(function() {
this.displayObject.x = this.mvt.modelToViewX(x);
});
},
updateY: function(model, y) {
this.updateLock(function() {
this.displayObject.y = this.mvt.modelToViewY(y);
});
},
updateMVT: function(mvt) {
this.mvt = mvt;
this.drawBody();
this.updateX(this.model, this.model.get('x'));
this.updateY(this.model, this.model.get('y'));
this.updateVelocity();
},
updateDestroyedState: function(body, destroyedInCollision) {
this.displayObject.visible = !destroyedInCollision;
},
enableInteraction: function() {
this.interactionEnabled = true;
this.body.buttonMode = true;
this.velocityMarker.visible = true;
this.arrowView.show();
},
disableInteraction: function() {
this.interactionEnabled = false;
this.body.buttonMode = false;
this.velocityMarker.visible = false;
this.arrowView.hide();
}
}, Constants.BodyView);
// Add input/update locking functionality to the prototype
defineInputUpdateLocks(BodyView);
return BodyView;
}); | Connexions/simulations | my-solar-system/src/js/views/body.js | JavaScript | agpl-3.0 | 8,953 |
import Cookies from 'js-cookie';
import Project from 'models/project';
import Iteration from 'models/iteration';
describe('Project model', function() {
let story;
let project;
beforeEach(function() {
Cookies.set('current_flow', 'progress_to_left', {expires: 365});
var Story = Backbone.Model.extend({
name: 'story',
fetch: function() {},
position: function() {},
labels: function() { return []; }
});
story = new Story({id: 456});
project = new Project({
id: 999, title: 'Test project', point_values: [0, 1, 2, 3],
last_changeset_id: null, iteration_start_day: 1, iteration_length: 1,
default_flow: Cookies.get('current_flow'),
current_flow: Cookies.get('current_flow')
});
project.projectBoard.stories.add(story);
});
describe('when instantiated', function() {
it('should exhibit attributes', function() {
expect(project.get('point_values'))
.toEqual([0, 1, 2, 3]);
});
it('should set up a story collection', function() {
expect(project.projectBoard.stories).toBeDefined();
expect(project.projectBoard.stories.url).toEqual('/projects/999/stories');
// Sets up a reference on the collection to itself
expect(project.projectBoard.project).toBe(project);
});
it('should set up a user collection', function() {
expect(project.users).toBeDefined();
expect(project.users.url).toEqual('/projects/999/users');
// Sets up a reference on the collection to itself
expect(project.users.project).toBe(project);
});
it("should have a default velocity of 10", function() {
expect(project.get('default_velocity')).toEqual(10);
});
it("should have a default story flow", function() {
expect(project.get('default_flow')).toEqual('progress_to_left');
});
});
describe('url', function() {
it('should have a url', function() {
expect(project.url()).toEqual('/projects/999');
});
});
describe('changesets', function() {
it('should load changesets when last_changeset_id is changed', function() {
var server = sinon.fakeServer.create();
var spy = sinon.spy(project, 'handleChangesets');
var changesets = [{"changeset":{"id":2,"story_id":456,"project_id":789}}];
server.respondWith(
"GET", "/projects/999/changesets?from=0&to=2", [
200, {"Content-Type": "application/json"},
JSON.stringify(changesets)
]
);
expect(project.get('last_changeset_id')).toBeNull();
project.set({last_changeset_id: 2});
expect(server.requests.length).toEqual(1);
server.respond();
expect(spy).toHaveBeenCalledWith(changesets);
server.restore();
});
it("should reload changed stories from changesets", function() {
var changesets = [{"changeset":{"id":123,"story_id":456,"project_id":789}}];
var getSpy = sinon.spy(project.projectBoard.stories, 'get');
var fetchSpy = sinon.spy(story, 'fetch');
project.handleChangesets(changesets);
expect(getSpy).toHaveBeenCalledWith(456);
expect(fetchSpy).toHaveBeenCalled();
});
it("should load new stories from changesets", function() {
var story_json = {"story":{"id":987,"title":"New changeset story"}};
var server = sinon.fakeServer.create();
server.respondWith(
"GET", "/projects/999/stories/987", [
200, {"Content-Type": "application/json"},
JSON.stringify(story_json)
]
);
var changesets = [{"changeset":{"id":123,"story_id":987,"project_id":789}}];
var getSpy = sinon.spy(project.projectBoard.stories, 'get');
var addSpy = sinon.spy(project.projectBoard.stories, 'add');
var initial_collection_length = project.projectBoard.stories.length;
project.handleChangesets(changesets);
expect(server.requests.length).toEqual(1);
server.respond();
expect(getSpy).toHaveBeenCalled();
expect(addSpy).toHaveBeenCalled();
expect(project.projectBoard.stories.length).toEqual(initial_collection_length + 1);
expect(project.projectBoard.stories.get(987).get('title')).toEqual("New changeset story");
server.restore();
});
it("should only reload a story once if present in multiple changesets", function() {
var story_json = {"story":{"id":987,"title":"New changeset story"}};
var server = sinon.fakeServer.create();
server.respondWith(
"GET", "/projects/999/stories/987", [
200, {"Content-Type": "application/json"},
JSON.stringify(story_json)
]
);
// set of changes represents the same story modified twice. It
// should only be loaded once.
var changesets = [
{"changeset":{"id":1,"story_id":987,"project_id":789}},
{"changeset":{"id":2,"story_id":987,"project_id":789}}
];
project.handleChangesets(changesets);
expect(server.requests.length).toEqual(1);
});
});
describe("iterations", function() {
it("should get the right iteration number for a given date", function() {
// is a Monday
project.set({start_date: "2011/07/25"});
var compare_date = new Date("2011/07/25");
expect(project.getIterationNumberForDate(compare_date)).toEqual(1);
compare_date = new Date("2011/08/01");
expect(project.getIterationNumberForDate(compare_date)).toEqual(2);
// With a 2 week iteration length, the date above will still be in
// iteration 1
project.set({iteration_length: 2});
expect(project.getIterationNumberForDate(compare_date)).toEqual(1);
});
it("should return the current iteration number", function() {
expect(project.currentIterationNumber()).toEqual(1);
});
it("should return the date for an iteration number", function() {
// is a Monday
project.set({start_date: "2011/07/25"});
expect(project.getDateForIterationNumber(1)).toEqual(new Date("2011/07/25"));
expect(project.getDateForIterationNumber(5)).toEqual(new Date("2011/08/22"));
project.set({iteration_length: 4});
expect(project.getDateForIterationNumber(1)).toEqual(new Date("2011/07/25"));
expect(project.getDateForIterationNumber(5)).toEqual(new Date("2011/11/14"));
// Sunday
project.set({iteration_start_day: 0});
expect(project.getDateForIterationNumber(1)).toEqual(new Date("2011/07/24"));
expect(project.getDateForIterationNumber(5)).toEqual(new Date("2011/11/13"));
// Tuesday - should evaluate to the Tuesday before the explicitly
// set start date (Monday)
project.set({iteration_start_day: 2});
expect(project.getDateForIterationNumber(1)).toEqual(new Date("2011/07/19"));
expect(project.getDateForIterationNumber(5)).toEqual(new Date("2011/11/08"));
});
it("should initialize with an array of iterations", function() {
expect(project.iterations).toEqual([]);
});
it("should get all the done iterations", function() {
var doneIteration = {
get: sinon.stub().withArgs('column').returns('#done')
};
var inProgressIteration = {
get: sinon.stub().withArgs('column').returns('#in_progress')
};
var backlogIteration = {
get: sinon.stub().withArgs('column').returns('#backlog')
};
var chillyBinIteration = {
get: sinon.stub().withArgs('column').returns('#chilly_bin')
};
project.iterations = [
doneIteration, inProgressIteration, backlogIteration, chillyBinIteration
];
expect(project.doneIterations()).toEqual([doneIteration]);
});
});
describe("start date", function() {
it("should return the start date", function() {
// Date is a Monday, and day 1 is Monday
project.set({start_date: "2011/09/12",iteration_start_day: 1});
expect(project.startDate()).toEqual(new Date("2011/09/12"));
// If the project start date has been explicitly set to a Thursday, but
// the iteration_start_day is Monday, the start date should be the Monday
// that immeadiatly preceeds the Thursday.
project.set({start_date: "2011/07/28"});
expect(project.startDate()).toEqual(new Date("2011/07/25"));
// The same, but time the iteration start day is 'after' the start
// date day, in ordinal terms, e.g. iteration start date is a Saturday,
// project start date is a Thursday. The Saturday prior to the Thursday
// should be returned.
project.set({iteration_start_day: 6});
expect(project.startDate()).toEqual(new Date("2011/07/23"));
// If the project start date is not set, it should be considered as the
// first iteration start day prior to today.
// FIXME - Stubbing Date is not working
var expected_date = new Date('2011/07/23');
var fake_today = new Date('2011/07/29');
// Stop JSHINT complaining about overriding Date
/*global Date: true*/
project.today = sinon.stub().returns(fake_today);
project.unset('start_date');
expect(project.startDate()).toEqual(expected_date);
});
});
describe("velocity", function() {
it("returns the default velocity when done iterations are empty", function() {
project.set({'default_velocity': 999});
expect(project.velocity()).toEqual(999);
});
it("should return velocity", function() {
var doneIterations = _.map([1,2,3,4,5], function(i) {
return {points: sinon.stub().returns(i)};
});
var doneIterationsStub = sinon.stub(project, 'doneIterations');
doneIterationsStub.returns(doneIterations);
// By default, should take the average of the last 3 iterations,
// (3 + 4 + 5) = 12 / 3 = 4
expect(project.velocity()).toEqual(4);
});
it("should ignore zero points done iterations while calculating velocity", function() {
var doneIterations = _.map([1,2,0,4,5], function(i) {
return {points: sinon.stub().returns(i)};
});
var doneIterationsStub = sinon.stub(project, 'doneIterations');
doneIterationsStub.returns(doneIterations);
// By default, should take the average of the last 3 iterations,
// (2 + 4 + 5) = 11 / 3 = 5
expect(project.velocity()).toEqual(3);
});
it("should floor the velocity when it returns a fraction", function() {
var doneIterations = _.map([3,2,2], function(i) {
return {points: sinon.stub().returns(i)};
});
var doneIterationsStub = sinon.stub(project, 'doneIterations');
doneIterationsStub.returns(doneIterations);
// Should floor the result
// (3 + 2 + 2) = 7 / 3 = 2.333333
expect(project.velocity()).toEqual(2);
});
it("should return the velocity when few iterations are complete", function() {
// Still calculate the average correctly if fewer than the expected
// number of iterations have been completed.
var doneIterations = _.map([3,1], function(i) {
return {points: sinon.stub().returns(i)};
});
var doneIterationsStub = sinon.stub(project, 'doneIterations');
doneIterationsStub.returns(doneIterations);
expect(project.velocity()).toEqual(2);
});
it("should not return less than 1", function() {
var doneIterations = _.map([0,0,0], function(i) {
return {points: sinon.stub().returns(i)};
});
var doneIterationsStub = sinon.stub(project, 'doneIterations');
doneIterationsStub.returns(doneIterations);
expect(project.velocity()).toEqual(1);
});
describe("when velocity is not set", function() {
describe("velocityIsFake", function() {
it("should be false", function() {
expect(project.velocityIsFake()).toBeFalsy();
});
});
it("returns the default velocity", function() {
project.set({'default_velocity': 99});
expect(project.velocity()).toEqual(99);
});
});
describe("when velocity is set to 20", function() {
beforeEach(function() {
project.velocity(20);
});
describe("velocityIsFake", function() {
it("should be true", function() {
expect(project.velocityIsFake()).toBeTruthy();
});
});
it("returns 20", function() {
expect(project.velocity()).toEqual(20);
});
});
describe("when velocity is set to less than 1", function() {
beforeEach(function() {
project.velocity(0);
});
it("sets the velocity to 1", function() {
expect(project.velocity()).toEqual(1);
});
});
describe("when velocity is set to the same as the real value", function() {
describe("velocity", function() {
beforeEach(function() {
project.set({'userVelocity': 20, velocityIsFake: true});
project.calculateVelocity = function() { return 20; };
project.velocity(20);
});
it("should unset userVelocity", function() {
expect(project.get('userVelocity')).toBeUndefined();
});
it("should be false", function() {
expect(project.velocityIsFake()).toBeFalsy();
});
});
});
describe("revertVelocity", function() {
beforeEach(function() {
project.set({userVelocity: 999, velocityIsFake: true});
});
it("unsets userVelocity", function() {
project.revertVelocity();
expect(project.get('userVelocity')).toBeUndefined();
});
it("sets velocityIsFake to false", function() {
project.revertVelocity();
expect(project.velocityIsFake()).toBeFalsy();
});
});
});
describe("appendIteration", function() {
let iteration;
beforeEach(function() {
iteration = {
get: sinon.stub()
};
});
it("should add the first iteration to the array", function() {
var stub = sinon.stub(Iteration, 'createMissingIterations');
stub.returns([]);
project.appendIteration(iteration);
expect(_.last(project.iterations)).toEqual(iteration);
expect(project.iterations.length).toEqual(1);
stub.restore();
});
it("should create missing iterations if required", function() {
var spy = sinon.spy(Iteration, 'createMissingIterations');
iteration.get.withArgs('number').returns(1);
project.iterations.push(iteration);
var currentIteration = {
get: sinon.stub().withArgs('number').returns(5)
};
project.appendIteration(currentIteration, '#done');
expect(spy).toHaveBeenCalledWith('#done', iteration, currentIteration);
expect(project.iterations.length).toEqual(5);
spy.restore();
});
});
describe("columns", function() {
it("should define the columns", function() {
expect(project.columnIds).toEqual([
'#done', '#in_progress', '#backlog', '#chilly_bin', '#search_results', '#epic'
]);
});
it("should return the columns after a given column", function() {
expect(project.columnsAfter('#done')).toEqual([
'#in_progress', '#backlog', '#chilly_bin', '#search_results', '#epic'
]);
expect(project.columnsAfter('#in_progress')).toEqual([
'#backlog', '#chilly_bin', '#search_results', '#epic'
]);
expect(project.columnsAfter('#backlog')).toEqual(['#chilly_bin', '#search_results', '#epic']);
expect(project.columnsAfter('#chilly_bin')).toEqual(['#search_results', '#epic']);
var currentProject = project;
expect(function() {currentProject.columnsAfter('#foobar');}).toThrow(
"#foobar is not a valid column"
);
});
it("should return the columns before a given column", function() {
expect(project.columnsBefore('#done')).toEqual([]);
expect(project.columnsBefore('#in_progress')).toEqual(['#done']);
expect(project.columnsBefore('#backlog')).toEqual([
'#done', '#in_progress'
]);
expect(project.columnsBefore('#chilly_bin')).toEqual([
'#done', '#in_progress', '#backlog'
]);
expect(project.columnsBefore('#search_results')).toEqual([
'#done', '#in_progress', '#backlog', '#chilly_bin'
]);
expect(project.columnsBefore('#epic')).toEqual([
'#done', '#in_progress', '#backlog', '#chilly_bin', '#search_results'
]);
let currentProject = project;
expect(function() {currentProject.columnsBefore('#foobar');}).toThrow(
"#foobar is not a valid column"
);
});
});
describe("rebuildIterations", function() {
beforeEach(function() {
project.projectBoard.stories.invoke = sinon.stub();
});
it("triggers a rebuilt-iterations event", function() {
var stub = sinon.stub();
project.on('rebuilt-iterations', stub);
project.rebuildIterations();
expect(stub).toHaveBeenCalled();
});
});
describe("toggleStoryFlow", function() {
it("should be able to toggle current_flow value", function() {
project.toggleStoryFlow();
expect(project.get('current_flow')).toBe('progress_to_right');
project.toggleStoryFlow();
expect(project.get('current_flow')).toBe('progress_to_left');
});
it("should be able to save the current story flow on cookies", function() {
project.toggleStoryFlow();
expect(Cookies.get('current_flow')).toBe('progress_to_right');
});
});
});
| Codeminer42/cm42-central | spec/javascripts/models/project_spec.js | JavaScript | agpl-3.0 | 17,485 |
/**
* ownCloud - breakout
*
* This file is licensed under the Affero General Public License version 3 or
* later. See the COPYING file.
*
* @author Volkan Gezer <volkangezer@gmail.com>
* @copyright Volkan Gezer 2014
*/
Game.ready(function() {
var game = Game.start('canvas', Breakout);
});
| vgezer/breakout | js/start.js | JavaScript | agpl-3.0 | 301 |
/*
* post.js
* Copyright (c) 2022 james@firefly-iii.org
*
* This file is part of Firefly III (https://github.com/firefly-iii).
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {api} from "boot/axios";
export default class Post {
post(submission) {
let url = '/api/v1/currencies';
return api.post(url, submission);
}
makeDefault(currency) {
let url = '/api/v1/currencies/' + currency + '/default';
return api.post(url);
}
}
| firefly-iii/firefly-iii | frontend/src/api/currencies/post.js | JavaScript | agpl-3.0 | 1,086 |
'use strict';
exports.up = function(knex, Promise) {
return knex.schema.table('devices', function(table) {
table.string('platform')
})
}
exports.down = function(knex, Promise) {
return knex.schema.table('devices', function(table) {
table.dropColumn('platform')
})
}
| Connoropolous/hylo-node | migrations/20150827153725_add_platform_to_device.js | JavaScript | agpl-3.0 | 284 |
jasmine.DEFAULT_TIMEOUT_INTERVAL = 25000; // sometimes a little slow, esp. on startup
if (typeof client != "undefined") {
throw "I thought require() took care of this?";
}
module.exports.client = client = null;
var latestWebdriverRequestDone = false;
var waitsForDone = function waitsForDone() {
waitsFor(function() {
var maybeTrue = latestWebdriverRequestDone;
latestWebdriverRequestDone = false;
return maybeTrue;
});
};
module.exports.waitsForDone = waitsForDone;
var sayDone = function sayDone() {
latestWebdriverRequestDone = true;
};
module.exports.sayDone = sayDone;
var runsAndWaits = function runsAndWaits(functionToRun) {
runs(function() {
latestWebdriverRequestDone = false;
functionToRun();
});
waitsForDone();
};
module.exports.runsAndWaits = runsAndWaits;
var exec = require('child_process').exec;
describe('system initialization', function() {
beforeAll(function() {
var webdriverjs = require("webdriverjs");
module.exports.client = client = webdriverjs.remote({logLevel: 'silent'});
client.init();
});
afterAll(function() {
client.end();
});
it("ensure beforeAll/afterAll runs", function() {});
});
| gleneivey/pairmatic2 | integration/client/seHelper.js | JavaScript | agpl-3.0 | 1,186 |
import Asset from 'hippo/models/asset';
import { pick, uniqBy, filter, isEmpty, find } from 'lodash';
import moment from 'moment';
import DateRange from 'hippo/lib/date-range';
import Config from 'hippo/config';
import { renameProperties } from 'hippo/lib/util';
import Page from 'hippo/models/page';
import {
BaseModel, identifiedBy, identifier, field, belongsTo, computed, hasMany,
} from './base';
import ShowTime from './show-time';
const formatTime = occurs => moment(occurs.occurs_at).format('h:mma');
@identifiedBy('sm/show')
export default class Show extends Page.hasPageMixin(BaseModel) {
static get embedURL() {
return `${Config.api_path}/sm/embed/shows`;
}
static fetchEmbedded(embedId) {
return this.Collection
.create()
.fetch({ url: `${this.embedURL}/${embedId}` });
}
static fetchPublicShow(id) {
const show = new Show({ idenfier: id });
return show.fetch({
url: this.embedURL,
query: { show_identifier: id },
});
}
@identifier id;
@field identifier = '';
@field title = '';
@field sub_title = '';
@field description = '';
@field venue_id;
@field message_id;
@field ticket_instructions;
@field presenter_id;
@field price;
@field capacity;
@field external_url;
@field can_purchase = false;
@field online_sales_halt_mins_before;
@field({ model: DateRange }) visible_during = new DateRange({
start: moment().startOf('day').toDate(),
end: moment().add(1, 'week').endOf('day').toDate(),
});
@belongsTo({ model: 'sm/venue' }) venue;
@belongsTo({ model: 'sm/presenter' }) presenter;
@belongsTo({ model: Page, inverseOf: 'owner' }) page;
@belongsTo({ model: Asset, inverseOf: 'owner' }) image;
@hasMany({ model: ShowTime, inverseOf: 'show' }) times;
set(attrs = {}) {
renameProperties(attrs, {
image_details: 'image',
venue_details: 'venue',
});
return super.set(attrs);
}
@computed get image_details() {
return this.image ? pick(this.image, 'id', 'file_data') : {};
}
@computed get hasPage() {
return !isEmpty(this.page);
}
@computed get futureTimes() {
return filter(this.times, o => o.isFuture);
}
@computed get commonTime() {
if (this.times.length < 2) { return null; }
const times = uniqBy(this.times, formatTime);
return 1 === times.length ? formatTime(times[0]) : null;
}
@computed get onlinePurchasableTimes() {
return filter(this.times, { canPurchaseOnline: true });
}
@computed get canPurchaseOnline() {
return Boolean(this.can_purchase && find(this.times, { canPurchaseOnline: true }));
}
}
| argosity/sm | client/sm/models/show.js | JavaScript | agpl-3.0 | 2,826 |
window.onload = dtableInit;
/* initialise le script */
function dtableInit() {
var table = document.getElementsByTagName('TABLE');
for ( var i = 0; i < table.length; i++ ) {
// on récupère tous les tableaux dynamiques
if ( table[i].className == 'dTable' ) {
var tbody = table[i].tBodies[0];
var newTr = tbody.rows[0].cloneNode(true);
// on masque la première ligne du tbody (la ligne de reference)
tbody.rows[0].style.display = 'none';
// on en ajoute une
tbody.appendChild(newTr);
}
}
}
/* trouve le tag "parentTagName" parent de "element" */
function getParent(element, parentTagName) {
if ( ! element )
return null;
else if ( element.nodeType == 1 && element.tagName.toLowerCase() == parentTagName.toLowerCase() )
return element;
else
return getParent(element.parentNode, parentTagName);
}
/* ajoute une ligne */
function addLigne(link) {
// 1. récuperer le node "TABLE" à manipuler
var td = link.parentNode;
var table = getParent(td,'TABLE');
// 2. on va manipuler le TBODY
var tbody = table.tBodies[0];
// 3. on clone la ligne de reference
var newTr = tbody.rows[0].cloneNode(true);
tbody.appendChild(newTr);
if ( document.all )
newTr.style.display = "block"; // pour IE
else
newTr.style.display = "table-row"; // pour Gecko
}
/* supprimer une ligne */
function delLigne(link) {
// 1. récuperer le node "TABLE" à manipuler
var td = link.parentNode;
var table = getParent(td, 'TABLE');
// 2. récuperer le TBODY
var tbody = table.tBodies[0];
// 3. Supprimer le TR
tbody.removeChild(getParent(td, 'TR'));
}
| guillaumemarion/Comptes-Boquette | JS/dtable.js | JavaScript | agpl-3.0 | 1,580 |
/*
* sweave.js
*
* Copyright (C) 2009-12 by RStudio, Inc.
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Unless you have received this program directly from RStudio pursuant
* to the terms of a commercial license agreement with RStudio, then
* this program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
define("mode/sweave", function(require, exports, module) {
var oop = require("ace/lib/oop");
var TextMode = require("ace/mode/text").Mode;
var Tokenizer = require("ace/tokenizer").Tokenizer;
var TextHighlightRules = require("ace/mode/text_highlight_rules").TextHighlightRules;
var SweaveBackgroundHighlighter = require("mode/sweave_background_highlighter").SweaveBackgroundHighlighter;
var SweaveHighlightRules = require("mode/sweave_highlight_rules").SweaveHighlightRules;
var RCodeModel = require("mode/r_code_model").RCodeModel;
var RMatchingBraceOutdent = require("mode/r_matching_brace_outdent").RMatchingBraceOutdent;
var unicode = require("ace/unicode");
var Utils = require("mode/utils");
var Mode = function(suppressHighlighting, session) {
if (suppressHighlighting)
this.$tokenizer = new Tokenizer(new TextHighlightRules().getRules());
else
this.$tokenizer = new Tokenizer(new SweaveHighlightRules().getRules());
this.codeModel = new RCodeModel(session, this.$tokenizer, /^r-/, /<<(.*?)>>/);
this.foldingRules = this.codeModel;
this.$sweaveBackgroundHighlighter = new SweaveBackgroundHighlighter(
session,
/^\s*\<\<.*\>\>=.*$/,
/^\s*@(?:\s.*)?$/,
false);
this.$session = session;
};
oop.inherits(Mode, TextMode);
(function() {
oop.implement(this, RMatchingBraceOutdent);
this.tokenRe = new RegExp("^["
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "_]+", "g"
);
this.nonTokenRe = new RegExp("^(?:[^"
+ unicode.packages.L
+ unicode.packages.Mn + unicode.packages.Mc
+ unicode.packages.Nd
+ unicode.packages.Pc + "_]|\s])+", "g"
);
this.$complements = {
"(": ")",
"[": "]",
'"': '"',
"'": "'",
"{": "}"
};
this.$reOpen = /^[(["'{]$/;
this.$reClose = /^[)\]"'}]$/;
this.insertChunkInfo = {
value: "<<>>=\n\n@\n",
position: {row: 0, column: 2}
};
this.getLanguageMode = function(position)
{
var state = Utils.getPrimaryState(this.$session, position.row);
return state.match(/^r-/) ? 'R' : 'TeX';
};
this.getNextLineIndent = function(state, line, tab)
{
state = Utils.primaryState(state);
return this.codeModel.getNextLineIndent(state, line, tab);
};
this.allowAutoInsert = this.smartAllowAutoInsert;
}).call(Mode.prototype);
exports.Mode = Mode;
});
| maligulzar/Rstudio-instrumented | src/gwt/acesupport/acemode/sweave.js | JavaScript | agpl-3.0 | 3,272 |
const routes = [
require('../features/status'),
require('../features/events')
];
module.exports = routes; | Hypernikao/who-brings-what | server/app/infrastructure/routes.js | JavaScript | agpl-3.0 | 109 |
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import { fetchFavourites } from '../../actions/interactions';
import { ScrollContainer } from 'react-router-scroll-4';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import ColumnBackButton from '../../components/column_back_button';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'favourited_by', props.params.statusId]),
});
@connect(mapStateToProps)
export default class Favourites extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
accountIds: ImmutablePropTypes.list,
};
componentWillMount () {
this.props.dispatch(fetchFavourites(this.props.params.statusId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this.props.dispatch(fetchFavourites(nextProps.params.statusId));
}
}
render () {
const { shouldUpdateScroll, accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='favourites' shouldUpdateScroll={shouldUpdateScroll}>
<div className='scrollable'>
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
</div>
</ScrollContainer>
</Column>
);
}
}
| unarist/mastodon | app/javascript/mastodon/features/favourites/index.js | JavaScript | agpl-3.0 | 1,883 |
var _ = require('lodash');
var $ = require('jquery');
// Signup and login page module.
module.exports = function(utils) {
// Internal validation cache.
var cache = {names: {}};
// Name-checking function that queries the server to see if a name is valid.
// This function is cached and rate-limited.
var checkName = _.debounce(function(name, callback) {
if (cache.names[name]) {
callback(cache.names[name]);
} else {
$.post('/api/validate/user', {name: name}, function(data) {
if (!_.isObject(data)) data = {reason: 'Server error.'};
callback(cache.names[name] = data);
});
}
}, 500);
// When user clicks question icon, focus on the field below it.
$('.field.explain + .question-icon').click(function() {
$(this).prevAll(".field.explain").focus();
});
// Copy the password from the password field to the confirmation field's pattern.
// It's wonderful the kinds of things browsers can do now :)
$('#signup .field[name=password]').on('keyup change', function() {
var escaped = utils.regExpEscape($(this).val());
var confirmation = $('.field[name=passwordConfirmation]');
confirmation.attr('pattern', escaped);
// We also now need to set the confirmation box's validation status.
if (escaped === '') {
var icon = 'asterisk'
} else {
var icon = confirmation.is(':valid') ? 'tick' : 'cross';
}
confirmation.siblings('.validation').children('.icon').attr('class', 'icon ' + icon);
});
// When email field changes in the signup page, show validity in the icon.
$('#signup .field[type=email], #signup .field[type=password]').on('keyup change', function() {
var elem = $(this);
if (elem.val() === '') {
var icon = 'asterisk'
} else {
var icon = elem.is(':valid') ? 'tick' : 'cross';
}
elem.siblings('.validation').children('.icon').attr('class', 'icon ' + icon);
});
// Verify name availability on signup.
$('#signup .field[name=username]').on('keyup change', function() {
var elem = $(this);
var value = elem.val();
if (value === '') {
var icon = 'asterisk';
} else {
if (elem.is(':valid')) {
// If the cache contains an answer, use that.
if (cache.names[value]) {
var icon = cache.names[value].valid ? 'tick' : 'cross';
} else {
// We'll have to check the database.
var icon = 'loading';
}
} else {
var icon = 'cross';
}
}
// If the field is blank, we'll leave an asterisk.
// If it's invalid, we'll leave a cross.
// If it's valid, we'll leave a loading icon, and check on the server after.
var validationIcon = elem.siblings('.validation').children('.icon');
validationIcon.attr('class', 'icon ' + icon);
// Now, if the the field wasn't blank, was valid, and not cached, we should check it.
if (icon === 'loading') {
// The name is only checked after half a second since the user stopped typing.
checkName(value, function(data) {
// Only change anything if the value hasn't been changed since last time.
if (elem.val() === value) {
icon = data.valid ? 'tick' : 'cross';
validationIcon.attr('class', 'icon ' + icon);
}
});
}
});
}
| CamiloMM/works-list | scripting/src/signup-and-login.js | JavaScript | agpl-3.0 | 3,682 |
OC.L10N.register(
"federation",
{
"Server added to the list of trusted ownClouds" : "Server wurde in die Liste der vertrauenswürdigen ownClouds aufgenommen",
"Server is already in the list of trusted servers." : "Server ist bereits in der Liste der vertrauenswürdigen Servern.",
"No ownCloud server found" : "Es wurde kein ownCloud Server gefunden",
"Could not add server" : "Konnte Server nicht hinzufügen",
"Federation" : "Federation",
"ownCloud Federation allows you to connect with other trusted ownClouds to exchange the user directory. For example this will be used to auto-complete external users for federated sharing." : "ownCloud Federation ermöglicht es Ihnen sich mit anderen vertrauenswürdigen Servern zu verbinden um das Benutzerverzeichnis auszutauschen. Dies wird, zum Beispiel, für die automatische Vervollständigung externer Benutzer verwendet."
},
"nplurals=2; plural=(n != 1);");
| sakukode/owncloud-custom | apps/federation/l10n/de_DE.js | JavaScript | agpl-3.0 | 939 |
me.controller('tradeFinderCtrl', [
'$scope',
function ($scope) {
"use strict";
}
]); | uplink42/etmv2 | marketexplorer/index/application/home/trade-finder-ctrl.js | JavaScript | agpl-3.0 | 110 |
require(["utils"],
function(utils) {
function loginCallback(data) {
if (data.result === "ok") {
$("#events #server-answer").empty();
$("#server-answer").text("Авторизация прошла успешно.").css("color", "green");
$("#logout-btn, #cabinet-btn").css("visibility", "visible");
$("#password, #username").val("");
} else if (data.result === "invalidCredentials") {
$("#server-answer").text("Неверный логин.").css("color", "red");
} else if (data.result === "badPassword") {
$("#server-answer").text("Неверный пароль.").css("color", "red");
} else if (data.result === "notEnabled") {
$("#server-answer").text("Ваш аккаунт заблокирован.").css("color", "red");
}
};
function logoutCallback(data) {
if (data.result === "ok") {
$("#server-answer").text("Вы вышли.").css("color", "green").css("visibility", "visible");
console.log("Вы вышли.");
location.href = "/"
} else if (data.result === "badSid") {
$("#server-answer").text("Invalid session ID.").css("color", "red");
}
};
$("#login-btn").click(function() {
var data = {};
data["login"] = $("#content #username").val();
data["password"] = $("#content #password").val();
utils.postRequest(data, loginCallback, "/registrationcontroller/login");
});
$("#logout-btn").click(function() {
utils.postRequest(null, logoutCallback, "/registrationcontroller/logout");
});
});
| klenin/orc | static/js/main.js | JavaScript | agpl-3.0 | 1,675 |
const path = require('path')
const fs = require('fs')
const Sequelize = require('sequelize')
const Umzug = require('umzug')
const _ = require('lodash')
const { upgradeInitializer } = require('../utils/upgrade')
const views = require('../migrations/views')
const Op = Sequelize.Op
const operatorsAliases = {
$eq: Op.eq,
$ne: Op.ne,
$gte: Op.gte,
$gt: Op.gt,
$lte: Op.lte,
$lt: Op.lt,
$not: Op.not,
$in: Op.in,
$notIn: Op.notIn,
$is: Op.is,
$like: Op.like,
$notLike: Op.notLike,
$ilike: Op.iLike,
$notILike: Op.notILike,
$regexp: Op.regexp,
$notRegexp: Op.notRegexp,
$iRegexp: Op.iRegexp,
$notIRegexp: Op.notIRegexp,
$between: Op.between,
$notBetween: Op.notBetween,
$overlap: Op.overlap,
$contains: Op.contains,
$contained: Op.contained,
$adjacent: Op.adjacent,
$strictLeft: Op.strictLeft,
$strictRight: Op.strictRight,
$noExtendRight: Op.noExtendRight,
$noExtendLeft: Op.noExtendLeft,
$and: Op.and,
$or: Op.or,
$any: Op.any,
$all: Op.all,
$values: Op.values,
$col: Op.col
}
module.exports = upgradeInitializer('ah17', {
name: 'sequelize',
loadPriority: 310,
initialize: function (api, next) {
api.models = {}
let createDb
let dropDb
if (api.config.sequelize.testing) {
api.config.sequelize.database = `${api.config.sequelize.database}_${process.pid}`
const { Client } = require('pg')
const client = new Client({
host: api.config.sequelize.host,
port: api.config.sequelize.port,
user: api.config.sequelize.username,
password: api.config.sequelize.password,
database: 'postgres'
})
createDb = async () => {
api.log(`connecting to ${api.config.sequelize.database}`, 'debug')
await client.connect()
const res = await client.query('CREATE DATABASE ' + api.config.sequelize.database)
api.log('created db', 'debug', res)
}
dropDb = async () => {
const res = await client.query('DROP DATABASE ' + api.config.sequelize.database)
api.log('dropped db', 'debug', res)
await client.end()
}
}
const sequelizeInstance = new Sequelize(
api.config.sequelize.database,
api.config.sequelize.username,
api.config.sequelize.password,
{
...api.config.sequelize,
operatorsAliases,
hooks: {
afterDefine (model) {
if (model.options.classMethods) {
Object.assign(model, model.options.classMethods)
delete model.options.classMethods
}
if (model.options.instanceMethods) {
Object.assign(model.prototype, model.options.instanceMethods)
delete model.options.instanceMethods
}
}
}
}
)
const migrationParams = [sequelizeInstance.getQueryInterface(), sequelizeInstance.constructor, function () {
throw new Error('Migration tried to use old style "done" callback. Please upgrade to "umzug" and return a promise instead.')
}]
const umzug = new Umzug({
storage: 'sequelize',
storageOptions: {
sequelize: sequelizeInstance
},
logging: (msg, ...params) => api.log(msg, 'info', ...params),
migrations: {
params: migrationParams,
path: api.projectRoot + '/migrations'
}
})
api.sequelize = {
createDb,
dropDb,
sequelize: sequelizeInstance,
umzug: umzug,
connect: function (next) {
const dir = path.normalize(api.projectRoot + '/models')
fs.readdirSync(dir).forEach(function (file) {
const filename = path.join(dir, file)
const nameParts = file.split('/')
const name = nameParts[(nameParts.length - 1)].split('.')[0]
api.models[name] = api.sequelize.sequelize.import(filename)
api.watchFileAndAct(filename, () => {
api.log('rebooting due to model change: ' + name, 'info')
delete require.cache[require.resolve(filename)]
api.commands.restart()
})
})
_.forEach(api.models, function (model, name) {
if (model.associate) { model.associate(api.models) }
})
api.sequelize.test(next)
},
loadFixtures: function (next) {
if (api.config.sequelize.loadFixtures) {
const SequelizeFixtures = require('sequelize-fixtures')
SequelizeFixtures.loadFile(api.projectRoot + '/test/fixtures/*.{json,yml,js}', api.models, { log: m => api.log(m, 'notice') })
.then(function () {
next()
})
.catch(function (err) {
console.error('Error loading fixtures', err)
next(err)
})
} else {
next()
}
},
autoMigrate: async function (next) {
try {
// auto migrate is true by default
if (api.config.sequelize.autoMigrate != null && !api.config.sequelize.autoMigrate) return
// check and migrate old schema
await checkMetaOldSchema(api)
await this.migrate()
} catch (err) {
const n = next
// prevent finally from calling next again
next = () => {}
n(err)
} finally {
next()
}
},
migrate: async function ({ forceViewsRecreate = false } = {}) {
// check if migrations are pending
const pending = await umzug.pending()
if (forceViewsRecreate || pending?.length) {
// remove views
await views.down(...migrationParams)
}
if (pending?.length) {
// apply migrations
await umzug.up()
api.log(`Applied ${pending.length} migrations`, 'info')
} else {
api.log('All migrations applied', 'info')
}
if (forceViewsRecreate || pending?.length) {
// create views if removed
await views.up(...migrationParams)
}
},
// api.sequelize.test([exitOnError=true], next);
// Checks to see if mysql can be reached by selecting the current time
// Arguments:
// - next (callback function(err)): Will be called after the test is complete
// If the test fails, the `err` argument will contain the error
test: function (next) {
api.sequelize.sequelize.query('SELECT 1').then(function () {
next()
}).catch(function (err) {
api.log(err, 'warning')
next(err)
})
}
}
next()
},
startPriority: 101, // aligned with actionhero's redis initializer
start: function (api, next) {
api.log('Starting sequelize...', 'info')
Promise.resolve()
.then(() => {
if (!api.config.sequelize.testing) return
api.log('Creating database...', 'debug')
return api.sequelize.createDb()
.then(() => api.log('Creating database... done', 'debug'))
})
.then(() => new Promise((resolve, reject) => api.sequelize.connect((err) => err ? reject(err) : resolve())))
.then(() => new Promise((resolve, reject) => { api.sequelize.autoMigrate((err) => err ? reject(err) : resolve()) }))
.then(() => new Promise((resolve, reject) => { api.sequelize.loadFixtures((err) => err ? reject(err) : resolve()) }))
.then(() => api.log(`Connected to ${api.config.sequelize.dialect}://${api.config.sequelize.host}:${api.config.sequelize.port}/${api.config.sequelize.database}`, 'info'))
.then(() => next(), (err) => {
console.error(err)
next(err)
})
},
stopPriority: 99999, // aligned with actionhero's redis initializer
stop: function (api, next) {
Promise.resolve()
.then(() => api.sequelize.sequelize.close())
.then(() => {
if (!api.config.sequelize.testing) return
return api.sequelize.dropDb()
})
.then(() => next(), (err) => {
console.error(err)
next(err)
})
}
})
function checkMetaOldSchema (api) {
// Check if we need to upgrade from the old sequelize migration format
return api.sequelize.sequelize.query('SELECT * FROM "SequelizeMeta"', { raw: true }).then(function (raw) {
const rows = raw[0]
if (rows.length && Object.hasOwnProperty.call(rows[0], 'id')) {
throw new Error('Old-style meta-migration table detected - please use `sequelize-cli`\'s `db:migrate:old_schema` to migrate.')
}
}).catch(Sequelize.DatabaseError, function () {
const noTableMsg = 'No SequelizeMeta table found - creating new table'
api.log(noTableMsg)
})
}
| BspbOrg/smartbirds-server | server/initializers/sequelize.js | JavaScript | agpl-3.0 | 8,604 |
/*
*
* (c) Copyright Ascensio System SIA 2010-2019
*
* This program is a free software product. You can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License (AGPL)
* version 3 as published by the Free Software Foundation. In accordance with
* Section 7(a) of the GNU AGPL its Section 15 shall be amended to the effect
* that Ascensio System SIA expressly excludes the warranty of non-infringement
* of any third-party rights.
*
* This program is distributed WITHOUT ANY WARRANTY; without even the implied
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. For
* details, see the GNU AGPL at: http://www.gnu.org/licenses/agpl-3.0.html
*
* You can contact Ascensio System SIA at 20A-12 Ernesta Birznieka-Upisha
* street, Riga, Latvia, EU, LV-1050.
*
* The interactive user interfaces in modified source and object code versions
* of the Program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU AGPL version 3.
*
* Pursuant to Section 7(b) of the License you must retain the original Product
* logo when distributing the program. Pursuant to Section 7(e) we decline to
* grant you any rights under trademark law for use of our trademarks.
*
* All the Product's GUI elements, including illustrations and icon sets, as
* well as technical writing content are licensed under the terms of the
* Creative Commons Attribution-ShareAlike 4.0 International. See the License
* terms at http://creativecommons.org/licenses/by-sa/4.0/legalcode
*
*/
/**
* LeftMenu.js
*
* Created by Maxim Kadushkin on 13 February 2014
* Copyright (c) 2018 Ascensio System SIA. All rights reserved.
*
*/
define([
'text!documenteditor/main/app/template/LeftMenu.template',
'jquery',
'underscore',
'backbone',
'common/main/lib/component/Button',
'common/main/lib/view/About',
/** coauthoring begin **/
'common/main/lib/view/Comments',
'common/main/lib/view/Chat',
/** coauthoring end **/
'common/main/lib/view/History',
'common/main/lib/view/Plugins',
'common/main/lib/view/About',
'common/main/lib/view/SearchDialog',
'documenteditor/main/app/view/FileMenu',
'documenteditor/main/app/view/Navigation'
], function (menuTemplate, $, _, Backbone) {
'use strict';
var SCALE_MIN = 40;
var MENU_SCALE_PART = 300;
DE.Views.LeftMenu = Backbone.View.extend(_.extend({
el: '#left-menu',
template: _.template(menuTemplate),
// Delegated events for creating new items, and clearing completed ones.
events: function() {
return {
/** coauthoring begin **/
'click #left-btn-comments': _.bind(this.onCoauthOptions, this),
'click #left-btn-chat': _.bind(this.onCoauthOptions, this),
/** coauthoring end **/
'click #left-btn-plugins': _.bind(this.onCoauthOptions, this),
'click #left-btn-navigation': _.bind(this.onCoauthOptions, this),
'click #left-btn-support': function() {
var config = this.mode.customization;
config && !!config.feedback && !!config.feedback.url ?
window.open(config.feedback.url) :
window.open('{{SUPPORT_URL}}');
}
}
},
initialize: function () {
this.minimizedMode = true;
this._state = {disabled: false};
},
render: function () {
var $markup = $(this.template({}));
this.btnSearch = new Common.UI.Button({
action: 'search',
el: $markup.elementById('#left-btn-search'),
hint: this.tipSearch + Common.Utils.String.platformKey('Ctrl+F'),
disabled: true,
enableToggle: true
});
this.btnAbout = new Common.UI.Button({
action: 'about',
el: $markup.elementById('#left-btn-about'),
hint: this.tipAbout,
enableToggle: true,
disabled: true,
toggleGroup: 'leftMenuGroup'
});
this.btnSupport = new Common.UI.Button({
action: 'support',
el: $markup.elementById('#left-btn-support'),
hint: this.tipSupport,
disabled: true
});
/** coauthoring begin **/
this.btnComments = new Common.UI.Button({
el: $markup.elementById('#left-btn-comments'),
hint: this.tipComments + Common.Utils.String.platformKey('Ctrl+Shift+H'),
enableToggle: true,
disabled: true,
toggleGroup: 'leftMenuGroup'
});
this.btnChat = new Common.UI.Button({
el: $markup.elementById('#left-btn-chat'),
hint: this.tipChat + Common.Utils.String.platformKey('Alt+Q'),
enableToggle: true,
disabled: true,
toggleGroup: 'leftMenuGroup'
});
this.btnComments.hide();
this.btnChat.hide();
this.btnComments.on('click', this.onBtnMenuClick.bind(this));
this.btnComments.on('toggle', this.onBtnCommentsToggle.bind(this));
this.btnChat.on('click', this.onBtnMenuClick.bind(this));
/** coauthoring end **/
this.btnPlugins = new Common.UI.Button({
el: $markup.elementById('#left-btn-plugins'),
hint: this.tipPlugins,
enableToggle: true,
disabled: true,
toggleGroup: 'leftMenuGroup'
});
this.btnPlugins.hide();
this.btnPlugins.on('click', this.onBtnMenuClick.bind(this));
this.btnNavigation = new Common.UI.Button({
el: $markup.elementById('#left-btn-navigation'),
hint: this.tipNavigation,
enableToggle: true,
disabled: true,
toggleGroup: 'leftMenuGroup'
});
this.btnNavigation.on('click', this.onBtnMenuClick.bind(this));
this.btnSearch.on('click', this.onBtnMenuClick.bind(this));
this.btnAbout.on('toggle', this.onBtnMenuToggle.bind(this));
this.menuFile = new DE.Views.FileMenu();
this.btnAbout.panel = new Common.Views.About({el: '#about-menu-panel', appName: 'Document Editor'});
this.$el.html($markup);
return this;
},
onBtnMenuToggle: function(btn, state) {
if (state) {
btn.panel['show']();
if (!this._state.pluginIsRunning)
this.$el.width(SCALE_MIN);
if (this.btnSearch.isActive())
this.btnSearch.toggle(false);
} else {
btn.panel['hide']();
}
DE.getController('Toolbar').DisableToolbar(state==true);
if (!this.supressEvents)
Common.NotificationCenter.trigger('layout:changed', 'leftmenu');
},
onBtnCommentsToggle: function(btn, state) {
if (!state)
this.fireEvent('comments:hide', this);
},
onBtnMenuClick: function(btn, e) {
this.supressEvents = true;
this.btnAbout.toggle(false);
if (btn.options.action == 'search') {
} else {
if (btn.pressed) {
if (!(this.$el.width() > SCALE_MIN)) {
this.$el.width(parseInt(Common.localStorage.getItem('de-mainmenu-width')) || MENU_SCALE_PART);
}
} else if (!this._state.pluginIsRunning) {
Common.localStorage.setItem('de-mainmenu-width',this.$el.width());
this.$el.width(SCALE_MIN);
}
}
this.supressEvents = false;
Common.NotificationCenter.trigger('layout:changed', 'leftmenu');
},
onCoauthOptions: function(e) {
/** coauthoring begin **/
if (this.mode.canCoAuthoring) {
if (this.mode.canViewComments) {
if (this.btnComments.pressed && this.btnComments.$el.hasClass('notify'))
this.btnComments.$el.removeClass('notify');
this.panelComments[this.btnComments.pressed?'show':'hide']();
this.fireEvent((this.btnComments.pressed) ? 'comments:show' : 'comments:hide', this);
}
if (this.mode.canChat) {
if (this.btnChat.pressed) {
if (this.btnChat.$el.hasClass('notify'))
this.btnChat.$el.removeClass('notify');
this.panelChat.show();
this.panelChat.focus();
} else
this.panelChat['hide']();
}
}
if (this.panelNavigation) {
if (this.btnNavigation.pressed) {
this.panelNavigation.show();
} else
this.panelNavigation['hide']();
}
/** coauthoring end **/
// if (this.mode.canPlugins && this.panelPlugins) {
// if (this.btnPlugins.pressed) {
// this.panelPlugins.show();
// } else
// this.panelPlugins['hide']();
// }
},
setOptionsPanel: function(name, panel) {
/** coauthoring begin **/
if (name == 'chat') {
this.panelChat = panel.render('#left-panel-chat');
} else if (name == 'comment') {
this.panelComments = panel;
} else /** coauthoring end **/
if (name == 'history') {
this.panelHistory = panel.render('#left-panel-history');
} else
if (name == 'plugins' && !this.panelPlugins) {
this.panelPlugins = panel.render(/*'#left-panel-plugins'*/);
} else
if (name == 'navigation' && !this.panelNavigation) {
this.panelNavigation = panel.render('#left-panel-navigation');
}
},
/** coauthoring begin **/
markCoauthOptions: function(opt, ignoreDisabled) {
if (opt=='chat' && this.btnChat.isVisible() &&
!this.btnChat.isDisabled() && !this.btnChat.pressed) {
this.btnChat.$el.addClass('notify');
}
if (opt=='comments' && this.btnComments.isVisible() && !this.btnComments.pressed &&
(!this.btnComments.isDisabled() || ignoreDisabled) ) {
this.btnComments.$el.addClass('notify');
}
},
/** coauthoring end **/
close: function(menu) {
if ( this.menuFile.isVisible() ) {
this.menuFile.hide();
} else {
this.btnAbout.toggle(false);
if (!this._state.pluginIsRunning)
this.$el.width(SCALE_MIN);
/** coauthoring begin **/
if (this.mode.canCoAuthoring) {
if (this.mode.canViewComments) {
this.panelComments['hide']();
if (this.btnComments.pressed)
this.fireEvent('comments:hide', this);
this.btnComments.toggle(false, true);
}
if (this.mode.canChat) {
this.panelChat['hide']();
this.btnChat.toggle(false);
}
}
/** coauthoring end **/
if (this.mode.canPlugins && this.panelPlugins && !this._state.pluginIsRunning) {
this.panelPlugins['hide']();
this.btnPlugins.toggle(false, true);
}
if (this.panelNavigation) {
this.panelNavigation['hide']();
this.btnNavigation.toggle(false, true);
}
}
},
isOpened: function() {
var isopened = this.btnSearch.pressed;
/** coauthoring begin **/
!isopened && (isopened = this.btnComments.pressed || this.btnChat.pressed);
/** coauthoring end **/
return isopened;
},
disableMenu: function(menu, disable) {
this.btnSearch.setDisabled(false);
this.btnAbout.setDisabled(false);
this.btnSupport.setDisabled(false);
/** coauthoring begin **/
this.btnComments.setDisabled(false);
this.btnChat.setDisabled(false);
/** coauthoring end **/
this.btnPlugins.setDisabled(false);
this.btnNavigation.setDisabled(false);
},
showMenu: function(menu, opts) {
var re = /^(\w+):?(\w*)$/.exec(menu);
if ( re[1] == 'file' ) {
if ( !this.menuFile.isVisible() ) {
// this.btnFile.toggle(true);
}
this.menuFile.show(re[2].length ? re[2] : undefined, opts);
} else {
/** coauthoring begin **/
if (menu == 'chat') {
if (this.btnChat.isVisible() &&
!this.btnChat.isDisabled() && !this.btnChat.pressed) {
this.btnChat.toggle(true);
this.onBtnMenuClick(this.btnChat);
this.onCoauthOptions();
this.panelChat.focus();
}
} else
if (menu == 'comments') {
if (this.btnComments.isVisible() &&
!this.btnComments.isDisabled() && !this.btnComments.pressed) {
this.btnComments.toggle(true);
this.onBtnMenuClick(this.btnComments);
this.onCoauthOptions();
}
}
/** coauthoring end **/
}
},
getMenu: function(type) {
switch (type) {
default: return null;
case 'file': return this.menuFile;
case 'about': return this.btnAbout.panel;
}
},
setMode: function(mode) {
this.mode = mode;
this.btnAbout.panel.setMode(mode);
return this;
},
showHistory: function() {
this._state.pluginIsRunning = false;
this.panelHistory.show();
this.panelHistory.$el.width((parseInt(Common.localStorage.getItem('de-mainmenu-width')) || MENU_SCALE_PART) - SCALE_MIN);
Common.NotificationCenter.trigger('layout:changed', 'history');
},
setDeveloperMode: function(mode, beta, version) {
if ( !this.$el.is(':visible') ) return;
if ((mode & Asc.c_oLicenseMode.Trial) || (mode & Asc.c_oLicenseMode.Developer)) {
if (!this.developerHint) {
var str = '';
if ((mode & Asc.c_oLicenseMode.Trial) && (mode & Asc.c_oLicenseMode.Developer))
str = this.txtTrialDev;
else if ((mode & Asc.c_oLicenseMode.Trial)!==0)
str = this.txtTrial;
else if ((mode & Asc.c_oLicenseMode.Developer)!==0)
str = this.txtDeveloper;
str = str.toUpperCase();
this.developerHint = $('<div id="developer-hint">' + str + '</div>').appendTo(this.$el);
this.devHeight = this.developerHint.outerHeight();
!this.devHintInited && $(window).on('resize', _.bind(this.onWindowResize, this));
this.devHintInited = true;
}
}
this.developerHint && this.developerHint.toggleClass('hidden', !((mode & Asc.c_oLicenseMode.Trial) || (mode & Asc.c_oLicenseMode.Developer)));
if (beta) {
if (!this.betaHint) {
var style = (mode) ? 'style="margin-top: 4px;"' : '',
arr = (version || '').split('.'),
ver = '';
(arr.length>0) && (ver += ('v. ' + arr[0]));
(arr.length>1) && (ver += ('.' + arr[1]));
this.betaHint = $('<div id="beta-hint"' + style + '>' + (ver + ' (beta)' ) + '</div>').appendTo(this.$el);
this.betaHeight = this.betaHint.outerHeight();
!this.devHintInited && $(window).on('resize', _.bind(this.onWindowResize, this));
this.devHintInited = true;
}
}
this.betaHint && this.betaHint.toggleClass('hidden', !beta);
var btns = this.$el.find('button.btn-category:visible'),
lastbtn = (btns.length>0) ? $(btns[btns.length-1]) : null;
this.minDevPosition = (lastbtn) ? (lastbtn.offset().top - lastbtn.offsetParent().offset().top + lastbtn.height() + 20) : 20;
this.onWindowResize();
},
setLimitMode: function() {
if ( !this.$el.is(':visible') ) return;
if (!this.limitHint) {
var str = this.txtLimit.toUpperCase();
this.limitHint = $('<div id="limit-hint" style="margin-top: 4px;">' + str + '</div>').appendTo(this.$el);
this.limitHeight = this.limitHint.outerHeight();
!this.devHintInited && $(window).on('resize', _.bind(this.onWindowResize, this));
this.devHintInited = true;
}
this.limitHint && this.limitHint.toggleClass('hidden', false);
var btns = this.$el.find('button.btn-category:visible'),
lastbtn = (btns.length>0) ? $(btns[btns.length-1]) : null;
this.minDevPosition = (lastbtn) ? (lastbtn.offset().top - lastbtn.offsetParent().offset().top + lastbtn.height() + 20) : 20;
this.onWindowResize();
},
onWindowResize: function() {
var height = (this.devHeight || 0) + (this.betaHeight || 0) + (this.limitHeight || 0);
var top = Math.max((this.$el.height()-height)/2, this.minDevPosition);
if (this.developerHint) {
this.developerHint.css('top', top);
top += this.devHeight;
}
if (this.betaHint) {
this.betaHint.css('top', top);
top += (this.betaHeight + 4);
}
this.limitHint && this.limitHint.css('top', top);
},
/** coauthoring begin **/
tipComments : 'Comments',
tipChat : 'Chat',
/** coauthoring end **/
tipAbout : 'About',
tipSupport : 'Feedback & Support',
tipSearch : 'Search',
tipPlugins : 'Plugins',
txtDeveloper: 'DEVELOPER MODE',
txtTrial: 'TRIAL MODE',
txtTrialDev: 'Trial Developer Mode',
tipNavigation: 'Navigation',
txtLimit: 'Limit Access'
}, DE.Views.LeftMenu || {}));
});
| ONLYOFFICE/web-apps | apps/documenteditor/main/app/view/LeftMenu.js | JavaScript | agpl-3.0 | 19,483 |
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React, { Component } from 'react';
import { bool, func, node, string } from 'prop-types';
import Button from 'instructure-ui/lib/components/Button';
import ArrowOpenLeft from 'instructure-icons/lib/Line/IconArrowOpenLeftLine';
import ArrowOpenRight from 'instructure-icons/lib/Line/IconArrowOpenRightLine';
export default class Carousel extends Component {
componentDidUpdate (prevProps) {
const selectedLast = prevProps.displayRightArrow && !this.props.displayRightArrow;
const selectedFirst = prevProps.displayLeftArrow && !this.props.displayLeftArrow;
if (selectedFirst) {
this.rightArrow.focus();
} else if (selectedLast) {
this.leftArrow.focus();
}
}
handleLeftArrowClick = () => {
this.props.onLeftArrowClick();
this.leftArrow.focus();
}
handleRightArrowClick = () => {
this.props.onRightArrowClick();
this.rightArrow.focus();
}
render () {
const leftArrow = (
<Button
disabled={this.props.disabled}
ref={(button) => { this.leftArrow = button }}
variant="icon"
onClick={this.handleLeftArrowClick}
size="small"
>
<ArrowOpenLeft title={this.props.leftArrowDescription} />
</Button>
);
const rightArrow = (
<Button
disabled={this.props.disabled}
ref={(button) => { this.rightArrow = button }}
variant="icon"
onClick={this.handleRightArrowClick}
size="small"
>
<ArrowOpenRight title={this.props.rightArrowDescription} />
</Button>
);
return (
<div id={this.props.id} className="carousel">
<div className="left-arrow-button-container">
{ this.props.displayLeftArrow && leftArrow }
</div>
<div style={{ flex: 1 }}>
{this.props.children}
</div>
<div className="right-arrow-button-container">
{ this.props.displayRightArrow && rightArrow }
</div>
</div>
);
}
}
Carousel.defaultProps = {
id: null,
showBorderBottom: true
};
Carousel.propTypes = {
id: string,
children: node.isRequired,
disabled: bool.isRequired,
displayLeftArrow: bool.isRequired,
displayRightArrow: bool.isRequired,
onLeftArrowClick: func.isRequired,
onRightArrowClick: func.isRequired,
leftArrowDescription: string.isRequired,
rightArrowDescription: string.isRequired
};
| venturehive/canvas-lms | app/jsx/gradezilla/default_gradebook/components/Carousel.js | JavaScript | agpl-3.0 | 3,087 |
(function($) {
$.fn.customFile = function(options) {
var settings = {
bgImage : "./icons/hdd_mount.png",
scrollInterval : 500
};
if(options) {
$.extend(settings, options);
}
return this.each(function() {
var self = this;
var s = settings;
$(this).val("");
$.fn.clearInterval = function() {
window.clearInterval(self.interval);
window.setTimeout(function() { $(self).siblings("input").val(""); },s.scrollInterval);
return $(self);
};
$(this).wrap('<span style="display:block;position:relative;width:80%;"></span>');
$(this).css("opacity","0").css("z-index",2).css("position","relative").css("cursor","pointer");
$(this).parent("span").append('<input type="text" readonly="true" class="uploadField" style="width:'+($(this).width()-15)+'px; margin-right:15px;padding-right:16px;background:#fff url('+settings.bgImage+') right center no-repeat;position:absolute;z-index:1;top:0px;left:0px;" />');
$(this).bind("change",function() {
$(this).clearInterval();
if ($(this).val()=="") return;
var inp = $(this).siblings("input");
inp.attr("realVal",$(this).val());
inp.val($(this).val());
this.interval = window.setInterval(function() {
inp.val(inp.val().substr(1));
if (inp.val()=="") inp.val(inp.attr("realVal"));
},s.scrollInterval);
});
return $(this);
});
};
})(jQuery); | irontec/Mintzatu | public/karma/modules/tablonfullcalendar/scripts/jq.customFile.js | JavaScript | agpl-3.0 | 1,528 |
/* -*- mode: espresso; espresso-indent-level: 2; indent-tabs-mode: nil -*- */
/* vim: set softtabstop=2 shiftwidth=2 tabstop=2 expandtab: */
(function(CATMAID) {
"use strict";
var ConnectivityMatrixWidget = function() {
this.widgetID = this.registerInstance();
this.matrix = new CATMAID.ConnectivityMatrix();
this.rowDimension = new CATMAID.BasicSkeletonSource(this.getName() + " Rows");
this.colDimension = new CATMAID.BasicSkeletonSource(this.getName() + " Columns");
// Synapse counts are only displayed if they are at least that big
this.synapseThreshold = 1;
// Color index for table cell coloring option
this.color = 0;
// Sorting indices for row and columns, default to name
this.rowSorting = 1;
this.colSorting = 1;
};
ConnectivityMatrixWidget.prototype = {};
$.extend(ConnectivityMatrixWidget.prototype, new InstanceRegistry());
// Make connectivity matrix widget available in CATMAID namespace
CATMAID.ConnectivityMatrixWidget = ConnectivityMatrixWidget;
/* Implement interfaces */
ConnectivityMatrixWidget.prototype.getName = function()
{
return "Connectivity Matrix " + this.widgetID;
};
/**
* Handle destruction of widget.
*/
ConnectivityMatrixWidget.prototype.destroy = function() {
NeuronNameService.getInstance().unregister(this);
this.content = null;
this.rowDimension.destroy();
this.colDimension.destroy();
this.unregisterInstance();
};
/* Non-interface methods */
/**
* Create an object with all relevant information for creating a CATMAID
* widget. All methods can expect to be executed in the context of this
* object.
*/
ConnectivityMatrixWidget.prototype.getWidgetConfiguration = function() {
return {
class: 'connectivity_matrix',
controlsID: 'connectivity_matrix_controls' + this.widgetID,
contentID: 'connectivity_matrix' + this.widgetID,
/**
* Create widget controls.
*/
createControls: function(controls) {
// Create hidden select elements for row and column sources
var rowSelect = CATMAID.skeletonListSources.createSelect(this.rowDimension);
rowSelect.style.display = 'none';
controls.appendChild(rowSelect);
var colSelect = CATMAID.skeletonListSources.createSelect(this.colDimension);
colSelect.style.display = 'none';
controls.appendChild(colSelect);
// This UI combines two skeleton source selects into one.
controls.appendChild(document.createTextNode('From'));
var sourceSelect = CATMAID.skeletonListSources.createSelect(this,
[this.rowDimension.getName(), this.colDimension.getName()]);
controls.appendChild(sourceSelect);
sourceSelect.onchange = function() {
rowSelect.value = this.value;
colSelect.value = this.value;
};
// Indicates if loaded skeletons should be part of a group
var loadAsGroup = false;
/**
* Load rows and/or coulmns and refresh.
*/
var loadWith = function(withRows, withCols) {
if (loadAsGroup) {
// Ask for group name
askForGroupName((function(name) {
return (!withRows || isValidGroupName(Object.keys(
this.rowDimension.groups), name)) &&
(!withCols || isValidGroupName(Object.keys(
this.colDimension.groups), name));
}).bind(this), (function(groupName) {
if (withRows) this.rowDimension.loadAsGroup(groupName);
if (withCols) this.colDimension.loadAsGroup(groupName);
if (withRows || withCols) this.update();
}).bind(this));
} else {
if (withRows) this.rowDimension.loadSource();
if (withCols) this.colDimension.loadSource();
if (withRows || withCols) this.update();
}
};
var asGroupCb = document.createElement('input');
asGroupCb.setAttribute('type', 'checkbox');
asGroupCb.checked = loadAsGroup;
asGroupCb.onclick = function() {
loadAsGroup = this.checked;
};
var asGroup = document.createElement('label');
asGroup.appendChild(asGroupCb);
asGroup.appendChild(document.createTextNode('As group'));
controls.appendChild(asGroup);
var loadRows = document.createElement('input');
loadRows.setAttribute("type", "button");
loadRows.setAttribute("value", "Append presynaptic neurons");
loadRows.onclick = loadWith.bind(this, true, false);
controls.appendChild(loadRows);
var loadColumns = document.createElement('input');
loadColumns.setAttribute("type", "button");
loadColumns.setAttribute("value", "Append postsynaptic neurons");
loadColumns.onclick = loadWith.bind(this, false, true);
controls.appendChild(loadColumns);
var loadAll = document.createElement('input');
loadAll.setAttribute("type", "button");
loadAll.setAttribute("value", "Append to both");
loadAll.onclick = loadWith.bind(this, true, true);
controls.appendChild(loadAll);
var clear = document.createElement('input');
clear.setAttribute("type", "button");
clear.setAttribute("value", "Clear");
clear.onclick = (function() {
if (confirm("Do you really want to clear the current selection?")) {
this.clear();
}
}).bind(this);
controls.appendChild(clear);
var max = 20;
var synapseThresholdSelect = document.createElement('select');
for (var i=1; i <= max; ++i) {
synapseThresholdSelect.options.add(
new Option(i, i, this.synapseThreshold === i));
}
synapseThresholdSelect.onchange = (function(e) {
this.synapseThreshold = e.target.value;
this.refresh();
}).bind(this);
var synapseThreshold = document.createElement('label');
synapseThreshold.appendChild(document.createTextNode('Syn. threshold'));
synapseThreshold.appendChild(synapseThresholdSelect);
controls.appendChild(synapseThreshold);
var sortOptionNames = sortOptions.map(function(o) {
return o.name;
});
var sortRowsSelect = document.createElement('select');
for (var i=0; i < sortOptionNames.length; ++i) {
var selected = (this.rowSorting === i);
sortRowsSelect.options.add(
new Option(sortOptionNames[i], i, selected, selected));
}
sortRowsSelect.onchange = (function(e) {
this.rowSorting = e.target.value;
this.refresh();
}).bind(this);
var postColor = document.createElement('label');
postColor.appendChild(document.createTextNode('Sort rows by'));
postColor.appendChild(sortRowsSelect);
controls.appendChild(postColor);
var sortColsSelect = document.createElement('select');
for (var i=0; i < sortOptionNames.length; ++i) {
var selected = (this.colSorting === i);
sortColsSelect.options.add(
new Option(sortOptionNames[i], i, selected, selected));
}
sortColsSelect.onchange = (function(e) {
this.colSorting = e.target.value;
this.refresh();
}).bind(this);
var postColor = document.createElement('label');
postColor.appendChild(document.createTextNode('Sort columns by'));
postColor.appendChild(sortColsSelect);
controls.appendChild(postColor);
var colorSelect = document.createElement('select');
for (var i=0; i < colorOptions.length; ++i) {
var selected = (this.color === i);
colorSelect.options.add(
new Option(colorOptions[i], i, selected, selected));
}
colorSelect.onchange = (function(e) {
this.color = parseInt(e.target.value, 10);
this.refresh();
}).bind(this);
var color = document.createElement('label');
color.appendChild(document.createTextNode('Color'));
color.appendChild(colorSelect);
controls.appendChild(color);
var update = document.createElement('input');
update.setAttribute("type", "button");
update.setAttribute("value", "Refresh");
update.onclick = this.update.bind(this);
controls.appendChild(update);
var exportCSV = document.createElement('input');
exportCSV.setAttribute("type", "button");
exportCSV.setAttribute("value", "Export CSV");
exportCSV.onclick = this.exportCSV.bind(this);
controls.appendChild(exportCSV);
},
/**
* Create widget content.
*/
createContent: function(container) {
this.content = container;
this.update();
}
};
};
/**
* Clear all sources.
*/
ConnectivityMatrixWidget.prototype.clear = function() {
this.rowDimension.clear();
this.colDimension.clear();
this.update();
};
/**
* Update names of neurons in connectivity widget.
*/
ConnectivityMatrixWidget.prototype.updateNeuronNames = function() {
this.refresh();
};
/**
* Refresh the UI without recreating the connectivity matrix.
*/
ConnectivityMatrixWidget.prototype.refresh = function(container) {
// Clrear container and add new table
$(this.content).empty();
// Sort row dimensions
var rowSort = sortOptions[this.rowSorting];
if (rowSort && CATMAID.tools.isFn(rowSort.sort)) {
this.rowDimension.sort(rowSort.sort.bind(this, this.matrix,
this.rowDimension, true));
this.matrix.refresh();
} else {
CATMAID.error('Could not find row sorting function with name ' +
this.rowSorting);
}
// Sort coumn dimensions
var colSort = sortOptions[this.colSorting];
if (colSort && CATMAID.tools.isFn(colSort.sort)) {
this.colDimension.sort(colSort.sort.bind(this, this.matrix,
this.colDimension, false));
} else {
CATMAID.error('Could not find column sorting function with name ' +
this.colSorting);
}
// Rebuild matrix with sorted skeletons (no back-end query)
this.matrix.rowSkeletonIDs = this.rowDimension.getSelectedSkeletons();
this.matrix.colSkeletonIDs = this.colDimension.getSelectedSkeletons();
this.matrix.rebuild();
// Create table
this.addConnectivityMatrixTable(this.matrix, this.content, this.synapseThreshold);
};
/**
* Recreate the connectivity matrix and refresh the UI.
*/
ConnectivityMatrixWidget.prototype.update = function(container) {
if (!this.matrix) {
return;
}
// Clrear container
var $content = $(this.content);
$content.empty();
var nRows = this.rowDimension.getNumberOfSkeletons();
var nCols = this.colDimension.getNumberOfSkeletons();
// If there are now row or column skeletons, display a message and return
if (0 === nRows && 0 === nCols) {
this.content.dataset.msg = "Please append row and column skeletons";
return;
} else if (0 === nRows) {
this.content.dataset.msg = "Please append row skeletons, " + nCols +
" column skeletons are already available.";
return;
} else if (0 === nCols) {
this.content.dataset.msg = "Please append column skeletons, " + nRows +
" row skeletons are already available.";
return;
} else {
this.content.dataset.msg = "Please wait, connectivity information is retrieved.";
}
// Update connectivity matrix and make sure all currently looked at
// skeletons are known to the neuron name service.
var nns = NeuronNameService.getInstance();
this.matrix.rowSkeletonIDs = this.rowDimension.getSelectedSkeletons();
this.matrix.colSkeletonIDs = this.colDimension.getSelectedSkeletons();
this.matrix.refresh()
.then(nns.registerAll.bind(nns, this, this.rowDimension.getSelectedSkeletonModels()))
.then(nns.registerAll.bind(nns, this, this.colDimension.getSelectedSkeletonModels()))
.then((function() {
// Clear any message
if (this.content.dataset.msg) delete this.content.dataset.msg;
// Create table
this.refresh();
}).bind(this));
};
/**
* Add a tabular representation of the connectivity matrix to the given DOM
* element.
*
* @param matrix {ConnectivityMatrix} The connectivity matrix to add.
* @param content {DOMElement} The element to add the table to.
* @param synThreshold {number} Maximum number of synapses not to display
* @returns the content element passed in.
*/
ConnectivityMatrixWidget.prototype.addConnectivityMatrixTable = function(
matrix, content, synThreshold) {
// Create table representation for connectivity matrix
var table = document.createElement('table');
table.setAttribute('class', 'partner_table');
// Add column header, prepend one blank cell for row headers
var colHeader = table.appendChild(document.createElement('tr'));
colHeader.appendChild(document.createElement('th'));
// Find maximum connection number in matrix
var maxConnections = matrix.getMaxConnections();
var walked = this.walkMatrix(matrix, handleColumn.bind(window, colHeader),
handleRow.bind(window, table), handleCell.bind(this));
if (walked) {
var infoBox = document.createElement('div');
infoBox.appendChild(document.createTextNode('The table below shows the ' +
'number of post-synaptic connections from row to column skeletons. ' +
'If there are no connections, no number is shown.'));
content.appendChild(infoBox);
// Append matrix to content
content.appendChild(table);
// Add a handler for openening connector selections for individual partners
$('a[partnerIDs]', table).click(function () {
var sourceIDs = $(this).attr('sourceIDs');
var partnerIDs = $(this).attr('partnerIDs');
var type = $(this).attr('type');
if (sourceIDs && partnerIDs) {
sourceIDs = JSON.parse(sourceIDs);
partnerIDs = JSON.parse(partnerIDs);
CATMAID.ConnectorSelection.show_shared_connectors(sourceIDs, partnerIDs,
type + "synaptic_to");
} else {
CATMAID.error("Could not find partner or source IDs!");
}
return true;
});
// Add a handler for selecting skeletons when their names are clicked
$(table).on('click', 'a[data-skeleton-ids]', function(e) {
var skeletonIDs = JSON.parse(this.dataset.skeletonIds);
if (!skeletonIDs || !skeletonIDs.length) {
CATMAID.warn('Could not find expected list of skleton IDs');
return;
}
if (1 === skeletonIDs.length) {
TracingTool.goToNearestInNeuronOrSkeleton('skeleton', skeletonIDs[0]);
} else {
var ST = new SelectionTable();
var models = skeletonIDs.reduce(function(o, skid) {
o[skid] = new SelectionTable.prototype.SkeletonModel(skid, "",
new THREE.Color().setRGB(1, 1, 0));
return o;
}, {});
WindowMaker.create('neuron-staging-area', ST);
ST.append(models);
}
});
}
return content;
// Create column
function handleColumn(tableHeader, id, colGroup, name, skeletonIDs) {
var th = createHeaderCell(name, colGroup, skeletonIDs);
tableHeader.appendChild(th);
}
// Create row
function handleRow(table, id, rowGroup, name, skeletonIDs) {
var row = document.createElement('tr');
table.appendChild(row);
var th = createHeaderCell(name, rowGroup, skeletonIDs);
row.appendChild(th);
return row;
}
// Chreate a cell with skeleton link
function createHeaderCell(name, group, skeletonIDs) {
var a = document.createElement('a');
a.href = '#';
a.setAttribute('data-skeleton-ids', JSON.stringify(skeletonIDs));
a.appendChild(document.createTextNode(name));
var th = document.createElement('th');
th.appendChild(a);
if (group) {
th.setAttribute('title', 'This group contains ' + group.length +
' skeleton(s): ' + group.join(', '));
}
return th;
}
// Create cell
function handleCell(row, rowName, rowSkids, colName, colSkids, connections) {
/* jshint validthis: true */ // `this` is bound to the connectivity matrix
var td = createSynapseCountCell("pre", rowName, rowSkids, colName, colSkids,
connections, synThreshold);
colorize(td, colorOptions[this.color], connections, 0, maxConnections);
row.appendChild(td);
}
};
/**
* Iterate over the current connectivity matrix and call the passed in
* functions when a column can be created, a row can be crated and a cell can
* be created.
*/
ConnectivityMatrixWidget.prototype.walkMatrix = function(
matrix, handleCol, handleRow, handleCell) {
var nRows = matrix.getNumberOfRows();
var nCols = matrix.getNumberOfColumns();
if (0 === nRows || 0 === nCols) {
return false;
}
var m = matrix.connectivityMatrix;
var nns = NeuronNameService.getInstance();
// Get group information
var nDisplayRows = this.rowDimension.orderedElements.length;
var nDisplayCols = this.colDimension.orderedElements.length;
for (var c=0; c<nDisplayCols; ++c) {
// Get skeleton or group name
var id = this.colDimension.orderedElements[c];
var colGroup = this.colDimension.groups[id];
var name = colGroup ? id : nns.getName(id);
var skeletonIDs = colGroup ? colGroup : [id];
handleCol(id, colGroup, name, skeletonIDs);
}
// Add row headers and connectivity matrix rows
var r = 0;
for (var dr=0; dr<nDisplayRows; ++dr) {
var c = 0;
// Get skeleton or rowGroup name and increase row skeleton counter
var rowId = this.rowDimension.orderedElements[dr];
var rowGroup = this.rowDimension.groups[rowId];
var rowName = rowGroup ? rowId : nns.getName(rowId);
var skeletonIDs = rowGroup ? rowGroup : [rowId];
var row = handleRow(rowId, rowGroup, rowName, skeletonIDs);
// Crete cells for each column in this row
for (var dc=0; dc<nDisplayCols; ++dc) {
// Aggregate group counts (if any)
var colId = this.colDimension.orderedElements[dc];
var colGroup = this.colDimension.groups[colId];
var colName = colGroup ? colId : nns.getName(colId);
var connections = aggregateMatrix(m, r, c,
rowGroup ? rowGroup.length : 1,
colGroup ? colGroup.length : 1);
// Create and handle in and out cells
var rowSkids = rowGroup ? rowGroup : [rowId];
var colSkids = colGroup ? colGroup : [colId];
handleCell(row, rowName, rowSkids, colName, colSkids, connections);
// Increase index for next iteration
c = colGroup ? c + colGroup.length : c + 1;
}
// Increase index for next iteration
r = rowGroup ? r + rowGroup.length : r + 1;
}
return true;
};
/**
* Export the currently displayed matrix as CSV file.
*/
ConnectivityMatrixWidget.prototype.exportCSV = function() {
if (!this.matrix) {
CATMAIR.error("Please load some data first.");
return;
}
// Create a new array that contains entries for each line. Pre-pulate with
// first element (empty upper left cell).
var lines = [['""']];
var walked = this.walkMatrix(this.matrix, handleColumn.bind(window, lines[0]),
handleRow.bind(window, lines), handleCell);
// Export concatenation of all lines, delimited buy new-line characters
if (walked) {
var text = lines.map(function(l) { return l.join(', '); }).join('\n');
saveAs(new Blob([text], {type: 'text/plain'}), 'connectivity-matrix.csv');
}
// Create header
function handleColumn(line, id, colGroup, name, skeletonIDs) {
line.push('"' + name + '"');
}
// Create row
function handleRow(lines, id, rowGroup, name, skeletonIDs) {
var line = ['"' + name + '"'];
lines.push(line);
return line;
}
// Create cell
function handleCell(line, rowName, rowSkids, colName, colSkids, connections) {
line.push(connections);
}
};
/**
* Aggregate the values of a connectivity matrix over the specified number of
* rows and columns, starting from the given position.
*/
function aggregateMatrix(matrix, r, c, nRows, nCols) {
var n = 0;
for (var i=0; i<nRows; ++i) {
for (var j=0; j<nCols; ++j) {
n += matrix[r + i][c + j];
}
}
return n;
}
/**
* Create a synapse count table cell.
*/
function createSynapseCountCell(sourceType, sourceName, sourceIDs, targetName, partnerIDs,
count, threshold) {
var td = document.createElement('td');
td.setAttribute('class', 'syncount');
if ("pre" === sourceType) {
td.setAttribute('title', 'From "' + sourceName + '" to "' + targetName +
'": ' + count + ' connection(s)');
} else {
td.setAttribute('title', 'From "' + targetName + '" to "' + sourceName +
'": ' + count + ' connection(s)');
}
if (count >= threshold) {
// Create a links that will open a connector selection when clicked. The
// handler to do this is created separate to only require one handler.
var a = document.createElement('a');
td.appendChild(a);
a.appendChild(document.createTextNode(count));
a.setAttribute('href', '#');
a.setAttribute('sourceIDs', JSON.stringify(sourceIDs));
a.setAttribute('partnerIDs', JSON.stringify(partnerIDs));
a.setAttribute('type', sourceType);
} else {
// Make a hidden span including the zero for semantic clarity and table exports.
var s = document.createElement('span');
td.appendChild(s);
s.appendChild(document.createTextNode(count));
s.style.display = 'none';
}
return td;
}
/**
* Display a modal dialog to ask the user for a group name.
*/
function askForGroupName(validGroupName, callback) {
var options = new OptionsDialog("Group properties");
options.appendMessage("Please choose a name for the new group.");
var nameField = options.appendField("Name: ", "groupname-typed", "", null);
var invalidMessage = options.appendMessage("Please choose a different name!");
invalidMessage.style.display = "none";
nameField.onkeyup = function(e) {
// Show a message if this name is already taken or invalid
var valid = validGroupName(this.value);
invalidMessage.style.display = valid ? "none" : "block";
};
options.onOK = function() {
if (!validGroupName(nameField.value)) {
CATMAID.error("Please choose a different group name!");
return false;
}
callback(nameField.value);
};
options.show("auto", "auto", true);
}
/**
* Test if a group name is valid, based on a list of existing group names.
*/
function isValidGroupName(existingNames, name) {
return -1 === existingNames.indexOf(name);
}
// The available color options for
var colorOptions = ["None"].concat(Object.keys(colorbrewer));
// The available sort options for rows and columns
var sortOptions = [
{
name: 'ID',
sort: function(matrix, src, isRow, a, b) {
return CATMAID.tools.compareStrings('' + a, '' + b);
}
},
{
name: 'Name',
sort: function(matrix, src, isRow, a, b) {
// Compare against the group name, if a or b is a group,
// otherwise use the name of the neuron name service.
var nns = NeuronNameService.getInstance();
a = src.isGroup(a) ? a : nns.getName(a);
b = src.isGroup(b) ? b : nns.getName(b);
return CATMAID.tools.compareStrings('' + a, '' + b);
}
},
{
name: 'Max synapse count (desc.)',
sort: function(matrix, src, isRow, a, b) {
return compareDescendingSynapseCount(matrix, src, isRow, a, b);
}
},
{
name: 'Max synapse count (asc.)',
sort: function(matrix, src, isRow, a, b) {
return -1 * compareDescendingSynapseCount(matrix, src, isRow, a, b);
}
},
{
name: 'Max total synapse count (desc.)',
sort: function(matrix, src, isRow, a, b) {
return compareDescendingTotalSynapseCount(matrix, src, isRow, a, b);
}
},
{
name: 'Max total synapse count (asc.)',
sort: function(matrix, src, isRow, a, b) {
return -1 * compareDescendingTotalSynapseCount(matrix, src, isRow, a, b);
}
}
];
/**
* Compare by the maximum synapse count in rows or columns a and b.
*/
var compareDescendingSynapseCount = function(matrix, src, isRow, a, b) {
var m = matrix.connectivityMatrix;
if (isRow) {
// Find maximum synapse counts in the given rows
var ia = matrix.rowSkeletonIDs.indexOf(a);
var ib = matrix.rowSkeletonIDs.indexOf(b);
var ca = m[ia];
var cb = m[ib];
if (!ca) throw new CATMAID.ValueError("Invalid column: " + ia);
if (!cb) throw new CATMAID.ValueError("Invalid column: " + ib);
return compareMaxInArray(ca, cb);
} else {
var ia = matrix.colSkeletonIDs.indexOf(a);
var ib = matrix.colSkeletonIDs.indexOf(b);
var maxa = 0, maxb = 0;
for (var i=0; i<matrix.getNumberOfRows(); ++i) {
if (m[i][ia] > maxa) maxa = m[i][ia];
if (m[i][ib] > maxb) maxb = m[i][ib];
}
return maxa === maxb ? 0 : (maxa > maxb ? -1 : 1);
}
};
/**
* Compare by the accumulated synapse count in rows or columns a and b.
*/
var compareDescendingTotalSynapseCount = function(matrix, src, isRow, a, b) {
// Aggregate synapses over all rows respective columns
var aAll = 0, bAll = 0;
var m = matrix.connectivityMatrix;
if (isRow) {
var ia = matrix.rowSkeletonIDs.indexOf(a);
var ib = matrix.rowSkeletonIDs.indexOf(b);
var nCols = matrix.getNumberOfColumns();
for (var j=0; j<nCols; ++j) {
aAll += m[ia][j];
bAll += m[ib][j];
}
} else {
var ia = matrix.colSkeletonIDs.indexOf(a);
var ib = matrix.colSkeletonIDs.indexOf(b);
var nRows = matrix.getNumberOfRows();
for (var j=0; j<nRows; ++j) {
aAll += m[j][ia];
bAll += m[j][ib];
}
}
// Compare aggregated synapses
return aAll === bAll ? 0 : (aAll > bAll ? -1 : 1);
};
/**
* Return 1 if array contains a higher value than any other value in array b.
* -1 if array b contains a higher value than array a. If their maximum value
* is the same, return 0.
*/
var compareMaxInArray = function(a, b) {
var maxa = 0;
for (var i=0; i<a.length; ++i) {
if (a[i] > maxa) maxa = a[i];
}
var maxb = 0;
for (var i=0; i<b.length; ++i) {
if (b[i] > maxb) maxb = b[i];
}
return maxa === maxb ? 0 : (maxa > maxb ? -1 : 1);
};
/**
* Set background color of a DOM element according to the given color scheme.
*/
var colorize = function(element, scheme, value, minValue, maxValue) {
var bg = null;
if (!scheme || "None" === scheme) return;
else if (colorbrewer.hasOwnProperty(scheme)) {
var sets = colorbrewer[scheme];
var range = maxValue - minValue + 1;
var relValue = value - minValue;
if (sets.hasOwnProperty(range)) {
// Perfect, one available scale fits our range
bg = sets[range][relValue];
} else {
// Scale range to fit value
var maxLength = Object.keys(sets).reduce(function(mv, v) {
v = parseInt(v, 10);
return v > mv ? v : mv;
}, 0);
var index = Math.min(maxLength - 1, Math.round(relValue * maxLength / range));
bg = sets[maxLength][index];
}
}
// Set background
element.style.backgroundColor = bg;
// Heuristic to find foreground color for children
var fg = CATMAID.tools.getContrastColor(bg);
for (var i=0; i<element.childNodes.length; ++i) {
element.childNodes[i].style.color = fg;
}
};
})(CATMAID);
| fzadow/CATMAID | django/applications/catmaid/static/js/widgets/connectivity_matrix.js | JavaScript | agpl-3.0 | 28,382 |
// Copyright (c) 2014,2015 Walter Bender
// Copyright (c) Yash Khandelwal, GSoC'15
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the The GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// You should have received a copy of the GNU Affero General Public
// License along with this library; if not, write to the Free Software
// Foundation, 51 Franklin Street, Suite 500 Boston, MA 02110-1335 USA
//
// Note: This code is inspired by the Python Turtle Blocks project
// (https://github.com/walterbender/turtleart), but implemented from
// scratch. -- Walter Bender, October 2014.
function facebookInit() {
window.fbAsyncInit = function () {
FB.init({
appId: '1496189893985945',
xfbml: true,
version: 'v2.1'
});
// ADD ADDITIONAL FACEBOOK CODE HERE
};
}
try {
(function (d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {
return;
}
js = d.createElement(s);
js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
} catch (e) {
}
var lang = document.webL10n.getLanguage();
if (lang.indexOf("-") != -1) {
lang = lang.slice(0, lang.indexOf("-"));
document.webL10n.setLanguage(lang);
}
// sugarizerCompatibility.ifInsideSugarizerHideLoading();
define(function (require) {
require("activity/sugarizer-compatibility");
require('activity/platformstyle');
require('easeljs');
require('tweenjs');
require('preloadjs');
require('howler');
require('mespeak');
require('Chart');
require('activity/utils');
require('activity/artwork');
require('activity/munsell');
require('activity/trash');
require('activity/turtle');
require('activity/palette');
require('activity/protoblocks');
require('activity/blocks');
require('activity/block');
require('activity/logo');
require('activity/clearbox');
require('activity/utilitybox');
require('activity/samplesviewer');
require('activity/basicblocks');
require('activity/blockfactory');
require('activity/analytics');
require('prefixfree.min');
require('activity/matrix');
require('activity/musicnotation');
// Manipulate the DOM only when it is ready.
require(['domReady!'], function (doc) {
if (sugarizerCompatibility.isInsideSugarizer()) {
sugarizerCompatibility.loadData(function () {
domReady(doc);
});
} else {
domReady(doc);
}
});
function domReady(doc) {
facebookInit();
window.scroll(0, 0);
var txt = "";
txt += "innerWidth: " + window.innerWidth + " ";
txt += "innerHeight: " + window.innerHeight + " ";
txt += "outerWidth: " + window.outerWidth + " ";
txt += "outerHeight: " + window.outerHeight + " ";
console.log(txt);
try {
meSpeak.loadConfig('lib/mespeak_config.json');
meSpeak.loadVoice('lib/voices/en/en.json');
} catch (e) {
console.log(e);
}
var canvas = docById('myCanvas');
var queue = new createjs.LoadQueue(false);
// Check for the various File API support.
if (window.File && window.FileReader && window.FileList && window.Blob) {
var files = true;
} else {
alert('The File APIs are not fully supported in this browser.');
var files = false;
}
// Set up a file chooser for the doOpen function.
var fileChooser = docById('myOpenFile');
// Set up a file chooser for the doOpenPlugin function.
var pluginChooser = docById('myOpenPlugin');
// The file chooser for all files.
var allFilesChooser = docById('myOpenAll')
// Are we running off of a server?
var server = true;
var musicBlocksScale = 1;
var stage;
var turtles;
var palettes;
var blocks;
var logo;
var clearBox;
var utilityBox;
var thumbnails;
var buttonsVisible = true;
var headerContainer = null;
var toolbarButtonsVisible = true;
var menuButtonsVisible = false;
var menuContainer = null;
var scrollBlockContainer = false;
var currentKey = '';
var currentKeyCode = 0;
var lastKeyCode = 0;
var pasteContainer = null;
var chartBitmap = null;
// Calculate the palette colors.
for (var p in PALETTECOLORS) {
PALETTEFILLCOLORS[p] = getMunsellColor(PALETTECOLORS[p][0], PALETTECOLORS[p][1], PALETTECOLORS[p][2]);
PALETTESTROKECOLORS[p] = getMunsellColor(PALETTECOLORS[p][0], PALETTECOLORS[p][1] - 30, PALETTECOLORS[p][2]);
PALETTEHIGHLIGHTCOLORS[p] = getMunsellColor(PALETTECOLORS[p][0], PALETTECOLORS[p][1] + 10, PALETTECOLORS[p][2]);
HIGHLIGHTSTROKECOLORS[p] = getMunsellColor(PALETTECOLORS[p][0], PALETTECOLORS[p][1] - 50, PALETTECOLORS[p][2]);
// console.log(p + ' ' + PALETTEFILLCOLORS[p] + ' ' + PALETTESTROKECOLORS[p] + ' ' + PALETTEHIGHLIGHTCOLORS[p] + ' ' + HIGHLIGHTSTROKECOLORS[p]);
}
pluginObjs = {
'PALETTEPLUGINS': {},
'PALETTEFILLCOLORS': {},
'PALETTESTROKECOLORS': {},
'PALETTEHIGHLIGHTCOLORS': {},
'FLOWPLUGINS': {},
'ARGPLUGINS': {},
'BLOCKPLUGINS': {},
'ONLOAD': {},
'ONSTART': {},
'ONSTOP': {}
};
// Stacks of blocks saved in local storage
var macroDict = {};
var stopTurtleContainer = null;
var stopTurtleContainerX = 0;
var stopTurtleContainerY = 0;
var cameraID = null;
var toLang = null;
var fromLang = null;
// initial scroll position
var scrollX = 0;
var scrollY = 0;
// default values
var CAMERAVALUE = '##__CAMERA__##';
var VIDEOVALUE = '##__VIDEO__##';
var DEFAULTDELAY = 500; // milleseconds
var TURTLESTEP = -1; // Run in step-by-step mode
var blockscale = 2;
var blockscales = [1, 1.5, 2, 3, 4];
// Time when we hit run
var time = 0;
// Used by pause block
var waitTime = {};
// Used to track mouse state for mouse button block
var stageMouseDown = false;
var stageX = 0;
var stageY = 0;
var onXO = (screen.width == 1200 && screen.height == 900) || (screen.width == 900 && screen.height == 1200);
console.log('on XO? ' + onXO);
var cellSize = 55;
if (onXO) {
cellSize = 75;
}
;
var onscreenButtons = [];
var onscreenMenu = [];
var helpContainer = null;
var helpIdx = 0;
var HELPCONTENT = [
[_('Welcome to Music Blocks'), _('Music Blocks is a collection of manipulative tools for exploring fundamental musical concepts in an integrative and fun way.'), 'activity/activity-icon-mouse-color.svg'],
[_('Meet "Mr. Mouse!"'), _('Mr. Mouse is our Music Blocks conductor. Mr. Mouse encourages you to explore the Musical Blocks, the Matrix, and the Performance/Notation possibilities of Music Blocks. "Let\'s start our tour!" '), 'activity/activity-icon-mouse-color.svg'],
[_('Palette buttons'), _('This toolbar contains the palette buttons Matrix, Chunk, Perform, Tone, Turtle, and more). Click to show the palettes of blocks and drag blocks from the palettes onto the canvas to use them.'), 'images/icons.svg'],
[_('Run fast'), _('Click to run the project in fast mode.'), 'header-icons/fast-button.svg'],
[_('Run slow'), _('Click to run the project in slow mode.'), 'header-icons/slow-button.svg'],
[_('Run music slow'), _('Click to run just the music in slow mode.'), 'header-icons/slow-music-button.svg'],
[_('Run step by step'), _('Click to run the project step by step.'), 'header-icons/step-button.svg'],
[_('Run note by note'), _('Click to run the music note by note.'), 'header-icons/step-music-button.svg'],
[_('Stop'), _('Stop the music (and the turtles).'), 'header-icons/stop-turtle-button.svg'],
[_('Clean'), _('Clear the screen and return the turtles to their initial positions.'), 'header-icons/clear-button.svg'],
[_('Show/hide palettes'), _('Hide or show the block palettes.'), 'header-icons/palette-button.svg'],
[_('Show/hide blocks'), _('Hide or show the blocks and the palettes.'), 'header-icons/hide-blocks-button.svg'],
[_('Expand/collapse collapsable blocks'), _('Expand or collapse start and action stacks.'), 'header-icons/collapse-blocks-button.svg'],
[_('Help'), _('Show these messages.'), 'header-icons/help-button.svg'],
[_('Expand/collapse option toolbar'), _('Click this button to expand or collapse the auxillary toolbar.'), 'header-icons/menu-button.svg'],
[_('Load samples from server'), _('This button opens a viewer for loading example projects.'), 'header-icons/planet-button.svg'],
[_('Copy'), _('The copy button copies a stack to the clipboard. It appears after a "long press" on a stack.'), 'header-icons/copy-button.svg'],
[_('Paste'), _('The paste button is enabled when there are blocks copied onto the clipboard.'), 'header-icons/paste-disabled-button.svg'],
[_('Save stack'), _('The save-stack button saves a stack onto a custom palette. It appears after a "long press" on a stack.'), 'header-icons/save-blocks-button.svg'],
[_('Cartesian'), _('Show or hide a Cartesian-coordinate grid.'), 'header-icons/Cartesian-button.svg'],
[_('Polar'), _('Show or hide a polar-coordinate grid.'), 'header-icons/polar-button.svg'],
[_('Settings'), _('Open a panel for configuring Turtle Blocks.'), 'header-icons/utility-button.svg'],
[_('Decrease block size'), _('Decrease the size of the blocks.'), 'header-icons/smaller-button.svg'],
[_('Increase block size'), _('Increase the size of the blocks.'), 'header-icons/bigger-button.svg'],
[_('Display statistics'), _('Display statistics about your Turtle project.'), 'header-icons/chart-button.svg'],
[_('Load plugin from file'), _('You can load new blocks from the file system.'), 'header-icons/plugin-button.svg'],
[_('Enable scrolling'), _('You can scroll the blocks on the canvas.'), 'header-icons/scroll-button.svg'],
[_('Delete all'), _('Remove all content on the canvas, including the blocks.'), 'header-icons/empty-trash-button.svg'],
[_('Undo'), _('Restore blocks from the trash.'), 'header-icons/restore-trash-button.svg'],
[_('Congratulations.'), _('You have finished the tour. Please enjoy Music Blocks!'), 'activity/activity-icon-color.svg']
]
pluginsImages = {};
function allClear() {
if (chartBitmap != null) {
stage.removeChild(chartBitmap);
chartBitmap = null;
}
logo.boxes = {};
logo.time = 0;
hideMsgs();
logo.setBackgroundColor(-1);
logo.lilypondOutput = LILYPONDHEADER;
for (var turtle = 0; turtle < turtles.turtleList.length; turtle++) {
logo.lilypondStaging[turtle] = [];
turtles.turtleList[turtle].doClear();
}
blocksContainer.x = 0;
blocksContainer.y = 0;
// Code specific to cleaning up music blocks
Element.prototype.remove = function() {
this.parentElement.removeChild(this);
}
NodeList.prototype.remove = HTMLCollection.prototype.remove = function() {
for(var i = 0, len = this.length; i < len; i++) {
if(this[i] && this[i].parentElement) {
this[i].parentElement.removeChild(this[i]);
}
}
}
var table = document.getElementById("myTable");
if(table != null) {
table.remove();
}
var canvas = document.getElementById("music");
var context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
document.getElementById('musicNotation').innerHTML = "";
document.getElementById('musicNotation').style.display = 'none';
if(musicnotation != null && musicnotation.musicContainer) {
musicnotation.musicContainer.removeAllChildren();
musicnotation.notationIndex = 0;
}
}
function doFastButton(env) {
logo.setTurtleDelay(0);
if (!turtles.running()) {
logo.runLogoCommands(null, env);
} else {
logo.step(null, env);
}
}
function doSlowButton() {
logo.setTurtleDelay(DEFAULTDELAY);
if (!turtles.running()) {
logo.runLogoCommands();
} else {
logo.step();
}
}
function doStepButton() {
var turtleCount = 0;
for (var turtle in logo.stepQueue) {
turtleCount += 1;
}
if (turtleCount == 0 || logo.turtleDelay != TURTLESTEP) {
// Either we haven't set up a queue or we are
// switching modes.
logo.setTurtleDelay(TURTLESTEP);
// Queue and take first step.
if (!turtles.running()) {
logo.runLogoCommands();
}
logo.step();
} else {
logo.setTurtleDelay(TURTLESTEP);
logo.step();
}
}
function doSlowMusicButton() {
logo.setNoteDelay(DEFAULTDELAY);
if (!turtles.running()) {
logo.runLogoCommands();
} else {
logo.stepNotes();
}
}
function doStepMusicButton() {
var turtleCount = 0;
for (var turtle in logo.stepQueue) {
turtleCount += 1;
}
if (turtleCount == 0 || logo.TurtleDelay != TURTLESTEP) {
// Either we haven't set up a queue or we are
// switching modes.
logo.setTurtleDelay(TURTLESTEP);
// Queue and take first step.
if (!turtles.running()) {
logo.runLogoCommands();
}
logo.stepNote();
} else {
logo.setTurtleDelay(TURTLESTEP);
logo.stepNote();
}
}
var stopTurtle = false;
function doStopButton() {
logo.doStopTurtle();
}
var cartesianVisible = false;
function doCartesian() {
if (cartesianVisible) {
hideCartesian();
cartesianVisible = false;
} else {
showCartesian();
cartesianVisible = true;
}
}
var polarVisible = false;
function doPolar() {
if (polarVisible) {
hidePolar();
polarVisible = false;
} else {
showPolar();
polarVisible = true;
}
}
function toggleScroller() {
scrollBlockContainer = !scrollBlockContainer;
}
function doAnalytics() {
document.body.style.cursor = 'wait';
var myChart = docById('myChart');
var ctx = myChart.getContext('2d');
var myRadarChart = null;
var scores = analyzeProject(blocks);
console.log(scores);
var data = scoreToChartData(scores);
var callback = function () {
var imageData = myRadarChart.toBase64Image();
var img = new Image();
img.onload = function () {
chartBitmap = new createjs.Bitmap(img);
stage.addChild(chartBitmap);
chartBitmap.x = (canvas.width / (2 * musicBlocksScale)) - (300);
chartBitmap.y = 0;
chartBitmap.scaleX = chartBitmap.scaleY = chartBitmap.scale = 600 / chartBitmap.image.width;
logo.hideBlocks();
update = true;
document.body.style.cursor = 'default';
};
img.src = imageData;
}
var options = getChartOptions(callback);
console.log('creating new chart');
myRadarChart = new Chart(ctx).Radar(data, options);
}
function doBiggerFont() {
if (blockscale < blockscales.length - 1) {
blockscale += 1;
blocks.setBlockScale(blockscales[blockscale]);
}
}
function doSmallerFont() {
if (blockscale > 0) {
blockscale -= 1;
blocks.setBlockScale(blockscales[blockscale]);
}
}
// Do we need to update the stage?
var update = true;
// The dictionary of action name: block
var actions = {};
// The dictionary of box name: value
var boxes = {};
// Coordinate grid
var cartesianBitmap = null;
// Polar grid
var polarBitmap = null;
// Msg block
var msgText = null;
// ErrorMsg block
var errorMsgText = null;
var errorMsgArrow = null;
var errorArtwork = {};
var ERRORARTWORK = ['emptybox', 'emptyheap', 'negroot', 'noinput', 'zerodivide', 'notanumber', 'nostack', 'notastring', 'nomicrophone'];
// Get things started
init();
function init() {
docById('loader').className = 'loader';
stage = new createjs.Stage(canvas);
createjs.Touch.enable(stage);
createjs.Ticker.timingMode = createjs.Ticker.RAF_SYNCHED;
createjs.Ticker.setFPS(30);
createjs.Ticker.addEventListener('tick', stage);
createjs.Ticker.addEventListener('tick', tick);
createMsgContainer('#ffffff', '#7a7a7a', function (text) {
msgText = text;
}, 55);
createMsgContainer('#ffcbc4', '#ff0031', function (text) {
errorMsgText = text;
}, 110);
createErrorContainers();
/* Z-Order (top to bottom):
* menus
* palettes
* blocks
* trash
* turtles
* logo (drawing)
*/
palettesContainer = new createjs.Container();
blocksContainer = new createjs.Container();
trashContainer = new createjs.Container();
turtleContainer = new createjs.Container();
stage.addChild(turtleContainer, trashContainer, blocksContainer,
palettesContainer);
setupBlocksContainerEvents();
trashcan = new Trashcan(canvas, trashContainer, cellSize, refreshCanvas);
turtles = new Turtles(canvas, turtleContainer, refreshCanvas);
blocks = new Blocks(canvas, blocksContainer, refreshCanvas, trashcan, stage.update);
palettes = initPalettes(canvas, refreshCanvas, palettesContainer, cellSize, refreshCanvas, trashcan, blocks);
musicnotation = new MusicNotation(turtles, stage);
matrix = new Matrix();
palettes.setBlocks(blocks);
turtles.setBlocks(blocks);
blocks.setTurtles(turtles);
blocks.setErrorMsg(errorMsg);
blocks.makeCopyPasteButtons(makeButton, updatePasteButton);
// TODO: clean up this mess.
logo = new Logo(matrix, musicnotation, canvas,
blocks, turtles, turtleContainer, refreshCanvas,
textMsg, errorMsg, hideMsgs, onStopTurtle,
onRunTurtle, getStageX, getStageY,
getStageMouseDown, getCurrentKeyCode,
clearCurrentKeyCode, meSpeak, saveLocally);
blocks.setLogo(logo);
// Set the default background color...
logo.setBackgroundColor(-1);
clearBox = new ClearBox(canvas, stage, refreshCanvas, sendAllToTrash);
utilityBox = new UtilityBox(canvas, stage, refreshCanvas, doBiggerFont, doSmallerFont, doOpenPlugin, doAnalytics, toggleScroller);
thumbnails = new SamplesViewer(canvas, stage, refreshCanvas, loadProject, loadRawProject, sendAllToTrash);
initBasicProtoBlocks(palettes, blocks);
// Load any macros saved in local storage.
macroData = storage.macros
if (macroData != null) {
processMacroData(macroData, palettes, blocks, macroDict);
}
// Blocks and palettes need access to the macros dictionary.
blocks.setMacroDictionary(macroDict);
palettes.setMacroDictionary(macroDict);
// Load any plugins saved in local storage.
pluginData = storage.plugins;
if (pluginData != null) {
var obj = processPluginData(pluginData, palettes, blocks, logo.evalFlowDict, logo.evalArgDict, logo.evalParameterDict, logo.evalSetterDict, logo.evalOnStartList, logo.evalOnStopList);
updatePluginObj(obj);
}
fileChooser.addEventListener('click', function (event) {
this.value = null;
});
fileChooser.addEventListener('change', function (event) {
// Read file here.
var reader = new FileReader();
reader.onload = (function (theFile) {
// Show busy cursor.
document.body.style.cursor = 'wait';
setTimeout(function () {
var rawData = reader.result;
var cleanData = rawData.replace('\n', ' ');
console.log(cleanData);
var obj = JSON.parse(cleanData);
console.log(obj)
blocks.loadNewBlocks(obj);
// Restore default cursor.
document.body.style.cursor = 'default';
}, 200);
});
reader.readAsText(fileChooser.files[0]);
}, false);
allFilesChooser.addEventListener('click', function (event) {
this.value = null;
});
pluginChooser.addEventListener('click', function (event) {
window.scroll(0, 0);
this.value = null;
});
pluginChooser.addEventListener('change', function (event) {
window.scroll(0, 0)
// Read file here.
var reader = new FileReader();
reader.onload = (function (theFile) {
// Show busy cursor.
document.body.style.cursor = 'wait';
setTimeout(function () {
obj = processRawPluginData(reader.result, palettes, blocks, errorMsg, logo.evalFlowDict, logo.evalArgDict, logo.evalParameterDict, logo.evalSetterDict, logo.evalOnStartList, logo.evalOnStopList);
// Save plugins to local storage.
if (obj != null) {
var foo = preparePluginExports(obj);
console.log(foo);
storage.plugins = foo; // preparePluginExports(obj));
}
// Refresh the palettes.
setTimeout(function () {
if (palettes.visible) {
palettes.hide();
}
palettes.show();
palettes.bringToTop();
}, 1000);
// Restore default cursor.
document.body.style.cursor = 'default';
}, 200);
});
reader.readAsText(pluginChooser.files[0]);
}, false);
// Workaround to chrome security issues
// createjs.LoadQueue(true, null, true);
// Enable touch interactions if supported on the current device.
// FIXME: voodoo
// createjs.Touch.enable(stage, false, true);
// Keep tracking the mouse even when it leaves the canvas.
stage.mouseMoveOutside = true;
// Enabled mouse over and mouse out events.
stage.enableMouseOver(10); // default is 20
cartesianBitmap = createGrid('images/Cartesian.svg');
polarBitmap = createGrid('images/polar.svg');
var URL = window.location.href;
var projectName = null;
var runProjectOnLoad = false;
try {
httpGet(null);
console.log('running from server or the user can access to examples.');
server = true;
} catch (e) {
console.log('running from filesystem or the connection isnt secure');
server = false;
}
setupAndroidToolbar();
// Scale the canvas relative to the screen size.
onResize();
var urlParts;
var env = [];
if (!sugarizerCompatibility.isInsideSugarizer() && URL.indexOf('?') > 0) {
var urlParts = URL.split('?');
if (urlParts[1].indexOf('&') > 0) {
var newUrlParts = urlParts[1].split('&');
for (var i = 0; i < newUrlParts.length; i++) {
if (newUrlParts[i].indexOf('=') > 0) {
var args = newUrlParts[i].split('=');
switch (args[0].toLowerCase()) {
case 'file':
projectName = args[1];
break;
case 'run':
if (args[1].toLowerCase() == 'true')
runProjectOnLoad = true;
break;
case 'inurl':
var url = args[1];
var getJSON = function (url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
getJSON(url).then(function (data) {
console.log('Your Json result is: ' + data.arg); //you can comment this, i used it to debug
n = data.arg;
env.push(parseInt(n));
}, function (status) { //error detection....
alert('Something went wrong.');
});
break;
case 'outurl':
var url = args[1];
break;
default:
errorMsg("Invalid parameters");
}
}
}
} else {
if (urlParts[1].indexOf('=') > 0)
var args = urlParts[1].split('=');
//File is the only arg that can stand alone
if (args[0].toLowerCase() == 'file') {
projectName = args[1];
}
}
}
if (projectName != null) {
setTimeout(function () {
console.log('load ' + projectName);
loadProject(projectName, runProjectOnLoad, env);
}, 2000);
} else {
setTimeout(function () {
loadStart();
}, 2000);
}
document.addEventListener('mousewheel', scrollEvent, false);
document.addEventListener('DOMMouseScroll', scrollEvent, false);
this.document.onkeydown = keyPressed;
}
function setupBlocksContainerEvents() {
var moving = false;
stage.on('stagemousemove', function (event) {
stageX = event.stageX;
stageY = event.stageY;
});
stage.on('stagemousedown', function (event) {
stageMouseDown = true;
if (stage.getObjectUnderPoint() !== null | turtles.running()) {
stage.on('stagemouseup', function (event) {
stageMouseDown = false;
});
return;
}
moving = true;
lastCords = {
x: event.stageX,
y: event.stageY
};
stage.on('stagemousemove', function (event) {
if (!moving) {
return;
}
if (scrollBlockContainer) {
blocksContainer.x += event.stageX - lastCords.x;
blocksContainer.y += event.stageY - lastCords.y;
lastCords = {
x: event.stageX,
y: event.stageY
};
refreshCanvas();
}
});
stage.on('stagemouseup', function (event) {
stageMouseDown = false;
moving = false;
}, null, true); // once = true
});
}
function scrollEvent(event) {
var data = event.wheelDelta || -event.detail;
var delta = Math.max(-1, Math.min(1, (data)));
var scrollSpeed = 3;
if (event.clientX < cellSize) {
palettes.menuScrollEvent(delta, scrollSpeed);
} else {
palette = palettes.findPalette(event.clientX / musicBlocksScale, event.clientY / musicBlocksScale);
if (palette) {
palette.scrollEvent(delta, scrollSpeed);
}
}
}
function getStageX() {
return turtles.screenX2turtleX(stageX / musicBlocksScale); // blocks.blocksScale); //music Blocks Scale???
}
function getStageY() {
return turtles.screenY2turtleY(stageY / musicBlocksScale); // blocks.blocksScale);
}
function getStageMouseDown() {
return stageMouseDown;
}
function setCameraID(id) {
cameraID = id;
}
function createGrid(imagePath) {
var img = new Image();
img.src = imagePath;
var container = new createjs.Container();
stage.addChild(container);
bitmap = new createjs.Bitmap(img);
container.addChild(bitmap);
bitmap.cache(0, 0, 1200, 900);
bitmap.x = (canvas.width - 1200) / 2;
bitmap.y = (canvas.height - 900) / 2;
bitmap.scaleX = bitmap.scaleY = bitmap.scale = 1;
bitmap.visible = false;
bitmap.updateCache();
return bitmap;
};
function createMsgContainer(fillColor, strokeColor, callback, y) {
var container = new createjs.Container();
stage.addChild(container);
container.x = (canvas.width - 1000) / 2;
container.y = y;
container.visible = false;
var img = new Image();
var svgData = MSGBLOCK.replace('fill_color', fillColor).replace(
'stroke_color', strokeColor);
img.onload = function () {
var msgBlock = new createjs.Bitmap(img);
container.addChild(msgBlock);
text = new createjs.Text('your message here',
'20px Arial', '#000000');
container.addChild(text);
text.textAlign = 'center';
text.textBaseline = 'alphabetic';
text.x = 500;
text.y = 30;
var bounds = container.getBounds();
container.cache(bounds.x, bounds.y, bounds.width, bounds.height);
var hitArea = new createjs.Shape();
hitArea.graphics.beginFill('#FFF').drawRect(0, 0, 1000, 42);
hitArea.x = 0;
hitArea.y = 0;
container.hitArea = hitArea;
container.on('click', function (event) {
container.visible = false;
// On the possibility that there was an error
// arrow associated with this container
if (errorMsgArrow !== null) {
errorMsgArrow.removeAllChildren(); // Hide the error arrow.
}
update = true;
});
callback(text);
blocks.setMsgText(text);
}
img.src = 'data:image/svg+xml;base64,' + window.btoa(
unescape(encodeURIComponent(svgData)));
};
function createErrorContainers() {
// Some error messages have special artwork.
for (var i = 0; i < ERRORARTWORK.length; i++) {
var name = ERRORARTWORK[i];
makeErrorArtwork(name);
}
}
function makeErrorArtwork(name) {
var container = new createjs.Container();
stage.addChild(container);
container.x = (canvas.width - 1000) / 2;
container.y = 110;
errorArtwork[name] = container;
errorArtwork[name].name = name;
errorArtwork[name].visible = false;
var img = new Image();
img.onload = function () {
console.log('creating error message artwork for ' + img.src);
var artwork = new createjs.Bitmap(img);
container.addChild(artwork);
var text = new createjs.Text('', '20px Sans', '#000000');
container.addChild(text);
text.x = 70;
text.y = 10;
var bounds = container.getBounds();
container.cache(bounds.x, bounds.y, bounds.width, bounds.height);
var hitArea = new createjs.Shape();
hitArea.graphics.beginFill('#FFF').drawRect(0, 0, bounds.width, bounds.height);
hitArea.x = 0;
hitArea.y = 0;
container.hitArea = hitArea;
container.on('click', function (event) {
container.visible = false;
// On the possibility that there was an error
// arrow associated with this container
if (errorMsgArrow !== null) {
errorMsgArrow.removeAllChildren(); // Hide the error arrow.
}
update = true;
});
}
img.src = 'images/' + name + '.svg';
}
function keyPressed(event) {
if (docById('labelDiv').classList.contains('hasKeyboard')) {
return;
}
var TAB = 9;
var ESC = 27;
var ALT = 18;
var CTRL = 17;
var SHIFT = 16;
var RETURN = 13;
var SPACE = 32;
// Captured by browser
var PAGE_UP = 33;
var PAGE_DOWN = 34;
var KEYCODE_LEFT = 37;
var KEYCODE_RIGHT = 39;
var KEYCODE_UP = 38;
var KEYCODE_DOWN = 40;
if (event.altKey) {
switch (event.keyCode) {
case 69: // 'E'
allClear();
break;
case 82: // 'R'
doFastButton();
break;
case 83: // 'S'
logo.doStopTurtle();
break;
}
} else if (event.ctrlKey) {
} else {
switch (event.keyCode) {
case TAB:
break;
case ESC:
// toggle full screen
toggleToolbar();
break
case RETURN:
// toggle run
logo.runLogoCommands();
break
default:
currentKey = String.fromCharCode(event.keyCode);
currentKeyCode = event.keyCode;
break;
}
}
}
function getCurrentKeyCode() {
return currentKeyCode;
}
function clearCurrentKeyCode() {
currentKey = '';
currentKeyCode = 0;
}
function onResize() {
if (docById('labelDiv').classList.contains('hasKeyboard')) {
return;
}
if (!platform.androidWebkit) {
var w = window.innerWidth;
var h = window.innerHeight;
} else {
var w = window.outerWidth;
var h = window.outerHeight;
}
var smallSide = Math.min(w, h);
if (smallSide < cellSize * 11) {
var mobileSize = true;
if (w < cellSize * 10) {
musicBlocksScale = smallSide / (cellSize * 11);
} else {
musicBlocksScale = Math.max(smallSide / (cellSize * 11), 0.75);
}
} else {
var mobileSize = false;
if (w > h) {
musicBlocksScale = w / 1200;
} else {
musicBlocksScale = w / 900;
}
}
stage.scaleX = musicBlocksScale;
stage.scaleY = musicBlocksScale;
stage.canvas.width = w;
stage.canvas.height = h;
console.log('Resize: scale ' + musicBlocksScale +
', windowW ' + w + ', windowH ' + h +
', canvasW ' + canvas.width + ', canvasH ' + canvas.height +
', screenW ' + screen.width + ', screenH ' + screen.height);
turtles.setScale(musicBlocksScale);
blocks.setScale(musicBlocksScale);
palettes.setScale(musicBlocksScale);
trashcan.resizeEvent(musicBlocksScale);
setupAndroidToolbar(mobileSize);
// Reposition coordinate grids.
cartesianBitmap.x = (canvas.width / (2 * musicBlocksScale)) - (600);
cartesianBitmap.y = (canvas.height / (2 * musicBlocksScale)) - (450);
polarBitmap.x = (canvas.width / (2 * musicBlocksScale)) - (600);
polarBitmap.y = (canvas.height / (2 * musicBlocksScale)) - (450);
update = true;
// Setup help now that we have calculated musicBlocksScale.
showHelp(true);
// Hide palette icons on mobile
if (mobileSize) {
palettes.hide();
} else {
palettes.show();
palettes.bringToTop();
}
// Music stuff
if (matrix.isMatrix == 1) {
matrixTable = document.getElementById("myTable");
if (matrixTable) {
matrixTable.setAttribute("width", w/2 + 'px');
}
}
}
window.onresize = function () {
onResize();
}
function restoreTrash() {
var dx = 0;
var dy = -cellSize * 3; // Reposition blocks about trash area.
for (var blk in blocks.blockList) {
if (blocks.blockList[blk].trash) {
blocks.blockList[blk].trash = false;
blocks.moveBlockRelative(blk, dx, dy);
blocks.blockList[blk].show();
if (blocks.blockList[blk].name == 'start' || blocks.blockList[blk].name == 'drum') {
turtle = blocks.blockList[blk].value;
turtles.turtleList[turtle].trash = false;
turtles.turtleList[turtle].container.visible = true;
}
}
}
update = true;
}
function deleteBlocksBox() {
clearBox.show(musicBlocksScale);
}
function doUtilityBox() {
utilityBox.show(musicBlocksScale);
}
// FIXME: confirm???
function sendAllToTrash(addStartBlock, doNotSave) {
var dx = 0;
var dy = cellSize * 3;
for (var blk in blocks.blockList) {
blocks.blockList[blk].trash = true;
blocks.moveBlockRelative(blk, dx, dy);
blocks.blockList[blk].hide();
if (blocks.blockList[blk].name == 'start' || blocks.blockList[blk].name == 'drum') {
console.log('start blk ' + blk + ' value is ' + blocks.blockList[blk].value)
turtle = blocks.blockList[blk].value;
if (turtle != null) {
console.log('sending turtle ' + turtle + ' to trash');
turtles.turtleList[turtle].trash = true;
turtles.turtleList[turtle].container.visible = false;
}
}
}
if (addStartBlock) {
var dataObjs = [[0, 'start', 250, 150, [null, null, null]],
[1, 'matrix', 450, 150, [null, 2, null]],
[2, 'pitch', 0, 0, [1, 3, 4, 5]],
[3, ['solfege', {value:'sol'}], 0, 0, [2]],
[4, ['number', {value:'4'}], 0, 0, [2]],
[5, 'pitch', 0, 0, [2, 6, 7, 8]],
[6, ['solfege', {value:'mi'}], 0, 0, [5]],
[7, ['number', {value:'4'}], 0, 0, [5]],
[8, 'pitch', 0, 0, [5, 9, 10, 11]],
[9, ['solfege', {value:'re'}], 0, 0, [8]],
[10, ['number', {value:'4'}], 0, 0, [8]],
[11, 'rhythm', 0, 0, [8, 12, 13, null]],
[12, ['number', {value:'3'}], 0, 0, [11]],
[13, ['number', {value:'4'}], 0, 0, [11]]];
blocks.loadNewBlocks(dataObjs);
} else if (!doNotSave) {
// Overwrite session data too.
saveLocally();
}
update = true;
}
function changePaletteVisibility() {
if (palettes.visible) {
palettes.hide();
} else {
palettes.show();
palettes.bringToTop();
}
}
function changeBlockVisibility() {
if (blocks.visible) {
logo.hideBlocks();
} else {
if (chartBitmap != null) {
stage.removeChild(chartBitmap);
chartBitmap = null;
}
logo.showBlocks();
}
}
function saveMusicNotations() {
var canvas = document.getElementById("canvasToSave");
var img = canvas.toDataURL("image/png");
//document.write('<img src="'+img+'"/>');*/
var link = document.createElement('a');
link.href = img;
link.download = 'Download.png';
document.body.appendChild(link);
link.click();
}
function toggleCollapsibleStacks() {
if (blocks.visible) {
console.log('calling toggleCollapsibles');
blocks.toggleCollapsibles();
}
}
function stop() {
// FIXME: who calls this???
createjs.Ticker.removeEventListener('tick', tick);
}
function onStopTurtle() {
// TODO: plugin support
if (!buttonsVisible) {
hideStopButton();
}
}
function onRunTurtle() {
// TODO: plugin support
// If the stop button is hidden, show it.
if (!buttonsVisible) {
showStopButton();
}
}
function refreshCanvas() {
update = true;
}
function tick(event) {
// This set makes it so the stage only re-renders when an
// event handler indicates a change has happened.
if (update) {
update = false; // Only update once
stage.update(event);
}
}
function doOpenSamples() {
console.log('save locally');
saveLocally();
thumbnails.show()
}
window.prepareExport = prepareExport
window.saveLocally = saveLocally
function saveLocally() {
if (sugarizerCompatibility.isInsideSugarizer()) {
//sugarizerCompatibility.data.blocks = prepareExport();
storage = sugarizerCompatibility.data;
} else {
storage = localStorage;
}
console.log('overwriting session data');
if (storage.currentProject === undefined) {
try {
storage.currentProject = 'My Project';
storage.allProjects = JSON.stringify(['My Project'])
} catch (e) {
// Edge case, eg. Firefox localSorage DB corrupted
console.log(e);
}
}
try {
var p = storage.currentProject;
storage['SESSION' + p] = prepareExport();
} catch (e) {
console.log(e);
}
// if (isSVGEmpty(turtles)) {
// We will use the music icon in these cases.
// return;
// }
var img = new Image();
var svgData = doSVG(canvas, logo, turtles, 320, 240, 320 / canvas.width);
img.onload = function () {
var bitmap = new createjs.Bitmap(img);
var bounds = bitmap.getBounds();
bitmap.cache(bounds.x, bounds.y, bounds.width, bounds.height);
try {
storage['SESSIONIMAGE' + p] = bitmap.getCacheDataURL();
} catch (e) {
console.log(e);
}
}
img.src = 'data:image/svg+xml;base64,' +
window.btoa(unescape(encodeURIComponent(svgData)));
// console.log(img.src);
if (sugarizerCompatibility.isInsideSugarizer()) {
sugarizerCompatibility.saveLocally();
}
}
function loadProject(projectName, run, env) {
//set default value of run
run = typeof run !== 'undefined' ? run : false;
// Show busy cursor.
document.body.style.cursor = 'wait';
// palettes.updatePalettes();
setTimeout(function () {
if (fileExt(projectName) != 'tb') {
projectName += '.tb';
}
try {
if (server) {
var rawData = httpGet(projectName);
console.log('receiving ' + rawData);
var cleanData = rawData.replace('\n', '');
}
var obj = JSON.parse(cleanData);
blocks.loadNewBlocks(obj);
console.log('save locally');
saveLocally();
} catch (e) {
console.log(e);
loadStart();
}
// Restore default cursor
document.body.style.cursor = 'default';
update = true;
}, 200);
if (run) {
setTimeout(function () {
changeBlockVisibility();
doFastButton(env);
}, 2000);
}
docById('loading-image-container').style.display = 'none';
}
function loadRawProject(data) {
console.log('loadRawProject ' + data);
document.body.style.cursor = 'wait';
allClear();
var obj = JSON.parse(data);
blocks.loadNewBlocks(obj);
docById('loading-image-container').style.display = 'none';
document.body.style.cursor = 'default';
}
function saveProject(projectName) {
// palettes.updatePalettes();
// Show busy cursor.
document.body.style.cursor = 'wait';
setTimeout(function () {
var punctuationless = projectName.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?@\[\\\]\^`{|}~']/g, '');
projectName = punctuationless.replace(/ /g, '_');
if (fileExt(projectName) != 'tb') {
projectName += '.tb';
}
try {
// Post the project
var returnValue = httpPost(projectName, prepareExport());
errorMsg('Saved ' + projectName + ' to ' + window.location.host);
var img = new Image();
var svgData = doSVG(canvas, logo, turtles, 320, 240, 320 / canvas.width);
img.onload = function () {
var bitmap = new createjs.Bitmap(img);
var bounds = bitmap.getBounds();
bitmap.cache(bounds.x, bounds.y, bounds.width, bounds.height);
// and base64-encoded png
httpPost(projectName.replace('.tb', '.b64'), bitmap.getCacheDataURL());
}
img.src = 'data:image/svg+xml;base64,' + window.btoa(
unescape(encodeURIComponent(svgData)));
// Restore default cursor
document.body.style.cursor = 'default';
return returnValue;
} catch (e) {
console.log(e);
// Restore default cursor
document.body.style.cursor = 'default';
return;
}
}, 200);
}
function loadStart() {
// where to put this?
// palettes.updatePalettes();
console.log(" LOAD START")
justLoadStart = function () {
console.log('loading start and a matrix');
var dataObjs = [[0, 'start', 250, 150, [null, null, null]],
[1, 'matrix', 450, 150, [null, 2, null]],
[2, 'pitch', 0, 0, [1, 3, 4, 5]],
[3, ['solfege', {value:'sol'}], 0, 0, [2]],
[4, ['number', {value:'4'}], 0, 0, [2]],
[5, 'pitch', 0, 0, [2, 6, 7, 8]],
[6, ['solfege', {value:'mi'}], 0, 0, [5]],
[7, ['number', {value:'4'}], 0, 0, [5]],
[8, 'pitch', 0, 0, [5, 9, 10, 11]],
[9, ['solfege', {value:'re'}], 0, 0, [8]],
[10, ['number', {value:'4'}], 0, 0, [8]],
[11, 'rhythm', 0, 0, [8, 12, 13, null]],
[12, ['number', {value:'3'}], 0, 0, [11]],
[13, ['number', {value:'4'}], 0, 0, [11]]];
blocks.loadNewBlocks(dataObjs);
}
if (sugarizerCompatibility.isInsideSugarizer()) {
storage = sugarizerCompatibility.data;
}
else {
storage = localStorage;
}
sessionData = null;
// Try restarting where we were when we hit save.
var currentProject = storage.currentProject;
sessionData = storage['SESSION' + currentProject];
if (sessionData) {
try {
if (sessionData == 'undefined' || sessionData == '[]') {
console.log('empty session found: loading start');
justLoadStart();
} else {
console.log('restoring session: ' + sessionData);
blocks.loadNewBlocks(JSON.parse(sessionData));
}
} catch (e) {
console.log(e);
}
} else {
justLoadStart();
}
update = true;
docById('loading-image-container').style.display = 'none';
}
function hideMsgs() {
errorMsgText.parent.visible = false;
if (errorMsgArrow !== null) {
errorMsgArrow.removeAllChildren();
refreshCanvas();
}
msgText.parent.visible = false;
for (var i in errorArtwork) {
errorArtwork[i].visible = false;
}
}
function textMsg(msg) {
if (msgText == null) {
// The container may not be ready yet... so do nothing
return;
}
var msgContainer = msgText.parent;
msgContainer.visible = true;
msgText.text = msg;
msgContainer.updateCache();
stage.setChildIndex(msgContainer, stage.getNumChildren() - 1);
}
function errorMsg(msg, blk, text) {
if (errorMsgText == null) {
// The container may not be ready yet... so do nothing
return;
}
if (blk !== undefined && blk !== null && !blocks.blockList[blk].collapsed) {
var fromX = (canvas.width - 1000) / 2;
var fromY = 128;
var toX = blocks.blockList[blk].x + blocksContainer.x;
var toY = blocks.blockList[blk].y + blocksContainer.y;
if (errorMsgArrow == null) {
errorMsgArrow = new createjs.Container();
stage.addChild(errorMsgArrow);
}
var line = new createjs.Shape();
errorMsgArrow.addChild(line);
line.graphics.setStrokeStyle(4).beginStroke('#ff0031').moveTo(fromX, fromY).lineTo(toX, toY);
stage.setChildIndex(errorMsgArrow, stage.getNumChildren() - 1);
var angle = Math.atan2(toX - fromX, fromY - toY) / Math.PI * 180;
var head = new createjs.Shape();
errorMsgArrow.addChild(head);
head.graphics.setStrokeStyle(4).beginStroke('#ff0031').moveTo(-10, 18).lineTo(0, 0).lineTo(10, 18);
head.x = toX;
head.y = toY;
head.rotation = angle;
}
switch (msg) {
case NOMICERRORMSG:
errorArtwork['nomicrophone'].visible = true;
stage.setChildIndex(errorArtwork['nomicrophone'], stage.getNumChildren() - 1);
break;
case NOSTRINGERRORMSG:
errorArtwork['notastring'].visible = true;
stage.setChildIndex(errorArtwork['notastring'], stage.getNumChildren() - 1);
break;
case EMPTYHEAPERRORMSG:
errorArtwork['emptyheap'].visible = true;
stage.setChildIndex(errorArtwork['emptyheap'], stage.getNumChildren() - 1);
break;
case NOSQRTERRORMSG:
errorArtwork['negroot'].visible = true;
stage.setChildIndex(errorArtwork['negroot'], stage.getNumChildren() - 1);
break;
case NOACTIONERRORMSG:
if (text == null) {
text = 'foo';
}
errorArtwork['nostack'].children[1].text = text;
errorArtwork['nostack'].visible = true;
errorArtwork['nostack'].updateCache();
stage.setChildIndex(errorArtwork['nostack'], stage.getNumChildren() - 1);
break;
case NOBOXERRORMSG:
if (text == null) {
text = 'foo';
}
errorArtwork['emptybox'].children[1].text = text;
errorArtwork['emptybox'].visible = true;
errorArtwork['emptybox'].updateCache();
stage.setChildIndex(errorArtwork['emptybox'], stage.getNumChildren() - 1);
break;
case ZERODIVIDEERRORMSG:
errorArtwork['zerodivide'].visible = true;
stage.setChildIndex(errorArtwork['zerodivide'], stage.getNumChildren() - 1);
break;
case NANERRORMSG:
errorArtwork['notanumber'].visible = true;
stage.setChildIndex(errorArtwork['notanumber'], stage.getNumChildren() - 1);
break;
case NOINPUTERRORMSG:
errorArtwork['noinput'].visible = true;
stage.setChildIndex(errorArtwork['noinput'], stage.getNumChildren() - 1);
break;
default:
var errorMsgContainer = errorMsgText.parent;
errorMsgContainer.visible = true;
errorMsgText.text = msg;
stage.setChildIndex(errorMsgContainer, stage.getNumChildren() - 1);
errorMsgContainer.updateCache();
break;
}
update = true;
}
function hideCartesian() {
cartesianBitmap.visible = false;
cartesianBitmap.updateCache();
update = true;
}
function showCartesian() {
cartesianBitmap.visible = true;
cartesianBitmap.updateCache();
update = true;
}
function hidePolar() {
polarBitmap.visible = false;
polarBitmap.updateCache();
update = true;
}
function showPolar() {
polarBitmap.visible = true;
polarBitmap.updateCache();
update = true;
}
function pasteStack() {
blocks.pasteStack();
}
function prepareExport() {
// We don't save blocks in the trash, so we need to
// consolidate the block list and remap the connections.
var blockMap = [];
var hasMatrixDataBlock = false;
for (var blk = 0; blk < blocks.blockList.length; blk++) {
var myBlock = blocks.blockList[blk];
if (myBlock.trash) {
// Don't save blocks in the trash.
continue;
}
blockMap.push(blk);
}
var data = [];
for (var blk = 0; blk < blocks.blockList.length; blk++) {
var myBlock = blocks.blockList[blk];
if (myBlock.trash) {
// Don't save blocks in the trash.
continue;
}
if (myBlock.isValueBlock() || myBlock.name == 'loadFile') {
// FIX ME: scale image if it exceeds a maximum size.
var args = {
'value': myBlock.value
};
} else if (myBlock.name == 'start' || myBlock.name == 'drum') {
// Find the turtle associated with this block.
turtle = turtles.turtleList[myBlock.value];
var args = {
'collapsed': myBlock.collapsed,
'xcor': turtle.x,
'ycor': turtle.y,
'heading': turtle.orientation,
'color': turtle.color,
'shade': turtle.value,
'pensize': turtle.stroke,
'grey': turtle.chroma
};
} else if (myBlock.name == 'action') {
var args = {
'collapsed': myBlock.collapsed
}
} else if (myBlock.name == 'namedbox') {
var args = {
'value': myBlock.privateData
}
} else if (myBlock.name == 'nameddo') {
var args = {
'value': myBlock.privateData
}
} else if (myBlock.name == 'nameddoArg') {
var args = {
'value': myBlock.privateData
}
} else if (myBlock.name == 'namedcalc') {
var args = {
'value': myBlock.privateData
}
} else if (myBlock.name == 'namedcalcArg') {
var args = {
'value': myBlock.privateData
}
} else if (myBlock.name == 'namedarg') {
var args = {
'value': myBlock.privateData
}
} else if (myBlock.name == 'matrixData') {
var args = {
'notes': window.savedMatricesNotes, 'count': window.savedMatricesCount
}
hasMatrixDataBlock = true;
} else {
var args = {}
}
connections = [];
for (var c = 0; c < myBlock.connections.length; c++) {
var mapConnection = blockMap.indexOf(myBlock.connections[c]);
if (myBlock.connections[c] == null || mapConnection == -1) {
connections.push(null);
} else {
connections.push(mapConnection);
}
}
data.push([blockMap.indexOf(blk), [myBlock.name, args], myBlock.container.x, myBlock.container.y, connections]);
}
return JSON.stringify(data);
}
function doOpenPlugin() {
// Click on the plugin open chooser in the DOM (.json).
pluginChooser.focus();
pluginChooser.click();
}
function saveToFile() {
var filename = prompt('Filename:');
if (fileExt(filename) != 'tb') {
filename += '.tb';
}
download(filename, 'data:text/plain;charset=utf-8,' + encodeURIComponent(prepareExport()));
};
function hideStopButton() {
stopTurtleContainer.x = stopTurtleContainerX;
stopTurtleContainer.y = stopTurtleContainerY;
stopTurtleContainer.visible = false;
}
function showStopButton() {
stopTurtleContainer.x = onscreenButtons[0].x;
stopTurtleContainer.y = onscreenButtons[0].y;
stopTurtleContainer.visible = true;
}
function playMusic(){
for (var blk in logo.blocks.blockList) {
var myBlock = logo.blocks.blockList[blk];
var thisBlock = myBlock.blocks.blockList.indexOf(myBlock);
if (myBlock.name == 'start' || myBlock.name == 'drum') {
var topBlock = logo.blocks.findTopBlock(thisBlock);
console.log('Playing through Play Button');
logo.runLogoCommands(topBlock);
}
}
}
function stopMusic() {
logo.doStopTurtle();
Tone.Transport.stop();
}
function updatePasteButton() {
pasteContainer.removeChild(pasteContainer.children[0]);
var img = new Image();
img.onload = function () {
var originalSize = 55; // this is the original svg size
var halfSize = Math.floor(cellSize / 2);
bitmap = new createjs.Bitmap(img);
if (cellSize != originalSize) {
bitmap.scaleX = cellSize / originalSize;
bitmap.scaleY = cellSize / originalSize;
}
bitmap.regX = halfSize / bitmap.scaleX;
bitmap.regY = halfSize / bitmap.scaleY;
pasteContainer.addChild(bitmap)
update = true;
}
img.src = 'header-icons/paste-button.svg';
}
function setupAndroidToolbar(showPalettesPopover) {
if (headerContainer !== undefined) {
stage.removeChild(headerContainer);
for (i in onscreenButtons) {
stage.removeChild(onscreenButtons[i]);
}
}
headerContainer = new createjs.Shape();
headerContainer.graphics.f(platformColor.header).r(0, 0,
screen.width / musicBlocksScale, cellSize);
if (platformColor.doHeaderShadow) {
headerContainer.shadow = new createjs.Shadow('#777', 0, 2, 2);
}
stage.addChild(headerContainer);
// Buttons used when running turtle programs
var buttonNames = [
['fast', doFastButton],
['slow', doSlowButton],
['step', doStepButton],
['slow-music', doSlowMusicButton],
// ['step-music', doStepMusicButton],
['stop-turtle', doStopButton],
['clear', allClear],
['palette', changePaletteVisibility],
['hide-blocks', changeBlockVisibility],
['collapse-blocks', toggleCollapsibleStacks],
['help', showHelp]
];
if (sugarizerCompatibility.isInsideSugarizer()) {
buttonNames.push(['sugarizer-stop', function () {
sugarizerCompatibility.data.blocks = prepareExport();
sugarizerCompatibility.saveLocally(function () {
sugarizerCompatibility.sugarizerStop();
});
}])
}
if (showPalettesPopover) {
buttonNames.unshift(['popdown-palette', doPopdownPalette])
}
var btnSize = cellSize;
var x = Math.floor(btnSize / 2);
var y = x;
var dx = btnSize;
var dy = 0;
for (var name in buttonNames) {
var container = makeButton(buttonNames[name][0] + '-button',
x, y, btnSize);
loadButtonDragHandler(container, x, y, buttonNames[name][1]);
onscreenButtons.push(container);
if (buttonNames[name][0] == 'stop-turtle') {
stopTurtleContainer = container;
stopTurtleContainerX = x;
stopTurtleContainerY = y;
}
x += dx;
y += dy;
}
setupRightMenu(musicBlocksScale);
}
function setupRightMenu(musicBlocksScale) {
if (menuContainer !== undefined) {
stage.removeChild(menuContainer);
for (i in onscreenMenu) {
stage.removeChild(onscreenMenu[i]);
}
}
// Misc. other buttons
var menuNames = [
['planet', doOpenSamples],
['paste-disabled', pasteStack],
['Cartesian', doCartesian],
['polar', doPolar],
// ['bigger', doBiggerFont],
// ['smaller', doSmallerFont],
// ['plugin', doOpenPlugin],
['utility', doUtilityBox],
['empty-trash', deleteBlocksBox],
['restore-trash', restoreTrash]
];
var btnSize = cellSize;
var x = Math.floor(canvas.width / musicBlocksScale) - btnSize / 2;
var y = Math.floor(btnSize / 2);
var dx = 0;
var dy = btnSize;
menuContainer = makeButton('menu-button', x, y, btnSize,
menuButtonsVisible ? 90 : undefined);
loadButtonDragHandler(menuContainer, x, y, doMenuButton);
for (var name in menuNames) {
x += dx;
y += dy;
var container = makeButton(menuNames[name][0] + '-button',
x, y, btnSize);
loadButtonDragHandler(container, x, y, menuNames[name][1]);
onscreenMenu.push(container);
container.visible = false;
}
if (menuButtonsVisible) {
for (button in onscreenMenu) {
onscreenMenu[button].visible = true;
}
}
}
function doPopdownPalette() {
var p = new PopdownPalette(palettes);
p.popdown();
}
function showHelp(firstTime) {
helpIdx = 0;
if (firstTime) {
if (helpContainer == null) {
helpContainer = new createjs.Container();
stage.addChild(helpContainer);
helpContainer.x = 65;
helpContainer.y = 65;
helpContainer.on('click', function (event) {
var bounds = helpContainer.getBounds();
if (event.stageY < helpContainer.y + bounds.height / 2) {
helpContainer.visible = false;
docById('helpElem').style.visibility = 'hidden';
} else {
helpIdx += 1;
if (helpIdx >= HELPCONTENT.length) {
helpIdx = 0;
}
var imageScale = 55 * musicBlocksScale;
helpElem.innerHTML = '<img src ="' + HELPCONTENT[helpIdx][2] + '" style="height:' + imageScale + 'px; width: auto"></img> <h2>' + HELPCONTENT[helpIdx][0] + '</h2><p>' + HELPCONTENT[helpIdx][1] + '</p>'
}
update = true;
});
var img = new Image();
img.onload = function () {
// console.log(musicBlocksScale);
bitmap = new createjs.Bitmap(img);
if (musicBlocksScale > 1) {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = musicBlocksScale;
} else {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = 1.125;
}
helpContainer.addChild(bitmap)
var bounds = helpContainer.getBounds();
var hitArea = new createjs.Shape();
hitArea.graphics.beginFill('#FFF').drawRect(bounds.x, bounds.y, bounds.width, bounds.height);
hitArea.x = 0;
hitArea.y = 0;
helpContainer.hitArea = hitArea;
docById('helpElem').innerHTML = '<img src ="' + HELPCONTENT[helpIdx][2] + '"</img> <h2>' + HELPCONTENT[helpIdx][0] + '</h2><p>' + HELPCONTENT[helpIdx][1] + '</p>'
if (!doneTour) {
docById('helpElem').style.visibility = 'visible';
}
update = true;
}
img.src = 'images/help-container.svg';
}
var helpElem = docById('helpElem');
helpElem.style.position = 'absolute';
helpElem.style.display = 'block';
helpElem.style.paddingLeft = 20 * musicBlocksScale + 'px';
helpElem.style.paddingRight = 20 * musicBlocksScale + 'px';
helpElem.style.paddingTop = '0px';
helpElem.style.paddingBottom = 20 * musicBlocksScale + 'px';
helpElem.style.fontSize = 20 * musicBlocksScale + 'px';
helpElem.style.color = '#ffffff';
helpElem.style.left = 65 * musicBlocksScale + 'px';
helpElem.style.top = 105 * musicBlocksScale + 'px';
var w = Math.min(300, 300 * musicBlocksScale);
var h = Math.min(300, 300 * musicBlocksScale);
helpElem.style.width = w + 'px';
helpElem.style.height = h + 'px';
if (musicBlocksScale > 1) {
bitmap.scaleX = bitmap.scaleY = bitmap.scale = musicBlocksScale;
}
}
doneTour = storage.doneTour === 'true'
if (firstTime && doneTour) {
docById('helpElem').style.visibility = 'hidden';
helpContainer.visible = false;
} else {
if (sugarizerCompatibility.isInsideSugarizer()) {
sugarizerCompatibility.data.doneTour = 'true'
} else {
storage.doneTour = 'true'
}
docById('helpElem').innerHTML = '<img src ="' + HELPCONTENT[helpIdx][2] + '"</img> <h2>' + HELPCONTENT[helpIdx][0] + '</h2><p>' + HELPCONTENT[helpIdx][1] + '</p>'
docById('helpElem').style.visibility = 'visible';
helpContainer.visible = true;
update = true;
// Make sure the palettes and the secondary menus are
// visible while help is shown.
palettes.show();
if (!menuButtonsVisible) {
doMenuAnimation(1);
}
}
}
function doMenuButton() {
doMenuAnimation(1);
}
function doMenuAnimation() {
var bitmap = last(menuContainer.children);
if (bitmap !== null) {
var r = bitmap.rotation;
createjs.Tween.get(bitmap)
.to({
rotation: r
})
.to({
rotation: r + 90
}, 500);
} else {
// Race conditions during load
setTimeout(doMenuAnimation, 50);
}
setTimeout(function () {
if (menuButtonsVisible) {
menuButtonsVisible = false;
for (button in onscreenMenu) {
onscreenMenu[button].visible = false;
}
} else {
menuButtonsVisible = true;
for (button in onscreenMenu) {
onscreenMenu[button].visible = true;
}
}
update = true;
}, 500);
}
function toggleToolbar() {
buttonsVisible = !buttonsVisible;
menuContainer.visible = buttonsVisible;
headerContainer.visible = buttonsVisible;
for (button in onscreenButtons) {
onscreenButtons[button].visible = buttonsVisible;
}
for (button in onscreenMenu) {
onscreenMenu[button].visible = buttonsVisible;
}
update = true;
}
function makeButton(name, x, y, size, rotation) {
var container = new createjs.Container();
if (name == 'paste-disabled-button') {
pasteContainer = container;
}
stage.addChild(container);
container.x = x;
container.y = y;
var img = new Image();
img.onload = function () {
var originalSize = 55; // this is the original svg size
var halfSize = Math.floor(size / 2);
bitmap = new createjs.Bitmap(img);
if (size != originalSize) {
bitmap.scaleX = size / originalSize;
bitmap.scaleY = size / originalSize;
}
bitmap.regX = halfSize / bitmap.scaleX;
bitmap.regY = halfSize / bitmap.scaleY;
if (rotation !== undefined) {
bitmap.rotation = rotation;
}
container.addChild(bitmap);
var hitArea = new createjs.Shape();
hitArea.graphics.beginFill('#FFF').drawEllipse(-halfSize, -halfSize, size, size);
hitArea.x = 0;
hitArea.y = 0;
container.hitArea = hitArea;
bitmap.cache(0, 0, size, size);
bitmap.updateCache();
update = true;
}
img.src = 'header-icons/' + name + '.svg';
return container;
}
function loadButtonDragHandler(container, ox, oy, action) {
// Prevent multiple button presses (i.e., debounce).
var locked = false;
container.on('mousedown', function (event) {
var moved = true;
var offset = {
x: container.x - Math.round(event.stageX / blocks.scale),
y: container.y - Math.round(event.stageY / blocks.scale)
};
var circles = showButtonHighlight(ox, oy, cellSize / 2,
event, musicBlocksScale, stage);
container.on('pressup', function (event) {
hideButtonHighlight(circles, stage);
container.x = ox;
container.y = oy;
if (action != null && moved && !locked) {
locked = true;
setTimeout(function () {
locked = false;
}, 500);
action();
}
moved = false;
});
});
}
// More music stuff we may not need
function clearMenus() {
if (headerContainer !== undefined) {
stage.removeChild(headerContainer);
for (i in onscreenButtons) {
stage.removeChild(onscreenButtons[i]);
}
}
if (menuContainer !== undefined) {
stage.removeChild(menuContainer);
for (i in onscreenMenu) {
stage.removeChild(onscreenMenu[i]);
}
}
}
function restoreHome() {
setupAndroidToolbar();
blocks.show();
for (var b = 0; b < blocks.blockList.length; b++) {
var blk = blocks.blockList[b];
if (blk.name == "forever" || blk.name == 'repeat' || blk.name == 'chunkTranspose') {
blocks.blockList[b].trash = true;
blocks.blockList[b].hide();
}
blocks.refreshCanvas();
palettes.show();
}
}
}
});
| khurtsidzecms/MusicBlocks | js/activity.js | JavaScript | agpl-3.0 | 81,754 |
builder.CreateFile("docx");
var oDocument = Api.GetDocument();
var oParagraph, oTable, oTableStyle, oCell, oTableCellPr;
oParagraph = oDocument.GetElement(0);
oParagraph.AddText("We create a 3x3 table and add the left 4 point blue border to all cells:");
oTableStyle = oDocument.CreateStyle("CustomTableStyle", "table");
oTable = Api.CreateTable(3, 3);
oTable.SetWidth("percent", 100);
oTableCellPr = oTableStyle.GetTableCellPr();
oTableCellPr.SetCellBorderLeft("single", 32, 0, 0, 0, 255);
oTable.SetStyle(oTableStyle);
oDocument.Push(oTable);
builder.SaveFile("docx", "SetCellBorderLeft.docx");
builder.CloseFile();
| ONLYOFFICE/doc-builder-testing | asserts/js/docx/smoke/api_table_cell_pr/set_cell_border_left.js | JavaScript | agpl-3.0 | 618 |
// Copyright 2016 Documize Inc. <legal@documize.com>. All rights reserved.
//
// This software (Documize Community Edition) is licensed under
// GNU AGPL v3 http://www.gnu.org/licenses/agpl-3.0.en.html
//
// You can operate outside the AGPL restrictions by purchasing
// Documize Enterprise Edition and obtaining a commercial license
// by contacting <sales@documize.com>.
//
// https://documize.com
import { inject as service } from '@ember/service';
import Component from '@ember/component';
export default Component.extend({
store: service(),
didReceiveAttrs() {
let p = this.get('store').createRecord('page');
let m = this.get('store').createRecord('pageMeta');
p.set('id', this.get('block.id'));
p.set('orgId', this.get('block.orgId'));
p.set('documentId', 'dummy');
p.set('contentType', this.get('block.contentType'));
p.set('pageType', this.get('block.pageType'));
p.set('title', this.get('block.title'));
p.set('body', this.get('block.body'));
p.set('rawBody', this.get('block.rawBody'));
p.set('excerpt', this.get('block.excerpt'));
m.set('pageId', this.get('block.id'));
m.set('orgId', this.get('block.orgId'));
m.set('documentId', 'dummy');
m.set('rawBody', this.get('block.rawBody'));
m.set('config', this.get('block.config'));
m.set('externalSource', this.get('block.externalSource'));
this.set('page', p);
this.set('meta', m);
this.set('editorType', 'section/' + this.get('block.contentType') + '/type-editor');
},
actions: {
onCancel() {
let cb = this.get('onCancel');
cb();
},
onAction(page, meta) {
let cb = this.get('onAction');
cb(page, meta);
}
}
});
| documize/community | gui/app/components/document/block-editor.js | JavaScript | agpl-3.0 | 1,687 |
/*globals describe before beforeEach afterEach it assert sinon ckan jQuery */
describe('ckan.module.CustomFieldsModule()', function () {
var CustomFieldsModule = ckan.module.registry['custom-fields'];
before(function (done) {
this.loadFixture('custom_fields.html', function (template) {
this.template = template;
done();
});
});
beforeEach(function () {
this.fixture.html(this.template);
this.el = this.fixture.find('[data-module]');
this.sandbox = ckan.sandbox();
this.sandbox.body = this.fixture;
this.module = new CustomFieldsModule(this.el, {}, this.sandbox);
});
afterEach(function () {
this.module.teardown();
});
describe('.initialize()', function () {
it('should bind all functions beginning with _on to the module scope', function () {
var target = sinon.stub(jQuery, 'proxyAll');
this.module.initialize();
assert.called(target);
assert.calledWith(target, this.module, /_on/);
target.restore();
});
it('should listen for changes to the last "key" input', function () {
var target = sinon.stub(this.module, '_onChange');
this.module.initialize();
this.module.$('input[name*=key]').change();
assert.calledOnce(target);
});
it('should listen for changes to all checkboxes', function () {
var target = sinon.stub(this.module, '_onRemove');
this.module.initialize();
this.module.$(':checkbox').trigger('change');
assert.calledOnce(target);
});
it('should add "button" classes to the remove input', function () {
this.module.initialize();
assert.equal(this.module.$('.checkbox.btn').length, 1, 'each item should have the .btn class');
assert.equal(this.module.$('.checkbox.icon-remove').length, 1, 'each item shoud have the .icon-remove class');
});
});
describe('.newField(element)', function () {
it('should append a new field to the element', function () {
var element = document.createElement('div');
sinon.stub(this.module, 'cloneField').returns(element);
this.module.newField();
assert.ok(jQuery.contains(this.module.el, element));
});
});
describe('.cloneField(element)', function () {
it('should clone the provided field', function () {
var element = document.createElement('div');
var init = sinon.stub(jQuery.fn, 'init', jQuery.fn.init);
var clone = sinon.stub(jQuery.fn, 'clone', jQuery.fn.clone);
this.module.cloneField(element);
assert.called(init);
assert.calledWith(init, element);
assert.called(clone);
init.restore();
clone.restore();
});
it('should return the cloned element', function () {
var element = document.createElement('div');
var cloned = document.createElement('div');
var init = sinon.stub(jQuery.fn, 'init', jQuery.fn.init);
var clone = sinon.stub(jQuery.fn, 'clone').returns(jQuery(cloned));
assert.ok(this.module.cloneField(element)[0] === cloned);
init.restore();
clone.restore();
});
});
describe('.resetField(element)', function () {
beforeEach(function () {
this.field = jQuery('<div><label for="field-1">Field 1</label><input name="field-1" value="value" /></div>');
});
it('should empty all input values', function () {
var target = this.module.resetField(this.field);
assert.equal(target.find(':input').val(), '');
});
it('should increment any integers in the input names by one', function () {
var target = this.module.resetField(this.field);
assert.equal(target.find(':input').attr('name'), 'field-2');
});
it('should increment any numbers in the label text by one', function () {
var target = this.module.resetField(this.field);
assert.equal(target.find('label').text(), 'Field 2');
});
it('should increment any numbers in the label for by one', function () {
var target = this.module.resetField(this.field);
assert.equal(target.find('label').attr('for'), 'field-2');
});
});
describe('.disableField(field, disable)', function () {
beforeEach(function () {
this.target = this.module.$('.control-custom:first');
});
it('should add a .disable class to the element', function () {
this.module.disableField(this.target);
assert.isTrue(this.target.hasClass('disabled'));
});
it('should set the disabled property on the input elements', function () {
this.module.disableField(this.target);
this.target.find(':input').each(function () {
if (jQuery(this).is(':checkbox')) {
assert.isFalse(this.disabled, 'checkbox should not be disabled');
} else {
assert.isTrue(this.disabled, 'input should be disabled');
}
});
});
it('should remove a .disable class to the element if disable is false', function () {
this.target.addClass('disable');
this.module.disableField(this.target, false);
assert.isFalse(this.target.hasClass('disabled'));
});
it('should unset the disabled property on the input elements if disable is false', function () {
this.target.find(':input:not(:checkbox)').prop('disabled', true);
this.module.disableField(this.target, false);
this.target.find(':input').each(function () {
if (jQuery(this).is(':checkbox')) {
assert.isFalse(this.disabled, 'checkbox should not be disabled');
} else {
assert.isFalse(this.disabled, 'input should not be disabled');
}
});
});
});
describe('._onChange(event)', function () {
it('should call .newField() with the custom control', function () {
var target = sinon.stub(this.module, 'newField');
var field = this.module.$('[name*=key]:last').val('test');
this.module._onChange(jQuery.Event('change', {target: field[0]}));
assert.called(target);
});
it('should not call .newField() if the target field is empty', function () {
var target = sinon.stub(this.module, 'newField');
var field = this.module.$('[name*=key]:last').val('');
this.module._onChange(jQuery.Event('change', {target: field[0]}));
assert.notCalled(target);
});
});
describe('._onRemove(event)', function () {
it('should call .disableField() with the custom control', function () {
var target = sinon.stub(this.module, 'disableField');
this.module._onRemove(jQuery.Event('change', {target: this.module.$(':checkbox')[0]}));
assert.called(target);
});
});
});
| sergitrilles/geoctheme | ckanext/geoc_theme/public/base/test/spec/modules/custom-fields.spec.js | JavaScript | agpl-3.0 | 6,608 |
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { Radio } from 'semantic-ui-react'
import { pluginsList, pluginsObject } from '../editorPlugins.js'
import { editorPluginsSelector } from '../selectors.js'
import { updatePlugins } from '../actions/editorPlugins.js'
const mapStateToProps = state => {
const { plugins } = editorPluginsSelector(state)
return {
plugins
}
}
const actionCreators = {
updatePlugins
}
class EditorPluginsSelector extends Component {
constructor(props) {
super(props)
}
remove(name) {
const { plugins, updatePlugins } = this.props
updatePlugins(plugins.filter(plugin => plugin !== name))
}
add(name) {
const { plugins, updatePlugins } = this.props
updatePlugins(plugins.concat([name]))
}
render() {
const { plugins } = this.props
return (
<div>
{
pluginsList.map(({ id, name }) => {
const active = plugins.includes(id)
const handler = () => active ? this.remove(id) : this.add(id)
return (
<Radio
toggle
key={name}
label={name}
onChange={handler}
checked={active}
/>
)
})
}
</div>
)
}
}
export default connect(mapStateToProps, actionCreators)(EditorPluginsSelector)
| ryo33/Yayaka19 | web/static/js/components/EditorPluginsSelector.js | JavaScript | agpl-3.0 | 1,400 |
/**
* Wrapper for binary operator.
* Ensures
*
* i >= j
* i0, j0, k0 >= 0
*
*/
export function wrapbin (fn){
return function(a, i0, i1, b, j0, j1, c, k0, k1){
var i, j, k;
k0 = Math.max(0, k0);
k = k1 - k0;
i0 = Math.max(0, i0, i1 - k);
j0 = Math.max(0, j0, j1 - k);
i = i1 - i0;
j = j1 - j0;
if(i < j)
return fn(b, j0, j1, a, i0, i1, c, k0, k1);
else
return fn(a, i0, i1, b, j0, j1, c, k0, k1);
};
}
| aureooms/js-integer-little-endian | src/0-legacy/others/wrap/wrapbin.js | JavaScript | agpl-3.0 | 447 |
/* routes/session.js
* Copyright 2015 Sergei Ianovich
*
* Licensed under AGPL-3.0 or later, see LICENSE
* Process Control Service Web Interface
*/
var User = require('../models/user');
var auth = require('./_auth');
function sessionNew(req, res) {
function renderNew () {
res.render('sessions/new', {
title: 'Sign in',
returnTo: req.query.returnTo
});
}
if (!req.session.operator)
return renderNew();
auth.loadOperatorFromSession(req, res, function () {
if (req.operator)
return res.redirect('/');
req.session.operator = undefined;
return renderNew();
})
}
module.exports.new = sessionNew;
function createSession(req, res) {
function signinFail() {
res.locals.err = { errors: { password: { type: 'signin' } } };
res.render('sessions/new', {
title: 'Sign in'
});
}
if (!req.operator)
return signinFail();
req.operator.authenticate(req.body.password, function (err, valid) {
if (err)
return res.send(500, 'Sorry, internal server error.');
if (!valid)
return signinFail();
req.session.operator = req.operator.email;
if (req.body.returnTo) {
res.redirect(req.body.returnTo);
} else {
res.redirect('/');
}
});
}
module.exports.create = [auth.loadOperatorByEmail,
createSession];
function destroySession(req, res) {
req.session.operator = undefined;
res.redirect('/signin');
}
module.exports.destroy = [auth.authenticate,
destroySession];
// vim:ts=2 sts=2 sw=2 et:
| sergeygaychuk/pcs-web | routes/session.js | JavaScript | agpl-3.0 | 1,565 |
import fs from 'fs'
import path from 'path'
import Sequelize from 'sequelize'
const basename = path.basename(module.filename)
const env = process.env.NODE_ENV || 'development'
const config = require(__dirname + '/../config/config.json')[env]
const sequelize = config.use_env_variable ?
new Sequelize(process.env[config.use_env_variable]) :
new Sequelize(config.database, config.username, config.password, config)
const files = fs.readdirSync(__dirname).filter(file => (
(file.indexOf('.') !== 0) &&
(file !== basename) &&
(file.slice(-3) === '.js')
))
const db = files.reduce((memo, file) => {
const model = sequelize.import(path.join(__dirname, file))
return {
...memo,
[model.name]: model,
}
}, {})
Object.keys(db).forEach(modelName =>
db[modelName].associate && db[modelName].associate(db))
db.sequelize = sequelize
db.Sequelize = Sequelize
export default db
| pletcher/mission-hacks | models/index.js | JavaScript | agpl-3.0 | 896 |
/**
*
* @param scriptBody
* @param builder
* @param builderParams
* @returns {{get: get}}
* @constructor
*/
function InlineScriptFactory( scriptBody, builder, builderParams ) {
return {
get: get
};
function get() {
var scriptBuilderParams = {
parentView: builderParams.parentView,
parent: builderParams.parent,
basePathOfProperty: builderParams.basePathOfProperty
};
var scriptMetadata = {
Body: scriptBody,
Name: 'InlineScript'
};
var script = builder.buildType( 'Script', scriptMetadata, scriptBuilderParams );
return function( context, args ) {
return script.call( null, context, args );
};
}
}
InfinniUI.InlineScriptFactory = InlineScriptFactory;
| InfinniPlatform/InfinniUI | app/executor/inlineScriptFactory.js | JavaScript | agpl-3.0 | 817 |
import config from '../../../common/config';
class ButtonObject extends Phaser.Button {
constructor(game, grid, grid_x, grid_y, blockSize, socket, color, hoverCallback=()=>{}) {
const x = game.world.centerX - grid.gridWidth / 2 + grid_x*grid.blockWidth;
const y = game.world.centerY - grid.gridHeight / 2 + grid_y*grid.blockHeight;
// configure button
super(game, x, y, null, null, null, 1, 0, 0, 0);
this.onInputDown.add(function () {
socket.emit("mouse_click", grid_x, grid_y);
});
this.onInputOver.add(function () {
if (grid_y >= config.GOAL.SAFE_ZONE) {
socket.emit("hover_change", grid_x, grid_y);
hoverCallback(grid_x, grid_y);
}
});
this.width = this.height = blockSize;
this.input.useHandCursor = false;
this.tint = color;
}
}
export default ButtonObject;
| ScriptaGames/SquareOff | client/src/objects/ButtonObject.js | JavaScript | agpl-3.0 | 931 |
"use strict";
$(document).ready(() => {
const registerServiceWorker = new MainController();
});
class MainController {
constructor() {
if (!navigator.serviceWorker) return;
navigator.serviceWorker.register("./sw.js").then((sw) => {
if (!navigator.serviceWorker.controller) {
return;
}
if (sw.waiting) {
MainController.updateReady(sw.waiting);
return;
}
if (sw.installing) {
MainController.trackInstalling(sw.installing);
return;
}
sw.addEventListener("updatefound", () => {
MainController.trackInstalling(sw.installing);
});
let refresh;
navigator.serviceWorker.addEventListener("controllerchange", () => {
if (refresh) return;
window.location.reload();
refresh = true;
});
});
fetchAllCurrencies();
}
static trackInstalling(worker) {
worker.addEventListener("statechange", () => {
if (worker.state === "installed") {
MainController.updateReady(worker);
}
});
}
static updateReady(worker) {
MainController.showAlert("New version available");
$("#refresh").click(() => worker.postMessage({ action: "skipWaiting" }));
}
static showAlert(message) {
$("#alert").css("display", "block");
$("#alert-message").innerHTML(message);
$("#dismiss").click(() => $("#alert").fadeOut());
}
}
if (!window.indexedDB) {
console.log("Your browser doesn't support IndexedDB");
}
const openDatabase = () => {
const DB_NAME = "pyc0d3r";
const database = indexedDB.open(DB_NAME, 1);
database.onerror = (event) => {
console.log("error opening web");
return false;
};
database.onupgradeneeded = (event) => {
let upgradeDB = event.target.result;
let objectStore = upgradeDB.createObjectStore("currencies");
};
return database;
};
const saveToDatabase = (data) => {
const db = openDatabase();
db.onsuccess = (event) => {
const query = event.target.result;
const currency = query
.transaction("currencies")
.objectStore("currencies")
.get(data.symbol);
currency.onsuccess = (event) => {
const dbData = event.target.result;
const store = query
.transaction("currencies", "readwrite")
.objectStore("currencies");
if (!dbData) {
store.add(data, data.symbol);
} else {
store.put(data, data.symbol);
}
};
};
};
const fetchFromDatabase = (symbol, amount) => {
const db = openDatabase();
db.onsuccess = (event) => {
document.getElementById("convert-btn").addEventListener("click", () => {
$(".results").html("");
});
const query = event.target.result;
const currency = query
.transaction("currencies")
.objectStore("currencies")
.get(symbol);
currency.onsuccess = (event) => {
const data = event.target.result;
if (data == null) {
$(".error_msg").append(`
<div class="output-results">
<span class="text-danger">
You are currently offline... please check your internet connectivity and try again.
</span>
</div>
`);
setTimeout((e) => $(".error_msg").html(""), 3000);
return;
}
let frElement = document.getElementById("from-currency");
let toElement = document.getElementById("to-currency");
let frText = frElement.options[frElement.selectedIndex].innerHTML;
let toText = toElement.options[toElement.selectedIndex].innerHTML;
$(".results").append(`
<div class="output-results">
<b>${amount} </b> <b> ${frText}</b><br> = <br><b>${(
amount * data.value
).toFixed(2)} ${toText}</b>
</div>
`);
};
};
};
const fetchAllCurrencies = (e) => {
$.get("https://free.currconv.com/api/v7/currencies", (data) => {
if (!data) console.log("Could not fetch any data");
const resultdata = objectToArray(data.results);
for (let val of resultdata) {
$("#from-currency").append(`
<option value="${val.id}">${val.id} (${val.currencyName})</option>
`);
$("#to-currency").append(`
<option value="${val.id}">${val.id} (${val.currencyName})</option>
`);
}
}).fail(() => console.log("Could not show any currencies Data"));
};
const convertCurrency = () => {
let fromCurrency = $("#from-currency").val();
let toCurrency = $("#to-currency").val();
let amount = $("#convert-amount").val();
document.getElementById("convert-btn").addEventListener("click", () => {
$(".output-results").html("");
});
if (fromCurrency == toCurrency) {
$(".error_msg").html(`
<div class="output-results">
<span class="text-danger">
Error you are wrong select again, Tip: the are the same currency
</span>
</div>
`);
return false;
}
let body = `${fromCurrency}_${toCurrency}`;
let query = {
q: body,
};
$.get("https://free.currconv.com/api/v7/convert", query, (data) => {
const pairs = objectToArray(data.results);
let frElement = document.getElementById("from-currency");
let toElement = document.getElementById("to-currency");
let frText = frElement.options[frElement.selectedIndex].innerHTML;
let toText = toElement.options[toElement.selectedIndex].innerHTML;
$.each(pairs, (index, val) => {
$(".results").append(`
<div class="output-results">
<b>${amount} </b> <b> ${frText}</b><br> = <br><b>${(amount * val.val).toFixed(
2
)} ${toText}</b>
</div>
`);
let object = {
symbol: body,
value: val.val,
};
saveToDatabase(object);
});
}).fail((err) => {
fetchFromDatabase(body, amount);
});
return false;
};
const objectToArray = (objects) => {
const results = Object.keys(objects).map((i) => objects[i]);
return results;
};
| umarbrowser/umarbrowser.github.io | js/app.js | JavaScript | agpl-3.0 | 5,864 |
export default () => document.getElementsByName('csrf-token')[0] ? document.getElementsByName('csrf-token')[0].content : 0;
| empirical-org/Empirical-Core | services/QuillLMS/client/app/bundles/Teacher/components/modules/get_auth_token.js | JavaScript | agpl-3.0 | 124 |
module.exports = {
"env": {
"es6": true,
"node": true
},
"extends": "eslint:recommended",
"rules": {
"indent": [
"error",
2
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
],
"no-console": 0
}
};
| sblosser/resting-odbc | .eslintrc.js | JavaScript | agpl-3.0 | 456 |
function insert_comment(form){ return legacy_filter('insert_comment', form, 'nproduct', 'procNproductInsertComment', filterAlertMessage, ['error','message','mid','document_srl','comment_srl'], '', {}) };
(function($){
var v=xe.getApp('validator')[0];if(!v)return false;
v.cast("ADD_FILTER", ["insert_comment", {'document_srl': {required:true},'nick_name': {required:true,maxlength:20},'password': {required:true},'email_address': {maxlength:250},'homepage': {maxlength:250},'content': {required:true,minlength:1}}]);
v.cast('ADD_MESSAGE',['document_srl','문서번호']);
v.cast('ADD_MESSAGE',['nick_name','닉네임']);
v.cast('ADD_MESSAGE',['password','비밀번호']);
v.cast('ADD_MESSAGE',['email_address','이메일 주소']);
v.cast('ADD_MESSAGE',['homepage','홈페이지']);
v.cast('ADD_MESSAGE',['content','내용']);
v.cast('ADD_MESSAGE',['mid','모듈 이름']);
v.cast('ADD_MESSAGE',['comment_srl','comment_srl']);
v.cast('ADD_MESSAGE',['parent_srl','parent_srl']);
v.cast('ADD_MESSAGE',['is_secret','is_secret']);
v.cast('ADD_MESSAGE',['notify_message','notify_message']);
v.cast('ADD_MESSAGE',['isnull','%s 값은 필수입니다.']);
v.cast('ADD_MESSAGE',['outofrange','%s의 글자 수를 맞추어 주세요.']);
v.cast('ADD_MESSAGE',['equalto','%s이(가) 잘못되었습니다.']);
v.cast('ADD_MESSAGE',['invalid','%s의 값이 올바르지 않습니다.']);
v.cast('ADD_MESSAGE',['invalid_email','%s의 값은 올바른 메일 주소가 아닙니다.']);
v.cast('ADD_MESSAGE',['invalid_userid','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_user_id','%s의 값은 영문, 숫자, _만 가능하며 첫 글자는 영문이어야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_homepage','%s의 형식이 잘못되었습니다.(예: http://www.xpressengine.com)']);
v.cast('ADD_MESSAGE',['invalid_url','%s의 형식이 잘못되었습니다.(예: http://www.xpressengine.com)']);
v.cast('ADD_MESSAGE',['invalid_korean','%s의 형식이 잘못되었습니다. 한글로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_korean_number','%s의 형식이 잘못되었습니다. 한글과 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_alpha','%s의 형식이 잘못되었습니다. 영문으로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_alpha_number','%s의 형식이 잘못되었습니다. 영문과 숫자로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_mid','%s의 형식이 잘못되었습니다. 첫 글자는 영문으로 시작해야 하며 \'영문+숫자+_\'로만 입력해야 합니다.']);
v.cast('ADD_MESSAGE',['invalid_number','%s의 형식이 잘못되었습니다. 숫자로만 입력해야 합니다.']);
})(jQuery); | umjinsun12/dngshin | files/cache/js_filter_compiled/9b37c1045d7ccfdec2a15b107342010b.ko.compiled.js | JavaScript | lgpl-2.1 | 2,826 |
var fs = require("fs");
var EJDB = require("../ejdb.js");
var now = new Date();
var jb = null;
module.exports.testSetup = function(test) {
jb = EJDB.open("var/tdbt2", EJDB.JBOWRITER | EJDB.JBOCREAT | EJDB.JBOTRUNC);
test.done();
};
module.exports.testSaveLoad = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
var parrot1 = {
"name" : "Grenny",
"type" : "African Grey",
"male" : true,
"age" : 1,
"birthdate" : now,
"likes" : ["green color", "night", "toys"],
"extra1" : null
};
var parrot2 = {
"name" : "Bounty",
"type" : "Cockatoo",
"male" : false,
"age" : 15,
"birthdate" : now,
"likes" : ["sugar cane"],
"extra1" : null
};
jb.save("parrots", [parrot1, null, parrot2], function(err, oids) {
test.ifError(err);
test.ok(oids);
test.equal(oids.length, 3);
test.equal(parrot1["_id"], oids[0]);
test.ok(oids[1] == null);
test.equal(parrot2["_id"], oids[2]);
jb.load("parrots", parrot2["_id"], function(err, obj) {
test.ifError(err);
test.ok(obj);
test.equal(obj._id, parrot2["_id"]);
test.equal(obj.name, "Bounty");
test.done();
});
});
};
module.exports.testQuery1 = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
jb.find("parrots", {}, function(err, cursor, count) {
test.ifError(err);
test.equal(count, 2);
test.ok(cursor);
var c = 0;
while (cursor.next()) {
++c;
var rv = cursor.object();
test.ok(rv);
test.ok(typeof rv["_id"] === "string");
test.ok(typeof rv["name"] === "string");
test.ok(typeof rv["age"] === "number");
test.ok(rv["birthdate"] && typeof rv["birthdate"] === "object");
test.ok(rv["birthdate"].constructor === Date);
test.ok(typeof rv["male"] === "boolean");
test.ok(rv["extra1"] === null);
test.ok(rv["likes"] && typeof rv["likes"] === "object");
test.ok(rv["likes"].constructor === Array);
test.ok(rv["likes"].length > 0);
}
test.equal(c, 2);
test.ifError(err);
//Query sync
cursor = jb.find("parrots", {});
test.ok(cursor);
test.equal(cursor.length, 2);
//Query sync, count mode
var count = jb.find("parrots", {}, {$onlycount : true});
test.equal(typeof count, "number");
test.equal(count, 2);
//Query sync, findOne
var obj = jb.findOne("parrots");
test.ok(obj);
test.ok(typeof obj["name"] === "string");
test.ok(typeof obj["age"] === "number");
//Async with one callback
jb.find("parrots", function(err, cursor, count) {
test.ifError(err);
test.equal(count, 2);
test.ok(cursor);
test.equal(cursor.length, 2);
test.done();
});
});
};
module.exports.testQuery2 = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
jb.find("parrots",
{name : /(grenny|bounty)/ig},
{$orderby : {name : 1}},
function(err, cursor, count) {
test.ifError(err);
test.ok(cursor);
test.equal(2, count);
for (var c = 0; cursor.next(); ++c) {
var rv = cursor.object();
if (c != 0) continue;
test.equal(rv["name"], "Bounty");
test.equal(cursor.field("name"), "Bounty");
test.equal(rv["type"], "Cockatoo");
test.equal(cursor.field("type"), "Cockatoo");
test.equal(rv["male"], false);
test.equal(cursor.field("male"), false);
test.equal(rv["age"], 15);
test.equal(cursor.field("age"), 15);
test.equal("" + rv["birthdate"], "" + now);
test.equal("" + cursor.field("birthdate"), "" + now);
test.equal(rv["likes"].join(","), "sugar cane");
test.equal(cursor.field("likes").join(","), "sugar cane");
}
test.done();
});
};
//Test with OR, cursor.reset
module.exports.testQuery3 = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
jb.find("parrots",
{}, //main query selector
[
//OR joined conditions
{name : "Grenny"},
{name : "Bounty"}
],
{$orderby : {name : 1}},
function(err, cursor, count) {
test.ifError(err);
test.ok(cursor);
test.equal(count, 2);
for (var c = 0; cursor.next(); ++c) {
var rv = cursor.object();
if (c != 1) continue;
test.equal(rv["name"], "Grenny");
test.equal(cursor.field("name"), "Grenny");
test.equal(rv["type"], "African Grey");
test.equal(cursor.field("type"), "African Grey");
test.equal(rv["male"], true);
test.equal(cursor.field("male"), true);
test.equal(rv["age"], 1);
test.equal(cursor.field("age"), 1);
test.equal("" + rv["birthdate"], "" + now);
test.equal("" + cursor.field("birthdate"), "" + now);
test.equal(rv["likes"].join(","), "green color,night,toys");
test.equal(cursor.field("likes").join(","), "green color,night,toys");
}
//test cursor reset
cursor.reset();
for (c = 0; cursor.next(); ++c);
test.equal(c, 2);
//explicit cursor close
cursor.close();
test.done();
});
};
module.exports.testCircular = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
//Circular query object
var cirQuery = {};
cirQuery.cq = cirQuery;
var err = null;
try {
jb.find("parrots", cirQuery, function(err, cursor, count) {
});
} catch (e) {
err = e;
}
test.ok(err);
test.equal(err.message, "Converting circular structure to JSON");
err = null;
try {
jb.save("parrots", [cirQuery]);
} catch (e) {
err = e;
}
test.ok(err);
test.equal(err.message, "Converting circular structure to JSON");
test.done();
};
module.exports.testSaveLoadBuffer = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
var sally = {
"name" : "Sally",
"mood" : "Angry",
"secret" : new Buffer("Some binary secrect", "utf8")
};
var molly = {
"name" : "Molly",
"mood" : "Very angry",
"secret" : null
};
jb.save("birds", sally, function(err, oids) {
test.ifError(err);
test.ok(oids);
test.ok(oids.length === 1);
test.ok(sally["_id"]);
var sallyOid = sally["_id"];
jb.load("birds", sallyOid, function(err, obj) {
test.ifError(err);
test.ok(obj["secret"] instanceof Buffer);
test.equal(obj["secret"], "Some binary secrect");
jb.save("birds", [sally, molly], function(err, oids) {
test.ifError(err);
test.ok(oids);
test.ok(oids.indexOf(sallyOid) !== -1);
test.done();
});
});
});
};
module.exports.testUseStringIndex = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
jb.find("birds", {"name" : "Molly"}, {"$explain" : true}, function(err, cursor, count, log) {
test.ifError(err);
test.ok(cursor);
test.ok(count == 1);
test.ok(log);
test.ok(log.indexOf("RUN FULLSCAN") !== -1);
//Now set the name string index
jb.ensureStringIndex("birds", "name", function(err) {
test.ifError(err);
jb.find("birds", {"name" : "Molly"}, {"$explain" : true}, function(err, cursor, count, log) {
test.ok(log.indexOf("MAIN IDX: 'sname'") !== -1);
test.done();
});
});
});
};
module.exports.testCMeta = function(test) {
var dm = jb.getDBMeta();
//console.log("dm=" + JSON.stringify(dm));
test.ok(dm);
test.equal(dm["file"], "var/tdbt2");
test.ok(dm["collections"]);
test.ok(dm["collections"].constructor == Array);
var parrots = dm["collections"][0];
test.ok(parrots);
test.equal(parrots["name"], "parrots");
//todo...
test.done();
};
module.exports.testUpdate1 = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
jb.update("parrots", {"name" : {"$icase" : "GRENNY"}, "$inc" : {"age" : 10}},
{"$explain" : true},
function(err, count, log) {
test.ifError(err);
test.equal(count, 1);
test.ok(log);
test.ok(log.indexOf("UPDATING MODE: YES") !== -1);
jb.findOne("parrots", {"age" : 11}, function(err, obj) { //age was incremented 1 + 10
test.ifError(err);
test.ok(obj);
test.equal(obj["name"], "Grenny");
jb.save("parrots", {"_id" : obj["_id"], "extra1" : 1}, {"$merge" : true}, function(err, ids) {
test.ifError(err);
test.ok(ids);
test.equal(ids.length, 1);
jb.load("parrots", ids[0], function(err, obj) {
test.ifError(err);
test.ok(obj);
test.equal(obj["name"], "Grenny");
test.equal(obj["extra1"], 1);
var q = {"_id" : {"$in" : ids}, "$set" : {"stime" : +new Date}};
jb.update("parrots", q, function(err, count) {
test.ifError(err);
test.equal(count, 1);
test.done();
});
});
});
});
});
};
module.exports.test_id$nin = function(test) {
jb.findOne("parrots", {}, function(err, obj) {
test.ifError(err);
test.ok(obj);
jb.find("parrots", {"_id" : {"$in" : [obj["_id"]]}}, function(err, cursor, count) {
test.ifError(err);
test.equal(count, 1);
test.ok(cursor.hasNext());
test.ok(cursor.next());
test.equal(cursor.field("_id"), obj["_id"]);
jb.find("parrots", {"_id" : {"$nin" : [obj["_id"]]}}, {"$explain" : true}, function(err, cursor, count, log) {
test.ifError(err);
test.ok(count > 0);
while (cursor.next()) {
test.ok(cursor.field("_id"));
test.ok(cursor.field("_id") != obj["_id"]);
test.ok(log.indexOf("RUN FULLSCAN") !== -1);
}
test.done();
});
});
});
};
module.exports.testRemove = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
jb.findOne("birds", {"name" : "Molly"}, function(err, obj) {
test.ifError(err);
test.ok(obj["_id"]);
test.equal(obj["mood"], "Very angry");
//Bye bye Molly!
jb.remove("birds", obj["_id"], function(err) {
test.ifError(err);
jb.findOne("birds", {"name" : "Molly"}, function(err, obj) {
test.ifError(err);
test.ok(obj === null);
test.done();
});
});
});
};
module.exports.testSync = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
jb.sync(function(err) {
test.ifError(err);
test.done();
});
};
module.exports.testRemoveColls = function(test) {
jb.dropCollection("birds", function(err) {
test.ifError(err);
jb.find("birds", {}, function(err, cursor, count) { //Query on not existing collection
test.ifError(err);
test.equal(count, 0);
test.ok(!cursor.next());
test.done();
});
});
};
module.exports.testTx1 = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
var obj = {
foo : "bar"
};
test.ok(jb.getTransactionStatus("bars") === false);
jb.beginTransaction("bars", function(err) {
test.ifError(err);
jb.save("bars", obj);
var id = obj["_id"];
test.ok(id);
obj = jb.load("bars", obj["_id"]);
test.ok(obj);
test.ok(jb.getTransactionStatus("bars") === true);
jb.rollbackTransaction("bars");
test.ok(jb.getTransactionStatus("bars") === false);
obj = jb.load("bars", obj["_id"]);
test.ok(obj == null);
jb.beginTransaction("bars", function(err) {
test.ifError(err);
test.ok(jb.getTransactionStatus("bars") === true);
test.ok(jb.load("bars", id) == null);
obj = {
foo : "bar"
};
jb.save("bars", obj);
id = obj["_id"];
test.ok(id);
test.ok(jb.load("bars", id));
jb.commitTransaction("bars", function(err) {
test.ifError(err);
jb.getTransactionStatus("bars", function(err, status) {
test.ifError(err);
test.ok(status === false);
test.ok(jb.load("bars", id));
test.done();
});
});
});
});
};
module.exports.testCreateCollectionOn$upsert = function(test) {
test.ok(jb);
test.ok(jb.isOpen());
jb.update("upsertcoll", {foo : "bar", $upsert : {foo : "bar"}}, function(err, count) {
test.ifError(err);
test.equal(count, 1);
jb.findOne("upsertcoll", {foo : "bar"}, function(err, obj) {
test.ifError(err);
test.ok(obj);
test.equal(obj.foo, "bar");
test.done();
});
});
};
module.exports.testFPIssue = function(test) {
test.ok(jb);
jb.save("test", {x: 2.3434343});
var x = jb.findOne("test");
test.equal(x.x, 2.3434343);
test.done();
};
module.exports.testClose = function(test) {
test.ok(jb);
jb.close();
test.done();
};
| poelzi/ejdb | node/tests/t2.js | JavaScript | lgpl-2.1 | 14,689 |
var bg = 0;
var mt = "none";
function setup(){
createCanvas(800,800);
background(bg);
}
function draw(){
bg = (bg + 1)%255;
background(bg);
stroke(200,0,0);
noFill();
text(mt,100,100);
}
function mouseClicked(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
mt = xhttp.responseText;
}
};
xhttp.open("GET", "sensor", true);
xhttp.send()
}
| johnpasquarello/ES-P5-8266 | webpages/sketch.js | JavaScript | lgpl-2.1 | 458 |
/**
* Copyright (C) 2005-2015 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Dave Draper
*/
define(["intern!object",
"intern/chai!assert",
"require",
"alfresco/TestCommon"],
function(registerSuite, assert, require, TestCommon) {
var browser;
registerSuite({
name: "FilteredList Tests (Use Case 1)",
setup: function() {
browser = this.remote;
return TestCommon.loadTestWebScript(this.remote, "/FilteredListUseCase1", "FilteredList Tests (Use Case 1").end();
},
beforeEach: function() {
browser.end();
},
// See AKU-508 for the context, but we want to make sure that opening a dialog will not trigger the filtered list
// to request data...
"Check displaying dialog does not reload list": function() {
return browser.findByCssSelector("#PDM_ITEM_1_SELECT_CONTROL span")
.clearLog()
.click()
.end()
.findByCssSelector("#PDM_ITEM_1_SELECT_CONTROL_menu tr[data-value='MODERATED']")
.click()
.end()
.findAllByCssSelector(".alfresco-dialog-AlfDialog.dialogDisplayed")
.end()
.getAllPublishes("ALF_RETRIEVE_DOCUMENTS_REQUEST_SUCCESS")
.then(function(payloads) {
assert.lengthOf(payloads, 0, "A request to load data should not have been made when the dialog opens");
});
},
"Post Coverage Results": function() {
TestCommon.alfPostCoverageResults(this, browser);
}
});
}); | nzheyuti/Aikau | aikau/src/test/resources/alfresco/lists/FilteredListUseCaseTest.js | JavaScript | lgpl-3.0 | 2,234 |
window.ST = window.ST || {};
/**
Use translations in JavaScript
Usage:
### Load the translations you need:
```haml
= js_t(["admin.categories.new", "admin.categories.edit"])
```
### Use loaded translations
```javascript
$('#new-link').text(ST.t("admin.categories.new"))
$('#new-link').text(ST.t("admin.categories.edit"))
```
*/
(function(exports) {
var store = {};
exports.t = function(key, opts) {
if(store[key] == null) {
throw new Error("No translation loaded: " + key);
}
return _.template(store[key], opts || {});
};
exports.loadTranslations = function(translations) {
_.extend(store, translations);
};
})(window.ST);
| ziyoucaishi/marketplace | app/assets/javascripts/translations.js | JavaScript | lgpl-3.0 | 689 |
/**
* An abstract base class to be extended.
*
* Represents a grid panel for containing layers
* that haven't yet been added to the map. Each row
* will be grouped under a heading, contain links
* to underlying data sources and have a spatial location
* that can be viewed by the end user.
*
* This class is expected to be extended for usage within
* the 'Registered Layers', 'Known Layers' and 'Custom Layers'
* panels in the portal. Support for KnownLayers/CSWRecords and
* other row types will be injected by implementing the abstract
* functions of this class
*
*/
Ext.define('portal.widgets.panel.BaseActiveRecordPanel', {
extend : 'portal.widgets.panel.CommonBaseRecordPanel',
alias: 'widget.baseactiverecordpanel',
visibleIcon : 'img/eye.png',
notVisibleIcon : 'img/eye_off.png',
constructor : function(cfg) {
var me = this;
me.listeners = Object.extend(me.listenersHere, cfg.listeners);
this.store = cfg.store;
Ext.apply(cfg, {
cls : 'auscope-dark-grid',
header: false,
hideSearch: true,
emptyText : '<p class="centeredlabel">No map layers currently loaded.</p>',
titleField: 'name',
titleIndex: 1,
allowReordering: true,
tools: [{
field: ['loading', 'active'],
clickHandler: Ext.bind(me._loadingClickHandler, this),
stopEvent: true,
tipRenderer: Ext.bind(me._loadingTipRenderer, this),
iconRenderer: Ext.bind(me._loadingRenderer, this)
},{
field: 'serviceInformation',
stopEvent: true,
clickHandler: Ext.bind(me._serviceInformationClickHandler, me),
tipRenderer: function(layer, tip) {
return 'Click for detailed information about the web services this layer utilises.';
},
iconRenderer: Ext.bind(me._serviceInformationRenderer, me)
},{
field: 'legend',
stopEvent: true,
clickHandler: function (value, record) {
Ext.bind(me._getLegendAction(record).execute(), me);
},
tipRenderer: function(layer, tip) {
return 'Show layer legend.';
},
iconRenderer: function(value, record) {
return 'portal-core/img/key.png';
}
},{
field: 'visible',
stopEvent: true,
tipRenderer: function(value, record, tip) {
var tip = 'Toggle layer visibility ';
if(record.visible){
tip+='off';
}else{
tip+='on';
}
return tip;
},
iconRenderer: function(value, record) {
if(record.visible){
return me.visibleIcon;
}else{
return me.notVisibleIcon;
}
},
clickHandler: function(value, record) {
me._setVisibilityAction(record).execute();
}
},{
field: 'active',
iconRenderer: function(value, record) {
return 'portal-core/img/cross.png';
},
tipRenderer: function(value, record) {
return 'Remove layer';
},
clickHandler: function(value, record) {
ActiveLayerManager.removeLayer(record);
}
}],
childPanelGenerator: function(layer) {
if(! layer) {
Ext.Error.raise("Expecting layer to be an actual layer for the ActiveLayersPanel but it is undefined")
}
var filterForm = cfg.layerFactory.formFactory.getFilterForm(layer).form; //ALWAYS recreate filter form - see https://jira.csiro.au/browse/AUS-2588
filterForm.setLayer(layer);
var filterPanel = me._getInlineLayerPanel(filterForm);
//Update the layer panel to use
if (filterForm) {
var filterer = layer.get('filterer');
if (filterer) {
var existingParams = filterer.getParameters();
filterForm.getForm().setValues(existingParams);
}
}
return filterPanel;
},
listeners: {
reorder: function(recordPanel, record) {
ActiveLayerManager.updateLayerOrder(me.map, record);
}
}
});
this.callParent(arguments);
},
_getLegendAction : function(layer){
var legend = layer.get('renderer').getLegend();
var text = 'Get Legend';
var getLegendAction = new Ext.Action({
text : text,
icon : legend.iconUrl,
//icon : null,
iconCls : 'portal-ux-menu-icon-size',
itemId : 'LegendAction',
handler : function(){
// this will be resized dynamically as legend content is added
var legendCallback = function(legend, resources, filterer, success, form, layer){
if (success && form) {
// allow more than one legend popup but only one per layer
var popupId = 'legendPopup_' + layer.get('id');
var popupWindow = Ext.get(popupId);
if (!popupWindow) {
popupWindow = Ext.create('Ext.window.Window', {
id : 'legendPopup',
title : 'Legend: '+ layer.get('name'),
layout : 'vbox',
maxHeight : Ext.get('center_region-map').getHeight(),
autoScroll : true,
items: form,
listeners: {
show: function() {
var container = Ext.get('center_region-map');
this.setPosition(container.getX()-1, container.getY()-1);
}
},
});
popupWindow.show();
}
return Ext.getCmp(popupWindow.id).focus();
}
};
var onlineResources = layer.getAllOnlineResources();
var filterer = layer.get('filterer');
var renderer = layer.get('renderer');
var legend = renderer.getLegend(onlineResources, filterer);
//VT: this style is just for the legend therefore no filter is required.
var styleUrl = layer.get('renderer').parentLayer.get('source').get('proxyStyleUrl');
var staticLegendURL = layer.get('source').get('staticLegendUrl');
if (staticLegendURL && staticLegendURL.length > 0) {
legend.getLegendComponent(onlineResources, filterer,"", true, Ext.bind(legendCallback, this, [layer], true), staticLegendURL, true);
} else if (styleUrl && styleUrl.length > 0) {
Ext.Ajax.request({
url: styleUrl,
timeout : 180000,
scope : this,
success:function(response,opts){
legend.getLegendComponent(onlineResources, filterer,response.responseText, true, Ext.bind(legendCallback, this, [layer], true), null, true);
},
failure: function(response, opts) {
legend.getLegendComponent(onlineResources, filterer,"", true, Ext.bind(legendCallback, this, [layer], true));
}
});
} else {
legend.getLegendComponent(onlineResources, filterer,"", true, Ext.bind(legendCallback, this, [layer], true), null, true);
}
}
});
return getLegendAction;
},
// Column Function
_setVisibilityAction : function(layer){
// var me = this;
var visibleLayerAction = new Ext.Action({
text : 'Toggle Layer Visibility OFF',
iconCls : 'visible_eye',
handler : function(){
// var layer = me.filterForm.layer;
layer.setLayerVisibility(!layer.visible);
}
});
return visibleLayerAction;
},
/**
* Column definition function to draw the panel when a row is clicked upon. Here is a common one to draw the WMS/WFS filter with Opacity, drop-downs etc..
* Override
*/
_getInlineLayerPanel : function(filterForm){
var me = this;
var panel = Ext.create('portal.widgets.panel.FilterPanel', {
menuFactory : this.menuFactory,
filterForm : filterForm,
detachOnRemove : false,
map : this.map,
menuItems : []
});
return panel
},
_playRenderer : function () {
return Ext.DomHelper.markup({
tag : 'img',
width : 16,
height : 16,
src: 'portal-core/img/play_blue.png'
});
},
_loadingRenderer : function(value, layer) {
if (value) {
return 'portal-core/img/loading.gif';
} else {
if(layer.get('active')){
var renderStatus = layer.get('renderer').renderStatus;
var listOfStatus=renderStatus.getParameters();
var errorCount = this._statusListErrorCount(listOfStatus);
var sizeOfList = Ext.Object.getSize(listOfStatus);
if(errorCount > 0 && errorCount == sizeOfList){
return 'portal-core/img/exclamation.png';
}else if(errorCount > 0 && errorCount < sizeOfList){
return 'portal-core/img/warning.png';
}else{
return 'portal-core/img/tick.png';
}
}else{
return 'portal-core/img/notloading.gif';
}
}
},
_statusListErrorCount : function(listOfStatus){
var match =["reached","error","did not complete","AJAX","Unable"];
var errorCount = 0;
for(key in listOfStatus){
for(var i=0; i< match.length; i++){
if(listOfStatus[key].indexOf(match[i]) > -1){
errorCount++;
break;
}
}
}
return errorCount;
},
_loadingTipRenderer : function(value, layer, tip) {
var renderer = layer.get('renderer');
var update = function(renderStatus, keys) {
tip.update(renderStatus.renderHtml());
};
//Update our tooltip as the underlying status changes
renderer.renderStatus.on('change', update, this);
tip.on('hide', function() {
renderer.renderStatus.un('change', update); //ensure we remove the handler when the tip closes
});
return renderer.renderStatus.renderHtml();
},
_loadingClickHandler : function(value, layer) {
var html = '<p>No Service recorded, Click on Add layer to map</p>';
if(layer){
var renderer = layer.get('renderer');
html = renderer.renderStatus.renderHtml();
}
var win = Ext.create('Ext.window.Window', {
title: 'Service Loading Status',
height: 200,
width: 500,
layout: 'fit',
items: { // Let's put an empty grid in just to illustrate fit layout
xtype: 'panel',
autoScroll : true,
html : html
}
});
win.show();
}
});
| GeoscienceAustralia/geoscience-portal | src/main/webapp/js/auscope/widgets/panel/BaseActiveRecordPanel.js | JavaScript | lgpl-3.0 | 12,619 |
/*
* Copyright (c) 2015 Memorial Sloan-Kettering Cancer Center.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY, WITHOUT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS
* FOR A PARTICULAR PURPOSE. The software and documentation provided hereunder
* is on an "as is" basis, and Memorial Sloan-Kettering Cancer Center has no
* obligations to provide maintenance, support, updates, enhancements or
* modifications. In no event shall Memorial Sloan-Kettering Cancer Center be
* liable to any party for direct, indirect, special, incidental or
* consequential damages, including lost profits, arising out of the use of this
* software and its documentation, even if Memorial Sloan-Kettering Cancer
* Center has been advised of the possibility of such damage.
*/
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This class is designed to retrieve PFAM data on demand.
*
* @param options additional options
*
* @author Selcuk Onur Sumer
*/
function PfamDataProxy(options)
{
var self = this;
// default options
var _defaultOpts = {
servletName: "getPfamSequence.json"
};
// merge options with default options to use defaults for missing values
var _options = jQuery.extend(true, {}, _defaultOpts, options);
// call super constructor to init options and other params
AbstractDataProxy.call(this, _options);
_options = self._options;
// map of <gene, data> pairs
var _pfamDataCache = {};
/**
* Initializes with full PFAM data. Once initialized with full data,
* this proxy class assumes that there will be no additional data.
*
* @param options data proxy options
*/
function fullInit(options)
{
//assuming the given data is a map of <gene, sequence data> pairs
_pfamDataCache = options.data;;
}
function getPfamData(servletParams, callback)
{
// TODO allow more than one gene at a time? (see MutationDataProxy)
var gene = servletParams.geneSymbol;
if (gene == null)
{
// no gene symbol provided, nothing to retrieve
callback(null);
return;
}
// retrieve data from the server if not cached
if (_pfamDataCache[gene] == undefined)
{
if (self.isFullInit())
{
callback(null);
return;
}
// process & cache the raw data
var processData = function(data) {
_pfamDataCache[gene] = data;
// forward the processed data to the provided callback function
callback(data);
};
// retrieve data from the servlet
$.getJSON(_options.servletName,
servletParams,
processData);
}
else
{
// data is already cached, just forward it
callback(_pfamDataCache[gene]);
}
}
// override required base functions
self.fullInit = fullInit;
// class specific functions
self.getPfamData = getPfamData;
}
// PdbDataProxy extends AbstractDataProxy...
PfamDataProxy.prototype = new AbstractDataProxy();
PfamDataProxy.prototype.constructor = PfamDataProxy;
| zhx828/mutation-mapper | src/js/data/PfamDataProxy.js | JavaScript | lgpl-3.0 | 3,571 |
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { translate } from '../../../helpers/l10n';
const ComponentsEmpty = () => (
<tr>
<td colSpan="2">
{translate('no_results')}
</td>
<td colSpan="6" />
</tr>
);
export default ComponentsEmpty;
| lbndev/sonarqube | server/sonar-web/src/main/js/apps/code/components/ComponentsEmpty.js | JavaScript | lgpl-3.0 | 1,091 |
/*
* Copyright (C) 2017 Czech Technical University in Prague
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
import React from "react";
import {Button, Modal} from "react-bootstrap";
import {FormattedMessage} from "react-intl";
import I18nWrapper from "../../i18n/I18nWrapper";
import injectIntl from "../../utils/injectIntl";
import Mask from "../Mask";
class DeleteReportDialog extends React.Component {
static propTypes = {
onClose: React.PropTypes.func.isRequired,
onSubmit: React.PropTypes.func.isRequired,
show: React.PropTypes.bool.isRequired,
reportType: React.PropTypes.string
};
constructor(props) {
super(props);
this.i18n = props.i18n;
this.state = {
loading: false
}
}
_onSubmit = () => {
this.setState({loading: true});
this.props.onSubmit();
};
render() {
return <Modal show={this.props.show} onHide={this.props.onClose}>
{this.state.loading ? <Mask/> : null}
<Modal.Header closeButton>
<Modal.Title>
<FormattedMessage id='delete-dialog.title' values={{type: this.props.reportType}}/>
</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.i18n('delete-dialog.content')}
</Modal.Body>
<Modal.Footer>
<Button bsStyle='warning' bsSize='small' onClick={this._onSubmit}>{this.i18n('delete')}</Button>
<Button bsSize='small' onClick={this.props.onClose}>{this.i18n('cancel')}</Button>
</Modal.Footer>
</Modal>;
}
}
export default injectIntl(I18nWrapper(DeleteReportDialog));
| kbss-cvut/reporting-tool | src/main/webapp/js/components/report/DeleteReportDialog.js | JavaScript | lgpl-3.0 | 2,323 |
var peg = require('pegjs');
var fs = require('fs');
var SFAFx = require('../sfafx.js');
console.log( "reading..." + process.argv[2] );
var sfaftxt = fs.readFileSync(process.argv[2],'utf8');
console.log( "read " + sfaftxt.length + " bytes ");
var est = 2750000.0;
console.log( "Estimated time: " + (sfaftxt.length / est) + " seconds at an estimated rate of " + est + " bytes/sec" );
var before = Date.now();
count = 0;
SFAFx_Parse_Time = function(){
count++;
if( count % 100 == 0 ){
var counttime = (Date.now()-before)/1000;
console.log( "Parsed: " + count + " at rate of " + (count/counttime) + " per sec");
}
}
try{
var records = SFAFx.toJSON(sfaftxt);
}catch( e ){
console.log( "parse exception");
console.log( e );
return;
}
var after = Date.now();
var time = (after-before)/1000;
console.log( " Time (sec):" + time );
console.log( "Text Length (bytes):" + sfaftxt.length );
console.log( " Records:" + records.length );
console.log( " Records (per sec):" + records.length / time );
console.log( " Bytes (per sec):" + sfaftxt.length / time );
| Sciumo/sfafxjs | test/timeparse.js | JavaScript | lgpl-3.0 | 1,094 |
module.exports = {
database: {
url: "mongodb://localhost/ideagarden",
options: {
user: "",
pass: ""
}
},
email:{
host: "localhost",
port: 25,
auth: {
user: "test@localhost",
pass: "dummy"
},
tls: {"rejectUnauthorized": false},
debug:true
},
secret: "dummy",
port: 80
};
| CodeForEindhoven/IdeaGarden | src/server/config.default.js | JavaScript | lgpl-3.0 | 405 |
isc.PortalLayout.create({
width: "100%",
height: "100%",
canResizePortlets: true,
portlets: [
[ // Array for left column
isc.Portlet.create({
title: "Portlet 1"
}),
[ // Array for a row
isc.Portlet.create({
title: "Portlet 2"
}),
isc.Portlet.create({
title: "Portlet 3"
})
]
],[ // Array for right column
[
isc.Portlet.create({
title: 'Portlet 4'
}),
isc.Portlet.create({
title: 'Portlet 5'
})
],
isc.Portlet.create({
title: 'Portlet 6'
})
]
]
});
| kylemwhite/isc | isomorphic_11.1p/system/reference/inlineExamples/layout/portal/portletResizing.js | JavaScript | lgpl-3.0 | 828 |
/*
* Source: https://github.com/mdn/webextensions-examples/tree/master/context-menu-copy-link-with-types
*/
function copyToClipboard(text) {
function oncopy(event) {
document.removeEventListener("copy", oncopy, true);
event.stopImmediatePropagation();
event.preventDefault();
event.clipboardData.setData("text/plain", text);
}
document.addEventListener("copy", oncopy, true);
document.execCommand("copy");
}
| KevinRoebert/ClearUrls | external_js/clipboard-helper.js | JavaScript | lgpl-3.0 | 461 |
function info_debug(text,object) {
if (enioka.ij.info_debug) {
enioka.ij.info_debug(text,object);
} else {
console.log(text,object);
}
}
function info_warn(text,object) {
if (enioka.ij.info_warn) {
enioka.ij.info_warn(text,object);
} else {
console.log(text,object);
}
}
function info_error(text,object) {
if (enioka.ij.info_error) {
enioka.ij.info_error(text,object);
} else {
console.log(text,object);
}
}
function user_debug(text,object) {
if (enioka.ij.user_debug) {
enioka.ij.user_debug(text,object);
} else {
console.log(text,object);
}
}
function user_warn(text,object) {
if (enioka.ij.user_warn) {
enioka.ij.user_warn(text,object);
} else {
console.log(text,object);
}
}
function user_error(text,object) {
if (enioka.ij.user_error) {
enioka.ij.user_error(text,object);
} else {
console.log(text,object);
}
}
| enioka/ij.js | lib/logger.js | JavaScript | lgpl-3.0 | 984 |
/**
* Copyright (C) 2005-2016 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* This test renders examples of Banner and LockedBanner.
*
* The test is simple and much of its validity is in the use of slightly damaged or incomplete models to inspect edge cases.
*
* @author Richard Smith
*/
define(["intern!object",
"intern/chai!expect",
"require",
"alfresco/TestCommon"],
function (registerSuite, expect, require, TestCommon) {
registerSuite(function(){
var browser;
return {
name: "Banner and Locked Banner Tests",
setup: function() {
browser = this.remote;
return TestCommon.loadTestWebScript(this.remote, "/Banner", "Banner and Locked Banner Tests").end();
},
beforeEach: function() {
browser.end();
},
"Check there are the expected number of banners successfully rendered": function () {
return browser.findAllByCssSelector("span.alfresco-renderers-Banner")
.then(function (banners){
expect(banners).to.have.length(7, "There should be 7 banners successfully rendered");
});
},
"Check 'BANNER' is displayed": function() {
return browser.findById("BANNER")
.isDisplayed()
.then(function (displayed){
expect(displayed).to.equal(true, "'BANNER' should be displayed");
});
},
"Check 'BANNER_EMPTY_MESSAGE' is not displayed": function() {
return browser.findById("BANNER_EMPTY_MESSAGE")
.isDisplayed()
.then(function (displayed){
expect(displayed).to.equal(false, "'BANNER_EMPTY_MESSAGE' should not be displayed");
});
},
"Check 'BANNER_NULL_MESSAGE' is not displayed": function() {
return browser.findById("BANNER_NULL_MESSAGE")
.isDisplayed()
.then(function (displayed){
expect(displayed).to.equal(false, "'BANNER_NULL_MESSAGE' should not be displayed");
});
},
"Check 'BANNER_NO_MESSAGE' is not displayed": function() {
return browser.findById("BANNER_NO_MESSAGE")
.isDisplayed()
.then(function (displayed){
expect(displayed).to.equal(false, "'BANNER_NO_MESSAGE' should not be displayed");
});
},
"Check 'LOCKED_BANNER_LOCK_OWNER' is displayed": function() {
return browser.findById("LOCKED_BANNER_LOCK_OWNER")
.isDisplayed()
.then(function (displayed){
expect(displayed).to.equal(true, "'LOCKED_BANNER_LOCK_OWNER' should be displayed");
});
},
"Check 'LOCKED_BANNER_WORKING_COPY_OWNER' is displayed": function() {
return browser.findById("LOCKED_BANNER_WORKING_COPY_OWNER")
.isDisplayed()
.then(function (displayed){
expect(displayed).to.equal(true, "'LOCKED_BANNER_WORKING_COPY_OWNER' should be displayed");
});
},
"Check 'LOCKED_BANNER_NO_MESSAGE' is not displayed": function() {
return browser.findById("LOCKED_BANNER_NO_MESSAGE")
.isDisplayed()
.then(function (displayed){
expect(displayed).to.equal(false, "'LOCKED_BANNER_NO_MESSAGE' should not be displayed");
});
},
"Post Coverage Results": function() {
TestCommon.alfPostCoverageResults(this, browser);
}
};
});
}); | jphuynh/Aikau | aikau/src/test/resources/alfresco/renderers/BannerTest.js | JavaScript | lgpl-3.0 | 4,165 |