text stringlengths 7 3.69M |
|---|
/**
* Name:Adam Zaimes
* Date: 9-23-2013
*
* Created by the JavaScript Development Team
* Class: PWA
* Goal: Goal7
*/
(function(){
//constructor
var Person = function(name, row) {
this.name = name;
this.action = Person.actions[Math.floor(Math.random() * Person.actions.length)];
this.job = Person.jobs[Math.floor(Math.random() * Person.jobs.length)];
this.row = row;
var id= document.getElementById("r"+this.row+"c3");
id.innerHTML=this.action;
};
//allows main.js to access
window.Person = Person;
Person.jobs = ["Student", "Mechanic", "Journalist", "Architect", "Psychologist"];
Person.actions = ["Sleeping", "Eating", "Working"];
//change actions at random
Person.prototype.update= function(){
if(Math.floor(Math.random() < .01)) {
//changes action
this.action = Person.actions[Math.floor(Math.random() * Person.actions.length)];
var id = document.getElementById("r" + this.row + "c3");
id.innerHTML=this.action;
}
};
})(); |
import React from 'react';
import './MainFeatures.css';
import Heading from '../../components/Heading';
import Paragraph from '../../components/Paragraph';
import Image from '../../components/Image';
import List from '../../components/List';
import ListItem from '../../components/ListItem';
import Container from '../../components/Container';
const MainFeatures = props => {
const { content } = props;
const MainFeaturesList = () => {
return <List>{MainFeaturesListItem}</List>;
};
// MainFeatures content model accepts an array of features
const MainFeaturesListItem = content.features.map((mainFeature, index) => {
const { heading, paragraph, image } = mainFeature;
const imageUrl = `uploads/${image.src}`;
return (
<ListItem key={index} className="MainFeaturesListItem">
<div className="MainFeaturesListItem--content">
<Heading element={heading.options.element}>{heading.text}</Heading>
<Paragraph>{paragraph.text}</Paragraph>
</div>
<Image src={imageUrl} alt={image.alt} />
</ListItem>
);
});
return (
<Container size="Narrow">
<Heading
element={content.heading.options.element}
variant="SectionHeading"
className="MainFeatures--SectionHeading"
>
{content.heading.text}
</Heading>
<MainFeaturesList />
</Container>
);
};
export default MainFeatures;
|
var express = require('express');
var Word = require('../services/word');
var router = express.Router();
var mongoose = require('mongoose');
function isMongoId(req, res, next) {
if (!mongoose.Types.ObjectId.isValid(req.params.id)) {
return res.status(400).send({
success: false,
msg: 'Parameter passed is not a valid Mongo ObjectId'
})
}
next()
}
router.get('/words', function(req, res) {
Word.list(function(words) {
res.json(words);
}, function(err) {
res.status(400).json(err);
});
});
router.post('/words', function(req, res) {
Word.save(req.body.name, function(word) {
res.status(201).json(word);
}, function(err) {
res.status(400).json(err);
});
});
/*router.put('/items/:id', function(req, res) {
Item.update(req.body.id, req.body.name, function(item) {
res.status(200).json(item);
}, function(err) {
res.status(400).json(err);
});
});
router.delete('/items/:id', isMongoId, function(req, res) {
Item.remove(req.params.id, function(item) {
res.status(200).json(item);
}, function(err) {
console.log(err);
res.status(400).json(err);
});
});*/
module.exports = router;
|
angular
.module("hotel.service", [])
.factory('hotel', ['$http', 'auth', function($http, auth) {
// Might use a resource here that returns a JSON array
var headers = {};
headers[API.token_name] = auth.getToken();
var dataHotel = {};
dataHotel.getHoteles = function() {
return ($http({
url: API.base_url + 'public/hotlistar2',
method: "GET",
headers: headers
}).success(function(data, status, headers, config) {
datos = data.data;
return datos;
}).error(function(err) {
error = err;
}))
};
dataHotel.getHotel = function(idHotel) {
return ($http({
url: API.base_url + 'public/hotobtener/' + idHotel,
method: "GET",
headers: headers
}).success(function(data, status, headers, config) {
datos = data.data;
return datos;
}).error(function(err) {
error = err;
}))
};
return dataHotel;
}]); |
import { graphql, useStaticQuery, navigate } from "gatsby"
import React from "react"
import Select from "react-select"
import makeAnimated from "react-select/animated"
import { theme } from "../utils/styles"
const animatedComponents = makeAnimated()
const styles = {
control: (styles, { isFocused, isSelected }) => ({
...styles,
minWidth: `175px`,
color: theme.colors.primary,
borderColor: "transparent",
transition: "all 200ms ease-in",
fontWeight: isFocused || isSelected ? "bolder" : "normal",
boxShadow: isFocused || isSelected ? "inset 0 0 0 2px" : "inset 0 0 0 1px",
"&:hover": {
boxShadow: "inset 0 0 0 2px",
fontWeight: "bolder",
},
marginBottom: 8,
fontSize: 16,
}),
input: styles => ({
...styles,
color: theme.colors.primary,
margin: "4px 0",
}),
option: (styles, { isFocused, isSelected }) => ({
...styles,
color: isSelected ? `white` : theme.colors.primary,
backgroundColor: isSelected
? theme.colors.primary
: isFocused
? theme.colors.secondary
: null,
fontSize: 16,
}),
dropdownIndicator: styles => ({
...styles,
"&:focus": {
color: theme.colors.primary,
},
"&:active": {
color: theme.colors.primary,
},
"&:hover": {
color: theme.colors.primary,
},
}),
indicatorSeparator: styles => ({
...styles,
backgroundColor: theme.colors.primary,
}),
placeholder: styles => ({ ...styles, color: theme.colors.primary }),
singleValue: styles => ({ ...styles, color: theme.colors.primary }),
}
export default ({ location }) => {
const path = location && location.pathname.replace("/", "")
const { allContentfulCategory } = useStaticQuery(
graphql`
query {
allContentfulCategory(filter: { node_locale: { eq: "ru" } }) {
edges {
node {
name
label
}
}
}
}
`
)
const categories = allContentfulCategory.edges.map(edge => ({
value: edge.node.name,
label: edge.node.label,
}))
const selectedOption = categories.find(category => category.value === path)
const handleChange = option => {
navigate(`/${option.value}`)
}
return (
<Select
components={animatedComponents}
options={categories}
styles={styles}
defaultValue={selectedOption}
onChange={handleChange}
placeholder="Продукция"
/>
)
}
|
define([
'../module'
],
function (module) {
'use strict';
module.directive('cmnBackButton', cmnBackButton);
cmnBackButton.$inject = ['$ionicConfig', '$window', '$timeout'];
return cmnBackButton;
function cmnBackButton($ionicConfig, $window, $timeout){
var directive = {
restrict: 'E'
, compile: compileFunc
}
return directive;
function compileFunc(tElement, tAttrs) {
// clone the back button, but as a <div>
var buttonEle = $window.document.createElement('button');
for (var n in tAttrs.$attr) {
buttonEle.setAttribute(tAttrs.$attr[n], tAttrs[n]);
}
if (!tAttrs.ngClick) {
buttonEle.setAttribute('ng-click', 'gbc.goBack()');
}
buttonEle.className = 'button back-button hide buttons ' + (tElement.attr('class') || '');
buttonEle.innerHTML = tElement.html() || '';
var childNode;
var hasIcon = hasIconClass(tElement[0]);
var hasInnerText;
var hasButtonText;
var hasPreviousTitle;
for (var x = 0; x < tElement[0].childNodes.length; x++) {
childNode = tElement[0].childNodes[x];
if (childNode.nodeType === 1) {
if (hasIconClass(childNode)) {
hasIcon = true;
} else if (childNode.classList.contains('default-title')) {
hasButtonText = true;
} else if (childNode.classList.contains('previous-title')) {
hasPreviousTitle = true;
}
} else if (!hasInnerText && childNode.nodeType === 3) {
hasInnerText = !!childNode.nodeValue.trim();
}
}
function hasIconClass(ele) {
return /ion-|icon/.test(ele.className);
}
var defaultIcon = $ionicConfig.backButton.icon();
if (!hasIcon && defaultIcon && defaultIcon !== 'none') {
buttonEle.innerHTML = '<i class="icon ' + defaultIcon + '"></i> ' + buttonEle.innerHTML;
buttonEle.className += ' button-clear';
}
if (!hasInnerText) {
var buttonTextEle = $window.document.createElement('span');
buttonTextEle.className = 'back-text';
if (!hasButtonText && $ionicConfig.backButton.text()) {
buttonTextEle.innerHTML += '<span class="default-title">' + $ionicConfig.backButton.text() + '</span>';
}
if (!hasPreviousTitle && $ionicConfig.backButton.previousTitleText()) {
buttonTextEle.innerHTML += '<span class="previous-title"></span>';
}
buttonEle.appendChild(buttonTextEle);
}
buttonEle.onclick = function(){
console.info('very ugly...');
$window.history.back();
}
tElement[0].parentNode.replaceChild(buttonEle, tElement[0]);
return function link($scope, $element, $attr){
$timeout(
function(){
var ionBackBtn = angular.element($window.document.querySelector('[nav-bar="active"]>ion-header-bar>.back-button'));
console.info('ionBackBtn', ionBackBtn)
var shouldShowCmnBackBtn = false;
if(ionBackBtn.length == 0){
shouldShowCmnBackBtn = true;
} else {
shouldShowCmnBackBtn = ionBackBtn.hasClass('hide');
}
console.info('shouldShowCmnBackBtn', shouldShowCmnBackBtn);
if(shouldShowCmnBackBtn){
$element.removeClass('hide');
}
}, 1000
)
}
}
}
});
|
let hw11_m_cases = {
2: [
[`first_half("foobar")`, "foo"],
[`first_half("hi")`, "h"],
[`first_half("abcdefghijkl")`, "abcdef"]
],
3: [
[`surround("<-->", "use substring")`, "<-use substring->"],
[`surround("####", "hashtag")`, "##hashtag##"],
[`surround("-__-", "-__-")`, "-_-__-_-"]
],
4: [
[`cutoff("Hello!")`, "ello"],
[`cutoff("abcdefg")`, "bcdef"],
[`cutoff(" ")`, ""]
],
5: [
[`combo("Billy", "bobjoe")`, "BillybobjoeBilly"],
[`combo("_qwerty_", "uiop")`, "uiop_qwerty_uiop"],
[`combo("", "a")`, "a"],
[`combo("c", "")`, "c"]
],
6: [
[`appears("lo", "Hello!")`, true],
[`appears("hi there", "hi there")`, true],
[`appears("billy bob joe", "bob")`, false],
[`appears(" ", "hello world")`, true]
]
};
|
ns("common") ;
var respParser = common.ajax.responseParser;
function makeDeviceHtml(devices, groupid) {
var muserid = $("#userSensorInfo>em").attr("value");
var html = "";
var devicename = undefined;
var max = 5;
var len = 0;
var checkboxhtml = "";
var selectedCheck = "";
len = devices.length;
if (devices.length < max) {
len = max;
}
if (devices.length > max) {
len += max - (len % max);
}
html += "\n <ul class=\"listTableBody\" id='listTableBody_" + groupid + "'>";
for (var i = 0; i < len; i++) {
if (devices[i] != undefined) {
if (devices[i].subuser != undefined) {
subUser = devices[i].subuser;
selectedCheck = "checked";
} else {
selectedCheck = "";
}
}
if (i > 0 && (i % max) == 0) {
html += "\n </ul>";
/* html += "\n <ul class=\"listTableBody\">"; */
html += "\n <ul class=\"listTableBody\" id='listTableBody_" + groupid + "'>";
}
devicename = "";
checkboxhtml = "";
if (devices[i] != undefined) {
devicename = devices[i].devicename;
checkboxhtml = "\n <input type=\"checkbox\" id=\"listChk" + devices[i].deviceid + "\" name=\"listChkbox\" data-src='" + devices[i].deviceid + "'" + selectedCheck + ">";
checkboxhtml += "\n <label for=\"listChk" + devices[i].deviceid + "\" class=\"listChk\"></label>";
}
html += "\n <li>";
html += checkboxhtml;
if (devicename != null && devicename != "") {
html += "\n <span class=\"sensorNameTxt\">" + devicename + "</span>"
}
html += "\n </li>";
}
html += "\n </ul>";
return html;
}
function makeDevice(group) {
var html = makeDeviceHtml(group.devices,group.groupid);
var listTableBodyID = "#listTableBody_" + group.groupid;
return html;
}
function listChkAllEvent(groupId) {
var checkedYn = $("#listChkAll" + groupId).prop("checked");
var listTableBody = $("ul#listTableBody_" + groupId + " li input[name=listChkbox]");
if (checkedYn) {
listTableBody.each(function() {
$(this).prop("checked", true); // 찍혔을떄
});
} else {
listTableBody.each(function() {
$(this).prop("checked", false);
});
}
}
function makeDeviceGroupHtml(group) {
var html = "";
html += "\n<div class=\"listTable listTableSensor\" id=\"listTableSensor_"+ group.groupid +"\">"
html += "\n <ul class='listTableHead' id='listTableHead" + group.groupid + "'>";
html += "\n <li><input type='checkbox' id='listChkAll" + group.groupid + "' onchange='listChkAllEvent(" + group.groupid + ")'><label for='listChkAll" + group.groupid + "' class='listChk'></label><span class='sensorGroupTxt'>" + group.groupname + "</span></li>";
html += "\n </ul>";
html += makeDevice(group);
html += "\n</div>";
return html ;
}
function makeDeviceGroup(group) {
var listTableID = "#listTableSensor_" + group.groupid;
if ($(listTableID).length > 0) {
return;
}
//listTableSensor
/* var listTableID= "#listTable_" + groupid; */
var html = makeDeviceGroupHtml(group);
$("#userSensorInfo").append(html);
}
function makeUserSensorBoardList() {
var muserid = $("#userSensorInfo>em").attr("value");
var errorComment = $.i18n.prop('common.error');
$.ajax({
type : "get",
url : "/openapi/deviceuser/getdevicelist",
dataType : "json",
data : {
"userid" : muserid
},
success : function(result) {
var respObj = respParser.parse(result);
var returnCode = result.returnCode;
if (respObj.isSuccess()) {
var data = respObj.getDataObj();
var group = undefined;
var groupid = undefined;
var groupname = undefined;
for (var i = 0; i < data.length; i++) {
group = data[i];
groupid = group.groupid;
groupname = group.groupname;
makeDeviceGroup(group);
}
} else {
alert(returnCode +" "+ errorComment);
}
},error: function (error) {
alert(errorComment);
}
});
}
function manageDeviceAuthor() {
var chekcedDeviceArr = "";
var userid = $("#userSensorInfo>em").attr("value");
var errorComment = $.i18n.prop('common.error');
$("input[name=listChkbox]").each(function() {
if ($(this).is(":checked")) {
chekcedDeviceArr += "," + $(this).attr("data-src");
}
});
chekcedDeviceArr = chekcedDeviceArr.replace(/^,/, "");
$.ajax({
type : "post",
url : "/openapi/deviceuser/create",
data : {
"userid" : userid,
"deviceid" : chekcedDeviceArr
},
success : function(result) {
var respObj = respParser.parse(result);
var returnCode = result.returnCode;
if (respObj.isSuccess()) {
var manageUpdate = $.i18n.prop('account.select.user.manage.update');
alert(manageUpdate);
history.back();
} else {
alert(returnCode +" "+ errorComment);
}
},
error: function (error) {
alert(errorComment);
}
});
}
$(function() {
makeUserSensorBoardList();
});
$(document).ready(function() {
$(".mMenu").click(function(){
$(".nav").toggleClass("mNavOn");
$(this).toggleClass("mMenuClose");
});
});
|
import React from 'react';
import { Box, useInView } from '@sparkpost/matchbox';
import { describe, add } from '@sparkpost/libby-react';
describe('useInView', () => {
add('example usage', () => {
const [ref, inView] = useInView();
React.useLayoutEffect(() => {
if (inView) {
console.log('scrolled into view');
}
}, [inView]);
return (
<>
<Box position="fixed">{inView ? 'In View: True' : 'In View: False'}</Box>
<Box height="2000px" bg="blue.300"></Box>
<Box ref={ref} height="200px" bg="blue.700"></Box>
<Box height="2000px" bg="blue.300"></Box>
</>
);
});
add('once set to false', () => {
const [ref, inView] = useInView({ once: false });
React.useLayoutEffect(() => {
if (inView) {
console.log('scrolled into view');
}
}, [inView]);
return (
<>
<Box position="fixed">{inView ? 'In View: True' : 'In View: False'}</Box>
<Box height="2000px" bg="blue.300"></Box>
<Box ref={ref} height="200px" bg="blue.700"></Box>
<Box height="2000px" bg="blue.300"></Box>
</>
);
});
});
|
import React, { Component } from 'react'
import { Jumbotron, Modal } from 'react-bootstrap'
class LogOut extends Component {
state = { show: false }
logOut() {
if (sessionStorage.getItem('jwtToken')) {
sessionStorage.removeItem('jwtToken')
return true
} else return false
}
render() {
return (
<div>
<Modal show={this.logOut()} onHide={this.logOut}>
<h1>Logout successful</h1>
</Modal>
</div>
)
}
}
export default LogOut
|
describe('Layout', () => {
it('should render non-mobile layout', () => {
cy.viewport(1500, 500);
cy.visit('/iframe.html?path=Layout__annotated-example-in-page&source=false');
cy.get('[data-id="annotated-section"]').should('have.attr', 'width', '0.3333333333333333');
cy.get('[data-id="detail-section"]').should('have.attr', 'width', '1');
});
it('should render mobile layout', () => {
cy.viewport(500, 500);
cy.visit('/iframe.html?path=Layout__annotated-example-in-page&source=false');
cy.get('[data-id="annotated-section"]').should('have.attr', 'width', '100%');
cy.get('[data-id="detail-section"]').should('have.attr', 'width', '100%');
});
});
|
var shaders = {}
function compileShader(gl, shaderSource, shaderType) {
// Create the shader object
var shader = gl.createShader(shaderType);
// Set the shader source code.
gl.shaderSource(shader, shaderSource);
// Compile the shader
gl.compileShader(shader);
// Check if it compiled
var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
if (!success) {
// Something went wrong during compilation; get the error
throw "could not compile shader:" + gl.getShaderInfoLog(shader);
}
return shader;
}
function createProgram(gl, name, vertexShader, fragmentShader) {
// create a program.
var progra = gl.createProgram();
// attach the shaders.
gl.attachShader(progra, vertexShader);
gl.attachShader(progra, fragmentShader);
// link the program.
gl.linkProgram(progra);
gl.deleteShader(vertexShader)
gl.deleteShader(fragmentShader)
// Check if it linked.
var success = gl.getProgramParameter(progra, gl.LINK_STATUS);
if (!success) {
// something went wrong with the link
throw ("program filed to link:" + gl.getProgramInfoLog (progra));
}
window.program = progra;
program.positionAttribute = gl.getAttribLocation(program, "a_position");
gl.enableVertexAttribArray(program.vertexAttribute);
program.normalAttribute = gl.getAttribLocation(program, "a_normal");
gl.enableVertexAttribArray(program.normalAttribute);
program.textureAttribute = gl.getAttribLocation(program, "a_texture");
gl.enableVertexAttribArray(program.textureAttribute);
shaders[name] = progra;
}
function openFile(name, filename){
$.get(filename + '.vs', function (vxShaderData) {
var vxShader = compileShader(gl, vxShaderData, gl.VERTEX_SHADER)
$.get(filename + '.frag', function (fragShaderData) {
var fragShader = compileShader(gl, fragShaderData, gl.FRAGMENT_SHADER)
createProgram(gl, name, vxShader, fragShader)
}, 'text');
}, 'text');
}
function createShader(shadername) {
openFile(shadername, 'shaders/' + shadername)
}
function useShader(shadername) {
window.program = shaders[shadername]
gl.useProgram(window.program);
}
module.exports = {
compileShader,
createShader,
useShader,
}
|
function sum() {
var sum = 0;
var args = [].slice.call(arguments);
args.forEach(function(el) {
sum += el;
});
return sum;
}
Function.prototype.myBind = function(obj) {
var fn = this;
var args = [].slice.call(arguments, 1);
return function() {
args = args.concat([].slice.call(arguments, 0));
fn.apply(obj, args);
};
};
function curriedSum(numArgs) {
var numbers = [];
function _curriedSum(num) {
numbers.push(num);
if (numbers.length >= numArgs) {
var sum = 0;
numbers.forEach(function(el) {
sum += el;
});
return sum;
} else {
return _curriedSum;
}
}
return _curriedSum;
}
var sum = curriedSum(4);
console.log(sum(5)(30)(20)(1));
Function.prototype.curry = function(numArgs) {
var args = [];
function _curried(value) {
args.push(value);
if (args.length >= numArgs) {
return this.apply(null, args);
} else {
return _curried;
}
}.myBind(this)
return _curried;
};
function sumThree(num1, num2, num3) {
return num1 + num2 + num3;
}
console.log(sumThree.curry(3)(4)(20)(6)); // 30
|
const connection = require('./lib/ogmneo');
const nodes = require('./lib/ogmneo-node');
const query = require('./lib/ogmneo-query');
const relations = require('./lib/ogmneo-relation');
const cypher = require('./lib/ogmneo-cypher');
const index = require('./lib/ogmneo-index');
const where = require('./lib/ogmneo-where');
const relationQuery = require('./lib/ogmneo-relation-query');
const { OGMNeoOperation, OGMNeoOperationBuilder } = require('./lib/ogmneo-operation');
const OGMNeoOperationExecuter = require('./lib/ogmneo-operation-executer');
module.exports = {
Connection: connection,
OGMNeoNode: nodes,
OGMNeoQuery: query,
OGMNeoRelation: relations,
OGMNeoCypher: cypher,
OGMNeoIndex: index,
OGMNeoWhere: where,
OGMNeoRelationQuery: relationQuery,
OGMNeoOperation: OGMNeoOperation,
OGMNeoOperationBuilder: OGMNeoOperationBuilder,
OGMNeoOperationExecuter: OGMNeoOperationExecuter,
//Simplified names
Node: nodes,
Query: query,
Relation: relations,
Cypher: cypher,
Index: index,
Where: where,
RelationQuery: relationQuery,
Operation: OGMNeoOperation,
OperationBuilder: OGMNeoOperationBuilder,
OperationExecuter: OGMNeoOperationExecuter
};
|
var pager_8h =
[
[ "Pager", "structPager.html", "structPager" ],
[ "MUTT_PAGER_NO_FLAGS", "pager_8h.html#a0a536da5cd7ad9b881a8079052853818", null ],
[ "MUTT_SHOWFLAT", "pager_8h.html#a9de40b1f09f9cfecdf91e9caf90d76ae", null ],
[ "MUTT_SHOWCOLOR", "pager_8h.html#a6a24d55872e15f42b6dfcf7d560953e2", null ],
[ "MUTT_HIDE", "pager_8h.html#a3a522d77e5eb5a2535ee3f19eb9076b4", null ],
[ "MUTT_SEARCH", "pager_8h.html#a86dceb4c81c65f8932681c9ae415ac7b", null ],
[ "MUTT_TYPES", "pager_8h.html#a3c0d5d14b66d13aaab3432324b66a92d", null ],
[ "MUTT_SHOW", "pager_8h.html#aea254a51f411edcf16a4c4a92c409709", null ],
[ "MUTT_PAGER_NSKIP", "pager_8h.html#a23ab9b0bfd87bca53161f920511d6f6d", null ],
[ "MUTT_PAGER_MARKER", "pager_8h.html#a7871a664a014cdfe77a99439fa99d4cb", null ],
[ "MUTT_PAGER_RETWINCH", "pager_8h.html#a0e433fa8f7c79dc0e8b5eaea4d7a340e", null ],
[ "MUTT_PAGER_ATTACHMENT", "pager_8h.html#aea42b8def2b025d157e3da6a1be2b20e", null ],
[ "MUTT_PAGER_NOWRAP", "pager_8h.html#a325eecb6e92fd9ea24c0ea630a84df6f", null ],
[ "MUTT_PAGER_LOGS", "pager_8h.html#a82c7ea12bf1e83aaa34ee1decdcab418", null ],
[ "MUTT_PAGER_MESSAGE", "pager_8h.html#ac14f9120c844296965a8a2c87dc5f541", null ],
[ "MUTT_DISPLAYFLAGS", "pager_8h.html#a45c117fe5bfea2a2e42c6571eb637b38", null ],
[ "PagerFlags", "pager_8h.html#a4b89dc870e3d48afbacfc74da0533898", null ],
[ "mutt_pager", "pager_8h.html#a4cc11143557f95ded6a80f3cffff4483", null ],
[ "mutt_buffer_strip_formatting", "pager_8h.html#a29a3939691dd7a49875fc11c290bdfe1", null ],
[ "mutt_clear_pager_position", "pager_8h.html#a52cb29b8a518d62062551b6ff7a3cb4f", null ],
[ "C_AllowAnsi", "pager_8h.html#a6b700cbac399d0f8221c7e61fcec27e1", null ],
[ "C_HeaderColorPartial", "pager_8h.html#a8b3696d504ae42d6bd92761c36932ad7", null ],
[ "C_PagerContext", "pager_8h.html#ad9e4cd6ca02577884aa93eed2061bbc6", null ],
[ "C_PagerIndexLines", "pager_8h.html#a8a2ea9f39ac5b790c9ba6c2d7bfae1ea", null ],
[ "C_PagerStop", "pager_8h.html#a68ce551360f9ef21bddce323cd5c908f", null ],
[ "C_SearchContext", "pager_8h.html#a7bcc9b4c39c4d3521107e8541594f58f", null ],
[ "C_SkipQuotedOffset", "pager_8h.html#a991a66797f24f565ba5d2968675f172c", null ],
[ "C_SmartWrap", "pager_8h.html#a25c1dd2ddd3e5c9425ee317835553131", null ],
[ "C_Smileys", "pager_8h.html#aa68ee60b325ec00be0ab092a52ecad10", null ],
[ "C_Tilde", "pager_8h.html#af45c1784dee197faf429be89ac0a97e1", null ]
]; |
var abilities, heros, vaingloryData;
vaingloryData = require('./index.js');
heros = vaingloryData.heros;
abilities = vaingloryData.abilities;
console.log(heros[0]);
/*
{ key: 'adagio', name: 'アダージオ' }
*/
console.log(abilities[0].key);
/*
adagio
*/
|
import React from 'react'
export default function Title({ children, title, subtitle }) {
return (
<div className='mx-2 mb-3'>
<h5 className='is-size-5 has-text-link'>{title}</h5>
<h3 className='has-text-link is-size-3 has-text-weight-bold has-text-link'>
{subtitle}
</h3>
<div style={{ maxWidth: 450 }}>{children}</div>
</div>
)
}
|
angular.module("wunderlistApp")
.controller("listCtrl", function ($scope, $http, listsUrl) {
$scope.addNewList = function (newListName) {
if (newListName == undefined || newListName == "") {
alert("You do not lead a list name! Please specify the field for the list name!");
} else {
var list = {
UserModelId: $scope.user.Id,
Name: newListName
}
$scope.newListName = "";
$http.post(listsUrl, list).success(function (newList) {
$scope.allListsUser.lists.push(newList);
$('#createListWindow').modal('hide');
});
}
}
function editTitle(id) {
$(".editingblock").addClass('hidden');
$("#editingblock_" + id).removeClass('hidden');
}
function changeTitle(list) {
var newName = $('#newTitle_' + list.Id).val();
list.Name = newName;
$http.put(listsUrl + list.Id, list).success(function (list) {
$(".editingblock").addClass("hidden");
});
}
$scope.$on("editTitleEvent", function (event, args) {
editTitle(args.taskId);
});
$scope.$on("changeTitleEvent", function (event, args) {
changeTitle(args.newList);
});
}); |
import React, { Component } from 'react';
export default class Controls extends Component{
render() {
return (
<div className="Controls">
<div className="Button">
<i className="fa fa-fw fa-play"></i>
</div>
</div>
)
}
}
|
//获取id,class,tagName
function getId(id) {
return typeof id === "string" ? document.getElementById(id): id;
}
function getClass(sClass, oParent) {
var aClass = [];
var reClass = new RegExp("(^| )" + sClass + "( |$)");
var aElem = getTagName("*", oParent);
for (var i = 0; i < aElem.length; i++) {
reClass.test(aElem[i].className) && aClass.push(aElem[i])
};
return aClass;
}
function getTagName(elem, obj) {
return (obj || document).getElementsByTagName(elem);
}
// 事件绑定,删除
var EventUtil = {
addHandler : function(oElement, sEvent, fnHandler) {
oElement.addEventListener ? oElement.addEventListener(sEvent, fnHandler, false) :
(oElement["_"+ sEvent + fnHandler] = fnHandler, oElement[sEvent + fnHandler] = function() {
oElement["_"+sEvent + fnHandler]()}, oElement.attachEvent("on" + sEvent, oElement[sEvent + fnHandler]))
},
removeHandler : function(oElement, sEvent, fnHandler) {
oElement.removeEventListener ? oElement.removeEventListener(sEvent,fnHandler, false) : oElement.detachEvent("on" + sEvent, oElement[sEvent + fnHandler])
},
addLoadHandler : function(fnHandler) {
this.addHandler(window,"load", fnHandler)
}
}
//设置css样式,读取css样式
function css(obj,attr,value) {
switch(arguments.length) {
case 2:
if(typeof arguments[1] == "object") {
for ( var i in attr) i == "opacticy" ? (obj.style["filter"] = "alpha(opacticy="+attr[i]+")", obj.style[i] = attr[i]/100) : obj.style[i] = attr[i];
}else{
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj, null)[attr]
}
break;
case 3:
attr == "opacity" ? (obj.style["filter"] = "alpha(opacity="+ value +")", obj.style[attr] = value/100 ) : obj.style[attr] = value;
break;
}
}
EventUtil.addLoadHandler(function() {
var oMsgBox = getId("oMsgBox");
var oUserName = getId("userName");
var oConBox = getId("conBox");
var oSendBtn = getId("sendBtn");
var oMaxNum = getClass("maxNum")[0];
var oCountTxt = getClass("countTxt")[0];
var oList = getClass("list")[0];
var oUl = getTagName("ul",oList)[0];
var aLi = getTagName("li", oList);
var aFtxt = getClass("f-text",oMsgBox);
var aImg = getTagName("img", getId("face"));
var bSend = false;
var oTmp = "";
var maxNum = 140;
//禁止表单提交
EventUtil.addHandler(getTagName("form", oMsgBox)[0], "submit", function(){ return false});
//为广播按钮绑定发送事件
EventUtil.addHandler(oSendBtn, "click" ,fnsend);
// 为Ctrl+Enter快捷键绑定发送事件
EventUtil.addHandler(document, "keyup", function(event){
var event = event || window.event;
event.ctrlKey && event.keyCode == 13 && fnsend()
});
//发送广播函数
function fnsend() {
var reg = /^\s*$/g;
if(reg.test(oUserName.value)){
alert("请填写您的姓名");
oUserName.focus();
}else if(!/^[u4e00-\u9fa5\w]{2,8}$/g.test(oUserName.value)) {
alert("姓名由2-8位字母、数字、下划线、汉字组成!");
oUserName.focus()
}else if(reg.test(oConBox.value)){
alert("随便说点什么吧!");
oConBox.focus()
}else if(!bSend){
alert("你输入的内容已超出限制,请检查!");
oConBox.focus()
}else{
var oLi = document.createElement("li");
var oDate = new Date();
oLi.innerHTML = "<div class=\"userPic\"><img src=\"" + getClass("current", getId("face"))[0].src + "\"> </div>\
<div class=\"content\">\
<div class=\"userName\"><a href=\"javascript:;\">"+oUserName.value+"</a>:</div>\
<div class=\"msgInfo\">"+oConBox.value.replace(/<[^>]*>| /ig,"")+"</div>\
<div class=\"times\"><span>"+format(oDate.getMonth()+1)+"月"+format(oDate.getDate())+"日"+format(oDate.getHours())+":"+format(oDate.getMinutes())+"</span><a class=\"del\" href=\"javascript:;\">删除</a></div>\
</div>";
}
//插入元素
aLi.length ? oUl.insertBefore(oLi,aLi[0]) : oUl.appendChild(oLi);
//重置表单
getTagName("form", oMsgBox)[0].reset();
for (var i = 0; i < aImg.length; i++) {
aImg[i].className = "";
};
aImg[0].className = "curent";
//将元素保存
var iHeight = oLi.clientHeight - parseFloat(css(oLi,"paddingTop")) - parseFloat(css(oLi,"paddingBottom"));
var alpha = count = 0;
css(oLi, {"opacity": "0", "height" : "0"});
timer = setInterval(function(){
css(oLi, {"display": "block", "opacity": "0", "height": (count += 8) + "px"});
if(count > iHeight){
clearInterval(timer);
css(oLi,"height",iHeight+"px");
timer = setInterval(function(){
css(oLi,"opacity", (alpha += 10));
alpha > 100 && (clearInterval(timer), css(oLi, "opacity", 100))
},30)
}
},30)
//调用鼠标划过/离开样式
liHover();
//调用删除函数
delLi()
}
//事件绑定,判断字符输入
EventUtil.addHandler(oConBox, "keyup", confine);
EventUtil.addHandler(oConBox, "focus", confine);
EventUtil.addHandler(oConBox, "change", confine);
//输入字符限制
function confine() {
var iLen = 0;
for (var i = 0; i < oConBox.value.length; i++) {
iLen += /[^\x00-\xff]/g.test(oConBox.value.charAt(i))?1:0.5;
};
oMaxNum.innerHTML = Math.abs(maxNum - Math.floor(iLen));
maxNum - Math.floor(iLen) >= 0 ? (css(oMaxNum,"color", ""), oCountTxt.innerHTML = "还能输入", bSend = true) :
(css(oMaxNum,"color","#f60"),oCountTxt.innerHTML = "已超出", bSend = false)
}
//加载即调用
confine();
// 广播按钮鼠标划过样式
EventUtil.addHandler(oSendBtn, "mouseover", function() {this.className = "hover"});
// 广播按钮鼠标离开样式
EventUtil.addHandler(oSendBtn, "mouseout", function() {this.className = ""})
// li鼠标划过/离开处理函数
function liHover(){
for (var i = 0; i < aLi.length; i++) {
//鼠标划过样式
EventUtil.addHandler(aLi[i],"mouseover",function(event){
this.className = "hover";
oTmp = getClass("times",this)[0];
var aA = getTagName("a", oTmp);
if(!aA.length){
var oA = document.createElement("a");
oA.innerHTMl = "删除";
oA.className = "del";
oA.href = "javascript:;";
oTmp.appendChild(oA)
}else{
aA[0].style.display = "block";
}
});
//鼠标离开样式
EventUtil.addHandler(aLi[i],"mouseout",function(){
this.className = "";
var oA = getTagName("a",getClass("times",this)[0])[0];
oA.style.display = "none"
})
};
}
liHover();
//删除功能
function delLi() {
var aA = getClass("del",oUl);
for (var i = 0; i < aA.length; i++) {
aA[i].onclick = function() {
var oParent = this.parentNode.parentNode.parentNode;
var alpha = 100;
var iHeight = oParent.offsetHeight;
timer = setInterval(function(){
css(oParent,"opacity",(alpha -= 10));
if(alpha < 0) {
clearInterval(timer);
timer = setInterval(function(){
iHeight -= 10;
iHeight < 0 && (iHeight = 0);
css(oParent, "iHeight", iHeight+"px");
iHeight == 0 && (clearInterval(timer),oUl.removeChild(oParent))
},30)
}
},30)
this.onclick = null
}
};
}
delLi();
//输入框获取焦点时样式
for (var i = 0; i < aFtxt.length; i++) {
EventUtil.addHandler(aFtxt[i],"focus", function() { this.className = "active"});
EventUtil.addHandler(aFtxt[i],"blur", function() {this.clearName = ""})
};
// 格式化时间,如果为一位数时补0
function format(str){
return str.toString().replace(/^(\d)$/,"0$1")
}
//头像
for (var i = 0; i < aImg.length; i++) {
aImg[i].onmouseover = function() {
this.className += " hover"
}
aImg[i].onmouseout = function() {
this.className = this.className.replace(/\s?hover/,"")
}
aImg[i].onclick = function () {
for (var i = 0; i < aImg.length; i++) {
aImg[i].className = "";
}
this.className = "current";
}
};
}) |
const path = require('path');
const Dotenv = require('dotenv-webpack');
const TerserJSPlugin = require('terser-webpack-plugin');
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
module.exports = (_, argv) => ({
entry: './src/app.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: argv.mode === 'production' ? '[name].[hash].js' : '[name].js'
},
optimization: {
minimizer: [new TerserJSPlugin({extractComments: false}), new OptimizeCSSAssetsPlugin({})],
moduleIds: 'hashed',
splitChunks: {
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all',
},
},
},
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
scss: 'vue-style-loader!css-loader!sass-loader'
}
}
},
{
test: /\.css$/,
use: [
argv.mode === 'production' ?
MiniCssExtractPlugin.loader :
'vue-style-loader',
'css-loader'
]
},
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
}
]
},
resolve: {
modules: [path.resolve(__dirname, './src'), 'node_modules'],
alias: { vue: 'vue/dist/vue.esm.js' }
},
devServer: {
host: 'localhost',
port: 8082,
publicPath: '/dist/'
},
plugins: [
new Dotenv({systemvars: argv.mode === 'production'}),
new VueLoaderPlugin(),
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
template: './index.ejs',
title: 'Indíces de valores financiais',
filename: '../index.html',
alwaysWriteToDisk: true
}),
new HtmlWebpackHarddiskPlugin(),
new MiniCssExtractPlugin({
filename: argv.mode !== 'production' ? '[name].css' : '[name].[hash].css',
chunkFilename: argv.mode !== 'production' ? '[id].css' : '[id].[hash].css'
})
]
});
|
import history from '../history';
import routes from '../constants/routes';
import {
EDIT_TOURNAMENT, TOURNAMENT_CREATED, TOURNAMENT_SAVED, TOURNAMENT_DELETED, SELECT_TOURNAMENT, SELECT_TOURNAMENT_TAB,
EDIT_USER, USER_CREATED, USER_SAVED,
CANCEL_EDIT
} from '../constants/action-types';
const mappings = {
[EDIT_TOURNAMENT]: tournament => `${routes.admin}/tournament/${tournament.id}`,
[TOURNAMENT_CREATED]: routes.admin,
[TOURNAMENT_SAVED]: routes.admin,
[TOURNAMENT_DELETED]: routes.admin,
[SELECT_TOURNAMENT]: tournament => `${routes.tournaments}/${tournament.id}`,
[SELECT_TOURNAMENT_TAB]: ({ tab, tournament }) => `${routes.tournaments}/${tournament.id}/${tab}`,
[EDIT_USER]: user => `${routes.admin}/user/${user.id}`,
[USER_CREATED]: routes.admin,
[USER_SAVED]: routes.admin,
[CANCEL_EDIT]: routes.admin
};
export default function impureRouting(state = {}, action) {
var route = mappings[action.type];
if (route) {
if (typeof route === 'function') {
route = route(action.payload);
}
history.pushState(null, route);
}
return state;
}
|
// Find the indices wchich add up k in an array
var a = [4, 2, 5, 1, 6, 0, 8, 0, 2],
k = 6,
x = 0,
r = {};
for (var i = 0; i < a.length; i += 1) {
for (var j = (i + 1); j < a.length; j += 1) {
sum = a[i] + a[j];
if (sum == k) {
r[x++] = i + ":" + j;
}
}
}
alert(JSON.stringify(r)); |
(function () {
/**
* Function that search if an object has all the specified methods and all those methods are functions.
*
* @since 4.7.7
*
* @param {Object} obj The object where all the methods might be stored
* @param {Array} methods An array with the name of all the methods to be tested
* @return {boolean} True if has all the methods false otherwise.
*/
function search_for_methods(obj, methods) {
// Object is not defined or does not exist on window nothing to do.
if (!obj || window[obj]) {
return false;
}
var search = methods.filter(function (name) {
// Test if the method is part of Obj and if is a function.
return obj[name] && "function" === typeof obj[name];
});
return methods.length === search.length;
}
/**
* Function to compare if the variable _ is from lodash by testing some of us unique methods.
*
* @since 4.7.7
*
* @return {boolean} True if the global _ is from lodash.
*/
function is_lodash() {
return search_for_methods(window._, [
"get",
"set",
"at",
"cloneDeep",
"some",
"every",
]);
}
window._lodash_tmp = false;
// If current _ is from lodash Store it in a temp variable before underscore is loaded
if ("_" in window && is_lodash()) {
window._lodash_tmp = _;
}
})();
|
/// <reference path="Lib/jquery.d.ts"/>
/// <reference path="Lib/knockout.d.ts"/>
/// <reference path="ViewBase.ts"/>
/// <reference path="DynamicViewModel.ts"/>
var CordSharp;
(function (CordSharp) {
var Binder = (function () {
function Binder() {
}
Binder.addBindingAttribute = function (targetElementId, targetId) {
$("#" + targetElementId).find("[" + Binder.DATA_BIND_SOURCE + "]").each(function (index, item) {
var element = $(this);
if (element.attr(Binder.DATA_BIND_SOURCE_ID) === undefined && element.attr(CordSharpView.ViewBase.DATA_CONTROL_ID) === targetElementId) {
var value = element.attr(Binder.DATA_BIND_SOURCE);
element.attr(Binder.DATA_BIND, value);
element.attr(Binder.DATA_BIND_SOURCE_ID, targetId);
}
});
ko.applyBindings(root, $("#" + targetElementId)[0]);
};
Binder.bind = function (jsonData, targetElementId) {
root.objTree(jsonData);
Binder.addBindingAttribute(targetElementId, Object.getOwnPropertyNames(jsonData)[0]);
};
Binder.unbindByControl = function (targetElementId, bindId) {
$("#" + targetElementId).find("[" + Binder.DATA_BIND + "]").each(function (index, item) {
var element = $(this);
if (element.attr(Binder.DATA_BIND_SOURCE_ID) === bindId) {
element.removeAttr(Binder.DATA_BIND);
element.removeAttr(Binder.DATA_BIND_SOURCE_ID);
}
});
ko.cleanNode($("#" + targetElementId)[0]);
};
Binder.unbind = function (bindId) {
delete root[bindId];
delete root["$" + bindId];
};
Binder.setValue = function (obje, value, path) {
if (_.isArray(value)) {
obje.removeAll();
for (var i in value) {
if (_.isObject(value[i])) {
var model = new CordSharp.DynamicViewModel(path + "." + i, value[i]);
obje.push(model);
} else {
obje.push(value[i]);
}
}
} else if (_.isObject(value)) {
Binder.propertyChangedObject(obje, value, path);
} else {
obje._isNotifyIgnored = true;
obje(value);
}
};
Binder.propertyChangedObject = function (obje, value, path) {
for (var i in value) {
Binder.setValue(obje[i], value[i], path);
}
};
Binder.getViewModelByPath = function (paths) {
var ref = root;
if (paths.length > 1) {
for (var i = 0; i < paths.length; i++) {
if (ref["$" + paths[i]] !== undefined) {
ref = ref["$" + paths[i]];
} else if (_.isArray(ref)) {
ref = ref[paths[i]];
} else {
ref = ref[paths[i]];
if (i !== paths.length - 1) {
ref = ref();
}
}
}
}
return ref;
};
Binder.propertyChanged = function (path, value) {
var prePaths = path.replace("[", ".").replace("]", "").split("@");
console.log("[Binder]prePaths ", prePaths);
var paths = prePaths[0].split(".");
var ref = Binder.getViewModelByPath(paths);
if (prePaths.length === 1) {
Binder.setValue(ref, value, prePaths[0]);
} else if (prePaths[1] === "Add") {
var index = ref.length;
var insertIndex = +prePaths[2];
for (var i = 0; i < value.length; i++) {
console.log("add ", value[i]);
if (_.isObject(value[i])) {
var model = new CordSharp.DynamicViewModel(prePaths[0] + "." + (index + i), value[i]);
ref.splice(insertIndex + i, 0, model);
} else {
ref.splice(insertIndex + i, 0, value[i]);
}
}
} else if (prePaths[1] === "Remove") {
ref.splice(value - 0, 1);
} else if (prePaths[1] === "Reset") {
ref.removeAll();
}
};
Binder.DATA_BIND_SOURCE = "data-bind-source";
Binder.DATA_BIND_SOURCE_ID = "data-source-id";
Binder.DATA_BIND = "data-bind";
return Binder;
})();
CordSharp.Binder = Binder;
})(CordSharp || (CordSharp = {}));
|
import React, { PropTypes, Component } from 'react';
import styles from './SelectStations.module.scss';
import cssModules from 'react-css-modules';
import { Snackbar } from 'material-ui';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as StationsActionCreators from '../../actions/stations';
import * as ScheduleActionCreators from '../../actions/schedule';
import * as GlobalActionCreators from '../../actions/index';
import {
ComponentLoadingIndicator,
StationsInputs
} from 'components';
const toGeo = ({
latitude,
longitude
}) => `lonlat:-${longitude},${latitude}`;
class SelectStations extends Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
this.handleSelectDeparture = this.handleSelectDeparture.bind(this);
this.handleSelectArrival = this.handleSelectArrival.bind(this);
this.handleCloseSnackbar = this.handleCloseSnackbar.bind(this);
this.handleClearStations = this.handleClearStations.bind(this);
this.handleSuccess = this.handleSuccess.bind(this);
this.handleErrors = this.handleErrors.bind(this);
this.handleMessage = this.handleMessage.bind(this);
this.fetchStations = this.fetchStations.bind(this);
this.handleRouting = this.handleRouting.bind(this);
this.state = {
snackbar: {
message: ''
}
};
}
componentDidMount() {
this.fetchStations();
}
componentWillReceiveProps(nextProps) {
const {
errors
} = nextProps;
if (errors.length > 0) {
this.handleErrors(errors);
}
}
handleSelectArrival(event, index, value) {
const {
actions
} = this.props;
actions.selectArrivalStation(value);
}
handleSelectDeparture(event, index, value) {
const {
actions
} = this.props;
actions.selectDepartureStation(value);
}
handleCloseSnackbar() {
const {
actions
} = this.props;
actions.clearStationErrors();
}
handleClearStations() {
const {
actions
} = this.props;
actions.clearSelectedStations();
}
fetchStations() {
const {
actions,
isOffline
} = this.props;
if (!navigator.onLine || isOffline) {
actions.loadStationsOffline();
} else {
actions.fetchStations();
}
}
handleMessage({ message }) {
this.setState({
snackbar: {
message
}
});
}
handleSubmit() {
const {
actions,
selectedDepartureStation,
selectedArrivalStation
} = this.props;
const dCode = selectedDepartureStation;
const aCode = selectedArrivalStation;
if (dCode && aCode) {
this.handleSuccess(dCode, aCode);
} else {
const errors = [];
if (!dCode) {
errors.push(
{
message: 'Please select a Departure Train Station'
}
);
}
if (!aCode) {
errors.push(
{
message: 'Please select an Arrival Train Station.'
}
);
}
actions.showStationErrors(errors);
}
}
handleSuccess(dep, arr) {
const {
actions,
stations
} = this.props;
this.handleRouting();
const departure = toGeo(
stations.filter(item =>
item.station_code === dep
)[0]
);
const arrival = toGeo(
stations.filter(item =>
item.station_code === arr
)[0]
);
if (navigator.offLine) {
actions.fetchDefaultSchedule();
} else {
actions.fetchSchedule(
departure,
arrival
);
}
}
handleRouting() {
const {
router
} = this.context;
router.push('/schedule');
}
handleErrors(errors) {
if (errors.length > 1) {
errors.forEach(item =>
setTimeout(
this.setState({
snackbar: {
message: item.message
}
}),
2000
)
);
} else if (errors.length > 0) {
this.setState({
snackbar: {
message: errors[0].message
}
});
} else {
this.setState({
snackbar: {
message: ''
}
});
}
}
render() {
const {
isLoading,
errors,
funMode,
mapMode,
selectedDepartureStation,
selectedArrivalStation,
stations
} = this.props;
const {
message
} = this.state.snackbar;
return (
<div className={styles.container}>
{isLoading ?
<ComponentLoadingIndicator funMode={funMode} />
:
<StationsInputs
isLoading={isLoading}
handleSelectArrival={this.handleSelectArrival}
selectedArrivalStation={selectedArrivalStation}
stations={stations}
selectedDepartureStation={selectedDepartureStation}
handleSelectDeparture={this.handleSelectDeparture}
handleSubmit={this.handleSubmit}
mapMode={mapMode}
onClearStations={this.handleClearStations}
/>
}
<Snackbar
open={errors.length > 0}
message={message || 'An unknown error occured'}
autoHideDuration={4000}
action="Close"
onActionTouchTap={this.handleCloseSnackbar}
onRequestClose={this.handleCloseSnackbar}
/>
</div>
);
}
}
SelectStations.propTypes = {
stations: PropTypes.array.isRequired,
selectedDepartureStation: PropTypes.string,
errors: PropTypes.array.isRequired,
selectedArrivalStation: PropTypes.string,
actions: PropTypes.object.isRequired,
isLoading: PropTypes.bool.isRequired,
isOffline: PropTypes.bool.isRequired,
funMode: PropTypes.bool.isRequired,
mapMode: PropTypes.bool.isRequired
};
SelectStations.contextTypes = {
router: React.PropTypes.object.isRequired
};
const mapStateToProps = (state) => ({
isLoading: state.stations.isLoading,
stations: state.stations.items,
errors: state.stations.errors,
selectedArrivalStation: state.stations.selectedArrivalStation,
selectedDepartureStation: state.stations.selectedDepartureStation,
funMode: state.settings.funMode,
mapMode: state.settings.mapMode,
isOffline: state.settings.offlineMode
});
const mapDispatchToProps =
(dispatch) => ({
actions: bindActionCreators(
Object.assign({},
StationsActionCreators,
ScheduleActionCreators,
GlobalActionCreators
), dispatch)
});
const SelectStationsStyled = cssModules(
SelectStations,
styles
);
export default connect(
mapStateToProps,
mapDispatchToProps
)(SelectStationsStyled);
|
const request = require('superagent')
const cheerio = require('cheerio')
const fs = require('fs-extra')
const index_fn = async (ctx, next) => {
let url = 'http://www.mmjpg.com/tag/meitui/'
request
.get(url + '1')
.then(function (res) {
console.log(res.text)
})
}
module.exports = {
'GET /reptile': index_fn
}
|
(function() {
angular.module('Data', ['ngProgress'])
.factory("Data", ['$http', 'ngProgressFactory', '$rootScope', '$q',
function ($http, ngProgressFactory, $rootScope, $q) {
var timestamp = new Date().getTime();
timestamp = '?&i='+timestamp;
var progressBar = ngProgressFactory.createInstance();
//progressBar.setParent(document.getElementById('main-container'));
progressBar.queue = 0;
progressBar.updateQueue = function(value){
var startedNow = true;
if(progressBar.queue == 0) startedNow = false;
//debugger;
progressBar.queue = progressBar.queue + value;
if(progressBar.queue > 0) {
if(!startedNow) {
progressBar.start();
}
else{
if(progressBar.queue != 1){
var newVal = (100 / progressBar.queue);
progressBar.set(newVal);
progressBar.start();
}
}
}
else{
progressBar.complete();
}
}
var obj = {};
var serviceBase = 'API/';
obj.handleError = function(e){
//debugger;
if(typeof(e.data) != 'undefined' && e.data){
console.log("POST failed",e);
console.log(e.data.status + " : " + e.data.message + " : " + e.data.cause);
$rootScope.hasError = true;
$rootScope.error = {
status: e.data.status,
message: e.data.message,
cause: e.data.cause
};
}else{
//don't think this will ever hit, unless server is unreachable?
$rootScope.hasError = true;
$rootScope.error = {
status: -1,
message: "uncaught exception",
cause: "check that the URL is correct and that the server is reachable."
};
}
};
obj.get = function (url, headers, params) {
//debugger;
progressBar.updateQueue(1);
return $http({
method: 'GET',
headers: headers,
url: url + params
}).catch(function(e){
obj.handleError(e);
}).then(function (results) {
progressBar.updateQueue(-1);
console.log("post results: ",results);
if(typeof results == 'undefined'){
return $rootScope.error;
}
return results;
});
};
obj.post = function (url, postBody, headers) {
progressBar.updateQueue(1);
return $http({
method: 'POST',
headers: headers,
url: url,
data: postBody
}).catch(function(e){
console.log("POST failure", e);
obj.handleError(e);
}).then(function (results) {
progressBar.updateQueue(-1);
console.log("post results: ",results);
if(typeof results == 'undefined'){
return $rootScope.error;
}
return results;
});
};
obj.delete = function (url, headers) {
//debugger;
progressBar.updateQueue(1);
return $http({
method: 'DELETE',
headers: headers,
url: url
}).then(function (results) {
progressBar.updateQueue(-1);
console.log("DELETE results: ");
console.log(results);
return results;
});
};
obj.put = function (q, object) {
return $http.put(serviceBase + q, object).then(function (results) {
console.log("put: " + JSON.stringify(results.data));
return results.data;
});
};
return obj;
}
])
})(); |
$(document).ready(function(){
buildFormValidate();
//Form
buildActivityFormSubmit();
buildActivityEditFormSubmit();
//View Activities
buildActivityEdit();
buildActivityDelete();
$('input[name=name]').on('blur', function(){
if (typeof localStorage.edit == "undefined"){
checkIfExistsActivity();
}
});
});
function checkIfExistsActivity(){
var name = $('input[name=name]').val();
$.ajax({
success: function(response){
printResponse(response);
if(response.exists){
$('input[name=name]').val('');
simpleToastr('Hey!', 'Já existe uma ativade igual.', 'warning');
return false;
}else{
return true;
}
},
error: function(response){
printResponse(response);
simpleToastr('Oops!', 'Algo deu errado! Tente novamente.', 'error');
},
url: prefixUrl + '/activity/checkIfExistsActivity',
type: 'POST',
data: {name: name, 'form-submitted': 'true'},
dataType: 'json'
});
}
function buildActivityFormSubmit(){
if (typeof localStorage.edit == "undefined"){
$('#activity-form').ajaxForm({
beforeSubmit: function(){
checkIfExistsActivity();
$('button[name=submit]').button('loading');
},
success: function(response){
printResponse(response);
if(response.successful){
simpleToastr('Yay!', 'Atividade adicionada com sucesso! :D', 'success');
}else{
simpleToastr('Oops!', 'Algo deu errado! Tente novamente.', 'error');
}
$('button[name=submit]').button('reset');
},
error: function(response){
printResponse(response);
simpleToastr('Oops!', 'Algo deu errado! Tente novamente.', 'error');
$('button[name=submit]').button('reset');
},
url: prefixUrl + '/activity/saveNew',
type: 'POST',
dataType: 'json',
clearForm: true,
resetForm: true
});
}
}
function buildActivityEditFormSubmit(){
if (typeof localStorage.edit != "undefined"){
$('input[name=id]').val(localStorage.id);
$('input[name=name]').val(localStorage.name);
$('textarea[name=description]').html(localStorage.description);
$('option[value=' + localStorage.type + ']').attr('selected', 'selected');
$('input[name=duration]').val(localStorage.duration);
$('textarea[name=goal]').html(localStorage.goal);
$('textarea[name=requirement]').html(localStorage.requirement);
$('button[name=submit]').html('Editar');
$('button[name=submit]').attr('data-loading-text', 'Editando...');
$('#activity-form').ajaxForm({
beforeSubmit: function(){
checkIfExistsActivity();
$('button[name=submit]').button('loading');
},
success: function(response){
printResponse(response);
if(response.successful){
lastPage = localStorage.lastPage;
delete localStorage.lastPage;
simpleAlert('Yay!', 'Atividade editada com sucesso! :D', 'success', function(){window.location.href = lastPage;});
}else{
simpleToastr('Oops!', 'Algo deu errado! Tente editar novamente.', 'error');
}
$('button[name=submit]').button('reset');
},
error: function(response){
printResponse(response);
simpleToastr('Oops!', 'Algo deu errado! Tente editar novamente.', 'error');
$('button[name=submit]').button('reset');
},
url: prefixUrl + '/activity/edit',
type: 'POST',
dataType: 'json',
clearForm: true,
resetForm: true
});
delete localStorage.edit;
delete localStorage.id;
delete localStorage.name;
delete localStorage.description;
delete localStorage.type;
delete localStorage.duration;
delete localStorage.goal;
delete localStorage.requirement;
}
}
function buildFormValidate(){
$("#activity-form").validate({
rules: {
name: {
required: true,
maxlength: 50
},
description: {
required: true
},
especificacoes: {
required: true
},
type: {
required: true
},
duration: {
required: true,
digits: true
},
goal: {
required: true
}
}
});
}
function buildActivityEdit(){
$('.edit').on('click.edit', function(e){
e.preventDefault();
var id = $(this).attr('activity');
editActivity(id);
});
}
function buildActivityDelete(){
$('.delete').on('click.delete', function(e){
e.preventDefault();
var id = $(this).attr('activity');
confirmAlert('Tem certeza?', 'A atividade será apagada pra sempre!', 'warning', 'Tenho certeza!', deleteActivity, id);
});
}
function editActivity(id){
$.ajax({
success: function(response){
printResponse(response);
if(response.successful){
localStorage.edit = true;
localStorage.id = response.id;
localStorage.name = response.name;
localStorage.description = response.description;
localStorage.type = response.type;
localStorage.duration = response.duration;
localStorage.goal = response.goal;
localStorage.requirement = response.requirement;
localStorage.lastPage = window.location.href.split('/').last();
window.location.href = "edit";
}
},
error: function(response){
printResponse(response);
simpleToastr('Oops!', 'Algo deu errado! Tente editar novamente.', 'error');
},
url: prefixUrl + '/activity/selectById',
type: 'POST',
data: {id: id, 'form-submitted': 'true'},
dataType: 'json'
});
}
function deleteActivity(id){
$.ajax({
success: function(response){
printResponse(response);
if(response.successful){
simpleToastr('Yay!', 'Atividade foi excluida por toda eternidade!', 'success');
$('div[activity=' + id + ']').remove();
}
},
error: function(response){
printResponse(response);
simpleToastr('Oops!', 'Algo deu errado! Tente deletar novamente.', 'error');
},
url: prefixUrl + '/activity/delete',
type: 'POST',
data: {id: id, 'form-submitted': 'true'},
dataType: 'json'
});
} |
module.exports = function(RED) {
function signalKSendPathValue(config) {
RED.nodes.createNode(this,config);
var node = this;
var app = node.context().global.get('app')
var source = config.name ? 'node-red-' + config.name : 'node-red'
var sentMeta = false
function showStatus(text) {
node.status({fill:"green",shape:"dot",text:text});
}
node.on('input', msg => {
if ( !msg.topic ) {
node.error('no topic for incomming message')
return
}
if ( typeof config.meta !== 'undefined' && config.meta !== "" && !sentMeta ) {
let delta = {
updates: [
{
meta: [
{
value: JSON.parse(config.meta),
path: msg.topic
}
]
}
]
}
if ( config.source && config.source.length > 0 ) {
delta.updates[0].$source = config.source
}
app.handleMessage(source, delta)
sentMeta = true
}
let delta = {
updates: [
{
values: [
{
value: msg.payload,
path: msg.topic
}
]
}
]
}
if ( config.source && config.source.length > 0 ) {
delta.updates[0].$source = config.source
}
let c = msg.topic.lastIndexOf('.')
showStatus(`${msg.topic.substring(c+1)}: ${msg.payload}`)
app.handleMessage(source, delta)
})
}
RED.nodes.registerType("signalk-send-pathvalue", signalKSendPathValue);
}
|
/*
Author: Kevin Ward
Class: ASD1211
*/
$("#home").on("pageinit", function() {
console.log("Home page loaded! Yay!");
// Home page code goes here.
$("header nav")
.slideDown()
;
var changePage = function(pageId) {
$('#' + pageId).trigger('pageinit');
$.mobile.changePage($('#' + pageId), {
type:"post",
data:$("petForm").serialize(),
reloadPage:true,
transition:"slide"
});
};
}); // End code for home page.
$("#addItem").on("pageinit", function() {
console.log("Add Item page loaded!");
// My Variables
var showPet = $("#showData");
showPet.on('click', readPet);
var clearLink = $("#clearData");
clearLink.on('click', deletePet);
var savePet = $("#submit");
savePet.on('click', createPet);
// This is supposed to create the variable doc to pass to the
//different functions, but it's not reading correctly for some reason.
/*var doc = {
};
doc._id = "pets:" + variable;
// to give it a custom id
doc.petGroups = "petGroup";
doc.petName = "petName";
doc.genderVal = "genderVal";
doc.favePet = "favePet";
doc.koolness = "koolness";
doc.comments = "comments";*/
// Create portion of CRUD
// Wrap in a save data function, like storeData from before.
var createPet = function(key){
$.couch.db("asd1211").saveDoc(doc, {
success: function(data) {
console.log(data);
$.each(data.rows, function(index, pet) {
var petValue = (pet.value || pet.doc);
});
$('#petForm').form('refresh');
},
error: function(status) {
console.log(status);
}
});
};
// Read portion of CRUD
var readPet = function(){
$.couch.db("asd1211").view(doc, {
success: function(data) {
console.log(data);
$('#petList').empty();
$.each(data.rows, function(index, pet) {
var item = (pet.value || pet.doc);
$('#petList').append(
$('<li>').append(
$('<a>')
.attr("href", "pets.html?group=" + item.koolPet_Groups)
.text(item.koolPet_Name + " in Group: " + item.koolPet_Groups)
)
);
});
$('#petList').listview('refresh');
},
error: function(status) {
console.log(status);
}
});
};
// Update portion of CRUD
var updatePet = function(key) {
$.couch.db("asd1211").openDoc(doc, {
success: function(data) {
console.log(data);
// Grab data from the item local storage.
var value = couch.db("asd1211").getItem(this.key);
var item = (pet.value || pet.doc);
// Populate the form fields with current localStorage values.
$("#petGroups").value = item.koolPet_Groups[1].val();
$("#petName").value = item.koolPet_Name[1].val();
var radios = document.forms[0].gender;
for (var i=0; i<radios.length; i++) {
if (radios[i].value == "Male" && item.gender[1] == "Male") {
radios[i].attr("checked", "checked");
} else if (radios[i].value == "Female" && item.gender[1] == "Female") {
radios[i].attr("checked", "checked");
};
};
if (item.favorite_KoolPet[1] == "Yes") {
$("#favePet").attr("value", "On");
};
$("#koolness").value = item.koolness[1].val();
$("#comments").value = item.comments[1].val();
// Remove the initial listener from the input "save pet" button.
createPet.off("click", submit);
// Change SaveData button Value to Edit Button
// $("submit").value = "Edit KoolPet";
$("#submit").val("Edit KoolPet!");
var editSubmit = $("#submit");
// Save the key value established in this function as a prop of the editSubmit event
// so we can use that value when we save the data we edited.
editSubmit.on("click", submit);
editSubmit.key = this.key;
},
error: function(status) {
console.log(status);
}
});
};
// My Clear Data Function
// Delete portion of CRUD
var deletePet = function(key) {
$.couch.db("asd1211").removeDoc(doc, {
success: function(data) {
if(couch.db("asd1211").length === 0) {
alert("No KoolPets in the KoolPetsDex.");
} else {
couch.db("asd1211").empty();
alert("All KoolPets have been Released!");
window.location.reload();
return false;
};
$('#petList').listview('refresh');
console.log(data);
},
error: function(data) {
console.log(status);
}
});
};
// This line of code is supposed to console log every div I click on in the add item page.
$('#petsForm div').on('click', function(e){
console.log(e);
});
$('#koolness').slider("refresh");
$('#petName').val("Enter KoolPet Name here!");
$('#petName').on('click', function() {
$('#petName').val("");
});
$('#comments').val("Place comments like birthday and others here.");
$('#comments').on('click', function() {
$('#comments').val("");
});
var myForm = $('#petForm'),
aierrorsLink = $('#aierrorsLink')
;
myForm.validate({
ignore: '.ignoreValidation',
invalidHandler: function(form, validator) {
aierrorsLink.click();
var html = '';
for(var key in validator.submitted) {
var label = $('label[for^="' + key + '"]').not('generated');
var legend = label.closest('fieldset').find('ui-controlgroup-label');
var fieldName = legend.length ? legend.text() : label.text();
html += '<li>' + fieldName + '</li>';
};
$("#addItemErrors ul").html(html);
},
submitHandler: function() {
var data = myForm.serializeArray();
storeData(key);
}
});
//any other code needed for addItem page goes here
// Save this code!
var changePage = function(pageId) {
$('#' + pageId).trigger('pageinit');
$.mobile.changePage($('#' + pageId), {
type:"post",
data:$("petForm").serialize(),
reloadPage:true,
transition:"slide"
});
};
}); // End code for page.
$("#showItem").on("pageinit", function() {
console.log("Show Item page loaded!");
// Page code goes here.
$("header nav")
.slideDown()
;
function searchInput() {
if ($('#searchField').val() === "") {
$('#searchResults').html("");
}
};
var changePage = function(pageId) {
$('#' + pageId).trigger('pageinit');
$.mobile.changePage($('#' + pageId), {
type:"post",
data:$("petForm").serialize(),
reloadPage:true,
transition:"slide"
});
};
var search = function() {
var getInput = $('#searchField').val();
var getCat = $().val();
var error = true;
var match;
if (getInput === "") {
alert("Please input a search term.");
return;
}
// Live Search
$("#filter").keyup(function(){
// Retrieve the input field text and reset the count to zero
var filter = $(this).val(), count = 0;
// Loop through the KoolPets list
$(".itemlist li").each(function(){
// If the list item does not contain the text phrase fade it out
if ($(this).text().search(new RegExp(filter, "i")) < 0) {
$(this).fadeOut();
// Show the list item if the phrase matches and increase the count by 1
} else {
$(this).show();
count++;
}
});
// Update the count
var numberItems = count;
$("#filter-count").text("Number of KoolPets = " + count);
}); // end live search
}; // end search function
//My Variables
/*var showPet = $("#showData");
showPet.on('click', readPet);*/
var clearLink = $("#clearData");
clearLink.on('click', deletePet);
//var showJSON = $("#sJ");
//showJSON.on('click', showJ);
//var showXML = $("#sX");
//showXML.on('click', showX);
//var showCSV = $("#sC");
//showCSV.on('click', showC);
// AJAX function to call the JSON data.
$.couch.db("asd1211").view("koolpetsdex/pets", {
success: function(data) {
console.log(data);
$('#petList').empty();
$.each(data.rows, function(index, pet) {
var item = (pet.value || pet.doc);
$('#petList').append(
$('<li>').append(
$('<a>')
.attr("href", "pets.html?group=" + item.koolPet_Groups)
.text("Name: " + item.koolPet_Name + ", Group: " + item.koolPet_Groups + ", Gender: " + item.gender + ", Favorite: " + item.favorite_KoolPet + ", Koolness Factor: " + item.koolness + ", Comments: " + item.comments)
)
//console.log(item.koolPet_Name + item.koolPet_Groups + item.gender + item.favorite_KoolPet + item.koolness + item.comments);
);
});
$('#petList').listview('refresh');
},
error: function(status) {
console.log(status);
}
});
// This is to get images for the correct category.
// This is just not working anyways.
/*var getImg = function(catName, makeSubList) {
var imgLi = $('<li>');
makeSubList.append(imgLi);
var newImg = $('<img>');
var setSrc = newImg.attr("src", "" + catName + ".png");
imgLi.append(newImg);
};*/
// My Clear Data Function
// Delete portion of CRUD
var deletePet = function(key) {
$.couch.db("asd1211").removeDoc(doc, {
success: function(data) {
if(localStorage.length === 0) {
alert("No KoolPets in the KoolPetsDex.");
} else {
couch.db("asd1211").empty();
alert("All KoolPets have been Released!");
window.location.reload();
return false;
};
$('#petList').listview('refresh');
console.log(data);
},
error: function(data) {
console.log(status);
}
});
};
}); // End code for page.
var urlVars = function(urlData) {
var urlData = $($.mobile.activePage).data("url");
var urlParts = urlData.split('?');
var urlPairs = urlParts[1].split('&');
var urlValues = {};
for (var pair in urlPairs) {
var keyValue = urlPairs[pair].split('=');
var key = decodeURIComponent(keyValue[0]);
var value = decodeURIComponent(keyValue[1]);
urlValues[key] = value;
}
console.log(urlValues);
return urlValues;
};
$("#showPets").on("pageinit", function() {
console.log("Show Pets page loaded!");
var pets = urlVars()["group"];
/*console.log(pets);
$.couch.db("asd1211").view("koolpetsdex/groups", {
key: "groups: " + "petGroups"
});*/
$.couch.db("asd1211").view("koolpetsdex/groups", {
success: function(data) {
key: "groups: " + "petGroups"
console.log(data);
$('#petList').empty();
$.each(data.rows, function(index, pet) {
var item = (pet.value || pet.doc);
$('#petList').append(
$('<li>').append(
$('<a>')
.attr("href", "pets.html?group=" + item.koolPet_Groups)
.text("Name: " + item.koolPet_Name + " in Group: " + item.koolPet_Groups + " " + item.genderVal)
)
//console.log(koolPet_Name + koolPet_Groups + gender + favorite_KoolPet + koolness + comments);
//console.log(petName + petGroups + genderVal + favePet + koolness + comments);
);
});
$('#petList').listview('refresh');
},
error: function(status) {
console.log(status);
}
});
var changePage = function(pageId) {
$('#' + pageId).trigger('pageinit');
$.mobile.changePage($('#' + pageId), {
type:"post",
data:$("petForm").serialize(),
reloadPage:true,
transition:"slide"
});
};
}); // End code for show pets page.
// Unneeded code anymore, but saving it for debugging, and refactoring later.
//The functions below can go inside or outside the pageinit function for the page in which it is needed.
//My storeData function
/*var storeData = function(key){
// If there isn't a key, this means this is a brand new item and we need a new key.
if (!key) {
var id = Math.floor(Math.random()*10000001);
} else {
// Set the id to the existing key I'm editing so that it will save over the data.
// The key is the same key that's been passed along from the editSubmit event handler
// to the validate function, and then passed here, into the storeData function.
id = key;
};
// Gather round ye olde form field values, and store in ye olde objects.
// Object props contain array with the form label and input value.
var pet = {};
pet.petGroups = ["KoolPet Type: ", $('#petGroups').val()];
pet.petName = ["KoolPet\'s Name: ", $('#petName').val()];
pet.genderVal = ["Gender: ", $('input:radio[name=genderVal]:checked').val()];
pet.favePet = ["Favorite KoolPet: ", $('input:slider[name=favePet]:on').val()];
pet.koolness = ["Koolness Factor: ", $('#koolness').val()];
pet.comments = ["Comments: ", $('#comments').val()];
// Save data into Local Storage: Use Stringify to convert the object to a string.
localStorage.setItem(id, JSON.stringify(item));
console.log(key.val());
alert("Pet saved to the KoolPetsDex!");
}; */
//This is to get images for the correct category.
/* var getImg = function(catName, makeSubList) {
var imgLi = $('<li>');
makeSubList.append(imgLi);
var newImg = $('<img>');
var setSrc = newImg.attr("src", "images/" + catName + ".png");
imgLi.append(newImg);
}; */
//My Make Item Links Function
// Create the edit and delete links for each stored item when displayed.
/* var makeItemLinks = function(key, linksLi) {
// Add edit single item link
var editLink = $('<a>');
editLink.attr("href", "#addItem");
editLink.key = key;
var editText = "Edit KoolPet";
editLink.addClass("editLink")
.on('click', editItem)
.html(editText);
linksLi.appendTo(editLink);
// Add my line break
var breakTag = $('<br>');
linksLi.append(breakTag);
// Add delete single item link
var deleteLink = $('<a>');
deleteLink.attr("href", "#addItem");
deleteLink.key = key;
var deleteText = "Release KoolPet";
deleteLink.addClass("deleteLink")
.on('click', deleteItem)
.html(deleteText);
linksLi.appendTo(deleteLink);
};
// This is supposed to write data from Local Storage back to the browser.
var makeDiv = $('<div>');
// makeDiv.attr("id", "items"); // Found out I don't need this line anymore.
var makeList = $('<ul>');
// makeDiv.appendChild(makeList); // Modified this line to work with my current code.
$('#petList').appendTo(makeList);
// This code should add the data to my page when I press show data.
$('#petList').append(makeDiv);
// $('petList').style.display = "block";
for (var i=0, len=localStorage.length; i<len; i++) {
var makeLi = $('<li>');
var linksLi = $('<div>');
makeList.append(makeLi);
var key = localStorage.key(i);
var value = localStorage.getItem(key);
// Convert strings back to being an object from localStorage value.
var object = JSON.parse(value);
var makeSubList = $('<div>');
makeLi.append(makeSubList);
// This next line is to grab the Img that fits the category it's in.
getImg(object.petGroups[1], makeSubList);
for (var n in object) {
var makeSubLi = $('<div>');
makeSubList.append(makeSubLi);
var optSubText = object[n][0] + " " + object[n][1];
makeSubLi.html(optSubText);
makeSubList.append(linksLi);
};
// Create the edit and delete buttons/link for each item in local storage.
makeItemLinks(localStorage.key(i), linksLi);
};
//My Edit Single Item Function
var editItem = function() {
// Grab data from the item local storage.
var value = localStorage.getItem(this.key);
var item = JSON.parse(value);
// Populate the form fields with current localStorage values.
$("#petGroups").value = item.petGroups[1].val();
$("#petName").value = item.petName[1].val();
var radios = document.forms[0].genderVal;
for (var i=0; i<radios.length; i++) {
if (radios[i].value == "Male" && item.genderVal[1] == "Male") {
radios[i].attr("checked", "checked");
} else if (radios[i].value == "Female" && item.genderVal[1] == "Female") {
radios[i].attr("checked", "checked");
};
};
if (item.favePet[1] == "Yes") {
$("#favePet").attr("value", "On");
};
$("#koolness").value = item.koolness[1].val();
$("#comments").value = item.comments[1].val();
// Remove the initial listener from the input "save pet" button.
storeData.off("click", submit);
// Change SaveData button Value to Edit Button
// $("submit").value = "Edit KoolPet";
$("#submit").val("Edit KoolPet!");
var editSubmit = $("submit");
// Save the key value established in this function as a prop of the editSubmit event
// so we can use that value when we save the data we edited.
editSubmit.on("click", submit);
editSubmit.key = this.key;
};
//My Delete Item Function
var deleteItem = function (){
var ask = confirm("Are you sure you want to release this KoolPet?");
if (ask) {
localStorage.removeItem(this.key);
alert("KoolPet WAS Released!!!");
window.location.reload();
} else {
alert("KoolPet was NOT Released!");
};
};*/
//My Clear Data Function
/*var clearDataStorage = function(){
if(localStorage.length === 0) {
alert("No KoolPets in the KoolPetsDex.");
} else {
localStorage.empty();
alert("All KoolPets have been Released!");
window.location.reload();
return false;
};
};*/
|
/*
* JavaScript Custom Forms 1.4.1
*/
jcf = {
// global options
modules: {},
plugins: {},
baseOptions: {
unselectableClass:'jcf-unselectable',
labelActiveClass:'jcf-label-active',
labelDisabledClass:'jcf-label-disabled',
classPrefix: 'jcf-class-',
hiddenClass:'jcf-hidden',
focusClass:'jcf-focus',
wrapperTag: 'div'
},
// replacer function
customForms: {
setOptions: function(obj) {
for(var p in obj) {
if(obj.hasOwnProperty(p) && typeof obj[p] === 'object') {
jcf.lib.extend(jcf.modules[p].prototype.defaultOptions, obj[p]);
}
}
},
replaceAll: function() {
for(var k in jcf.modules) {
var els = jcf.lib.queryBySelector(jcf.modules[k].prototype.selector);
for(var i = 0; i<els.length; i++) {
if(els[i].jcf) {
// refresh form element state
els[i].jcf.refreshState();
} else {
// replace form element
if(!jcf.lib.hasClass(els[i], 'default') && jcf.modules[k].prototype.checkElement(els[i])) {
new jcf.modules[k]({
replaces:els[i]
});
}
}
}
}
},
refreshAll: function() {
for(var k in jcf.modules) {
var els = jcf.lib.queryBySelector(jcf.modules[k].prototype.selector);
for(var i = 0; i<els.length; i++) {
if(els[i].jcf) {
// refresh form element state
els[i].jcf.refreshState();
}
}
}
},
refreshElement: function(obj) {
if(obj && obj.jcf) {
obj.jcf.refreshState();
}
},
destroyAll: function() {
for(var k in jcf.modules) {
var els = jcf.lib.queryBySelector(jcf.modules[k].prototype.selector);
for(var i = 0; i<els.length; i++) {
if(els[i].jcf) {
els[i].jcf.destroy();
}
}
}
}
},
// detect device type
isTouchDevice: ('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch,
isWinPhoneDevice: navigator.msPointerEnabled && /MSIE 10.*Touch/.test(navigator.userAgent),
// define base module
setBaseModule: function(obj) {
jcf.customControl = function(opt){
this.options = jcf.lib.extend({}, jcf.baseOptions, this.defaultOptions, opt);
this.init();
};
for(var p in obj) {
jcf.customControl.prototype[p] = obj[p];
}
},
// add module to jcf.modules
addModule: function(obj) {
if(obj.name){
// create new module proto class
jcf.modules[obj.name] = function(){
jcf.modules[obj.name].superclass.constructor.apply(this, arguments);
}
jcf.lib.inherit(jcf.modules[obj.name], jcf.customControl);
for(var p in obj) {
jcf.modules[obj.name].prototype[p] = obj[p]
}
// on create module
jcf.modules[obj.name].prototype.onCreateModule();
// make callback for exciting modules
for(var mod in jcf.modules) {
if(jcf.modules[mod] != jcf.modules[obj.name]) {
jcf.modules[mod].prototype.onModuleAdded(jcf.modules[obj.name]);
}
}
}
},
// add plugin to jcf.plugins
addPlugin: function(obj) {
if(obj && obj.name) {
jcf.plugins[obj.name] = function() {
this.init.apply(this, arguments);
}
for(var p in obj) {
jcf.plugins[obj.name].prototype[p] = obj[p];
}
}
},
// miscellaneous init
init: function(){
if(navigator.msPointerEnabled) {
this.eventPress = 'MSPointerDown';
this.eventMove = 'MSPointerMove';
this.eventRelease = 'MSPointerUp';
} else {
this.eventPress = this.isTouchDevice ? 'touchstart' : 'mousedown';
this.eventMove = this.isTouchDevice ? 'touchmove' : 'mousemove';
this.eventRelease = this.isTouchDevice ? 'touchend' : 'mouseup';
}
return this;
},
initStyles: function() {
// create <style> element and rules
var head = document.getElementsByTagName('head')[0],
style = document.createElement('style'),
rules = document.createTextNode('.'+jcf.baseOptions.unselectableClass+'{'+
'-moz-user-select:none;'+
'-webkit-tap-highlight-color:rgba(255,255,255,0);'+
'-webkit-user-select:none;'+
'user-select:none;'+
'}');
// append style element
style.type = 'text/css';
if(style.styleSheet) {
style.styleSheet.cssText = rules.nodeValue;
} else {
style.appendChild(rules);
}
head.appendChild(style);
}
}.init();
/*
* Custom Form Control prototype
*/
jcf.setBaseModule({
init: function(){
if(this.options.replaces) {
this.realElement = this.options.replaces;
this.realElement.jcf = this;
this.replaceObject();
}
},
defaultOptions: {
// default module options (will be merged with base options)
},
checkElement: function(el){
return true; // additional check for correct form element
},
replaceObject: function(){
this.createWrapper();
this.attachEvents();
this.fixStyles();
this.setupWrapper();
},
createWrapper: function(){
this.fakeElement = jcf.lib.createElement(this.options.wrapperTag);
this.labelFor = jcf.lib.getLabelFor(this.realElement);
jcf.lib.disableTextSelection(this.fakeElement);
jcf.lib.addClass(this.fakeElement, jcf.lib.getAllClasses(this.realElement.className, this.options.classPrefix));
jcf.lib.addClass(this.realElement, jcf.baseOptions.hiddenClass);
},
attachEvents: function(){
jcf.lib.event.add(this.realElement, 'focus', this.onFocusHandler, this);
jcf.lib.event.add(this.realElement, 'blur', this.onBlurHandler, this);
jcf.lib.event.add(this.fakeElement, 'click', this.onFakeClick, this);
jcf.lib.event.add(this.fakeElement, jcf.eventPress, this.onFakePressed, this);
jcf.lib.event.add(this.fakeElement, jcf.eventRelease, this.onFakeReleased, this);
if(this.labelFor) {
this.labelFor.jcf = this;
jcf.lib.event.add(this.labelFor, 'click', this.onFakeClick, this);
jcf.lib.event.add(this.labelFor, jcf.eventPress, this.onFakePressed, this);
jcf.lib.event.add(this.labelFor, jcf.eventRelease, this.onFakeReleased, this);
}
},
fixStyles: function() {
// hide mobile webkit tap effect
if(jcf.isTouchDevice) {
var tapStyle = 'rgba(255,255,255,0)';
this.realElement.style.webkitTapHighlightColor = tapStyle;
this.fakeElement.style.webkitTapHighlightColor = tapStyle;
if(this.labelFor) {
this.labelFor.style.webkitTapHighlightColor = tapStyle;
}
}
},
setupWrapper: function(){
// implement in subclass
},
refreshState: function(){
// implement in subclass
},
destroy: function() {
if(this.fakeElement && this.fakeElement.parentNode) {
this.fakeElement.parentNode.removeChild(this.fakeElement);
}
jcf.lib.removeClass(this.realElement, jcf.baseOptions.hiddenClass);
this.realElement.jcf = null;
},
onFocus: function(){
// emulated focus event
jcf.lib.addClass(this.fakeElement,this.options.focusClass);
},
onBlur: function(cb){
// emulated blur event
jcf.lib.removeClass(this.fakeElement,this.options.focusClass);
},
onFocusHandler: function() {
// handle focus loses
if(this.focused) return;
this.focused = true;
// handle touch devices also
if(jcf.isTouchDevice) {
if(jcf.focusedInstance && jcf.focusedInstance.realElement != this.realElement) {
jcf.focusedInstance.onBlur();
jcf.focusedInstance.realElement.blur();
}
jcf.focusedInstance = this;
}
this.onFocus.apply(this, arguments);
},
onBlurHandler: function() {
// handle focus loses
if(!this.pressedFlag) {
this.focused = false;
this.onBlur.apply(this, arguments);
}
},
onFakeClick: function(){
if(jcf.isTouchDevice) {
this.onFocus();
} else if(!this.realElement.disabled) {
this.realElement.focus();
}
},
onFakePressed: function(e){
this.pressedFlag = true;
},
onFakeReleased: function(){
this.pressedFlag = false;
},
onCreateModule: function(){
// implement in subclass
},
onModuleAdded: function(module) {
// implement in subclass
},
onControlReady: function() {
// implement in subclass
}
});
/*
* JCF Utility Library
*/
jcf.lib = {
bind: function(func, scope){
return function() {
return func.apply(scope, arguments);
}
},
browser: (function() {
var ua = navigator.userAgent.toLowerCase(), res = {},
match = /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec(ua) ||
/(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+))?/.exec(ua) || [];
res[match[1]] = true;
res.version = match[2] || "0";
res.safariMac = ua.indexOf('mac') != -1 && ua.indexOf('safari') != -1;
return res;
})(),
getOffset: function (obj) {
if (obj.getBoundingClientRect && !navigator.msPointerEnabled) {
var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
var clientLeft = document.documentElement.clientLeft || document.body.clientLeft || 0;
var clientTop = document.documentElement.clientTop || document.body.clientTop || 0;
return {
top:Math.round(obj.getBoundingClientRect().top + scrollTop - clientTop),
left:Math.round(obj.getBoundingClientRect().left + scrollLeft - clientLeft)
}
} else {
var posLeft = 0, posTop = 0;
while (obj.offsetParent) {posLeft += obj.offsetLeft; posTop += obj.offsetTop; obj = obj.offsetParent;}
return {top:posTop,left:posLeft};
}
},
getScrollTop: function() {
return window.pageYOffset || document.documentElement.scrollTop;
},
getScrollLeft: function() {
return window.pageXOffset || document.documentElement.scrollLeft;
},
getWindowWidth: function(){
return document.compatMode=='CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth;
},
getWindowHeight: function(){
return document.compatMode=='CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight;
},
getStyle: function(el, prop) {
if (document.defaultView && document.defaultView.getComputedStyle) {
return document.defaultView.getComputedStyle(el, null)[prop];
} else if (el.currentStyle) {
return el.currentStyle[prop];
} else {
return el.style[prop];
}
},
getParent: function(obj, selector) {
while(obj.parentNode && obj.parentNode != document.body) {
if(obj.parentNode.tagName.toLowerCase() == selector.toLowerCase()) {
return obj.parentNode;
}
obj = obj.parentNode;
}
return false;
},
isParent: function(child, parent) {
while(child.parentNode) {
if(child.parentNode === parent) {
return true;
}
child = child.parentNode;
}
return false;
},
getLabelFor: function(object) {
var parentLabel = jcf.lib.getParent(object,'label');
if(parentLabel) {
return parentLabel;
} else if(object.id) {
return jcf.lib.queryBySelector('label[for="' + object.id + '"]')[0];
}
},
disableTextSelection: function(el){
if (typeof el.onselectstart !== 'undefined') {
el.onselectstart = function() {return false};
} else if(window.opera) {
el.setAttribute('unselectable', 'on');
} else {
jcf.lib.addClass(el, jcf.baseOptions.unselectableClass);
}
},
enableTextSelection: function(el) {
if (typeof el.onselectstart !== 'undefined') {
el.onselectstart = null;
} else if(window.opera) {
el.removeAttribute('unselectable');
} else {
jcf.lib.removeClass(el, jcf.baseOptions.unselectableClass);
}
},
queryBySelector: function(selector, scope){
return this.getElementsBySelector(selector, scope);
},
prevSibling: function(node) {
while(node = node.previousSibling) if(node.nodeType == 1) break;
return node;
},
nextSibling: function(node) {
while(node = node.nextSibling) if(node.nodeType == 1) break;
return node;
},
fireEvent: function(element,event) {
if(element.dispatchEvent){
var evt = document.createEvent('HTMLEvents');
evt.initEvent(event, true, true );
return !element.dispatchEvent(evt);
}else if(document.createEventObject){
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt);
}
},
isParent: function(p, c) {
while(c.parentNode) {
if(p == c) {
return true;
}
c = c.parentNode;
}
return false;
},
inherit: function(Child, Parent) {
var F = function() { }
F.prototype = Parent.prototype
Child.prototype = new F()
Child.prototype.constructor = Child
Child.superclass = Parent.prototype
},
extend: function(obj) {
for(var i = 1; i < arguments.length; i++) {
for(var p in arguments[i]) {
if(arguments[i].hasOwnProperty(p)) {
obj[p] = arguments[i][p];
}
}
}
return obj;
},
hasClass: function (obj,cname) {
return (obj.className ? obj.className.match(new RegExp('(\\s|^)'+cname+'(\\s|$)')) : false);
},
addClass: function (obj,cname) {
if (!this.hasClass(obj,cname)) obj.className += (!obj.className.length || obj.className.charAt(obj.className.length - 1) === ' ' ? '' : ' ') + cname;
},
removeClass: function (obj,cname) {
if (this.hasClass(obj,cname)) obj.className=obj.className.replace(new RegExp('(\\s|^)'+cname+'(\\s|$)'),' ').replace(/\s+$/, '');
},
toggleClass: function(obj, cname, condition) {
if(condition) this.addClass(obj, cname); else this.removeClass(obj, cname);
},
createElement: function(tagName, options) {
var el = document.createElement(tagName);
for(var p in options) {
if(options.hasOwnProperty(p)) {
switch (p) {
case 'class': el.className = options[p]; break;
case 'html': el.innerHTML = options[p]; break;
case 'style': this.setStyles(el, options[p]); break;
default: el.setAttribute(p, options[p]);
}
}
}
return el;
},
setStyles: function(el, styles) {
for(var p in styles) {
if(styles.hasOwnProperty(p)) {
switch (p) {
case 'float': el.style.cssFloat = styles[p]; break;
case 'opacity': el.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+styles[p]*100+')'; el.style.opacity = styles[p]; break;
default: el.style[p] = (typeof styles[p] === 'undefined' ? 0 : styles[p]) + (typeof styles[p] === 'number' ? 'px' : '');
}
}
}
return el;
},
getInnerWidth: function(el) {
return el.offsetWidth - (parseInt(this.getStyle(el,'paddingLeft')) || 0) - (parseInt(this.getStyle(el,'paddingRight')) || 0);
},
getInnerHeight: function(el) {
return el.offsetHeight - (parseInt(this.getStyle(el,'paddingTop')) || 0) - (parseInt(this.getStyle(el,'paddingBottom')) || 0);
},
getAllClasses: function(cname, prefix, skip) {
if(!skip) skip = '';
if(!prefix) prefix = '';
return cname ? cname.replace(new RegExp('(\\s|^)'+skip+'(\\s|$)'),' ').replace(/[\s]*([\S]+)+[\s]*/gi,prefix+"$1 ") : '';
},
getElementsBySelector: function(selector, scope) {
if(typeof document.querySelectorAll === 'function') {
return (scope || document).querySelectorAll(selector);
}
var selectors = selector.split(',');
var resultList = [];
for(var s = 0; s < selectors.length; s++) {
var currentContext = [scope || document];
var tokens = selectors[s].replace(/^\s+/,'').replace(/\s+$/,'').split(' ');
for (var i = 0; i < tokens.length; i++) {
token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
if (token.indexOf('#') > -1) {
var bits = token.split('#'), tagName = bits[0], id = bits[1];
var element = document.getElementById(id);
if (tagName && element.nodeName.toLowerCase() != tagName) {
return [];
}
currentContext = [element];
continue;
}
if (token.indexOf('.') > -1) {
var bits = token.split('.'), tagName = bits[0] || '*', className = bits[1], found = [], foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements;
if (tagName == '*') {
elements = currentContext[h].getElementsByTagName('*');
} else {
elements = currentContext[h].getElementsByTagName(tagName);
}
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = [];
var currentContextIndex = 0;
for (var k = 0; k < found.length; k++) {
if (found[k].className && found[k].className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'))) {
currentContext[currentContextIndex++] = found[k];
}
}
continue;
}
if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
var tagName = RegExp.$1 || '*', attrName = RegExp.$2, attrOperator = RegExp.$3, attrValue = RegExp.$4;
if(attrName.toLowerCase() == 'for' && this.browser.msie && this.browser.version < 8) {
attrName = 'htmlFor';
}
var found = [], foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements;
if (tagName == '*') {
elements = currentContext[h].getElementsByTagName('*');
} else {
elements = currentContext[h].getElementsByTagName(tagName);
}
for (var j = 0; elements[j]; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = [];
var currentContextIndex = 0, checkFunction;
switch (attrOperator) {
case '=': checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue) }; break;
case '~': checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('(\\s|^)'+attrValue+'(\\s|$)'))) }; break;
case '|': checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))) }; break;
case '^': checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0) }; break;
case '$': checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length) }; break;
case '*': checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1) }; break;
default : checkFunction = function(e) { return e.getAttribute(attrName) };
}
currentContext = [];
var currentContextIndex = 0;
for (var k = 0; k < found.length; k++) {
if (checkFunction(found[k])) {
currentContext[currentContextIndex++] = found[k];
}
}
continue;
}
tagName = token;
var found = [], foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements = currentContext[h].getElementsByTagName(tagName);
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = found;
}
resultList = [].concat(resultList,currentContext);
}
return resultList;
},
scrollSize: (function(){
var content, hold, sizeBefore, sizeAfter;
function buildSizer(){
if(hold) removeSizer();
content = document.createElement('div');
hold = document.createElement('div');
hold.style.cssText = 'position:absolute;overflow:hidden;width:100px;height:100px';
hold.appendChild(content);
document.body.appendChild(hold);
}
function removeSizer(){
document.body.removeChild(hold);
hold = null;
}
function calcSize(vertical) {
buildSizer();
content.style.cssText = 'height:'+(vertical ? '100%' : '200px');
sizeBefore = (vertical ? content.offsetHeight : content.offsetWidth);
hold.style.overflow = 'scroll'; content.innerHTML = 1;
sizeAfter = (vertical ? content.offsetHeight : content.offsetWidth);
if(vertical && hold.clientHeight) sizeAfter = hold.clientHeight;
removeSizer();
return sizeBefore - sizeAfter;
}
return {
getWidth:function(){
return calcSize(false);
},
getHeight:function(){
return calcSize(true)
}
}
}()),
domReady: function (handler){
var called = false
function ready() {
if (called) return;
called = true;
handler();
}
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", ready, false);
} else if (document.attachEvent) {
if (document.documentElement.doScroll && window == window.top) {
function tryScroll(){
if (called) return
if (!document.body) return
try {
document.documentElement.doScroll("left")
ready()
} catch(e) {
setTimeout(tryScroll, 0)
}
}
tryScroll()
}
document.attachEvent("onreadystatechange", function(){
if (document.readyState === "complete") {
ready()
}
})
}
if (window.addEventListener) window.addEventListener('load', ready, false)
else if (window.attachEvent) window.attachEvent('onload', ready)
},
event: (function(){
var guid = 0;
function fixEvent(e) {
e = e || window.event;
if (e.isFixed) {
return e;
}
e.isFixed = true;
e.preventDefault = e.preventDefault || function(){this.returnValue = false}
e.stopPropagation = e.stopPropagaton || function(){this.cancelBubble = true}
if (!e.target) {
e.target = e.srcElement
}
if (!e.relatedTarget && e.fromElement) {
e.relatedTarget = e.fromElement == e.target ? e.toElement : e.fromElement;
}
if (e.pageX == null && e.clientX != null) {
var html = document.documentElement, body = document.body;
e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0);
e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0);
}
if (!e.which && e.button) {
e.which = e.button & 1 ? 1 : (e.button & 2 ? 3 : (e.button & 4 ? 2 : 0));
}
if(e.type === "DOMMouseScroll" || e.type === 'mousewheel') {
e.mWheelDelta = 0;
if (e.wheelDelta) {
e.mWheelDelta = e.wheelDelta/120;
} else if (e.detail) {
e.mWheelDelta = -e.detail/3;
}
}
return e;
}
function commonHandle(event, customScope) {
event = fixEvent(event);
var handlers = this.events[event.type];
for (var g in handlers) {
var handler = handlers[g];
var ret = handler.call(customScope || this, event);
if (ret === false) {
event.preventDefault()
event.stopPropagation()
}
}
}
var publicAPI = {
add: function(elem, type, handler, forcedScope) {
if (elem.setInterval && (elem != window && !elem.frameElement)) {
elem = window;
}
if (!handler.guid) {
handler.guid = ++guid;
}
if (!elem.events) {
elem.events = {};
elem.handle = function(event) {
return commonHandle.call(elem, event);
}
}
if (!elem.events[type]) {
elem.events[type] = {};
if (elem.addEventListener) elem.addEventListener(type, elem.handle, false);
else if (elem.attachEvent) elem.attachEvent("on" + type, elem.handle);
if(type === 'mousewheel') {
publicAPI.add(elem, 'DOMMouseScroll', handler, forcedScope);
}
}
var fakeHandler = jcf.lib.bind(handler, forcedScope);
fakeHandler.guid = handler.guid;
elem.events[type][handler.guid] = forcedScope ? fakeHandler : handler;
},
remove: function(elem, type, handler) {
var handlers = elem.events && elem.events[type];
if (!handlers) return;
delete handlers[handler.guid];
for(var any in handlers) return;
if (elem.removeEventListener) elem.removeEventListener(type, elem.handle, false);
else if (elem.detachEvent) elem.detachEvent("on" + type, elem.handle);
delete elem.events[type];
for (var any in elem.events) return;
try {
delete elem.handle;
delete elem.events;
} catch(e) {
if(elem.removeAttribute) {
elem.removeAttribute("handle");
elem.removeAttribute("events");
}
}
if(type === 'mousewheel') {
publicAPI.remove(elem, 'DOMMouseScroll', handler);
}
}
}
return publicAPI;
}())
}
// init jcf styles
jcf.lib.domReady(function(){
jcf.initStyles();
});
// custom select module
jcf.addModule({
name:'select',
selector:'select',
defaultOptions: {
useNativeDropOnMobileDevices: true,
hideDropOnScroll: true,
showNativeDrop: false,
handleDropPosition: true,
selectDropPosition: 'bottom', // or 'top'
wrapperClass:'select-area',
focusClass:'select-focus',
dropActiveClass:'select-active',
selectedClass:'item-selected',
currentSelectedClass:'current-selected',
disabledClass:'select-disabled',
valueSelector:'span.center',
optGroupClass:'optgroup',
openerSelector:'a.select-opener',
selectStructure:'<span class="left"></span><span class="center"></span><a class="select-opener"></a>',
wrapperTag: 'span',
classPrefix:'select-',
dropMaxHeight: 200,
dropFlippedClass: 'select-options-flipped',
dropHiddenClass:'options-hidden',
dropScrollableClass:'options-overflow',
dropClass:'select-options',
dropClassPrefix:'drop-',
dropStructure:'<div class="drop-holder"><div class="drop-list"></div></div>',
dropSelector:'div.drop-list'
},
checkElement: function(el){
return (!el.size && !el.multiple);
},
setupWrapper: function(){
jcf.lib.addClass(this.fakeElement, this.options.wrapperClass);
this.realElement.parentNode.insertBefore(this.fakeElement, this.realElement);
this.fakeElement.innerHTML = this.options.selectStructure;
this.fakeElement.style.width = (this.realElement.offsetWidth > 0 ? this.realElement.offsetWidth + 'px' : 'auto');
// show native drop if specified in options
if(jcf.baseOptions.useNativeDropOnMobileDevices && (jcf.isTouchDevice || jcf.isWinPhoneDevice)) {
this.options.showNativeDrop = true;
}
if(this.options.showNativeDrop) {
this.fakeElement.appendChild(this.realElement);
jcf.lib.removeClass(this.realElement, this.options.hiddenClass);
jcf.lib.setStyles(this.realElement, {
top:0,
left:0,
margin:0,
padding:0,
opacity:0,
border:'none',
position:'absolute',
width: jcf.lib.getInnerWidth(this.fakeElement) - 1,
height: jcf.lib.getInnerHeight(this.fakeElement) - 1
});
jcf.lib.event.add(this.realElement, 'touchstart', function(){
this.realElement.title = '';
}, this)
}
// create select body
this.opener = jcf.lib.queryBySelector(this.options.openerSelector, this.fakeElement)[0];
this.valueText = jcf.lib.queryBySelector(this.options.valueSelector, this.fakeElement)[0];
jcf.lib.disableTextSelection(this.valueText);
this.opener.jcf = this;
if(!this.options.showNativeDrop) {
this.createDropdown();
this.refreshState();
this.onControlReady(this);
this.hideDropdown(true);
} else {
this.refreshState();
}
this.addEvents();
},
addEvents: function(){
if(this.options.showNativeDrop) {
jcf.lib.event.add(this.realElement, 'click', this.onChange, this);
} else {
jcf.lib.event.add(this.fakeElement, 'click', this.toggleDropdown, this);
}
jcf.lib.event.add(this.realElement, 'change', this.onChange, this);
},
onFakeClick: function() {
// do nothing (drop toggles by toggleDropdown method)
},
onFocus: function(){
jcf.modules[this.name].superclass.onFocus.apply(this, arguments);
if(!this.options.showNativeDrop) {
// Mac Safari Fix
if(jcf.lib.browser.safariMac) {
this.realElement.setAttribute('size','2');
}
jcf.lib.event.add(this.realElement, 'keydown', this.onKeyDown, this);
if(jcf.activeControl && jcf.activeControl != this) {
jcf.activeControl.hideDropdown();
jcf.activeControl = this;
}
}
},
onBlur: function(){
if(!this.options.showNativeDrop) {
// Mac Safari Fix
if(jcf.lib.browser.safariMac) {
this.realElement.removeAttribute('size');
}
if(!this.isActiveDrop() || !this.isOverDrop()) {
jcf.modules[this.name].superclass.onBlur.apply(this);
if(jcf.activeControl === this) jcf.activeControl = null;
if(!jcf.isTouchDevice) {
this.hideDropdown();
}
}
jcf.lib.event.remove(this.realElement, 'keydown', this.onKeyDown);
} else {
jcf.modules[this.name].superclass.onBlur.apply(this);
}
},
onChange: function() {
this.refreshState();
},
onKeyDown: function(e){
this.dropOpened = true;
jcf.tmpFlag = true;
setTimeout(function(){jcf.tmpFlag = false},100);
var context = this;
context.keyboardFix = true;
setTimeout(function(){
context.refreshState();
},10);
if(e.keyCode == 13) {
context.toggleDropdown.apply(context);
return false;
}
},
onResizeWindow: function(e){
if(this.isActiveDrop()) {
this.hideDropdown();
}
},
onScrollWindow: function(e){
if(this.options.hideDropOnScroll) {
this.hideDropdown();
} else if(this.isActiveDrop()) {
this.positionDropdown();
}
},
onOptionClick: function(e){
var opener = e.target && e.target.tagName && e.target.tagName.toLowerCase() == 'li' ? e.target : jcf.lib.getParent(e.target, 'li');
if(opener) {
this.dropOpened = true;
this.realElement.selectedIndex = parseInt(opener.getAttribute('rel'));
if(jcf.isTouchDevice) {
this.onFocus();
} else {
this.realElement.focus();
}
this.refreshState();
this.hideDropdown();
jcf.lib.fireEvent(this.realElement, 'change');
}
return false;
},
onClickOutside: function(e){
if(jcf.tmpFlag) {
jcf.tmpFlag = false;
return;
}
if(!jcf.lib.isParent(this.fakeElement, e.target) && !jcf.lib.isParent(this.selectDrop, e.target)) {
this.hideDropdown();
}
},
onDropHover: function(e){
if(!this.keyboardFix) {
this.hoverFlag = true;
var opener = e.target && e.target.tagName && e.target.tagName.toLowerCase() == 'li' ? e.target : jcf.lib.getParent(e.target, 'li');
if(opener) {
this.realElement.selectedIndex = parseInt(opener.getAttribute('rel'));
this.refreshSelectedClass(parseInt(opener.getAttribute('rel')));
}
} else {
this.keyboardFix = false;
}
},
onDropLeave: function(){
this.hoverFlag = false;
},
isActiveDrop: function(){
return !jcf.lib.hasClass(this.selectDrop, this.options.dropHiddenClass);
},
isOverDrop: function(){
return this.hoverFlag;
},
createDropdown: function(){
// remove old dropdown if exists
if(this.selectDrop) {
this.selectDrop.parentNode.removeChild(this.selectDrop);
}
// create dropdown holder
this.selectDrop = document.createElement('div');
this.selectDrop.className = this.options.dropClass;
this.selectDrop.innerHTML = this.options.dropStructure;
jcf.lib.setStyles(this.selectDrop, {position:'absolute'});
this.selectList = jcf.lib.queryBySelector(this.options.dropSelector,this.selectDrop)[0];
jcf.lib.addClass(this.selectDrop, this.options.dropHiddenClass);
document.body.appendChild(this.selectDrop);
this.selectDrop.jcf = this;
jcf.lib.event.add(this.selectDrop, 'click', this.onOptionClick, this);
jcf.lib.event.add(this.selectDrop, 'mouseover', this.onDropHover, this);
jcf.lib.event.add(this.selectDrop, 'mouseout', this.onDropLeave, this);
this.buildDropdown();
},
buildDropdown: function() {
// build select options / optgroups
this.buildDropdownOptions();
// position and resize dropdown
this.positionDropdown();
// cut dropdown if height exceedes
this.buildDropdownScroll();
},
buildDropdownOptions: function() {
this.resStructure = '';
this.optNum = 0;
for(var i = 0; i < this.realElement.children.length; i++) {
this.resStructure += this.buildElement(this.realElement.children[i], i) +'\n';
}
this.selectList.innerHTML = this.resStructure;
},
buildDropdownScroll: function() {
if(this.options.dropMaxHeight) {
if(this.selectDrop.offsetHeight > this.options.dropMaxHeight) {
this.selectList.style.height = this.options.dropMaxHeight+'px';
this.selectList.style.overflow = 'auto';
this.selectList.style.overflowX = 'hidden';
jcf.lib.addClass(this.selectDrop, this.options.dropScrollableClass);
}
}
jcf.lib.addClass(this.selectDrop, jcf.lib.getAllClasses(this.realElement.className, this.options.dropClassPrefix, jcf.baseOptions.hiddenClass));
},
parseOptionTitle: function(optTitle) {
return (typeof optTitle === 'string' && /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i.test(optTitle)) ? optTitle : '';
},
buildElement: function(obj, index){
// build option
var res = '', optImage;
if(obj.tagName.toLowerCase() == 'option') {
if(!jcf.lib.prevSibling(obj) || jcf.lib.prevSibling(obj).tagName.toLowerCase() != 'option') {
res += '<ul>';
}
optImage = this.parseOptionTitle(obj.title);
res += '<li rel="'+(this.optNum++)+'" class="'+(obj.className? obj.className + ' ' : '')+(index % 2 ? 'option-even ' : '')+'jcfcalc"><a href="#">'+(optImage ? '<img src="'+optImage+'" alt="" />' : '')+'<span>' + obj.innerHTML + '</span></a></li>';
if(!jcf.lib.nextSibling(obj) || jcf.lib.nextSibling(obj).tagName.toLowerCase() != 'option') {
res += '</ul>';
}
return res;
}
// build option group with options
else if(obj.tagName.toLowerCase() == 'optgroup' && obj.label) {
res += '<div class="'+this.options.optGroupClass+'">';
res += '<strong class="jcfcalc"><em>'+(obj.label)+'</em></strong>';
for(var i = 0; i < obj.children.length; i++) {
res += this.buildElement(obj.children[i], i);
}
res += '</div>';
return res;
}
},
positionDropdown: function(){
var ofs = jcf.lib.getOffset(this.fakeElement), selectAreaHeight = this.fakeElement.offsetHeight, selectDropHeight = this.selectDrop.offsetHeight;
var fitInTop = ofs.top - selectDropHeight >= jcf.lib.getScrollTop() && jcf.lib.getScrollTop() + jcf.lib.getWindowHeight() < ofs.top + selectAreaHeight + selectDropHeight;
if((this.options.handleDropPosition && fitInTop) || this.options.selectDropPosition === 'top') {
this.selectDrop.style.top = (ofs.top - selectDropHeight)+'px';
jcf.lib.addClass(this.selectDrop, this.options.dropFlippedClass);
} else {
this.selectDrop.style.top = (ofs.top + selectAreaHeight)+'px';
jcf.lib.removeClass(this.selectDrop, this.options.dropFlippedClass);
}
this.selectDrop.style.left = ofs.left+'px';
this.selectDrop.style.width = this.fakeElement.offsetWidth+'px';
},
showDropdown: function(){
document.body.appendChild(this.selectDrop);
jcf.lib.removeClass(this.selectDrop, this.options.dropHiddenClass);
jcf.lib.addClass(this.fakeElement,this.options.dropActiveClass);
this.positionDropdown();
// highlight current active item
var activeItem = this.getFakeActiveOption();
this.removeClassFromItems(this.options.currentSelectedClass);
jcf.lib.addClass(activeItem, this.options.currentSelectedClass);
// show current dropdown
jcf.lib.event.add(window, 'resize', this.onResizeWindow, this);
jcf.lib.event.add(window, 'scroll', this.onScrollWindow, this);
jcf.lib.event.add(document, jcf.eventPress, this.onClickOutside, this);
this.positionDropdown();
},
hideDropdown: function(partial){
if(this.selectDrop.parentNode) {
if(this.selectDrop.offsetWidth) {
this.selectDrop.parentNode.removeChild(this.selectDrop);
}
if(partial) {
return;
}
}
if(typeof this.origSelectedIndex === 'number') {
this.realElement.selectedIndex = this.origSelectedIndex;
}
jcf.lib.removeClass(this.fakeElement,this.options.dropActiveClass);
jcf.lib.addClass(this.selectDrop, this.options.dropHiddenClass);
jcf.lib.event.remove(window, 'resize', this.onResizeWindow);
jcf.lib.event.remove(window, 'scroll', this.onScrollWindow);
jcf.lib.event.remove(document.documentElement, jcf.eventPress, this.onClickOutside);
if(jcf.isTouchDevice) {
this.onBlur();
}
},
toggleDropdown: function(){
if(!this.realElement.disabled) {
if(jcf.isTouchDevice) {
this.onFocus();
} else {
this.realElement.focus();
}
if(this.isActiveDrop()) {
this.hideDropdown();
} else {
this.showDropdown();
}
this.refreshState();
}
},
scrollToItem: function(){
if(this.isActiveDrop()) {
var dropHeight = this.selectList.offsetHeight;
var offsetTop = this.calcOptionOffset(this.getFakeActiveOption());
var sTop = this.selectList.scrollTop;
var oHeight = this.getFakeActiveOption().offsetHeight;
//offsetTop+=sTop;
if(offsetTop >= sTop + dropHeight) {
this.selectList.scrollTop = offsetTop - dropHeight + oHeight;
} else if(offsetTop < sTop) {
this.selectList.scrollTop = offsetTop;
}
}
},
getFakeActiveOption: function(c) {
return jcf.lib.queryBySelector('li[rel="'+(typeof c === 'number' ? c : this.realElement.selectedIndex) +'"]',this.selectList)[0];
},
calcOptionOffset: function(fake) {
var h = 0;
var els = jcf.lib.queryBySelector('.jcfcalc',this.selectList);
for(var i = 0; i < els.length; i++) {
if(els[i] == fake) break;
h+=els[i].offsetHeight;
}
return h;
},
childrenHasItem: function(hold,item) {
var items = hold.getElementsByTagName('*');
for(i = 0; i < items.length; i++) {
if(items[i] == item) return true;
}
return false;
},
removeClassFromItems: function(className){
var children = jcf.lib.queryBySelector('li',this.selectList);
for(var i = children.length - 1; i >= 0; i--) {
jcf.lib.removeClass(children[i], className);
}
},
setSelectedClass: function(c){
jcf.lib.addClass(this.getFakeActiveOption(c), this.options.selectedClass);
},
refreshSelectedClass: function(c){
if(!this.options.showNativeDrop) {
this.removeClassFromItems(this.options.selectedClass);
this.setSelectedClass(c);
}
if(this.realElement.disabled) {
jcf.lib.addClass(this.fakeElement, this.options.disabledClass);
if(this.labelFor) {
jcf.lib.addClass(this.labelFor, this.options.labelDisabledClass);
}
} else {
jcf.lib.removeClass(this.fakeElement, this.options.disabledClass);
if(this.labelFor) {
jcf.lib.removeClass(this.labelFor, this.options.labelDisabledClass);
}
}
},
refreshSelectedText: function() {
if(!this.dropOpened && this.realElement.title) {
this.valueText.innerHTML = this.realElement.title;
} else {
if(this.realElement.options[this.realElement.selectedIndex].title) {
var optImage = this.parseOptionTitle(this.realElement.options[this.realElement.selectedIndex].title);
this.valueText.innerHTML = (optImage ? '<img src="'+optImage+'" alt="" />' : '') + this.realElement.options[this.realElement.selectedIndex].innerHTML;
} else {
this.valueText.innerHTML = this.realElement.options[this.realElement.selectedIndex].innerHTML;
}
}
},
refreshState: function(){
this.origSelectedIndex = this.realElement.selectedIndex;
this.refreshSelectedClass();
this.refreshSelectedText();
if(!this.options.showNativeDrop) {
this.positionDropdown();
if(this.selectDrop.offsetWidth) {
this.scrollToItem();
}
}
}
}); |
/* eslint-disable no-unused-vars */
import Vue from 'vue';
import Vuex from 'vuex';
import { mount } from 'avoriaz';
import Home from '@/components/Home';
/* eslint-enable no-unused-vars */
Vue.use(Vuex);
describe('Home.vue', () => {
let store = null;
it('should render correct contents', () => {
store = new Vuex.Store({
getters: {
isLoggedIn() {
return false;
},
teamId() {
return null;
},
},
});
const wrapper = mount(Home, { store });
const cardsTitle = wrapper.find('.CardTitle');
expect(cardsTitle[0].text()).to.equal('Welcome to Assist!');
expect(cardsTitle[1].text()).to.equal("What's this?");
expect(cardsTitle[2].text()).to.equal("What's BuzzerBeater");
});
});
|
export const MODEL_SELECT_REQUEST_REFERENCE = {
header: "",
fields: [
{
title: "Company Name",
key: "comName",
placeholder: "Company Name",
validation: false,
messageError: "",
columnField: true,
type: "select",
canEdit: true,
onChange: null
},
{
title: "Request Type",
key: "type",
placeholder: "Request Type",
validation: false,
messageError: "",
columnField: true,
type: "select",
canEdit: true,
onChange: null,
disabled: true
},
{
title: "Sub Type",
key: "subType",
placeholder: "Sub Type",
validation: false,
messageError: "",
columnField: true,
type: "select",
canEdit: true,
onChange: null,
disabled: true
},
{
key: "subtypeDescription",
styleInput: { color: "#c3c3c3" }
},
{
title: "Request Reason",
key: "requestReason",
placeholder: "Request Reason",
validation: false,
messageError: "",
type: "textArea",
rows: "5",
styleInput: { resize: "none" },
canEdit: true,
onChange: null,
showTitle: true
},
{
title: "Ref Type",
key: "referenceType",
placeholder: "Ref Type",
validation: false,
messageError: "",
columnField: true,
type: "select",
canEdit: true,
onChange: null,
disabled: true
}
],
lang: "request-create"
};
|
'use strict';
const path = require('path');
const pkg = require(path.join(__dirname, '/../package.json'));
const abiMap = require(path.join(__dirname, '/../abi-map.json'));
const os = require('os');
const Utils = require('./utils').Utils;
const ProfileRecorder = require('./profile_recorder').ProfileRecorder;
const SamplerScheduler = require('./sampler_scheduler').SamplerScheduler;
const CpuSampler = require('./samplers/cpu_sampler').CpuSampler;
const AllocationSampler = require('./samplers/allocation_sampler').AllocationSampler;
const AsyncSampler = require('./samplers/async_sampler').AsyncSampler;
let profiler = null;
class AutoProfiler {
constructor() {
this.AGENT_FRAME_REGEXP = /node_modules\/@instana\//;
this.version = pkg.version;
this.addon = undefined;
this.profilerStarted = false;
this.profilerDestroyed = false;
this.utils = new Utils(this);
this.profileRecorder = new ProfileRecorder(this);
this.cpuSamplerScheduler = new SamplerScheduler(this, new CpuSampler(this), {
logPrefix: 'CPU profiler',
maxProfileDuration: 10 * 1000,
maxSpanDuration: 2 * 1000,
spanInterval: 16 * 1000,
reportInterval: 120 * 1000
});
this.allocationSamplerScheduler = new SamplerScheduler(this, new AllocationSampler(this), {
logPrefix: 'Allocation profiler',
maxProfileDuration: 20 * 1000,
maxSpanDuration: 4 * 1000,
spanInterval: 16 * 1000,
reportInterval: 120 * 1000
});
this.asyncSamplerScheduler = new SamplerScheduler(this, new AsyncSampler(this), {
logPrefix: 'Async profiler',
maxProfileDuration: 20 * 1000,
maxSpanDuration: 4 * 1000,
spanInterval: 16 * 1000,
reportInterval: 120 * 1000
});
this.options = undefined;
this.samplerActive = false;
this.exitHandlerFunc = undefined;
}
getLogger() {
/* eslint-disable no-console */
return {
debug: function(msg) {
console.log(msg);
},
info: function(msg) {
console.log(msg);
},
error: function(msg) {
console.log(msg);
},
exception: function(err) {
console.log(err.message, err.stack);
}
};
/* eslint-enable no-console */
}
getOption(name, defaultVal) {
if (!this.options || !this.options[name]) {
return defaultVal;
} else {
return this.options[name];
}
}
loadAddon(addonPath) {
try {
this.addon = require(addonPath);
return true;
} catch (err) {
// not found
}
return false;
}
start(opts) {
if (this.profilerStarted) {
return;
}
if (opts) {
this.options = opts;
} else {
this.options = {};
}
if (!this.matchVersion('v4.0.0', null)) {
this.error('Supported Node.js version 4.0.0 or higher');
return;
}
// disable CPU profiler by default for 7.0.0-8.9.3 because of the memory leak.
if (
this.options.cpuProfilerDisabled === undefined &&
(this.matchVersion('v7.0.0', 'v8.9.3') || this.matchVersion('v9.0.0', 'v9.2.1'))
) {
this.log('CPU profiler disabled.');
this.options.cpuProfilerDisabled = true;
}
// disable allocation profiler by default up to version 8.5.0 because of segfaults.
if (this.options.allocationProfilerDisabled === undefined && this.matchVersion(null, 'v8.5.0')) {
this.log('Allocation profiler disabled.');
this.options.allocationProfilerDisabled = true;
}
// load native addon
let addonFound = false;
let abi = abiMap[process.version];
if (abi) {
let addonPath = `../addons/${os.platform()}-${process.arch}/autoprofile-addon-v${abi}.node`;
if (this.loadAddon(addonPath)) {
addonFound = true;
this.log('Using pre-built native addon.');
} else {
this.log('Could not find pre-built addon: ' + addonPath);
}
}
if (!addonFound) {
if (this.loadAddon('../build/Release/autoprofile-addon.node')) {
this.log('Using built native addon.');
} else {
this.error('Finding/loading of native addon failed. Profiler will not start.');
return;
}
}
if (this.profilerDestroyed) {
this.log('Destroyed profiler cannot be started');
return;
}
if (!this.options.dashboardAddress) {
this.options.dashboardAddress = this.SAAS_DASHBOARD_ADDRESS;
}
this.cpuSamplerScheduler.start();
this.allocationSamplerScheduler.start();
this.asyncSamplerScheduler.start();
this.profileRecorder.start();
this.exitHandlerFunc = () => {
if (!this.profilerStarted || this.profilerDestroyed) {
return;
}
try {
this.destroy();
} catch (err) {
this.exception(err);
}
};
process.once('exit', this.exitHandlerFunc);
this.profilerStarted = true;
this.log('Profiler started');
}
destroy() {
if (!this.profilerStarted) {
this.log('Profiler has not been started');
return;
}
if (this.profilerDestroyed) {
return;
}
process.removeListener('exit', this.exitHandlerFunc);
this.cpuSamplerScheduler.stop();
this.allocationSamplerScheduler.stop();
this.asyncSamplerScheduler.stop();
this.profileRecorder.stop();
this.profilerDestroyed = true;
this.log('Profiler destroyed');
}
matchVersion(min, max) {
let versionRegexp = /v?(\d+)\.(\d+)\.(\d+)/;
let m = versionRegexp.exec(process.version);
let currN = 1e9 * parseInt(m[1], 10) + 1e6 * parseInt(m[2], 10) + 1e3 * parseInt(m[3], 10);
let minN = 0;
if (min) {
m = versionRegexp.exec(min);
minN = 1e9 * parseInt(m[1], 10) + 1e6 * parseInt(m[2], 10) + 1e3 * parseInt(m[3], 10);
}
let maxN = Infinity;
if (max) {
m = versionRegexp.exec(max);
maxN = 1e9 * parseInt(m[1], 10) + 1e6 * parseInt(m[2], 10) + 1e3 * parseInt(m[3], 10);
}
return currN >= minN && currN <= maxN;
}
debug(message) {
this.getLogger().debug(message);
}
log(message) {
this.getLogger().info(message);
}
error(message) {
this.getLogger().error(message);
}
exception(err) {
this.getLogger().error(err.message, err.stack);
}
setTimeout(func, t) {
return setTimeout(() => {
try {
func.call(this);
} catch (err) {
this.exception(err);
}
}, t);
}
setInterval(func, t) {
return setInterval(() => {
try {
func.call(this);
} catch (err) {
this.exception(err);
}
}, t);
}
}
exports.start = function(opts) {
if (!profiler) {
profiler = new AutoProfiler();
profiler.start(opts);
}
return profiler;
};
exports.destroy = function() {
if (profiler) {
profiler.destroy();
}
};
exports.AutoProfiler = AutoProfiler;
|
// import IframeResizer from 'iframe-resizer-react'
// const Code = (props) => {
// let lang = props.data.lang;
// const code = RichText.asText(props.data.code);
// return (
// <div>
// <IframeResizer
// src={`https://nnja-carbon.now.sh/embed?code=${code}&l=${lang}&bg=rgba(255%2C255%2C255%2C0)&dsyoff=10px&dsblur=31px`}
// style={{ width: '1px', minWidth: '100%', border: 0}}
// sandbox="allow-scripts allow-same-origin">
// </IframeResizer>
// </div>
// )}
// export default Code |
const utils1 = require("../../../modules/IMPmodules/util")
const util = new utils1()
function collisions2player(entities, i, j) {
entity_1 = entities[i]
entity_2 = entities[j]
if (entity_1 && entity_2) {
if (entity_2.type == 40) {
if (entity_1.type == 2 || entity_1.class == "Food") {
if (entity_1.isloaded) {
if (entity_1.y > entity_2.y - entity_2.height / 2 &&
entity_2.x - entity_2.width / 2 < entity_1.x &&
entity_1.y < entity_2.y + entity_2.height / 2 &&
entity_2.x + entity_2.width / 2 > entity_1.x) {
entity_1.biome = 1
if (entity_2.specType == 0) {
if (!entity_1.isflying) {
if (entity_1.whichbiome != 5 && entity_1.whichbiome != 6) {
entity_1.pos.x -= 1.5
}
}
} else {
if (!entity_1.isflying) {
if (entity_1.whichbiome != 5 && entity_1.whichbiome != 6) {
entity_1.pos.x += 1.5
}
}
}
}
}
}
}
if (entity_1.biome != 1) {
if (entity_2.type == 12) {
if (entity_1.y > entity_2.y - entity_2.height / 2 &&
entity_2.x - entity_2.width / 2 < entity_1.x &&
entity_1.y < entity_2.y + entity_2.height / 2 &&
entity_2.x + entity_2.width / 2 > entity_1.x) {
entity_1.biome = 1
}
}
if (entity_1.type != 3) {
if (entity_2.type == 4 || entity_2.type == 10 || entity_2.type == 34) {
let distance = util.getDistance2D(entity_1.x, entity_1.y, entity_2.x, entity_2.y)
if (distance <= entity_2.radius) {
entity_1.biome = 1
}
}
}
}
if (entity_1.biome != 0) {
if (entity_2.type == 1) {
if (entity_1.y > entity_2.y - entity_2.height / 2 &&
entity_2.x - entity_2.width / 2 < entity_1.x &&
entity_1.y < entity_2.y + entity_2.height / 2 &&
entity_2.x + entity_2.width / 2 > entity_1.x) {
entity_1.biome = 0
}
}
}
if (entity_1.biome != 2) {
if (entity_2.type == 16) {
if (entity_1.y > entity_2.y - entity_2.height / 2 &&
entity_2.x - entity_2.width / 2 < entity_1.x &&
entity_1.y < entity_2.y + entity_2.height / 2 &&
entity_2.x + entity_2.width / 2 > entity_1.x) {
entity_1.biome = 2
}
}
}
if (entity_1.biome != 4) {
if (entity_2.type == 47) {
let distance = util.getDistance2D(entity_1.x, entity_1.y, entity_2.x, entity_2.y)
if (distance <= entity_2.radius) {
entity_1.biome = 4
}
}
}
if (entity_1.biome != 3) {
if (entity_2.type == 44) {
let distance = util.getDistance2D(entity_1.x, entity_1.y, entity_2.x, entity_2.y)
if (distance <= entity_2.radius) {
entity_1.biome = 3
}
}
}
}
}
collisions2player.prototype = {}
module.exports = collisions2player |
export const SHOW_ALERT = 'SHOW_ALERT';
export const HIDE_ALERT = 'HIDE_ALERT';
export const GET_CARS = 'GET_CARS';
export const SET_CAR_STATUS = 'SET_CAR_STATUS';
export const SET_LOADING = 'SET_LOADING';
|
#!/usr/bin/env node
import start from '../fileSystem_function';
start(); |
/**
This is a Book class object created to be consumed and generate 5 different books
*/
class Book {
//Attributes
constructor(name, author, genre, price, pagesNumber, selling) {
(this.name = name),
(this.author = author),
(this.genre = genre),
(this.price = price),
(this.pagesNumber = pagesNumber);
this.selling = selling;
}
//Methods
changePrice(newPrice) {
this.price = newPrice;
}
updateSelling(newNumber) {
this.selling = newNumber;
}
}
export default Book;
|
import React from 'react';
class Logout extends React.Component {
click = ( ) => {
localStorage.clear()
this.props.history.push('/')
// <div className='log-out-div'>
// <button onClick={this.click}>logout</button>
// </div>
}
render() {
return (
<div className='log-out-div' onClick={this.click}>
<div ontouchstart="">
<div className="button">
<a className="Logout-a" href="#">Log Out</a>
</div>
</div>
</div>
)
}
}
export default Logout;
|
'use strict';
import React, {Component} from 'react';
export class CardTitleInput extends Component{
constructor(props) {
super(props);
this.state = {
item: props.item
};
this.handleTitleChange = this.handleTitleChange.bind(this);
this.onUpdate = props.onUpdate;
}
render() {
const item = this.state.item;
return (
<div className="card-input-title">
<input type="text" value={item.content} onChange={ this.handleTitleChange } />
</div>
);
}
handleTitleChange(event) {
let item = this.state.item;
item.content = event.target.value;
this.updateItem(item)
}
updateItem(item){
this.setState({
item: item
});
this.onUpdate(item);
}
}
|
import React from "react";
// react component that copies the given text inside your clipboard
// import { CopyToClipboard } from "react-copy-to-clipboard";
// reactstrap components
import { } from "reactstrap";
// core components
import Header from "components/Headers/Header.js";
// reactstrap components
import {
Card,
CardHeader,
Container,
Row,
} from "reactstrap";
// import { CardBody, CardTitle, Col } from "reactstrap";
import Logo from "../../assets/My-Images/logo_real.png";
import Image1 from "../../assets/My-Images/image1.png";
import Image2 from "../../assets/My-Images/image2.png";
import Image3 from "../../assets/My-Images/image3.png";
import Image4 from "../../assets/My-Images/image4.png";
// core components
//import Header from "components/Headers/Header.js";
import "./style_orders.scss";
// import Caard from "components/Components/Card";
// import MyCarousel from "components/Components/MyCarousel";
// import CardSpecial from "./CardSpecial";
// import ArgonHeaderCards from "./ArgonHeaderCards";
import BlueCards from "components/Components/BlueCards";
import "./indexUser_style.scss";
function IndexUser() {
return (
<>
<Header />
{/* Page content */}
<Container className="mt--7" fluid>
{/* Table */}
<Row>
<div className="col">
<Card className="shadow shadow1">
<CardHeader className="bg-transparent">
<h3 className="mb-0 welcomeTostorak">
{" "}
<img className="Logo" src={Logo} alt="logo" /> Welcome to
storaak
</h3>
<p className="pleaseConfirm">
please confirm your email , {" "}
<span className="clickHere">click here</span>
</p>
</CardHeader>
</Card>
</div>
</Row>
<button className="thisMonth">
<p>
This month <i className="fas fa-chevron-down"></i>
</p>
</button>
<Container>
{/* I want this part Responsive
/ <Row lg="12" xs="1" sm="2" md="6">*/}
<Row>
<ul className="caard-list ">
<BlueCards />
<BlueCards />
<BlueCards />
<BlueCards />
</ul>
</Row>
</Container>
<Row>
<div className="col">
<Card className="shadow shadow2">
<CardHeader className="bg-transparent">
<div>
<h1>
<i className="fas fa-shopping-cart"></i>
New Orders
</h1>
<br />
<p className="tableOrder">
Order No. Client
Order History Edit
History Shippment
Payment Status
Notes
Total
</p>
<h3 className="noteOrder">There's no orders right now</h3>
</div>
</CardHeader>
</Card>
</div>
</Row>
<br />
<br />
<ul className="caard-list ">
<Row>
<div className="col">
<Card className="shadow shadow3 shadow31">
<CardHeader className="bg-transparent">
<div>
<h1 className="Title2Card">
<i className="fas fa-shopping-cart text-primary"></i>
Top Selling
</h1>
</div>
<button className="AddItems">
<p>
Add Items <i className="fas fa-plus "></i>
</p>
</button>
</CardHeader>
</Card>
</div>
</Row>
<Row
style={
{
// marginLeft: "100px"
}
}
>
<div className="col">
<Card className="shadow shadow3 shadow32">
<CardHeader className="bg-transparent">
<div>
<h1 className="Title2Card">
<i className="fas fa-shopping-cart text-danger"></i>
Products almost sold out
</h1>
</div>
<button className="AddItems">
<p>
AddItems <i className="fas fa-plus"></i>
</p>
</button>
</CardHeader>
</Card>
</div>
</Row>
</ul>
<br />
<br />
<Row>
<div className="col">
<Card className="shadow shadow2">
<CardHeader className="bg-transparent">
<div>
<h3 className="noteOrder">
<i className="fas fa-chevron-down downn"></i>
There's no orders right now
</h3>
</div>
</CardHeader>
</Card>
</div>
</Row>
{/* <ArgonHeaderCards /> */}
{/* Table */}
{/* First try Flex */}
<br />
<br />
<div className="containerFlex1">
<div className="flexCard11">
<Row>
<div className="col">
<Card className="shadow">
<CardHeader className="bg-transparent">
<div className="HorizentalOne">
<h1 >Set up the Store</h1>
<button className="btnflexCards bg-danger"> click me</button>
<img src={Image1} alt="image1" />
</div>
<div className="VerticalOne">
<p>Set up the Store</p>
<button className="btnflexCards bg-primary"> click me</button>
</div>
</CardHeader>
</Card>
</div>
</Row>
</div>
<div className="flexCard12">
<Row>
<div className="col">
<Card className="shadow">
<CardHeader className="bg-transparent">
<div className="HorizentalOne">
<h1>Set up the Store</h1>
<button className="btnflexCards bg-success"> click me</button>
<img src={Image2} alt="image2" />
</div>
<div className="VerticalOne">
<p>Set up the Store</p>
<button className="btnflexCards bg-primary"> click me</button>
</div>
</CardHeader>
</Card>
</div>
</Row>
</div>
</div>
<br />
<br />
<br />
<div className="containerFlex2">
<div className="flexCard21">
<Row>
<div className="col">
<Card className="shadow">
<CardHeader className="bg-transparent">
<div className="HorizentalOne">
<h1>Set up the Store</h1>
<button className="btnflexCards bg-danger"> click me</button>
<img src={Image3} alt="image3" />
</div>
<div className="VerticalOne">
<p>Set up the Store</p>
<button className="btnflexCards bg-primary"> click me</button>
</div>
</CardHeader>
</Card>
</div>
</Row>
</div>
<div className="flexCard22">
<Row>
<div className="col">
<Card className="shadow">
<CardHeader className="bg-transparent">
<div className="HorizentalOne">
<h1>Set up the Store</h1>
<button className="btnflexCards bg-danger"> click me</button>
<img src={Image4} alt="image5" />
</div>
<div className="VerticalOne">
<p>Set up the Store</p>
<button className="btnflexCards bg-primary"> click me</button>
</div>
</CardHeader>
</Card>
</div>
</Row>
</div>
</div>
<br />
<br />
<br />
</Container>
</>
);
}
export default IndexUser;
|
import React from "react";
import withStyles from "@material-ui/core/styles/withStyles";
import { styles } from "../styles/modalStyles";
import { Typography } from "@material-ui/core";
import {
FacebookIcon,
TwitterIcon,
TwitterShareButton,
EmailShareButton,
FacebookShareButton,
EmailIcon
} from "react-share";
const SocialShareIcons = props => {
const { classes } = props;
return (
<div className={classes.shareRating}>
<div className={classes.shareIcons}>
<FacebookShareButton
quote={props.gif.title}
url={props.gif.images.original.url}
round={true}
>
<FacebookIcon size={32} round={true} />
</FacebookShareButton>
<TwitterShareButton url={props.gif.images.original.url}>
<TwitterIcon size={32} round={true} />
</TwitterShareButton>
<EmailShareButton
url={props.gif.images.original.url}
subject={props.gif.title}
image={props.gif.images.original.url}
>
<EmailIcon size={32} round={true} />
</EmailShareButton>
</div>
<Typography className={classes.rating}>
Rating: {props.gif.rating.toUpperCase()}
</Typography>
</div>
);
};
export default withStyles(styles)(SocialShareIcons);
|
import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import { Box, TextInput } from 'grommet';
import KeyboardEventHandler from 'react-keyboard-event-handler';
import Button from 'UI/Button';
import { Label } from 'UI/Labels';
import { Tag, Close } from 'grommet-icons';
// eslint-disable-next-line
import { camelCase } from 'lodash';
import './LabelPicker.scss';
const LabelInput = ({
onAdd,
color,
onChange,
onRemove,
value,
suggestions,
}) => {
const [currentTag, setCurrentTag] = React.useState('');
const [box, setBox] = React.useState();
const boxRef = React.useCallback(setBox, []);
const updateCurrentTag = (event) => {
setCurrentTag(event.target.value);
if (onChange) {
onChange(event);
}
};
const onAddTag = (tag) => {
setCurrentTag('');
if (onAdd) {
onAdd(tag);
}
};
const onEnter = () => {
if (currentTag.length) {
onAddTag(currentTag);
}
};
const renderValue = () => {
const titles = [];
const Labels = [];
for (let i = 0; i < value.length; i += 1) {
const v = value[i];
if (titles.indexOf(v.title) === -1) {
titles.push(v.title);
Labels.push(
<Label
key={`${v}${i + 0}`}
color={color}
onClick={() => {
onRemove(v);
}}
label={(
<React.Fragment>
{(v && v.title) || v}
<Close color="accent-2" size="12px" />
</React.Fragment>
)}
/>,
);
}
}
return Labels;
};
return (
<KeyboardEventHandler
handleKeys={['enter']}
onKeyEvent={(key) => {
if (key === 'enter') {
onEnter();
}
}}
>
<Box
direction="row"
align="center"
pad={{ horizontal: 'xsmall' }}
margin="xsmall"
className="label-picker-input"
background="accent-1"
border="all"
ref={boxRef}
wrap
>
{value.length > 0 && renderValue()}
<Box flex style={{ minWidth: '120px', color }}>
<TextInput
type="search"
plain
dropTarget={box}
suggestions={suggestions}
onChange={updateCurrentTag}
value={currentTag}
autoFocus
onSelect={(event) => {
event.stopPropagation();
onAddTag(event.suggestion);
}}
/>
</Box>
</Box>
</KeyboardEventHandler>
);
};
LabelInput.propTypes = {
onAdd: PropTypes.func.isRequired,
color: PropTypes.string,
onChange: PropTypes.func.isRequired,
value: PropTypes.array,
onRemove: PropTypes.func.isRequired,
suggestions: PropTypes.array,
};
LabelInput.defaultProps = {
value: [],
suggestions: [],
color: '',
};
const LabelPicker = (props) => {
const {
globalLabels, cardLabels, onRemove, onAdd, onChange, color,
} = props;
const [selectedTags, setSelectedTags] = React.useState(cardLabels);
const [suggestions, setSuggestions] = React.useState(globalLabels);
const [inputHidden, toggleInput] = useState(true);
useEffect(() => {
setSelectedTags(cardLabels);
}, [cardLabels]);
const transformTag = (tag) => {
const newTag = camelCase(tag);
return newTag.startsWith('#') ? newTag : `#${newTag}`;
};
const onRemoveTag = (tag) => {
const labelTitle = transformTag(tag.title || tag);
const removeIndex = selectedTags.map(t => t.title).indexOf(labelTitle);
const newTags = [...selectedTags];
if (removeIndex >= 0) {
newTags.splice(removeIndex, 1);
}
onChange(cardLabels.filter(l => l.title !== labelTitle));
onRemove({ title: labelTitle });
setSelectedTags(newTags);
};
const onAddTag = (tag) => {
const labelTitle = transformTag(tag);
const labelTitles = selectedTags.map(t => t.title);
if (labelTitles.indexOf(labelTitle) === -1) {
onAdd({ title: labelTitle });
onChange([...(cardLabels || []), { title: labelTitle }]);
setSelectedTags([...selectedTags, labelTitle]);
}
};
const onFilterSuggestion = (v) => {
setSuggestions(
globalLabels.filter(
suggestion => suggestion
&& suggestion.toLowerCase().indexOf(v && v.toLowerCase()) >= 0,
),
);
};
return (
<Box flex direction="row" justify="start">
<Button
className="label-picker-button"
onClick={() => toggleInput(!inputHidden)}
primary
color="accent-1"
>
<Tag color="brand" />
</Button>
{!inputHidden && (
<LabelInput
placeholder="Search for aliases..."
suggestions={suggestions.splice(0, 10)}
plain
value={selectedTags}
color={color}
onRemove={onRemoveTag}
onAdd={onAddTag}
onChange={v => onFilterSuggestion(v.target.value)}
/>
)}
</Box>
);
};
LabelPicker.propTypes = {
globalLabels: PropTypes.array,
cardLabels: PropTypes.array,
color: PropTypes.string,
onChange: PropTypes.func.isRequired,
onAdd: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
};
LabelPicker.defaultProps = {
cardLabels: [],
color: null,
globalLabels: [''],
};
export default LabelPicker;
|
/*
** 右键菜单
*/
HROS.popupMenu = (function () {
return {
init: function () {
$('.popup-menu').on('contextmenu', function () {
return false;
});
//动态控制多级菜单的显示位置
$('body').on('mouseenter', '.popup-menu li', function () {
if ($(this).children('.popup-menu').length == 1) {
$(this).children('a').addClass('focus');
$(this).children('.popup-menu').show();
if ($(this).parents('.popup-menu').offset().left + $(this).parents('.popup-menu').width() * 2 + 10 < $(window).width()) {
$(this).children('.popup-menu').css({
left: $(this).parents('.popup-menu').width() - 5,
top: 0
});
} else {
$(this).children('.popup-menu').css({
left: -1 * $(this).parents('.popup-menu').width(),
top: 0
});
}
if ($(this).children('.popup-menu').offset().top + $(this).children('.popup-menu').height() + 10 > $(window).height()) {
$(this).children('.popup-menu').css({
top: $(window).height() - $(this).children('.popup-menu').height() - $(this).children('.popup-menu').offset().top - 10
});
}
}
}).on('mouseleave', '.popup-menu li', function () {
$(this).children('a').removeClass('focus');
$(this).children('.popup-menu').hide();
});
},
/*
** 应用右键
*/
app: function (obj) {
HROS.window.show2under();
if (!TEMP.popupMenuApp) {
TEMP.popupMenuApp = $(
'<div class="popup-menu app-menu"><ul>' +
'<li style="border-bottom:1px solid #F0F0F0"><a menu="open" href="javascript:;">打开</a></li>' +
'<li>' +
'<a menu="move" href="javascript:;">移动到<b class="arrow">»</b></a>' +
'<div class="popup-menu"><ul>' +
'<li><a menu="moveto" desk="1" href="javascript:;">桌面1</a></li>' +
'<li><a menu="moveto" desk="2" href="javascript:;">桌面2</a></li>' +
'<li><a menu="moveto" desk="3" href="javascript:;">桌面3</a></li>' +
'<li><a menu="moveto" desk="4" href="javascript:;">桌面4</a></li>' +
'<li><a menu="moveto" desk="5" href="javascript:;">桌面5</a></li>' +
'</ul></div>' +
'</li>' +
'<li><a menu="edit" href="javascript:;"><b class="edit"></b>编辑</a></li>' +
'<li><a menu="del" href="javascript:;"><b class="uninstall"></b>卸载</a></li>' +
'</ul></div>'
);
$('body').append(TEMP.popupMenuApp);
}
$('.app-menu a[menu="moveto"]').removeClass('disabled');
if (obj.parent().hasClass('desktop-apps-container')) {
$('.app-menu a[menu="moveto"]').each(function () {
if ($(this).attr('desk') == HROS.CONFIG.desk) {
$(this).addClass('disabled');
}
});
}
//绑定事件
$('.app-menu a[menu="moveto"]').off('click').on('click', function () {
var id = obj.attr('appid'),
from = obj.index(),
to = 99999,
todesk = $(this).attr('desk'),
fromdesk = HROS.CONFIG.desk,
fromfolderid = obj.parents('.folder-window').attr('appid') || obj.parents('.quick_view_container').attr('appid');
if (HROS.base.checkLogin()) {
if (!HROS.app.checkIsMoving()) {
var rtn = false;
if (obj.parent().hasClass('dock-applist')) {
if (HROS.app.dataDockToOtherdesk(id, from, todesk)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=dock-otherdesk&id=' + id + '&from=' + from + '&todesk=' + todesk
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
} else if (obj.parent().hasClass('desktop-apps-container')) {
if (HROS.app.dataDeskToOtherdesk(id, from, to, 'a', todesk, fromdesk)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=desk-otherdesk&id=' + id + '&from=' + from + '&to=' + to + '&todesk=' + todesk + '&fromdesk=' + fromdesk
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
} else {
if (HROS.app.dataFolderToOtherdesk(id, from, todesk, fromfolderid)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=folder-otherdesk&id=' + id + '&from=' + from + '&todesk=' + todesk + '&fromfolderid=' + fromfolderid
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
}
}
} else {
if (obj.parent().hasClass('dock-applist')) {
HROS.app.dataDockToOtherdesk(id, from, todesk);
} else if (obj.parent().hasClass('desktop-apps-container')) {
HROS.app.dataDeskToOtherdesk(id, from, to, 'a', todesk, fromdesk);
} else {
HROS.app.dataFolderToOtherdesk(id, from, todesk, fromfolderid);
}
}
$('.popup-menu').hide();
});
$('.app-menu a[menu="open"]').off('click').on('click', function () {
HROS.window.create(obj.attr('realappid'), obj.attr('type'));
$('.popup-menu').hide();
});
$('.app-menu a[menu="edit"]').off('click').on('click', function () {
if (HROS.base.checkLogin()) {
$.dialog.open('sysapp/dialog/app.php?id=' + obj.attr('appid'), {
id: 'editdialog',
title: '编辑应用“' + obj.children('span').text() + '”',
width: 600,
height: 350
});
} else {
HROS.base.login();
}
$('.popup-menu').hide();
});
$('.app-menu a[menu="del"]').off('click').on('click', function () {
HROS.app.dataDeleteByAppid(obj.attr('appid'));
HROS.widget.removeCookie(obj.attr('realappid'), obj.attr('type'));
HROS.app.remove(obj.attr('appid'), function () {
obj.find('img, span').show().animate({
opacity: 'toggle',
width: 0,
height: 0
}, 500, function () {
obj.remove();
HROS.deskTop.resize();
});
});
$('.popup-menu').hide();
});
return TEMP.popupMenuApp;
},
papp: function (obj) {
HROS.window.show2under();
if (!TEMP.popupMenuPapp) {
TEMP.popupMenuPapp = $(
'<div class="popup-menu papp-menu"><ul>' +
'<li style="border-bottom:1px solid #F0F0F0"><a menu="open" href="javascript:;">打开</a></li>' +
'<li>' +
'<a menu="move" href="javascript:;">移动到<b class="arrow">»</b></a>' +
'<div class="popup-menu"><ul>' +
'<li><a menu="moveto" desk="1" href="javascript:;">桌面1</a></li>' +
'<li><a menu="moveto" desk="2" href="javascript:;">桌面2</a></li>' +
'<li><a menu="moveto" desk="3" href="javascript:;">桌面3</a></li>' +
'<li><a menu="moveto" desk="4" href="javascript:;">桌面4</a></li>' +
'<li><a menu="moveto" desk="5" href="javascript:;">桌面5</a></li>' +
'</ul></div>' +
'</li>' +
'<li><a menu="edit" href="javascript:;"><b class="edit"></b>编辑</a></li>' +
'<li><a menu="del" href="javascript:;"><b class="del"></b>删除</a></li>' +
'</ul></div>'
);
$('body').append(TEMP.popupMenuPapp);
}
$('.papp-menu a[menu="moveto"]').removeClass('disabled');
if (obj.parent().hasClass('desktop-apps-container')) {
$('.papp-menu a[menu="moveto"]').each(function () {
if ($(this).attr('desk') == HROS.CONFIG.desk) {
$(this).addClass('disabled');
}
});
}
//绑定事件
$('.papp-menu a[menu="moveto"]').off('click').on('click', function () {
var id = obj.attr('appid'),
from = obj.index(),
to = 99999,
todesk = $(this).attr('desk'),
fromdesk = HROS.CONFIG.desk,
fromfolderid = obj.parents('.folder-window').attr('appid') || obj.parents('.quick_view_container').attr('appid');
if (HROS.base.checkLogin()) {
var rtn = false;
if (obj.parent().hasClass('dock-applist')) {
if (HROS.app.dataDockToOtherdesk(id, from, todesk)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=dock-otherdesk&id=' + id + '&from=' + from + '&todesk=' + todesk
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
} else if (obj.parent().hasClass('desktop-apps-container')) {
if (HROS.app.dataDeskToOtherdesk(id, from, to, 'a', todesk, fromdesk)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=desk-otherdesk&id=' + id + '&from=' + from + '&to=' + to + '&todesk=' + todesk + '&fromdesk=' + fromdesk
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
} else {
if (HROS.app.dataFolderToOtherdesk(id, from, todesk, fromfolderid)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=folder-otherdesk&id=' + id + '&from=' + from + '&todesk=' + todesk + '&fromfolderid=' + fromfolderid
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
}
} else {
if (obj.parent().hasClass('dock-applist')) {
HROS.app.dataDockToOtherdesk(id, from, todesk);
} else if (obj.parent().hasClass('desktop-apps-container')) {
HROS.app.dataDeskToOtherdesk(id, from, to, 'a', todesk, fromdesk);
} else {
HROS.app.dataFolderToOtherdesk(id, from, todesk, fromfolderid);
}
}
$('.popup-menu').hide();
});
$('.papp-menu a[menu="open"]').off('click').on('click', function () {
switch (obj.attr('type')) {
case 'papp':
HROS.window.create(obj.attr('realappid'), obj.attr('type'));
break;
case 'pwidget':
HROS.widget.create(obj.attr('realappid'), obj.attr('type'));
break;
}
$('.popup-menu').hide();
});
$('.papp-menu a[menu="edit"]').off('click').on('click', function () {
if (HROS.base.checkLogin()) {
$.dialog.open('sysapp/dialog/papp.php?id=' + obj.attr('appid'), {
id: 'editdialog',
title: '编辑私人应用“' + obj.children('span').text() + '”',
width: 600,
height: 450
});
} else {
HROS.base.login();
}
$('.popup-menu').hide();
});
$('.papp-menu a[menu="del"]').off('click').on('click', function () {
HROS.app.dataDeleteByAppid(obj.attr('appid'));
HROS.widget.removeCookie(obj.attr('realappid'), obj.attr('type'));
HROS.app.remove(obj.attr('appid'), function () {
obj.find('img, span').show().animate({
opacity: 'toggle',
width: 0,
height: 0
}, 500, function () {
obj.remove();
HROS.deskTop.resize();
});
});
$('.popup-menu').hide();
});
return TEMP.popupMenuPapp;
},
/*
** 文件夹右键
*/
folder: function (obj) {
HROS.window.show2under();
if (!TEMP.popupMenuFolder) {
TEMP.popupMenuFolder = $(
'<div class="popup-menu folder-menu"><ul>' +
'<li><a menu="view" href="javascript:;">预览</a></li>' +
'<li style="border-bottom:1px solid #F0F0F0"><a menu="open" href="javascript:;">打开</a></li>' +
'<li>' +
'<a menu="move" href="javascript:;">移动到<b class="arrow">»</b></a>' +
'<div class="popup-menu"><ul>' +
'<li><a menu="moveto" desk="1" href="javascript:;">桌面1</a></li>' +
'<li><a menu="moveto" desk="2" href="javascript:;">桌面2</a></li>' +
'<li><a menu="moveto" desk="3" href="javascript:;">桌面3</a></li>' +
'<li><a menu="moveto" desk="4" href="javascript:;">桌面4</a></li>' +
'<li><a menu="moveto" desk="5" href="javascript:;">桌面5</a></li>' +
'</ul></div>' +
'</li>' +
'<li><a menu="rename" href="javascript:;"><b class="edit"></b>重命名</a></li>' +
'<li><a menu="del" href="javascript:;"><b class="del"></b>删除</a></li>' +
'</ul></div>'
);
$('body').append(TEMP.popupMenuFolder);
}
$('.folder-menu a[menu="moveto"]').removeClass('disabled');
if (obj.parent().hasClass('desktop-apps-container')) {
$('.folder-menu a[menu="moveto"]').each(function () {
if ($(this).attr('desk') == HROS.CONFIG.desk) {
$(this).addClass('disabled');
}
});
}
//绑定事件
$('.folder-menu a[menu="view"]').off('click').on('click', function () {
HROS.folderView.get(obj);
$('.popup-menu').hide();
});
$('.folder-menu a[menu="open"]').off('click').on('click', function () {
HROS.window.create(obj.attr('realappid'), obj.attr('type'));
$('.popup-menu').hide();
});
$('.folder-menu a[menu="moveto"]').off('click').on('click', function () {
var id = obj.attr('appid'),
from = obj.index(),
to = 99999,
todesk = $(this).attr('desk'),
fromdesk = HROS.CONFIG.desk,
fromfolderid = obj.parents('.folder-window').attr('appid') || obj.parents('.quick_view_container').attr('appid');
if (HROS.base.checkLogin()) {
var rtn = false;
if (obj.parent().hasClass('dock-applist')) {
if (HROS.app.dataDockToOtherdesk(id, from, todesk)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=dock-otherdesk&id=' + id + '&from=' + from + '&todesk=' + todesk
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
} else if (obj.parent().hasClass('desktop-apps-container')) {
if (HROS.app.dataDeskToOtherdesk(id, from, to, 'a', todesk, fromdesk)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=desk-otherdesk&id=' + id + '&from=' + from + '&to=' + to + '&todesk=' + todesk + '&fromdesk=' + fromdesk
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
} else {
if (HROS.app.dataFolderToOtherdesk(id, from, todesk, fromfolderid)) {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=moveMyApp&movetype=folder-otherdesk&id=' + id + '&from=' + from + '&todesk=' + todesk + '&fromfolderid=' + fromfolderid
}).done(function (responseText) {
HROS.VAR.isAppMoving = false;
});
}
}
} else {
if (obj.parent().hasClass('dock-applist')) {
HROS.app.dataDockToOtherdesk(id, from, todesk);
} else if (obj.parent().hasClass('desktop-apps-container')) {
HROS.app.dataDeskToOtherdesk(id, from, to, 'a', todesk, fromdesk);
} else {
HROS.app.dataFolderToOtherdesk(id, from, todesk, fromfolderid);
}
}
$('.popup-menu').hide();
});
$('.folder-menu a[menu="rename"]').off('click').on('click', function () {
if (HROS.base.checkLogin()) {
$.dialog({
id: 'addfolder',
title: '重命名“' + obj.find('span').text() + '”文件夹',
padding: 0,
content: editFolderDialogTemp({
'name': obj.find('span').text(),
'src': obj.find('img').attr('src')
}),
ok: function () {
if ($('#folderName').val() != '') {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=updateFolder&name=' + $('#folderName').val() + '&icon=' + $('.folderSelector img').attr('src') + '&id=' + obj.attr('appid')
}).done(function (responseText) {
HROS.app.get();
});
} else {
$('.folderNameError').show();
return false;
}
},
cancel: true
});
$('.folderSelector').off('click').on('click', function () {
$('.fcDropdown').show();
});
$('.fcDropdown_item').off('click').on('click', function () {
$('.folderSelector img').attr('src', $(this).children('img').attr('src')).attr('idx', $(this).children('img').attr('idx'));
$('.fcDropdown').hide();
});
} else {
HROS.base.login();
}
$('.popup-menu').hide();
});
$('.folder-menu a[menu="del"]').off('click').on('click', function () {
$.dialog({
id: 'delfolder',
title: '删除“' + obj.find('span').text() + '”文件夹',
content: '删除文件夹的同时会删除文件夹内所有应用',
icon: 'warning',
ok: function () {
HROS.app.remove(obj.attr('appid'), function () {
HROS.app.dataDeleteByAppid(obj.attr('appid'));
obj.find('img, span').show().animate({
opacity: 'toggle',
width: 0,
height: 0
}, 500, function () {
obj.remove();
HROS.deskTop.resize();
});
});
},
cancel: true
});
$('.popup-menu').hide();
});
return TEMP.popupMenuFolder;
},
/*
** 文件右键
*/
file: function (obj) {
HROS.window.show2under();
if (!TEMP.popupMenuFile) {
TEMP.popupMenuFile = $(
'<div class="popup-menu file-menu"><ul>' +
'<li style="border-bottom:1px solid #F0F0F0"><a menu="download" href="javascript:;">下载</a></li>' +
'<li><a menu="del" href="javascript:;"><b class="del"></b>删除</a></li>' +
'</ul></div>'
);
$('body').append(TEMP.popupMenuFile);
}
//绑定事件
$('.file-menu a[menu="download"]').off('click').on('click', function () {
$('body').append(fileDownloadTemp({
appid: obj.attr('appid')
}));
$('.popup-menu').hide();
});
$('.file-menu a[menu="del"]').off('click').on('click', function () {
HROS.app.dataDeleteByAppid(obj.attr('appid'));
HROS.app.remove(obj.attr('appid'), function () {
obj.find('img, span').show().animate({
opacity: 'toggle',
width: 0,
height: 0
}, 500, function () {
obj.remove();
HROS.deskTop.resize();
});
});
$('.popup-menu').hide();
});
return TEMP.popupMenuFile;
},
/*
** 应用码头右键
*/
dock: function () {
HROS.window.show2under();
if (!TEMP.popupMenuDock) {
TEMP.popupMenuDock = $(
'<div class="popup-menu dock-menu"><ul>' +
'<li><a menu="dockPos" pos="top" href="javascript:;"><b class="hook"></b>向上停靠</a></li>' +
'<li><a menu="dockPos" pos="left" href="javascript:;"><b class="hook"></b>向左停靠</a></li>' +
'<li><a menu="dockPos" pos="right" href="javascript:;"><b class="hook"></b>向右停靠</a></li>' +
'<li><a menu="dockPos" pos="none" href="javascript:;">隐藏</a></li>' +
'</ul></div>'
);
$('body').append(TEMP.popupMenuDock);
//绑定事件
$('.dock-menu a[menu="dockPos"]').on('click', function () {
if ($(this).attr('pos') == 'none') {
$.dialog({
title: '温馨提示',
icon: 'warning',
content: '<p>如果应用码头存在应用,隐藏后会将应用转移到当前桌面。</p><p>若需要再次开启,可在桌面空白处点击右键,进入「 桌面设置 」里开启。</p>',
ok: function () {
HROS.dock.updatePos('none');
},
cancel: true
});
} else {
HROS.dock.updatePos($(this).attr('pos'));
}
$('.popup-menu').hide();
});
}
$('.dock-menu a[menu="dockPos"]').each(function () {
$(this).children('.hook').hide();
if ($(this).attr('pos') == HROS.CONFIG.dockPos) {
$(this).children('.hook').show();
}
$('.popup-menu').hide();
});
return TEMP.popupMenuDock;
},
/*
** 任务栏右键
*/
task: function (obj) {
HROS.window.show2under();
if (!TEMP.popupMenuTask) {
TEMP.popupMenuTask = $(
'<div class="popup-menu task-menu"><ul>' +
'<li><a menu="max" href="javascript:;">最大化</a></li>' +
'<li style="border-bottom:1px solid #F0F0F0"><a menu="hide" href="javascript:;">最小化</a></li>' +
'<li><a menu="close" href="javascript:;">关闭</a></li>' +
'</ul></div>'
);
$('body').append(TEMP.popupMenuTask);
}
//绑定事件
$('.task-menu a[menu="max"]').off('click').on('click', function () {
HROS.window.max(obj.attr('appid'), obj.attr('type'));
$('.popup-menu').hide();
});
$('.task-menu a[menu="hide"]').off('click').on('click', function () {
HROS.window.hide(obj.attr('appid'), obj.attr('type'));
$('.popup-menu').hide();
});
$('.task-menu a[menu="close"]').off('click').on('click', function () {
HROS.window.close(obj.attr('appid'), obj.attr('type'));
$('.popup-menu').hide();
});
return TEMP.popupMenuTask;
},
/*
** 桌面右键
*/
desk: function () {
HROS.window.show2under();
if (!TEMP.popupMenuDesk) {
TEMP.popupMenuDesk = $(
'<div class="popup-menu desk-menu"><ul>' +
'<li><a menu="hideall" href="javascript:;">显示桌面</a></li>' +
'<li style="border-bottom:1px solid #F0F0F0"><a menu="closeall" href="javascript:;">关闭所有窗口</a></li>' +
'<li>' +
'<a href="javascript:;">新建<b class="arrow">»</b></a>' +
'<div class="popup-menu"><ul>' +
'<li><a menu="addfolder" href="javascript:;"><b class="folder"></b>新建文件夹</a></li>' +
'<li><a menu="addpapp" href="javascript:;"><b class="customapp"></b>新建私人应用</a></li>' +
'</ul></div>' +
'</li>' +
'<li style="border-bottom:1px solid #F0F0F0"><b class="upload"></b><a menu="uploadfile" href="javascript:;">上传文件</a></li>' +
'<li><a menu="themes" href="javascript:;"><b class="themes"></b>主题设置</a></li>' +
'<li><a menu="setting" href="javascript:;"><b class="setting"></b>桌面设置</a></li>' +
'<li style="border-bottom:1px solid #F0F0F0">' +
'<a href="javascript:;">图标设置<b class="arrow">»</b></a>' +
'<div class="popup-menu"><ul>' +
'<li>' +
'<a href="javascript:;">排列<b class="arrow">»</b></a>' +
'<div class="popup-menu"><ul>' +
'<li><a menu="orderby" orderby="x" href="javascript:;"><b class="hook"></b>横向排列</a></li>' +
'<li><a menu="orderby" orderby="y" href="javascript:;"><b class="hook"></b>纵向排列</a></li>' +
'</ul></div>' +
'</li>' +
'<li>' +
'<a href="javascript:;">尺寸<b class="arrow">»</b></a>' +
'<div class="popup-menu"><ul>' +
'<li><a menu="size" size="s" href="javascript:;"><b class="hook"></b>小图标</a></li>' +
'<li><a menu="size" size="m" href="javascript:;"><b class="hook"></b>大图标</a></li>' +
'</ul></div>' +
'</li>' +
'</ul></div>' +
'</li>' +
'<li><a menu="lock" href="javascript:;">锁定</a></li>' +
'<li><a menu="logout" href="javascript:;">注销</a></li>' +
'</ul></div>'
);
$('body').append(TEMP.popupMenuDesk);
if (!HROS.base.checkLogin()) {
$('body .desk-menu li a[menu="logout"]').parent().remove();
}
//绑定事件
$('.desk-menu a[menu="orderby"]').on('click', function () {
HROS.app.updateXY($(this).attr('orderby'));
$('.popup-menu').hide();
});
$('.desk-menu a[menu="size"]').on('click', function () {
HROS.app.updateSize($(this).attr('size'));
$('.popup-menu').hide();
});
$('.desk-menu a[menu="hideall"]').on('click', function () {
HROS.window.hideAll();
$('.popup-menu').hide();
});
$('.desk-menu a[menu="closeall"]').on('click', function () {
HROS.window.closeAll();
$('.popup-menu').hide();
});
$('.desk-menu a[menu="addfolder"]').on('click', function () {
if (HROS.base.checkLogin()) {
$.dialog({
id: 'addfolder',
title: '新建文件夹',
padding: 0,
content: editFolderDialogTemp({
'name': '新建文件夹',
'src': 'img/ui/folder_default.png'
}),
ok: function () {
if ($('#folderName').val() != '') {
$.ajax({
type: 'POST',
url: ajaxUrl,
data: 'ac=addFolder&name=' + $('#folderName').val() + '&icon=' + $('.folderSelector img').attr('src') + '&desk=' + HROS.CONFIG.desk
}).done(function (responseText) {
HROS.app.get();
});
} else {
$('.folderNameError').show();
return false;
}
},
cancel: true
});
$('.folderSelector').on('click', function () {
$('#addfolder .fcDropdown').show();
return false;
});
$(document).click(function () {
$('#addfolder .fcDropdown').hide();
});
$('.fcDropdown_item').on('click', function () {
$('.folderSelector img').attr('src', $(this).children('img').attr('src')).attr('idx', $(this).children('img').attr('idx'));
$('#addfolder .fcDropdown').hide();
});
} else {
HROS.base.login();
}
$('.popup-menu').hide();
});
$('.desk-menu a[menu="addpapp"]').on('click', function () {
if (HROS.base.checkLogin()) {
$.dialog.open('sysapp/dialog/papp.php?desk=' + HROS.CONFIG.desk, {
id: 'editdialog',
title: '新建私人应用',
width: 600,
height: 450
});
} else {
HROS.base.login();
}
$('.popup-menu').hide();
});
$('.desk-menu a[menu="uploadfile"]').on('click', function () {
HROS.window.createTemp({
appid: 'hoorayos-scwj',
title: '上传文件',
url: 'sysapp/upload/index.php',
width: 750,
height: 600,
isflash: false
});
$('.popup-menu').hide();
});
$('.desk-menu a[menu="themes"]').on('click', function () {
if (HROS.base.checkLogin()) {
HROS.window.createTemp({
appid: 'hoorayos-ztsz',
title: '主题设置',
url: '/PlatformSetting/SystemWallPaper',
width: 580,
height: 520,
isflash: false
});
} else {
HROS.base.login();
}
$('.popup-menu').hide();
});
$('.desk-menu a[menu="setting"]').on('click', function () {
if (HROS.base.checkLogin()) {
HROS.window.createTemp({
appid: 'hoorayos-zmsz',
title: '桌面设置',
url: '/PlatformSetting/DeskTopSetting',
width: 750,
height: 450,
isflash: false
});
} else {
HROS.base.login();
}
$('.popup-menu').hide();
});
$('.desk-menu a[menu="lock"]').on('click', function () {
HROS.lock.show();
$('.popup-menu').hide();
});
$('.desk-menu a[menu="logout"]').on('click', function () {
HROS.base.logout();
$('.popup-menu').hide();
});
}
$('.desk-menu a[menu="orderby"]').each(function () {
$(this).children('.hook').hide();
if ($(this).attr('orderby') == HROS.CONFIG.appXY) {
$(this).children('.hook').show();
}
$('.popup-menu').hide();
});
$('.desk-menu a[menu="size"]').each(function () {
$(this).children('.hook').hide();
if ($(this).attr('size') == HROS.CONFIG.appSize) {
$(this).children('.hook').show();
}
$('.popup-menu').hide();
});
return TEMP.popupMenuDesk;
},
hide: function () {
$('.popup-menu').hide();
}
}
})(); |
import React from 'react'
import ReactDOM from 'react-dom'
import { Link } from 'react-router-dom'
class Button extends React.Component {
constructor(props) {
super(props)
this.state= {
active: false
}
}
handleMouseOver = (e) => {
if(e.target.classList.contains('btn-style-1')) {
this.setState({
active: true
})
}
}
handleMouseOut = (e) => {
if(e.target.classList.contains('btn-style-1')) {
this.setState({
active: false
})
}
}
handleClick = (e) => {
// btn style 4 click function
if(e.target.classList.contains('btn-style-4')) {
e.target.classList.remove('animate')
e.target.classList.add('animate')
setTimeout(function() {
e.target.classList.remove('animate')
},700)
e.target.querySelector('.button-cover').style.backgroundImage='radial-gradient(circle,'+this.props.bgColor+' 20%,transparent 20%),radial-gradient(circle,'+this.props.bgColor+' 20%,transparent 20%),radial-gradient(circle,'+this.props.bgColor+' 20%,transparent 20%),radial-gradient(circle,transparent 10%, '+this.props.bgColor+' 15%,transparent 20%),radial-gradient(circle,'+this.props.bgColor+' 20%,transparent 20%),radial-gradient(circle,transparent 10%, '+this.props.bgColor+' 15%,transparent 20%),radial-gradient(circle,'+this.props.bgColor+' 20%,transparent 20%),radial-gradient(circle,'+this.props.bgColor+' 20%,transparent 20%)'
}
e.persist()
}
componentDidMount() {
const el = ReactDOM.findDOMNode(this)
const width = el.offsetWidth
this.setState({
height: width
})
}
render() {
const style = {
button: {
background: this.props.bgColor,
borderColor: this.props.bgColor,
color: this.state.active ? this.props.bgColor : this.props.Color
},
button_cover: {
backgroundColor: this.props.bgColor,
borderColor: this.props.bgColor,
color: this.state.active ? this.props.bgColor : this.props.Color,
height: this.state.height
}
}
return(
<Link className={this.props.className} style={{...style.button,...this.props.componentStyle}} to={this.props.to ? this.props.to : "button"} onMouseOver={this.handleMouseOver} onMouseLeave= {this.handleMouseOut} onClick={(e) => {this.handleClick(e); this.props.onClick && this.props.onClick()}}>
{this.props.icon ? <i className={this.props.icon} style={{marginRight: this.props.children ? 10 : 0}} /> : undefined}
{this.props.children}
<span className="button-cover" style={style.button_cover}></span>
</Link>
);
}
}
export default Button |
module.exports = function(grunt) {
var pkg = grunt.file.readJSON('package.json');
grunt.initConfig({
browserify: {
dist: {
src: 'js/main.js',
dest: 'build/build.js'
}
}
});
Object.keys(pkg.devDependencies).forEach(function (devDependency) {
if (devDependency.match(/^grunt\-/)) {
grunt.loadNpmTasks(devDependency);
}
});
grunt.registerTask('default', [ 'browserify' ]);
}; |
/*EXPECTED
42
*/
class _Main {
static function main(args : string[]) : void {
[ [42] ].forEach((item) -> {
log item.join(", ");
});
}
}
// vim: set expandtab tabstop=2 shiftwidth=2 ft=jsx:
|
var weatherStation = {
update: [],
addObserver: function(f) {
this.update.push(f);
},
notify: function() {
for (var i = 0; i < this.update.length; i++) {
var f = this.update[i];
f.apply(this, arguments);
}
}
};
weatherStation.addObserver(function(weather) {
console.log("The current temp is: " + weather.temp);
});
weatherStation.addObserver(function(weather) {
console.log("The current pressure is: " + weather.pressure);
});
weatherStation.notify({ temp: 87, pressure: 29.93 }); |
import Helpers from './Helpers';
// import useSound from 'use-sound';
// import boop from '../../sounds/boop.mp3';
const Socket = () => {
const [CreateElement] = Helpers();
// const [emitBoop] = useSound(
// boop,
// { volume: 0.25 }
// );
const postMessage = (emittedUser, emittedMessage, userClass, audio) => {
if(emittedMessage === null) return;
const chatContainer = document.getElementById('chat');
const message = CreateElement('div', { className: `${userClass}`});
const sender = CreateElement('h3', { innerHTML: `${emittedUser}` });
const text = CreateElement('p', { innerHTML: `${emittedMessage}` });
message.appendChild(sender);
message.appendChild(text);
chatContainer.appendChild(message);
chatContainer.scrollTop = (chatContainer.scrollHeight - chatContainer.clientHeight);
// if(audio) emitBoop();
};
return [postMessage];
}
export default Socket; |
{
"version": 1586742186,
"fileList": [
"data.js",
"c2runtime.js",
"jquery-2.1.1.min.js",
"offlineClient.js",
"images/sprite-sheet0.png",
"images/regis-sheet0.png",
"images/sprite3-sheet0.png",
"images/sprite4-sheet0.png",
"images/saka.png",
"media/theme (online-audio-converter.com) (1).ogg",
"icon-16.png",
"icon-32.png",
"icon-114.png",
"icon-128.png",
"icon-256.png",
"loading-logo.png",
"s1.mp4",
"s2.mp4",
"s3.mp4",
"s4.mp4",
"s5.mp4",
"s6.mp4",
"s7.mp4",
"scene-12.png",
"s6-2.mp4",
"s7-2.mp4"
]
} |
const JenisHarga = require(model + 'guru/jenis-harga.model')
async function index(req,res){
let data = await JenisHarga.query()
this.responseSuccess({
code:200,
status: true,
values: data,
message: 'Data Jenis Harga Berhasil di Dapatkan'
})
}
async function store(req,res){
let request = req.body
await this.validation(request,{
jenis_harga: 'required'
})
await JenisHarga.query().insert({
jenis_harga: request.jenis_harga
})
this.responseSuccess({
code:201,
status: true,
values: {},
message: 'Data Jenis Harga Berhasil di Tambahkan'
})
}
async function update(req,res){
let request = req.body
await this.validation(request,{
jenis_harga: 'required'
})
let update = await JenisHarga.query().update({
jenis_harga: request.jenis_harga
})
.where('id_jenis_harga', request.id)
if(update){
this.responseSuccess({
code:200,
status: true,
values:{},
message: 'Data Jenis Harga Berhasil di Update'
})
}else{
this.responseError({
code:400,
status: false,
values:{},
message: 'Data Jenis Harga Gagal di Update'
})
}
}
async function destroy(req,res){
let hapus = await JenisHarga.query().deleteById(req.params.id)
if(hapus){
this.responseSuccess({
code:200,
status: true,
values: {},
message: 'Data Jenis Harga Berhasil di Hapus'
})
}else{
this.responseError({
code:400,
status: false,
values: {},
message: 'Data Jenis Harga Gagal di Hapus'
})
}
}
module.exports = {
index, store, update, destroy
} |
const {db}=require('./db/models')
const {app}=require('./server')
const start=async()=>{
try{
await db.sync();
app.listen(3131,()=>{
console.log("Server started")
})
}
catch(e){
console.error(e)
}
}
start() |
'use strict';
var path = require('path');
var yeoman = require('yeoman-generator');
var assert = require('yeoman-generator').assert;
var helpers = require('yeoman-generator').test;
var os = require('os');
var fs = require('fs');
var mkdirp = require('mkdirp');
describe('angularwebpackgenerator:app', function () {
before(function (done) {
helpers.run(path.join(__dirname, '..','generators','app'))
.withOptions({ skipInstall: true })
.withPrompts({ appName: 'testApp' })
.on('end', done);
});
it('creates files', function () {
assert.file([
'bower.json',
'package.json',
'webpack.config.js',
path.join("test", "karma.config.js"),
path.join("test", "test-context.js"),
path.join("test", "karma.config.js"),
path.join("src", "core", "bootstrap.js"),
path.join("src", "core", "core.directives.js"),
path.join("src", "core", "core.factories.js"),
path.join("src", "core", "core.providers.js"),
path.join("src", "core", "core.services.js"),
path.join("src", "pages", "home", "home.routing.js"),
path.join("src", "pages", "home", "controllers", "home.controller.js"),
path.join("src", "pages", "home", "controllers", "home.controller.spec.js"),
path.join("src", "pages", "home", "views", "home.html"),
path.join("src", "pages", "login", "login.routing.js"),
path.join("src", "pages", "login", "controllers", "login.controller.js"),
path.join("src", "pages", "login", "controllers", "login.controller.spec.js"),
path.join("src", "pages", "login", "views", "login.html"),
path.join("src", "views", "app.html"),
path.join("src", "views", "login.html")
]);
});
});
describe('angularwebpackgenerator:controller', function() {
before(function (done) {
helpers.run(path.join(__dirname, '..', 'generators', 'controller'))
.withOptions({ skipInstall: true })
.withPrompts({})
.on('end', done);
});
it('creates files', function() {
assert.file([
path.join('src', 'pages', 'home', 'controllers', 'index.controller.js'),
path.join('src', 'pages', 'home', 'controllers', 'index.controller.spec.js'),
path.join('src', 'pages', 'home', 'home.routing.js'),
path.join('src', 'pages', 'home', 'views', 'index.html')
]);
});
});
describe('angularwebpackgenerator:route', function() {
before(function(done) {
helpers.run(path.join(__dirname, '..', 'generators', 'route'))
.withOptions({ skipInstall: true })
.withPrompts({})
.on('end', done);
});
it('create file route', function() {
assert.file([
path.join('src', 'pages', 'home', 'home.routing.js')
]);
});
});
|
import React from 'react';
import { View, Text, StyleSheet, Button } from 'react-native';
import { Navigation } from 'react-native-navigation';
export class HomeScreen extends React.Component {
goToSecond = () => {
Navigation.showModal({
stack: {
children: [{
component: {
name: 'app.second',
options: {
topBar: {
title: {
text: 'Modal',
},
},
},
},
}],
},
});
}
render () {
return (
<View style={styles.container}>
<Text>Home Screen</Text>
<Button title={'Second Screen'} onPress={this.goToSecond}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
|
import { Link } from "react-router-dom";
import Like from "./common/like.jsx";
import Table from "./table";
const FoodsTable = ({
items = [],
onToggleLike,
onDelete,
sortColumn,
onSort,
}) => {
const columns = [
{
label: "Title",
path: "title",
content: (food) => <Link to={`/foods/${food._id}`}>{food.title}</Link>,
},
{ label: "Category", path: "category.name" },
{ label: "Price", path: "price" },
{ label: "Amount", path: "amount" },
{ label: "Unit", path: "unit" },
{
label: "Action",
content: ({ liked, _id }) => (
<>
<Like liked={liked} onToggleLike={() => onToggleLike(_id)} />
<button
className="btn btn-md btn-danger"
onClick={() => onDelete(_id)}
>
Delete
</button>
</>
),
},
];
return (
<Table
columns={columns}
sortColumn={sortColumn}
onSort={onSort}
data={items}
/>
);
};
export default FoodsTable;
|
const express = require('express');
const app = express();
const path = require('path');
const passport = require('./server_modules/passport');
const profileRoute = require('./server_modules/routes/profile');
const searchRoute = require('./server_modules/routes/searchRoute');
const bodyParser = require('body-parser');
const classSearch = require('./server_modules/routes/classSearch');
const io = require('./server_modules/socket.js');
// Includes a bodyParser to parse JSON files
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// Links all resources to 'client' folder
app.use(express.static('client'));
let { sessionMid, router: passportRouter } = passport(app);
// Includes all routes
app.use('/classSearch', classSearch);
app.use('/google', passportRouter);
app.use('/profile', profileRoute);
app.use('/searchRoute', searchRoute);
// Establishes EJS view engine in 'views' folder
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, '/views'));
// Establish home page
app.get('/', function(req, res) {
let input = {
loggedIn: req.isAuthenticated() && req.user.extra === undefined,
};
if (req.session.deleted) {
input['deleted'] = req.session.deleted;
req.session.deleted = null;
} else if (req.session.reviewed) {
input['reviewed'] = req.session.reviewed;
req.session.reviewed = null;
}
res.render('search', input);
});
// Error route for non-existant routes
app.use((req, res, next) => {
if (!req.route) {
return next(new Error(`No route ${req.originalUrl}`));
} next();
});
// Error route for run-time errors
// eslint-disable-next-line no-unused-vars
app.use((error, req, res, next) => {
console.log(error);
res.render('error', { err: error.message });
});
// Sets up port connection
const PORT = process.env.PORT || 5000;
let server = app.listen(PORT, function() {
console.log(`Server started on Port ${PORT}`);
});
io(server, sessionMid); |
import { useEffect, useState } from "react";
import walpaper from '../img/walpaper.jpg'
const BASE_URL = 'https://api.themoviedb.org/3/trending/all/day?'
const KEY = 'api_key=cc6ee35910514ca0be06cec0f3330408'
function Movies() {
const [trendingMovies, setTrendingMovies] = useState([])
useEffect(() => {
const getMovies = async () => {
const request = await fetch(BASE_URL + KEY)
const data = await request.json()
setTrendingMovies(data.results)
}
getMovies()
}, [])
return (
<div>
<div style={{ display: 'flex', flexWrap: 'wrap', backgroundImage:"url("+ walpaper + ")", justifyContent: 'center', gap: '5px' }}>
{ trendingMovies.length === 0 ? (<p>Fetching Movies...</p>) : (
trendingMovies.map((movie) => (
<div style={{
padding: '40px',
background: 'rgb(0, 76, 153)'
}}>
<img src={`https://image.tmdb.org/t/p/original${movie.poster_path}`} alt='movie poster' style={{
width: '300px',
height: '200px',
objectFit: 'cover'
}} />
<p style={{
maxWidth: '300px',
maxHeight: '50px',
textAlign: 'center',
fontSize: '24px',
}}>{movie.name || movie.title}</p>
<hr />
<p style={{
maxWidth: '300px',
maxHeight: '100px;',
textAlign: 'center',
overflow: 'auto',
fontSize: '12px;',
}}>{movie.overview}</p>
</div>
))
)
}
</div>
</div>
);
}
export default Movies;
|
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
const home = () => import('views/home/home');
const cart = () => import('views/cart/cart');
const category = () => import('views/category/category');
const profile = () => import('views/profile/profile');
const routes=[
{path:'/home',component:home},
{path:'/cart',component:cart},
{path:'/category',component:category},
{path:'/profile',component:profile}
]
const router = new Router({
mode: 'history',
routes
})
export default router
|
var counter = 1 // This is a 'counter' variable.
var total = 0 // This is our utility variable, 'total'
while (counter <= 10) { // If the condition is true, it enters the loop
total = total + counter // We add the current value of 'counter' to 'total'
counter = counter + 1 // Here we add 1 to the counter. This is known as
// 'incrementing' the counter.
console.log( total ) // And finally, we output 'total'
}
|
import express from "express";
import levelSchema from "../model/model.level";
const router = express.Router();
// router.use("/", getLevel);
// function getLevel() {
router.get("/", async (req, res, next) => {
console.log("GET Route /");
try {
let result = await levelSchema.find();
res.status(200).send(result);
console.log(`Found ${Object.keys(result).length} entries`);
} catch (error) {
next(error);
}
console.log("End GET Route /");
});
// Post an array of Artifacts to DB
router.post("/post", async (req, res, next) => {
const body = req.body;
console.log("POST Route /level/post");
await body.map(async v => {
levelSchema.create({ ...v }, error => {
if (error) {
Logger.error(error);
res.status(400).send(error);
}
});
});
console.log(`DB got ${body.length} new entry`);
res.status(200).send("OK");
console.log("End POST Route /artifact/post");
});
// }
export default router;
|
import axios from 'axios'
import * as Loading from "./loading";
import {Message} from "element-ui";
export function request(config) {
// 1.创建axios的实例
// axios.create返回的是一个函数,当用小括号调用时,返回的是一个Promise
const instance = axios.create({
baseURL: 'http://www.phpdemo.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json;'
},
})
// 2.axios的拦截器
//2.1请求拦截的作用
instance.interceptors.request.use(config => {
// console.log(config);
//拦截成功后需要用return返回config
//往请求头header里添加token
config.headers.token=window.sessionStorage.getItem('token')
Loading.showFullScreenLoading()
setTimeout(()=>{
Loading.tryHideFullScreenLoading()
}, 30000);
// console.log(config.headers)
return config
}, err => {
console.log(err);
})
//2.2响应拦截
instance.interceptors.response.use(res => {
//关闭loading加载
Loading.tryHideFullScreenLoading()
//拦截后需要将res返回,如果不需要vue自动添加的东西,可以只返回data
return res.data
}, err => {
console.log(err);
})
// 3.发送真正的网络请求
return instance(config)
} |
function mash(){
return "You will live in a " + getHouse() + " , travel to " + getTravelCount() + " countries, have a pet named "+ getPet() +
", and go to " + getdestination();
}
function ranNumGenerator(Num1){
let ranDecimal = Math.random();
let randNum = ranDecimal * Num1;
let ranInteger = Math.floor(randNum);
return ranInteger;
}
let userInput = process.argv[2];
function getHouse(){
let houseArray= [userInput||"Apartment","Penthouse","House","Cabinet"];
let ranIndex = ranNumGenerator();
if(ranIndex= 1){
ranIndex = 1
}
return houseArray[ranIndex]
}
function getTravelCount(){
let randTravelCount = ranNumGenerator(101);
return randTravelCount;
}
function getPet(){
let randomPets =["Akamaru","Sparky","Krypto","Wolf"];
let bop =ranNumGenerator();
if(bop < 0.5){
bop = 1
}
else{
bop = 2
}
return randomPets[bop];
}
function getdestination(){
let ranDestin = ["Venus","China","Tanzania","Poland"];
let Amir = ranNumGenerator(ranDestin.length);
return ranDestin[Amir];
}
function getOccupation(){
let ranOccu = ["Entrepreneur","Real estate agent","Sensei","Big Business owner"];
let Fisher = ranNumGenerator(ranOccu.length);
return ranOccu[Fisher];
}
let ok = mash();
console.log(ok);
|
const dbConn = require('../config/db');
// Constula básica para obtener todas las categorias de la tabla 'category' , sin filtros
const SQL_FIND_ALL = "SELECT * FROM category";
const SQL_ADD = "INSERT INTO category set ?";
const SQL_EDIT = "SELECT * FROM category WHERE category_id = ?";
const SQL_UPDATE = "UPDATE category set ? WHERE category_id = ?";
const SQL_DELETE = "DELETE FROM category WHERE category_id = ?";
const model = {};
model.list = () => {
return new Promise((resolve, reject) => {
dbConn.query(
SQL_FIND_ALL,
(err, result) => {
if (err) {
console.log("ERROR! Durante la consulta a la tabla category:" + err);
reject(err);
}
else {
console.log("Consulta a la tabla category: OK!");
resolve(result);
}
})
})
}
model.add = (add) => {
return new Promise((resolve, reject) => {
dbConn.query(
SQL_ADD, [add], (err, result) => {
if (err) {
console.log("ERROR! Durante la insercción en la tabla category:" + err);
reject(err);
}
else {
console.log("insercción en la tabla category: OK!");
resolve(result);
}
})
})
}
model.edit = (edit) => {
return new Promise((resolve, reject) => {
dbConn.query(
SQL_EDIT, [edit], (err, result) => {
if (err) {
console.log("ERROR! :" + err);
reject(err);
}
else {
console.log(" OK!");
resolve(result);
}
})
})
}
model.update = (update, id) => {
return new Promise((resolve, reject) => {
dbConn.query(
SQL_UPDATE, [update, id], (err, result) => {
if (err) {
console.log("ERROR! Durante la modificación en la tabla category:" + err);
reject(err);
}
else {
console.log("Modificación en la tabla category: OK!");
resolve(result);
}
})
})
}
model.delete = (id) => {
return new Promise((resolve, reject) => {
dbConn.query(
SQL_DELETE, [id], (err, result) => {
if (err) {
console.log("ERROR! Durante el borrado en la tabla category:" + err);
reject(err);
}
else {
console.log("el borrado en la tabla category: OK!");
resolve(result);
}
})
})
}
module.exports = model; |
var searchData=
[
['wczytaj',['wczytaj',['../class_collar.html#afc3896d8ee90af37df36c85e79618708',1,'Collar::wczytaj()'],['../class_dog.html#ac733e8051c2b086366871ad8b037873c',1,'Dog::wczytaj()']]]
];
|
var generate = function (number) {
switch (number) {
case 1:
window.location.href = "https://www.php.net/";
break;
case 2:
window.location.href = "https://kotlinlang.org/";
break;
case 3:
window.location.href = "https://www.javascript.com/";
break;
case 4:
window.location.href = "https://www.java.com/en/";
break;
case 5:
window.location.href = "https://www.python.org/";
break;
case 6:
window.location.href = "https://laravel.com/";
break;
case 7:
window.location.href = "https://nodejs.org/en/";
break;
case 8:
window.location.href = "https://www.mysql.com/";
break;
case 9:
window.location.href = "https://www.postgresql.org/";
break;
case 10:
window.location.href = "https://www.android.com/";
break;
case 11:
window.location.href = "https://www.figma.com/";
break;
case 12:
window.location.href = "https://github.com/";
break;
case 13:
window.location.href = "https://www.docker.com/";
break;
default:
break;
}
} |
exports.contactTemplate = event => {
const {
emailAddress,
galleryPieceLink,
galleryPieceName,
message,
name,
phoneNumber,
website
} = event;
let html = "";
html += `
<html>
<head>
<meta name="viewport" content="width=device-width">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Contact Form Submission</title>
<style>
h3 {
margin: 1rem 20% 0.25rem 1rem;
padding: 1rem 0 0.25rem;
}
.contact_info {
background-color: rgba(120, 186, 251, 0.6);
color: rgba(0, 0, 0, 0.8);
margin: 1rem;
padding: 0 0.5rem 1rem 0.5rem;
width: 30%;
}
.contact_category {
border-spacing: 1rem;
font-size: 1.5rem;
font-weight: bold;
padding: 0.5rem 0 0;
}
.contact_value {
border: 1px solid rgba(0, 0, 0, 0.5);
background-color: #ffffff;
font-size: 1.5rem;
padding: 0.5rem;
}
</style>
</head>
<body>
<h3>
Someone has contacted you for more information.
<br />
<br /> Here is their contact info below:
</h3>
<table class="contact_info">
<tr class="contact_widget">
<td class="contact_category">
Email
</td>
</tr>
<tr class="contact_widget">
<td class="contact_value">
${emailAddress}
</td>
</tr>
`;
if (website) {
html += `
<tr class="contact_widget">
<td class="contact_category">
Website
</td>
</tr>
<tr class="contact_widget">
<td class="contact_value">
${website}
</td>
</tr>
`;
}
if (name) {
html += `
<tr class="contact_widget">
<td class="contact_category">
Name
</td>
</tr>
<tr class="contact_widget">
<td class="contact_value">
${name}
</td>
</tr>
`;
}
if (phoneNumber) {
const formattedPhoneNumber = `(${phoneNumber.slice(
0,
3
)}) ${phoneNumber.slice(3, 6)}-${phoneNumber.slice(6, 10)}`;
html += `
<tr class="contact_widget">
<td class="contact_category">
Phone Number
</td>
</tr>
<tr class="contact_widget">
<td class="contact_value">
${formattedPhoneNumber}
</td>
</tr>
`;
}
if (galleryPieceLink) {
html += `
<tr class="contact_widget">
<td class="contact_category">
Gallery Piece
</td>
</tr>
<tr class="contact_widget">
<td class="contact_value">
<a href="${galleryPieceLink}">${galleryPieceName}</a>
</td>
</tr>
`;
}
if (message) {
html += `
<tr class="contact_widget">
<td class="contact_category">
Message
</td>
</tr>
<tr class="contact_widget">
<td class="contact_value">
${message}
</td>
</tr>
`;
}
html += `</table></body></html>`;
return html;
};
|
import axios from 'axios'
const marvelAPI = axios.create({
baseURL : 'http://gateway.marvel.com/v1/public',
headers :{
Accept : 'application/json',
'Content-Type' : 'application/json'
},
timeout : 10000
})
marvelAPI.defaults.params = {
apiKey : 'bda12c2070a7b1fd1ea89ad11722acba',
hash : '3821fc91ed145bc4ddf1563418992ed9',
ts: 1
};
marvelAPI.interceptors.request.use(async config =>{
return config
},
function(error){
return Promise.reject(error)
})
export default marvelAPI; |
/*
* Trial databases
*/
app.component('prmSearchResultJournalIndicationLineAfter', {
bindings: { parentCtrl: '<' },
controller: 'prmSearchResultJournalIndicationLineAfter',
template: `<div class="trial-indicator"></div>`,
});
app.controller('prmSearchResultJournalIndicationLineAfter', ['$scope', '$rootScope', function($scope, $rootScope){
this.$onInit = function () {
var vm = this;
if(typeof vm.parentCtrl.item.pnx.display.lds13 !== "undefined") {
if (vm.parentCtrl.item.pnx.display.lds13.indexOf('*TRIALS*') >= 0) {
var briefRecordID = "SEARCH_RESULT_RECORDID_alma" + vm.parentCtrl.item.pnx.display.mms;
var fullRecordID = briefRecordID + "_FULL_VIEW";
if (document.getElementById(briefRecordID)) {
var recordID = briefRecordID;
}
if (document.getElementById(fullRecordID)) {
var recordID = fullRecordID;
}
var trialNode = document.getElementById(recordID).getElementsByClassName("trial-indicator")[0];
trialNode.innerHTML = '<img src="/discovery/custom/01CDL_SCR_INST-USCS/img/stopwatch.png" width="20" height="20" /><span>Trial Database</span>';
}
}
}
}]);
|
import Koa from "koa";
import bodyParser from "koa-bodyparser";
import convert from "koa-convert";
import logger from "koa-logger";
import mongoose from "mongoose";
import cors from "koa-cors";
import setUpPassport from "../src/middleware/passport";
import { errorMiddleware } from "../src/middleware";
import config from "../config";
import modules from "../src/modules";
console.log("🐝 Starting", config);
const app = new Koa();
mongoose.Promise = global.Promise;
if (process.env.NODE_ENV !== "test") {
mongoose.connect(
`mongodb://${config.database.host}/${config.database.databaseName}`,
config.database.options
);
}
app.use(cors());
app.use(convert(logger()));
app.use(bodyParser());
app.use(errorMiddleware());
const passport = setUpPassport(config);
app.use(passport.initialize());
modules(app);
if (process.env.NODE_ENV !== "test") {
app.listen(config.port, () => {
console.log(`Server started on ${config.port}`);
});
}
export default app;
|
import * as wss from "./wss.js";
import * as webRTCHandler from "./webRTCHandler.js";
import * as ui from "./ui.js";
let strangerCallType;
export const changeStrangerConnectionStatus = (status) => {
const data = { status };
wss.changeClusterAConnectionStatus(data);
};
// ClusterB Connection status
export const changeClusterBConnectionStatus = (status) => {
const data = { status };
wss.changeClusterBConnectionStatus(data);
};
export const getStrangerSocketIdAndConnect = (data) => {
const { callType, clusterB } = data;
strangerCallType = callType;
if (clusterB === true) {
wss.getClusterBSocketId();
} else {
wss.getClusterASocketId();
}
};
export const connectWithStranger = (data) => {
if (data.randomStrangerSocketId) {
webRTCHandler.sendPreOffer(strangerCallType, data.randomStrangerSocketId);
} else {
// no user is available for connection
ui.showNoStrangerAvailableDialog();
}
};
|
let path = require('path');
let express = require('express');
let cors = require('cors');
const SDC = require('statsd-client');
let sdc = new SDC({host: '192.168.0.100', port: process.env.STATSD_PORT || 8125, debug: false});
let app = express();
let staticPath = path.join(__dirname, '/');
app.use(cors());
app.use(express.static(staticPath));
app.get('/statsd', function (req, res) {
res.send('ok');
sdc.timing('socketio.server_pong_latency', parseInt(req.query.time));
});
app.listen(8080, () => {
console.log('listening');
}); |
//helper class for custom XR events
class Event {
constructor(name) {
this.name = name;
this.callbacks = [];
}
registerCallback(callback) {
this.callbacks.push(callback);
}
}
class EventHandler {
constructor() {
this.events = {};
}
registerEvent(eventName) {
var event = new Event(eventName);
this.events[eventName] = event;
}
dispatchEvent(eventName, eventArgs) {
this.events[eventName].callbacks.forEach(function (callback) {
callback(eventArgs);
});
}
addEventListener(eventName, callback) {
this.events[eventName].registerCallback(callback);
}
}
// main state singleton
class StateClass {
constructor() {
this.globals = {};
this.isPrimary = true; // until claimed otherwise by a PeerConnection
this.isXRSession = false;
this.isPaused = false;
this.currentSession = null;
this.debugMode = false;
this.eventHandler = new EventHandler();
this.eventHandler.registerEvent("xrsessionstarted");
this.eventHandler.registerEvent("xrsessionended");
this.eventHandler.registerEvent("inputsourceschange");
this.eventHandler.registerEvent("selectend");
this.eventHandler.registerEvent("selectstart");
this.eventHandler.registerEvent("select");
this.eventHandler.registerEvent("squeezeend");
this.eventHandler.registerEvent("squeezestart");
this.eventHandler.registerEvent("squeeze");
this.eventHandler.registerEvent("peerconnected");
this.eventHandler.registerEvent("peerdisconnected");
this.bindKeys();
}
bindKeys() {
document.addEventListener("keydown", e => {
if (!e.shiftKey) return;
switch (e.keyCode) {
case 192: // tilde
this.debugMode = !this.debugMode;
console.log("Debug: " + this.debugMode);
break;
case 80: //"p"
this.isPaused = !this.isPaused;
console.log("Paused: " + this.isPaused);
break;
default:
break;
}
});
}
}
const State = new StateClass();
export default State;
|
import addZero from './addZero.js';
export const musicPlayerInit = () => {
const audio = document.querySelector('.audio');
const audioPlayer = document.querySelector('.audio-player');
const audioImg = document.querySelector('.audio-img');
const audioHeader = document.querySelector('.audio-header');
const audioButtonPlay = document.querySelector('.audio-button__play');
const audioTimePassed = document.querySelector('.audio-time__passed');
const audioProgressTiming = document.querySelector('.audio-progress__timing');
const audioProgress = document.querySelector('.audio-progress');
const audioTimeTotal = document.querySelector('.audio-time__total');
const audioNavigation = document.querySelector('.audio-navigation');
const audioVolumeBar = document.querySelector('.audio-volume__bar');
const tracks = ['flow', 'hello', 'speed'];
let currentTrackIndex = 1;
//setTrackData(tracks[1]);
function setTrackData(track) {
let paused = audioPlayer.paused;
audioProgressTiming.style.width = 0;
audioPlayer.src = `audio/${track}.mp3`;
audioImg.src = `audio/${track}.jpg`;
audioHeader.textContent = track.charAt(0).toUpperCase() + track.slice(1);
audioPlayer.addEventListener('canplay', () => {
timeUpdate();
});
if (paused) {
audioPlayer.pause();
} else {
audioPlayer.play();
}
}
function prevAudioTrack() {
if (currentTrackIndex !== 0) {
currentTrackIndex--;
} else {
currentTrackIndex = tracks.length - 1;
}
let track= tracks[currentTrackIndex];
setTrackData(track);
}
function nextAudioTrack() {
if (currentTrackIndex !== tracks.length - 1) {
currentTrackIndex++;
} else {
currentTrackIndex = 0;
}
let track= tracks[currentTrackIndex];
setTrackData(track);
}
function setAudioProgress(offset) {
audioProgressTiming.style.width = offset + '%';
audioPlayer.currentTime = offset * audioPlayer.duration / 100;
}
function toggleAudioPlay() {
if (audioPlayer.paused) {
audioPlayer.play();
audioButtonPlay.classList.remove('fa-play');
audioButtonPlay.classList.add('fa-pause');
audio.classList.add('play');
} else {
audioPlayer.pause();
audioButtonPlay.classList.add('fa-play');
audioButtonPlay.classList.remove('fa-pause');
audio.classList.remove('play');
}
}
function volumeChange(value) {
audioPlayer.volume = value / 100;
}
function timeUpdate() {
let currentTime = audioPlayer.currentTime || 0;
let duration = audioPlayer.duration || 0;
let currentSeconds = Math.floor(currentTime % 60);
let currentMinutes = Math.floor(currentTime / 60);
let durationSeconds = Math.floor(duration % 60);
let durationMinutes = Math.floor(duration / 60);
audioTimePassed.textContent = `${addZero(currentMinutes)}:${addZero(currentSeconds)}`;
audioTimeTotal.textContent = `${addZero(durationMinutes)}:${addZero(durationSeconds)}`;
audioProgressTiming.style.width = (currentTime / duration * 100) + '%';
}
audioNavigation.addEventListener('click', function(event) {
const target = event.target;
if (target.classList.contains('audio-button__prev')) {
prevAudioTrack();
} else if (target.classList.contains('audio-button__play')) {
toggleAudioPlay();
} else if (target.classList.contains('audio-button__next')) {
nextAudioTrack();
} else if (target.closest('.audio-progress')) {
let offset = (event.offsetX / audioProgress.offsetWidth * 100);
setAudioProgress(offset);
} else if (target.classList.contains('audio-volume__down')) {
audioPlayer.muted = !audioPlayer.muted;
} else if (target.classList.contains('audio-volume__up')) {
const max = audioVolumeBar.value = audioVolumeBar.max;
volumeChange(max);
audioPlayer.muted = false;
}
else {
return false;
}
});
audioPlayer.addEventListener('timeupdate', timeUpdate);
audioVolumeBar.addEventListener('input', () => {
volumeChange(audioVolumeBar.value);
});
audioVolumeBar.value = audioPlayer.volume * 100;
musicPlayerInit.stop = () => {
if (!audioPlayer.paused) {
toggleAudioPlay();
}
};
} |
/*
* @Description: 常规路线
* @Author: 彭善智
* @LastEditors: 彭善智
* @Date: 2019-04-24 18:26:49
* @LastEditTime: 2019-05-15 10:41:26
*/
import { getRoutePriceDetails } from 'getData'
import { nowDate, copy } from 'utils/common'
const state = {
calendarDate: "", //日期信息
opt: "", //日期列表
sureDate: "", //选中的日期
dataList: "", //日历展示的日期
adultNum: 0, //大人数量
childNum: 0, //小孩数量
insurance: "", //保险信息
orderid: "", //订单ID
routeid: "", //常规路线ID
oneNum: 0, //单人间
twoNum: 0, //双人间
threeNum: 0, //三人间
fourNum: 0, //四人间
arrangeNum: 0, //配房数量
oneCost:0, //单人房价格
twoCost:0, //双人房价格
threeCost:0, //三人房价格
fourCost:0, //四人房价格
arrangeCost:0, //配房价格
route: "", //参团详情
}
const getters = {
//订单价格
orderPrice: (state)=> {
return state.oneNum * state.oneCost + state.twoNum * state.twoCost + state.threeNum * state.threeCost +
state.fourNum * state.fourCost + state.arrangeNum * state.arrangeCost +
// (state.adultNum + state.childNum) * (state.route ? state.route.price : 0 )
+ ((state.insurance? state.insurance.price * (state.childNum + state.adultNum) : 0));
},
//选中的日期 yyyy-mm-dd
beginDate: (state)=> {
if(state.sureDate){
return nowDate(0, new Date(state.sureDate));
}
}
}
const mutations = {
//日期初始化
calendarDateInit(state){
state.opt = ""
state.sureDate = ""
state.dataList = ""
state.adultNum = 0
state.childNum = 0
state.insurance = ""
state.orderid = ""
state.oneNum = 0
state.twoNum = 0
state.threeNum = 0
state.fourNum = 0
state.arrangeNum = 0
state.oneCost = 0
state.twoCost = 0
state.threeCost = 0
state.fourCost = 0
state.arrangeCost = 0
state.insurance = ""
},
calendarDateChange: (state, calendarDate)=> {
state.calendarDate = calendarDate;
console.log(state)
},
//设置日历日期
setOpt: (state, opt)=> {
state.opt = opt;
console.log(state);
},
//设置常规路线ID
setRouteid: (state, routeid)=> {
state.routeid = routeid;
console.log(state)
},
//设置房间价格
setCost: (state, cost)=>{
[state.oneCost, state.twoCost, state.threeCost, state.fourCost, state.arrangeCost] =
[cost.oneCost || state.oneCost|| 0, cost.twoCost || cost.twoCost || 0, cost.threeCost || state.threeCost ||0,
cost.fourCost || state.fourCost || 0, cost.arrangeCost || state.arrangeCost || 0]
},
//判断是否是闰年
isLeapYear(state) {
if ((state.calendarDate.year % 4 == 0) && (state.calendarDate.year % 100 != 0 || state.calendarDate.year % 400 == 0)) {
state.calendarDate.isLeapYear = true;
} else {
state.calendarDate.isLeapYear = false;
}
},
//获取上个月下个月天数
getDays(state) {
if (parseInt(state.calendarDate.month) == 1) {
state.calendarDate.lastDays = new Date(state.calendarDate.year - 1, 12, 0).getDate();
state.calendarDate.lastMonth = new Date(state.calendarDate.year - 1, 12, 0).getMonth() + 1;
state.calendarDate.lastYear = new Date(state.calendarDate.year - 1, 12, 0).getFullYear();
} else {
state.calendarDate.lastDays = new Date(state.calendarDate.year, state.calendarDate.month - 1, 0).getDate();
state.calendarDate.lastMonth = new Date(state.calendarDate.year, state.calendarDate.month - 1, 0).getMonth() + 1;
state.calendarDate.lastYear = new Date(state.calendarDate.year, state.calendarDate.month - 1, 0).getFullYear();
}
if (parseInt(state.calendarDate.month) == 12) {
state.calendarDate.nextDays = new Date(state.calendarDate.year + 1, 1, 0).getDate();
state.calendarDate.nextMonth = new Date(state.calendarDate.year + 1, 1, 0).getMonth() + 1;
state.calendarDate.nextYear = new Date(state.calendarDate.year + 1, 1, 0).getFullYear();
} else {
state.calendarDate.nextDays = new Date(state.calendarDate.year, state.calendarDate.month + 1, 0).getDate();
state.calendarDate.nextMonth = new Date(state.calendarDate.year, state.calendarDate.month + 1, 0).getMonth() + 1;
state.calendarDate.nextYear = new Date(state.calendarDate.year, state.calendarDate.month + 1, 0).getFullYear();
}
state.calendarDate.days = new Date(state.calendarDate.year, state.calendarDate.month, 0).getDate();
},
//改变选中的日期
activeChange(state){
state.dataList.map((list)=>{
Vue.set(list, "check", false);
if(list.flag && state.sureDate && checkDate(state.sureDate,list.date)){
Vue.set(list, "check", true);
}
})
},
//设置日历展示的日期
setDataList(state, dataList) {
state.dataList = dataList;
},
//设置选中的日期
setSureDate(state, sureDate){
state.sureDate = sureDate;
},
setAdultNum(state, adultNum){
state.adultNum = adultNum;
},
setChildNum(state, childNum){
state.childNum = childNum;
},
setOneNum(state, oneNum){
state.oneNum = oneNum;
},
setTwoNum(state, twoNum){
state.twoNum = twoNum;
},
setThreeNum(state, threeNum){
state.threeNum = threeNum;
},
setFourNum(state, fourNum){
state.fourNum = fourNum;
},
setArrangeNum(state, arrangeNum){
state.arrangeNum = arrangeNum;
},
setRoute(state, route) {
state.route = route;
},
InsuranceSet(state, insurance){
state.insurance = insurance;
},
orderidSet(state, orderid){
state.orderid = orderid;
},
}
const actions = {
//日期初始化
calendarDateInit: ({commit, dispatch})=> {
let calendarDate = {}
calendarDate.today = new Date();
calendarDate.year = calendarDate.today.getFullYear();
calendarDate.month = calendarDate.today.getMonth() + 1;
calendarDate.date = calendarDate.today.getDate();
calendarDate.day = calendarDate.today.getDay();
commit("calendarDateChange", calendarDate)
commit("calendarDateInit")
dispatch("calendarClick")
},
//获取日期价格
async calendarClick({state, getters, commit, dispatch }) {
let priceDate = state.calendarDate.year + "-" + (state.calendarDate.month > 9 ? state.calendarDate.month : "0" + state.calendarDate.month);
let data = await getRoutePriceDetails({
routeid: state.routeid,
priceDate: priceDate,
})
console.log(data)
if(data && data.length > 0){
commit("setOpt",data)
commit("setCost",data[0])
}
dispatch("getIndexDay")
},
//天数初始化
getIndexDay({state, commit, dispatch }) {
commit("isLeapYear");
commit("getDays");
// let calendarDate = state.calendarDate;
let calendarDate = copy(state.calendarDate)
let dataList = [];
calendarDate.monthStart = new Date(calendarDate.year + "/" + calendarDate.month + "/1").getDay();
if (calendarDate.monthStart == 0) {
calendarDate.monthStart = 7;
}
for (let i = calendarDate.monthStart; i > 0; i--) {
let map = {};
map.flag = false;
map.day = calendarDate.lastDays - i + 1;
map.date = calendarDate.lastYear + "-" + calendarDate.lastMonth + "-" + (calendarDate.lastDays - i +
1);
dataList.push(map);
}
for (var k = 0; k < calendarDate.days; k++) {
let map = {};
map.flag = false;
map.day = k + 1;
map.date = calendarDate.year + "-" + calendarDate.month + "-" + (k + 1);
for (let d in state.opt) {
map.state = state.opt[d].state;//房间数量情况
map.price = state.opt[d].price;//价格
map.flag = checkDate(map.date, state.opt[d].date);
if (map.flag) {
break;
}
}
dataList.push(map);
}
for (let j = 0; j < (42 - calendarDate.days - calendarDate.monthStart); j++) {
let map = {};
map.flag = false;
map.day = j + 1;
map.date = calendarDate.nextYear + "-" + calendarDate.nextMonth + "-" + (j + 1);
dataList.push(map);
}
commit("setDataList",dataList)
if(state.sureDate){
commit("activeChange")
}
console.log(dataList)
console.log(calendarDate)
},
//点击左边月份
async monthLeftClick({state, commit, dispatch}){
// let calendarDate = [...state.calendarDate]
let calendarDate = copy(state.calendarDate)
if (calendarDate.month <= 1) {
calendarDate.year -= 1;
calendarDate.month = 12;
} else {
calendarDate.month -= 1;
}
await commit("calendarDateChange", calendarDate)
dispatch("calendarClick")
},
//点击右边月份
async monthRightClick({state, commit, dispatch}){
// let calendarDate = [...state.calendarDate];
let calendarDate = copy(state.calendarDate)
// let calendarDate = {}
if (calendarDate.month == 12) {
calendarDate.year += 1;
calendarDate.month = 1;
} else {
calendarDate.month += 1;
}
await commit("calendarDateChange", calendarDate)
dispatch("calendarClick")
},
//点击日期
dayClick({state, commit, dispatch},index) {
commit("setSureDate", state.dataList[index].date)
if(state.dataList[index].flag){
commit("activeChange")
}
},
}
//判断日期是否相等
const checkDate = (dateStr1, dateStr2)=>{
let date1 = dateStr1.split("-");
let date2 = dateStr2.split("-");
if (date1[1] < 10 && date1[1].length < 2) {
date1[1] = "0" + date1[1];
}
if (date1[2] < 10 && date1[2].length < 2) {
date1[2] = "0" + date1[2];
}
if (date2[1] < 10 && date2[1].length < 2) {
date2[1] = "0" + date2[1];
}
if (date2[2] < 10 && date2[2].length < 2) {
date2[2] = "0" + date2[2];
}
date1 = date1.join("-");
date2 = date2.join("-");
return date1 == date2;
}
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
|
function odswierzanie_cpr()
{
var zegarek= new Date();
var sekunda = zegarek.getSeconds();
var sekunda_wynik= zegarek.sekunda_wynik;
sekunda_wynik= 59-sekunda;
if (sekunda_wynik<10) sekunda_wynik = "0"+sekunda_wynik;
var min = zegarek.getMinutes();
var min_minus= 60;
var min_wynik= zegarek.min_wynik;
if (min>30 )
min_wynik= (min_minus-(min-30));
else
min_wynik=(30-min);
if(min_wynik<10) min_wynik= "0"+min_wynik;
//var godz = 17;
var godz = zegarek.getHours();
//var godz_dn= 19;
var godz_wynik=zegarek.godz_wynik;
if (godz >7 && godz<19 &&min>=30)
godz_wynik=(19-godz-1);
if (godz >7 && godz<19 && min<30)
godz_wynik=(19-godz);
if (godz==19 && min<30)
godz_wynik=0;
if (godz==19 && min>30)
godz_wynik=11;
if (godz >19&& godz<24&& min<=30)
godz_wynik=(24-(godz-7));
if (godz >19&& godz<24&& min>30)
godz_wynik=(23-(godz-7));
if (godz >=0&& godz<7&& min<=30)
godz_wynik=(7-godz);
if (godz >=0&& godz<7&& min>30)
godz_wynik=(7-godz-1);
if (godz==7 && min<30)
godz_wynik=0;
if (godz==7 && min>30)
godz_wynik=11;
if(godz_wynik<10) godz_wynik = "0"+godz_wynik;
document.getElementById("czas_cpr").innerHTML =godz_wynik+":"+min_wynik+":"+sekunda_wynik;
setTimeout("odswierzanie_cpr()",1000);
} |
import checksum, { getOddPositions, getEvenPositions, getSum} from './checksum';
it('checksum returns correct value as per documentation', () => {
expect(checksum('8533218192162301367')).toEqual(3);
});
it('filter odd positions', () => {
expect(getOddPositions([1, 2, 3, 4, 5])).toEqual([2,4]);
});
it('filter even positions', () => {
expect(getEvenPositions([1, 2, 3, 4, 5])).toEqual([1,3,5]);
});
it('check for sumOf', () => {
expect(getSum([2,2,2,2,2,2])).toEqual(12);
}); |
const DB = require("./DB");
const Order = require("./Orders");
let id = 0;
//GENERATING USER ID STARTING FROM 1
function idGenerator() {
id == 0 ? (id = 1) : (id = ++id);
return id;
}
function User(name, email, password) {
this.id = idGenerator();
this.name = name;
this.email = email;
this.password = password;
this.isAdmin = false;
this.isDeleted = false;
}
User.prototype.save = function() {
if (this.name == "" || this.email == "" || this.password == "")
return "WARNING: All feilds are required";
let user = DB.Users.filter(e => e.email === this.email);
if (user.length !== 0) return "ERROR: Email already exists";
user_payload = {
id: this.id,
name: this.name,
email: this.email,
password: this.password,
isAdmin: this.isAdmin,
isDeleted: this.isDeleted
};
DB["Users"].push(user_payload);
return "SUCCESS: Account saved";
};
User.prototype.readSingleUser = function(id) {
if (typeof id !== "number") return "INVALID: ID must be a Number";
let user = DB.Users.find(e => e.id === id);
return !user ? "INFO: No such User" : user;
};
User.prototype.updateUser = function(name, email, password) {
if (name == "" || email == "" || password == "") {
return "WARNING: To update, all feilds must be filled";
} else {
DB.Users.map(e => {
if (e.id === this.id) {
e.name = name;
e.email = email;
e.password = password;
}
});
return "SUCCESS: Record Updated";
}
};
User.prototype.searchUserByName = function(name) {
if (name == "" || typeof name !== "string") {
return "WARNING: Search by name";
} else {
let user = DB.Users.filter(e => e.name === name && e.isDeleted === false);
if (user.length === 0) {
return "INFO: No such user";
} else {
console.log("SUCCESS: Record Found");
return user[0];
}
}
};
User.prototype.makeOrder = function(...products) {
if (products.length === 0) {
return "WARNING: Input cannot be empty";
} else {
return Order.prototype.createOrder(products, this.id);
}
};
module.exports = User;
|
import * as R from "ramda";
import { recipeTypes } from "./types";
const initialState = {
items: {},
};
export const recipeReducer = (state = initialState, action) => {
switch (action.type) {
case recipeTypes.RECIPE_GET_ITEMS_SUCCESS: {
const items = R.indexBy(R.prop("id"))(action.payload);
return {
...state,
items,
};
}
case recipeTypes.RECIPE_GET_ITEM_SUCCESS: {
const item = action.payload;
return {
...state,
items: {
...state.items,
[item.id]: {
...item,
},
},
};
}
case recipeTypes.CHANGE_LIKE_ITEM_SUCCESS: {
const like = action.payload;
const currentRecipe = R.prop(like.recipe.id, state.items);
const isIncludeLike = R.compose(
R.not,
R.equals(-1),
R.findIndex(R.propEq("id", like.id))
);
const newLikes = R.ifElse(
isIncludeLike,
R.filter(R.compose(R.not, R.equals(like.id), R.prop("id"))),
R.concat([like])
)(currentRecipe.likes);
return {
...state,
items: {
...state.items,
[like.recipe.id]: {
...currentRecipe,
likes: newLikes,
},
},
};
}
default:
return state;
}
};
|
import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import { getArrivalsToStop, getStopData } from '../../helpers/fetchUtils';
import { Map } from '../Map/Map';
import { Loading } from '../Loading/Loading';
import { LineItem } from '../LineItem/LineItem';
import style from './StopPage.css';
const mapOptions = {
googleMapURL: "https://maps.googleapis.com/maps/api/js?key=AIzaSyBzJHmR-D-VJ9fVj8PhKz1z5hhKwhPJ-Ys",
loadingElement: <div style={{ height: `100%` }} />,
containerElement: <div style={{ height: `400px`, marginBottom: `30px` }} />,
mapElement: <div style={{ height: `100%` }} />
};
class StopPageComponent extends Component {
state = {
arrivals: [],
stopData: {},
loading: true
}
componentDidMount () {
this.getStop(this.props.match.params.id);
}
async getStop (id) {
this.setState({
stopData: await getStopData(id),
arrivals: await getArrivalsToStop(id),
loading: false
});
}
render () {
const { history } = this.props;
const { arrivals, stopData, loading } = this.state;
return (
<React.Fragment>
<p onClick={history.goBack} className={style.back}>← Back</p>
{loading ? <Loading/> :
<div>
<h1>Stop {stopData.commonName}</h1>
<Map {...mapOptions} markerShown coord={{ lat: parseFloat(stopData.lat), lng: parseFloat(stopData.lon) }} />
{arrivals.length > 0 && <h2>Arrivals</h2>}
{arrivals.length > 0 ? arrivals.map((item, index) => {
return <LineItem key={index} id={item.lineId} name={item.lineName} arrival={item} />;
}) : 'No arrivals info'}
</div>
}
</React.Fragment>
);
}
}
export const StopPage = withRouter(StopPageComponent);
StopPage.propTypes = {
history: PropTypes.object,
match: PropTypes.object
};
|
class Configer {
constructor () {};
static SOURCE_GAME_WIDTH = 750;
static SOURCE_GAME_HEIGHT =1334;
static GAME_WIDTH = Configer.SOURCE_GAME_WIDTH;
static GAME_HEIGHT = Configer.SOURCE_GAME_HEIGHT;
static HALF_GAME_WIDTH = Configer.GAME_WIDTH * .5;
static HALF_GAME_HEIGHT = Configer.GAME_HEIGHT * .5;
static WORLD_SCALE = 1;
}
export default Configer; |
/*
*@desc the Subscriber container used by REDUX
*@author Sylvia Onwukwe
*/
import { connect } from "react-redux";
import SubscribersComponent from "../../Admin/AllSubscribers/allSubscribers";
import {
fetchSubscribers,
deleteSubscriber
} from "../../actions/actions_admin_subscribers"
const mapStateToProps = state => ({
subscriber: state.subscriber
});
const mapDispatchToProps = (dispatch, newProps) =>{
return {
fetchSubscribers: () => {
dispatch(fetchSubscribers());
},
deleteSubscriber: (subscriberID) => {
dispatch(deleteSubscriber(subscriberID));
}
}
}
const Subscribers = connect(
mapStateToProps,
mapDispatchToProps
)(SubscribersComponent);
export default Subscribers;
|
import YoutubePlaylistAdapter from 'ember-youtube-data-model/adapters/youtube/playlist';
export default YoutubePlaylistAdapter;
|
import WItems from "./WItems.js";
import { observer } from "mobx-react";
import styled from "styled-components";
import { useState } from "react";
const List = styled.div`
padding: 10px;
display: grid;
float: left;
font-size: 13pt;
margin-right: 30px;
background: #f2f3f5;
width: 400px;
`;
const Title = styled.p`
font-weight: bold;
`;
const WatchedList = ({ watchedmovies }) => {
const [query, setQuery] = useState("");
const watchedlist = watchedmovies
.filter((movie) => movie.watched === true)
.filter((movie) => movie.name.toLowerCase().includes(query.toLowerCase()));
return (
<List>
<Title>Watched</Title>
<btn>{watchedlist.length}</btn>
<input
onChange={(event) => setQuery(event.target.value)}
placeholder="Search movies..."
></input>
<br />
{watchedlist.length
? watchedlist.map((movie) => <WItems watchedmovie={movie} />)
: "movie not found"}
</List>
);
};
export default observer(WatchedList);
|
const staticData = require('./staticData');
const getCategoryResponse = (category = '') => {
const tasks = staticData.hasOwnProperty(category) ? staticData[category] : [];
const hasTasks = tasks.length > 0;
return {
status: hasTasks ? 200 : 404,
categoryName: category.toString(),
totalResults: tasks.length,
tasks,
}
}
module.exports = getCategoryResponse; |
import React, {Fragment} from 'react';
import {Form, Input, InputNumber, Upload, DatePicker, Icon, Button, Select, message, Switch} from 'antd';
import moment from 'moment';
const Option = Select.Option;
const FormItem = Form.Item;
const {TextArea} = Input;
const BasicInfo = ({form, wEmpresa, editAnimal, handleEmpresa, editMode,handleEditMode, id,empresa, options_raza, tipo_animal, arete_siniga, merma, arete_rancho, fecha_entrada, peso_entrada, descripcion, raza, color, options_empresa,lote, ref_factura_original, owner, costo_inicial, fierro_nuevo, fierro_original , costo_kilo, options, facturas, searchFactura, saveFactura, stateFactura, fierrosO, fierrosN, fierroO, fierroN}) => {
const handleSubmit = (e) => {
e.preventDefault();
form.validateFields((err, values) => {
console.log(values)
if (!err) {
if(!values.lote_id) delete values.lote_id;
if(!values.raza_id) delete values.raza_id;
if(!values.empresa_id) delete values.empresa_id;
/*if(!values.raza_id) values['raza_id'] = null;
if(!values.empresa_id) values['empresa_id'] = null;*/
if(!values.tipo_animal) delete values.tipo_animal;
if(!values.ref_factura_original_id) delete values.ref_factura_original_id;
/* if(!values.costo_inicial) delete values.costo_inicial;
if(!values.costo_kilo) delete values.costo_kilo;
if(!values.peso_entrada) delete values.peso_entrada;*/
console.log(values);
values['id']=id;
values['ref_factura_original_id'] = stateFactura !==null ? stateFactura:ref_factura_original && ref_factura_original !==null?ref_factura_original.id:null;
editAnimal(values)
.then(r=>{
console.log(r)
message.success('Editado con éxito');
handleEditMode()
}).catch(e=>{
message.error('Ocurrió un error')
console.log(e)
})
}
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
});
};
const opciones = [{
name :'becerro',
id: 1
},{
name:'toro',
id:3
},{
name:'vaca',
id:4
},{
name:'vaquilla',
id:5
}
];
let tipos = opciones.map((a) => <Option key={a.name}>{a.name}</Option>);
fierrosO = fierrosO.map((f, key)=><Option key={f.id} value={parseInt(f.id, 10)}>{f.codigo}</Option>)
fierrosN = fierrosN.map((f, key)=><Option key={f.id} value={parseInt(f.id, 10)}>{f.codigo}</Option>)
return (
<Fragment>
<Form style={{width:'100%', padding:'1% 3%'}} onSubmit={handleSubmit}>
<div style={{display:'flex',flexDirection:'row', justifyContent:'space-around', flexWrap:'wrap' }}>
<FormItem
label="Arete Rancho"
style={{width:'250px'}}>
{form.getFieldDecorator('arete_rancho', {
initialValue:arete_rancho,
rules: [{
required: true, message: 'Completa el campo!',
}],
})(
<Input
disabled={!editMode}
/>
)}
</FormItem>
<FormItem
label="Arete Siniga"
style={{width:'200px'}}>
{form.getFieldDecorator('arete_siniga', {
initialValue:arete_siniga,
rules: [{
required: true, message: 'Completa el campo!',
}],
})(
<Input
disabled={!editMode}
/>
)}
</FormItem>
<FormItem
label="Fecha Registro">
{form.getFieldDecorator('fecha_entrada', {
initialValue:moment(fecha_entrada)
})(
<DatePicker
disabled={!editMode}/>
)}
</FormItem>
<FormItem
label={"Tipo"}
style={{width:'200px'}}
>
{form.getFieldDecorator('tipo_animal', {
initialValue:tipo_animal,
rules: [{
required: false, message: 'Completa el campo!',
}],
props:{
placeholder:'Selecciona un tipo',
}
})(
<Select disabled={!editMode} placeholder={"Selecciona un tipo"}>
{tipos}
</Select>
)}
</FormItem>
<FormItem label={'Empresa?'}>
<Switch disabled={!editMode} defaultChecked={wEmpresa} onChange={handleEmpresa} checkedChildren="E" unCheckedChildren="P"/>
</FormItem>
{!wEmpresa?
<FormItem
label="Propietario">
{form.getFieldDecorator('owner', {
initialValue:owner
})(
<Input
style={{widht:'200px'}}
disabled={!editMode}
/>
)}
</FormItem>:
<FormItem label={'Empresa'}>
{form.getFieldDecorator('empresa_id', {
initialValue:empresa?empresa.id:'',
})(
<Select
disabled={!editMode}
style={{width:'200px'}}>
{options_empresa}
</Select>
)}
</FormItem>}
<FormItem
label="Factura Inicial"
style={{width:'200px'}}>
{form.getFieldDecorator('ref_factura_original_id', {
initialValue:ref_factura_original?ref_factura_original.factura:null,
rules: [{
required: false, message: 'Completa el campo!',
}],
})(
<Select
disabled={!editMode}
placeholder={"Factura"}
showSearch
onSearch={searchFactura}
filterOption={false}
>
{
facturas.length >0? facturas.map((a, key) => <Option key={key} value={a.factura} ><div onClick={()=>saveFactura(a.id)} ><span>{a.factura}</span></div></Option>):<Option key={999999} disabled >No encontrado</Option>
}
</Select>
)}
</FormItem>
<FormItem
label="Peso Entrada"
style={{width:'150px'}}>
{form.getFieldDecorator('peso_entrada', {
initialValue:peso_entrada
})(
<InputNumber
style={{width:'150px'}}
disabled={!editMode}
step={0.01}
min={0}
formatter={value => `${value}kg`}
parser={value => value.replace('kg', '')}
/>
)}
</FormItem>
<FormItem
label="Costo Kilo"
style={{width:'150px'}}>
{form.getFieldDecorator('costo_kilo', {
initialValue:costo_kilo
})(
<InputNumber
style={{width:'150px'}}
disabled={!editMode}
step={0.01}
formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
parser={value => value.replace(/\$\s?|(,*)/g, '')}
/>
)}
</FormItem>
<FormItem
label="Costo Inicial"
style={{width:'150px'}}>
{form.getFieldDecorator('costo_inicial', {
initialValue:(form.getFieldValue('costo_kilo')*form.getFieldValue('peso_entrada')).toFixed(2),
})(
<InputNumber
style={{width:'150px'}}
disabled={true}
step={0.01}
formatter={value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
parser={value => value.replace(/\$\s?|(,*)/g, '')}
/>
)}
</FormItem>
<FormItem
label="Costo Merma"
style={{width:'150px'}}>
{form.getFieldDecorator('merma', {
initialValue:merma
})(
<InputNumber
style={{width:'150px'}}
disabled={!editMode}
step={0.01}
formatter={value => `${value}%`}
parser={value => value.replace('%', '')}
/>
)}
</FormItem>
<FormItem
label="Raza">
{form.getFieldDecorator('raza_id', {
initialValue:raza?raza.id:''
})(
<Select
style={{width:'150px'}}
disabled={!editMode}
>
{options_raza}
</Select>
)}
</FormItem>
<FormItem
label="Color">
{form.getFieldDecorator('color', {
initialValue:color
})(
<Input
disabled={!editMode}
/>
)}
</FormItem>
<FormItem
label={"Lote"}
style={{width:'40%'}}>
{form.getFieldDecorator('lote_id',{
initialValue:lote?lote.id:''
})(
<Select
disabled={!editMode}
placeholder={"Selecciona un Lote"}>
{options}
</Select>
)}
</FormItem>
<FormItem
label="Descripción"
style={{width:'50%'}}>
{form.getFieldDecorator('descripcion', {
initialValue:descripcion
})(
<TextArea autosize
disabled={!editMode}
/>
)}
</FormItem>
</div>
{/* <FormItem
label="Comentarios">
{form.getFieldDecorator('comentarios', {
initialValue:comentarios
})(
<Input
disabled={!editMode}
/>
)}
</FormItem>*/}
<div style={{display:'flex', flexWrap:'wrap', justifyContent:'space-around'}}>
<FormItem
label="Fierro Original"
style={{width:'45%'}}>
{fierro_original&&!editMode?
<img src={fierro_original} alt="" style={{width:'200px', height:'200px'}}/>:
<div className="dropbox">
{form.getFieldDecorator('fierro_original',{
initialValue:fierro_original
})(
<Upload.Dragger name="files" disabled={!editMode}>
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-hint">Da click o arrastra un archivo</p>
</Upload.Dragger>)}
</div>}
</FormItem>
<FormItem
onChange={()=>{}}
label="Fierro Nuevo"
style={{width:'45%'}}
>
{fierro_nuevo&&!editMode?
<img src={fierro_nuevo} alt="" style={{width:'200px', height:'200px'}}/>:
<div className="dropbox">
{form.getFieldDecorator('fierro_nuevo',{
initialValue:fierro_nuevo
})(
<Upload.Dragger name="files" disabled={!editMode}>
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-hint">Da click o arrastra un archivo</p>
</Upload.Dragger>)}
</div>}
</FormItem>
<FormItem
label={"Fierro Original"}
style={{width:'45%'}}
>
{form.getFieldDecorator('fierroO_id', {
initialValue:fierroO?fierroO.id:'',
props:{
placeholder:'Selecciona un Lote',
}
})(
<Select placeholder={"Selecciona un Fierro Original"} disabled={!editMode}>
{fierrosO}
</Select>
)}
{fierroO?<img src={fierroO.imagen} alt="" style={{width:'200px', height:'200px'}}/>:''}
</FormItem>
<FormItem
label={"Fierro Nuevo"}
style={{width:'45%'}}
>
{form.getFieldDecorator('fierroN_id', {
initialValue:fierroN?fierroN.id:'',
props:{
placeholder:'Selecciona un Fierro Nuevo',
}
})(
<Select placeholder={"Selecciona un Fierro Nuevo"} disabled={!editMode}>
{fierrosN}
</Select>
)}
{fierroN?<img src={fierroN.imagen} alt="" style={{width:'200px', height:'200px'}}/>:''}
</FormItem>
</div>
<FormItem>
{editMode?
<Button
htmlType="submit"
size="large"
type={"primary"}
style={{width:'100%'}}
>
Guardar
</Button>:''}
</FormItem>
</Form>
{!editMode?
<Button
onClick={handleEditMode}
htmlType="button"
style={{width:'100%'}}
>
Editar
</Button>:''}
</Fragment>
)
};
const BasicInfoAndEdit = Form.create()(BasicInfo);
export default BasicInfoAndEdit; |
function ShootingStars( position, velocity ){
this.position = position;
this.velocity = velocity.normalize();
this.velocity.mult(random(20, 60));
}
ShootingStars.prototype.show = function(){
fill(255);
ellipse(this.position.x, this.position.y, 1, 1);
}
ShootingStars.prototype.update = function(){
this.position.add(this.velocity);
}
ShootingStars.prototype.isDead = function(){
// if ((this.position.x < 0 || this.position.x > width) && (this.position.y < 0 || this.position.y > height)){
// return true;
// }else{
// return false;
// }
return (this.position.x < 0 || this.position.x > width) && (this.position.y < 0 || this.position.y > height/3000000)
} |
'use strict';
var assign = require('object-assign');
hexo.config.calendar = assign({
single: true,
root: 'calendar/'
}, hexo.config.calendar);
hexo.extend.generator.register('calendar', require('./lib/generator'));
|
import React, {Component} from 'react';
import { Route, NavLink } from 'react-router-dom';
import WorkSpaceCard from '../components/WorkSpaceCard'
class DocumentsShow extends Component {
render() {
const {match, documents} = this.props
return (
<div>
{documents.map(document => (
<div key={document.extension} >
<Route exact path={match.url}
render={() =>
<NavLink to={`/documents/${document.extension}`}>Workspace {document.extension}</NavLink>
} />
<Route path={`${match.url}/${document.extension}`}
render={() =>
<WorkSpaceCard document={document} />
} />
</div>
))}
</div>
);
}
}
export default DocumentsShow; |
/*
*
* productInfoService.js
*
* Copyright (c) 2016 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*
*
*/
'use strict';
/**
* Constructs a service to pass data between a hosting controller and the product information panel.
*/
(function(){
angular.module('productMaintenanceUiApp').service('ProductInfoService', productInfoService);
/**
* Construct the service. The hosting controller is responsible for showing and hiding the panel, this
* controller just manages state on whether or not it should he displayed. The hosting controller needs to have
* the following methods defined:
*
* setError - sets an error message to be displayed.
*
* @returns {{ProductInfoService}}
*/
function productInfoService(){
var self = this;
self.visible = false;
self.productId = null;
self.comparisonProductId = null;
self.error = null;
self.sourceController = null;
self.itemId = null;
return {
/**
* The function to show the panel.
*
* @param sourceController The controller that is requesting the product information panel to show.
* @param productId The ID of the product whose information is being requested.
* @param comparisonProductId Optional Product ID to show in comparison to the main product ID.
* @param itemId option item code for when Item code search is done.
*/
show:function(sourceController, productId, comparisonProductId, itemId) {
self.sourceController = sourceController;
self.productId = productId;
self.comparisonProductId = comparisonProductId;
self.visible = true;
self.itemId = itemId;
},
/**
* Hides the panel.
*/
hide:function() {
self.sourceController = null;
self.productId = null;
self.comparisonProductId = null;
self.visible = false;
},
/**
* Returns whether or not this panel should be visible.
*
* @returns {boolean}
*/
isVisible:function(){
return self.visible;
},
/**
* Returns the ID of the product being shown.
* @returns {null|int}
*/
getProductId:function(){
return self.productId;
},
/**
* Returns the item code of the product being shown.
* @returns {null|int}
*/
getProductItemCode:function(){
return self.itemId;
},
getComparisonProductId:function() {
return self.comparisonProductId;
},
/**
* Called to send an error back to the hosting panel.
*
* @param error The error message.
*/
setError: function(error) {
self.sourceController.setError(error);
}
}
}
})();
|
import $ from 'jquery'
module.exports = (str) => {
var pagetop = $(str)
pagetop.on('click', () => {
$('html,body').animate(
{
scrollTop: '0'
},
1000,
'easeOutExpo'
)
})
}
|
;(function(Date) {
var test_date = new Date('2000')
, offset = test_date.getTimezoneOffset()
, offset_hour = Math.abs(Math.floor(offset / 60))
, offset_minute = Math.abs(offset % 60)
, isodate = /^(\d{4})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?:\:(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:?\d{2}))?$/
if(offset && !test_date.getUTCHours()) {
Date.__parse = Date.parse
offset = offset > 0 ? '-' : '+'
offset += (offset_hour < 10 ? '0' : '') + offset_hour
offset += (offset_minute < 10 ? '0' : '') + offset_minute
Date.parse = function(str) {
var m
if(m = isodate.exec(str)) {
if(!m[4]/*hour not set*/) str += 'T00:00'
if(!m[8]/*timezone not set*/) str += offset
}
return Date.__parse(str)
}
Date.fromString = function(str) {
return new Date(Date.parse(str))
}
}
}(Date)) |
export function initialize(container, application) {
//application.deferReadiness();
//
var session = container.lookup('session:current-user');
debugger;
if (session.access_token) {
$.ajaxSetup({
headers: { "Authorization": "Bearer " + session.access_token }
});
}
//
//container.lookup('store:main').find('user', 1).then(function(user) {
// application.register('user:current', user, { instantiate: false, singleton: true });
// application.inject('route', 'currentUser', 'user:current');
// application.inject('controller', 'currentUser', 'user:current');
// application.advanceReadiness();
//}, function() {
// application.advanceReadiness();
//});
}
export default {
name: 'current-user',
after: 'simple-auth',
initialize: initialize
};
|
'use strict';
// 首页控制器
app.controller('HomeController', ['$scope','$state', '$cookieStore',
function($scope,$state, $cookieStore) {
var cookie = $cookieStore.get('username');
console.log(cookie);
if(!cookie){
$state.go('access.signin');
return;
}
//left menu Array
$scope.initCenterMenu = function(){
for(var i=0; i<$scope.app.centerMenuArray.length; i++){
var obj = $scope.app.centerMenuArray[i];
var centerMenu = "";
centerMenu+= "<div class='col-md-2 col-sm-3 col-xs-4'>";
centerMenu+= ("<a ui-sref='"+obj.url+"' class='bg"+obj.bgClass+" app-item' href='#/"+obj.url.replace(/\./g,"/")+"'>");
centerMenu+= ("<i class='fa "+obj.imageClass+" text-white text-3x'></i>");
centerMenu+= ("<span class='text-white font-thin h4'>"+obj.name+"</span>");
centerMenu+= "</a>";
centerMenu+= "</div>";
$(".row.text-center").append(centerMenu);
}
var addBtn = "<div class='col-md-2 col-sm-3 col-xs-4'><a ui-sref='app.org' class='bg-white app-item add-item'>"
+"<i class='fa fa-plus text-dark text-3x'></i><span class='text-dark font-thin h4 block'>添加模块</span></a></div>";
$(".row.text-center").append(addBtn);
}
if($scope.app.centerMenuArray&&$scope.app.centerMenuArray.length>0){
$scope.initCenterMenu();
}else{
$scope.app.ui.init();
$scope.initCenterMenu();
$scope.app.ui.initLeftMenu();
}
//$scope.user = {};
//var days = 1;
//var exp = new Date();
//exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
//console.log(response.headers('Set-Cookie'));
//document.cookie = 'JSESSIONID=' + escape('1CAEA6F42C32BDC35784264D187EBB92') + ';expires = ' + exp.toGMTString();
//$cookies.username = escape($scope.user.name) + ';expires = ' + exp.toGMTString();;
//$state.go('app.home');
}
]); |
$(document).ready(function() {
$('#mail_smtpauth').change(function () {
if (!this.checked) {
$('#mail_credentials').addClass('hidden');
} else {
$('#mail_credentials').removeClass('hidden');
}
});
$('#mail_smtpmode').change(function () {
if ($(this).val() !== 'smtp') {
$('#setting_smtpauth').addClass('hidden');
$('#setting_smtphost').addClass('hidden');
$('#mail_smtpsecure_label').addClass('hidden');
$('#mail_smtpsecure').addClass('hidden');
$('#mail_credentials').addClass('hidden');
} else {
$('#setting_smtpauth').removeClass('hidden');
$('#setting_smtphost').removeClass('hidden');
$('#mail_smtpsecure_label').removeClass('hidden');
$('#mail_smtpsecure').removeClass('hidden');
if ($('#mail_smtpauth').is(':checked')) {
$('#mail_credentials').removeClass('hidden');
}
}
});
$('#mail_general_settings_form').change(function () {
OC.msg.startSaving('#mail_settings_msg');
var post = $("#mail_general_settings_form").serialize();
$.post(OC.generateUrl('/settings/admin/mailsettings'), post, function (data) {
OC.msg.finishedSaving('#mail_settings_msg', data);
});
});
$('#mail_credentials_settings_submit').click(function () {
OC.msg.startSaving('#mail_settings_msg');
var post = $("#mail_credentials_settings").serialize();
$.post(OC.generateUrl('/settings/admin/mailsettings/credentials'), post, function (data) {
OC.msg.finishedSaving('#mail_settings_msg', data);
});
});
$('#sendtestemail').click(function (event) {
event.preventDefault();
OC.msg.startAction('#sendtestmail_msg', t('settings', 'Sending...'));
$.post(OC.generateUrl('/settings/admin/mailtest'), '', function (data) {
OC.msg.finishedAction('#sendtestmail_msg', data);
});
});
}); |
const GROUND_COVER = {
url: 'images/groundcover',
description: 'ground cover'
}
const PAVERS = {
url: 'images/pavers',
description: 'pavers'
}
const TURF = {
url: 'images/grass',
description: 'turf'
}
const LOGO = {
url: 'images/yardzen-logo-black',
description: 'Yardzen logo'
}
const HANGING_LIGHT = {
url: 'images/hanging-lights',
description: 'Hanging Lights'
}
const GROUND_LIGHT = {
url: 'images/ground-lights',
description: 'Ground Lights'
}
const GRAVEL = {
url: 'images/gravel',
description: 'Gravel pathway'
}
const REDWOOD_FENCE = {
url: 'images/redwood-fence',
description: 'Redwood fence'
}
const LANTERNS = {
url: 'images/lanterns',
description: 'lanterns'
}
const PLYWOOD_FENCE = {
url: 'images/plywood-fence',
description: 'plywood fence'
}
const BAMBOO_SHROUD = {
url: 'images/bamboo-shroud',
description: 'bamboo shroud'
}
const POOL = {
url: 'images/pool',
description: 'pool'
}
const FOUNTAIN = {
url: 'images/fountain',
description: 'fountain'
}
const PERGOLA = {
url: 'images/pergola',
description: 'pergola'
}
const TAJ_MAJAL = {
url: 'images/taj-mahal',
description: 'Taj Mahal'
}
const PIRATE_SHIP = {
url: 'images/pirate-ship',
description: 'Pirate Ship'
}
const COMPOSITE = {
url: 'images/composite',
description: 'Composite'
}
const REDWOOD = {
url: 'images/redwood',
description: 'Redwood'
}
/**
* By storing image paths in this file, we can ensure
* that all our images are ADA (American Disabilities Assoc.) compliant
* and disabled people have a good experience.
*/
export default Object.freeze({
LOGO,
GROUND_COVER,
PAVERS,
TURF,
HANGING_LIGHT,
GROUND_LIGHT,
GRAVEL,
REDWOOD_FENCE,
LANTERNS,
PLYWOOD_FENCE,
BAMBOO_SHROUD,
POOL,
FOUNTAIN,
PERGOLA,
TAJ_MAJAL,
PIRATE_SHIP,
COMPOSITE,
REDWOOD
})
|
import React from 'react';
import GoogleMapReact from 'google-map-react';
import './map.css';
const Marker = () => (
<div className="drawnMarker"></div>
);
const API = {
KEY_GOOGLE: 'AIzaSyBEf_H_vpLcCgnZT2Z_EQ4eGiq5THzGz1k',
LANGUAGE: 'en'
};
const MAPDATA = {
ZOOM: 15,
LAT: 35.6895000,
LNG: 139.6917100
};
const mapConfig = {
center: [MAPDATA.LAT, MAPDATA.LNG],
zoom: MAPDATA.ZOOM
};
class Maps extends React.Component {
render() {
const markers = this.props.venues.map((venue, i) => {
const marker = {
position: {
lat: venue.location.lat,
lng: venue.location.lng
}
}
return <Marker key={i} lat={marker.position.lat} lng={marker.position.lng} />
});
return (
<div className="mapContainer">
<div className="mapElement">
<GoogleMapReact
defaultCenter={mapConfig.center}
defaultZoom={mapConfig.zoom}
bootstrapURLKeys={{
key: API.KEY_GOOGLE,
language: API.LANGUAGE
}}>
{ markers }
</GoogleMapReact>
</div>
</div>
);
}
}
export default Maps;
|
// 自定义组件名, 组件 json vue
Vue.component( 'page-head' , {
// 反引号 Esc 下面的那个按键, 反引号定义的字符串, 内部可以换行, 不需要拼接字符串
// 这里没错, 是外面的 detail.html 页面代码的问题,已经修改
template : `
<div class="container header">
<div class="span5">
<div class="logo">
<a href="index.html">
<img src="image/r___________renleipic_01/logo.png" alt="依依不舍"/>
</a>
</div>
</div>
<div class="span9">
<div class="headerAd">
<img src="image/header.jpg" width="320" height="50" alt="正品保障" title="正品保障"/>
</div>
</div>
<div class="span10 last">
<div class="topNav clearfix">
<ul>
<li id="headerLogin" class="headerLogin" style="display: list-item;">
Song|
</li>
<li id="headerLogin" class="headerLogin" style="display: list-item;">
<a href="olist.html">我的订单</a>|
</li>
<li id="headerRegister" class="headerRegister" style="display: list-item;">
<a href="index.html">退出</a>|
</li>
<li id="headerUsername" class="headerUsername"></li>
<li id="headerLogout" class="headerLogout">
<a>[退出]</a>|
</li>
<li>
<a>会员中心</a>
|
</li>
<li>
<a>购物指南</a>
|
</li>
<li>
<a>关于我们</a>
</li>
</ul>
</div>
<div class="cart">
<a href="cart.html">购物车</a>
</div>
<div class="phone">
客服热线:
<strong>96008/53277764</strong>
</div>
</div>
<div class="span24">
<ul class="mainNav">
<li>
<a href="index.html">首页</a>
|
</li>
<li>
<a href="clist.html#1">
女装男装
</a>
|</li>
<li>
<a href="clist.html#2">
鞋靴箱包
</a>
|</li>
<li>
<a href="clist.html#3">
运动户外
</a>
|</li>
<li>
<a href="clist.html#4">
珠宝配饰
</a>
|</li>
<li>
<a href="clist.html#5">
手机数码
</a>
|</li>
<li>
<a href="clist.html#6">
家电办公
</a>
|</li>
<li>
<a href="clist.html#7">
护肤彩妆
</a>
|</li>
</ul>
</div>
<slot></slot>
</div>
`
} );
Vue.component('page-foot',{
template :`
<div class="container footer">
<div class="span24">
<div class="footerAd">
<img src="image/footer.jpg" width="950" height="52" alt="我们的优势" title="我们的优势">
</div> </div>
<div class="span24">
<ul class="bottomNav">
<li>
<a>关于我们</a>
|
</li>
<li>
<a>联系我们</a>
|
</li>
<li>
<a>招贤纳士</a>
|
</li>
<li>
<a>法律声明</a>
|
</li>
<li>
<a>友情链接</a>
|
</li>
<li>
<a target="_blank">支付方式</a>
|
</li>
<li>
<a target="_blank">配送方式</a>
|
</li>
<li>
<a>服务声明</a>
|
</li>
<li>
<a>广告声明</a>
</li>
</ul>
</div>
<div class="span24">
<div class="copyright">Copyright © 2005-2013 大麦商城 版权所有</div>
</div>
</div>
`
});
|
import React from 'react';
import { Link } from 'react-router-dom';
const NavBar = props => (
<nav className="light-blue lighten-1" role="navigation">
<div className="nav-wrapper container">
<Link id="logo-container" className="brand-logo" to="/">
<i className="material-icons">local_library</i> MHA
</Link>
<ul className="right hide-on-med-and-down">
<li>
<Link to="/campuses/">Campuses</Link>
</li>
<li>
<Link to="/students/">Students</Link>
</li>
</ul>
<ul id="nav-mobile" className="sidenav">
<li>
<Link to="/campuses/">Campuses</Link>
</li>
<li>
<Link to="/students/">Students</Link>
</li>
</ul>
<a
href="#"
data-target="nav-mobile"
className="sidenav-trigger btn-floating btn-large teal"
>
<i className="material-icons">menu</i>
</a>
</div>
</nav>
);
export default NavBar;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.