text stringlengths 7 3.69M |
|---|
import React, { Component } from "react";
import "./App.css";
import UserInput from "./UserInput/UserInput";
import UserOutput from "./UserOutput/UserOutput";
class App extends Component {
state = {
usernames: ["antjori", "ant", "jo", "ri"]
};
changeStateHandler = event => {
this.setState({
usernames: [event.target.value, "ant", "jo", "ri"]
});
};
render() {
return (
<div className="App">
<UserInput
changed={this.changeStateHandler}
original={this.state.usernames[0]}
/>
<UserOutput username={this.state.usernames[0]} />
<UserOutput username={this.state.usernames[1]} />
<UserOutput username={this.state.usernames[2]} />
<UserOutput username={this.state.usernames[3]} />
</div>
);
}
}
export default App;
|
import React from 'react';
import { Meteor } from 'meteor/meteor';
import {ReactPageClick} from 'react-page-click';
import {
removeBookmark,
refreshBookmark,
updateBookmark,
incBookmarkViews
} from '../../api/bookmarks/methods';
import {can} from '/imports/modules/permissions.js';
import {Loading} from '/imports/ui/components/loading';
import ReactTooltip from 'react-tooltip';
export class Bookmark extends React.Component {
constructor(props) {
super(props);
this.state = {
isShowingActions: false,
isModalOpen: false,
isLoading: false
};
this._handleActionsToggle = this._handleActionsToggle.bind(this);
this._handleRemoveAction = this._handleRemoveAction.bind(this);
this._handleBookmarkRefresh = this._handleBookmarkRefresh.bind(this);
this._handleBookmarkEdit = this._handleBookmarkEdit.bind(this);
this._handeBookmarkClick = this._handeBookmarkClick.bind(this);
}
/**
* Helpers
*/
_shortUrl() {
return this.props.url.replace(/.*?:\/\//g,"").replace("www.","");
}
_thumbnail() {
let thumbSrc = '/img/no-image.png';
if(this.props.webshotUrl){
thumbSrc = this.props.webshotUrl
}
else if (this.props.image){
thumbSrc = this.props.image
}
return <img src={thumbSrc} alt="thumbnail" width="100%" />
}
/**
* Renderers
*/
_renderBookmarkActions() {
const bookmarkActions = (
<ul className="bookmark-actions">
<li>
<a onClick={this._handeBookmarkClick} href={this.props.url} target="_blank">
<i className="fa fa-eye"></i>
<span className="bookmark-action-text"> View</span>
</a>
</li>
<li>
<a onClick={this._handleBookmarkRefresh}><i className="fa fa-refresh"></i>
<span className="bookmark-action-text"> Refresh</span>
</a>
</li>
<li>
<a onClick={this._handleBookmarkEdit}><i className="fa fa-pencil"></i>
<span className="bookmark-action-text"> Edit</span>
</a>
</li>
<li>
<a onClick={this._handleRemoveAction} ><i className="fa fa-trash"></i>
<span className="bookmark-action-text"> Remove</span>
</a>
</li>
</ul>
);
return bookmarkActions;
}
_renderBookmarkThumb() {
const bookmarkThumb = (
<a onClick={this._handeBookmarkClick} href={this.props.url} target="_blank" className="clickable-url">
{this._thumbnail()}
</a>
);
return bookmarkThumb;
}
_renderThumbOrActions() {
if(this.state.isShowingActions && !this.props.readOnly){
return this._renderBookmarkActions();
}
else {
return this._renderBookmarkThumb();
}
}
_renderActionsToggleBtn() {
const actionsToggleBtn = (
<span className="bookmark-actions-toggle" onClick={this._handleActionsToggle}>
<i className={this.state.isShowingActions ? 'fa fa-undo' : 'fa fa-cog'}></i>
</span>
)
if(!this.props.readOnly){
return actionsToggleBtn;
}
}
_renderBookmarkInner() {
const innerContent = (
<div className="inner">
<h4 data-tip={this.props.title} data-for={this.props.id}>
<a href={this.props.url} target="_blank">{this.props.title}</a>
</h4>
<div className="bookmark-content">
{this._renderThumbOrActions()}
</div>
<div className="bookmark-footer">
<div className="bookmark-url-wrapper">
<span className="bookmark-url">{this._shortUrl()}</span>
</div>
{this._renderActionsToggleBtn()}
</div>
</div>
);
const innerLoading = (
<div className="inner">
<Loading/>
</div>
)
return !this.state.isLoading ? innerContent : innerLoading;
}
/**
* Handlers
*/
_handleActionsToggle(e) {
e.preventDefault();
this.setState(prevState => ({
isShowingActions: !prevState.isShowingActions
}));
}
_handleRemoveAction(e) {
e.preventDefault();
removeBookmark.call({bookmarkId: this.props.id}, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
}
});
}
_handleBookmarkRefresh(e) {
e.preventDefault();
this.setState({isLoading: true, isShowingActions: false});
refreshBookmark.call({bookmarkId: this.props.id}, (err) => {
this.setState({isLoading: false})
});
}
_handleBookmarkEdit(e) {
e.preventDefault();
this.props.editBookmarkHandler(this.props.id);
}
_handeBookmarkClick(e) {
incBookmarkViews.call({bookmarkId: this.props.id}, null);
}
render() {
return (
<div id={this.props.id} className="bookmark-card">
{this._renderBookmarkInner()}
<ReactTooltip id={this.props.id} place="top" multiline={true} effect="solid" />
</div>
);
}
}
Bookmark.propTypes = {
id: React.PropTypes.string,
title: React.PropTypes.string,
url: React.PropTypes.string,
image: React.PropTypes.string,
folderId: React.PropTypes.string,
webshotUrl: React.PropTypes.string,
editBookmarkHandler: React.PropTypes.func,
readOnly: React.PropTypes.bool,
};
|
// // // const animals = ["cow", "chicken", "pig", "fish"]
// // // /*
// // // A function whose purpose is to cook an animal and
// // // return the processed result
// // // */
// // // const cookIt = function (animal) {
// // // switch (animal) {
// // // case "cow":
// // // console.log("steak");
// // // break;
// // // case "chicken":
// // // console.log("drumstick");
// // // break;
// // // case "pig":
// // // console.log("bacon");
// // // break;
// // // case "fish":
// // // console.log("sushi");
// // // break;
// // // }
// // // }
// // // // Execute the cookIt function for each item in the array
// // // animals.forEach(cookIt)
// // //---------------------------------ARRAY METHODS--------------------------------------------------
// // //--------------------------------FIRST EXERCISE--------------------------------------------------
// // // /*
// // // Use the forEach method to add the name of each planet
// // // to a section element in your HTML with an id of "planets".
// // // Use string templates to construct the DOM elements.
// // // */
const planets = ["mercury", "venus", "earth", "mars", "jupiter", "saturn", "uranus", "neptune"]
const planetEl = document.getElementById("planets")
const planetsList = function (planet) {
const planetsListName = document.createElement("section")
planetsListName.innerHTML = planet
planetEl.appendChild(planetsListName)
console.log("list of planets", planetsListName)
}
planets.forEach(planetsList)
// // //--------------------------------SECOND EXERCISE--------------------------------------------------
// // /*
// // Use the map method to create a new array where the
// // first letter of each planet is capitalized. Use the
// // `toUpperCase()` method on strings.
// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase
// // */
const capPlanets = planets.map(function (planet) {
// return planet.toUpperCase(1)+ planet.slice(1);
return planet.charAt(0).toUpperCase() + planet.slice(1);
// return planet.charAt(0).toUpperCase().slice(1);
})
console.log(planets)
console.log("capitilized planets", capPlanets)
capPlanets.forEach(planetsList)
// // //--------------------------------THIRD EXERCISE--------------------------------------------------
// // /*
// // Use the filter method to create a new array that
// // contains planets with the letter 'e'. Use the `includes()`
// // method on strings.
// // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
// // */
const ePlanets = planets.filter(planet => {
const containsE = (planet.includes("e"))
console.log("planets contain e", containsE)
return containsE
})
console.log(ePlanets)
console.log(planets)
// // //--------------------------------FOURTH EXERCISE--------------------------------------------------
// const monthlyRainfall = [23, 32, 27, 20, 20, 31, 33, 26, 19, 12]
// // ES6+ syntax
// const totalRainfall = monthlyRainfall.reduce(
// (currentTotal, next) => currentTotal + next
// )
// // Traditional syntax
// const totalRainfall = monthlyRainfall.reduce(
// function (currentTotal, next) {
// return currentTotal + next
// }
// )
// // Use the reduce method to create a sentence from the words in the following array
const words = ["The", "early", "bird", "might", "get", "the", "worm", "but", "the", "second", "mouse", "gets", "the", "cheese"]
const sentence = words.reduce(
function (currentTotal, next) {
return `${currentTotal} ${next}`
}
)
console.log(sentence)
|
'use strict';
module.exports = function(app) {
app.controller('headerCtrl', ['$location', 'Auth', '$window', function($location, Auth, $window) {
var vm = this;
vm.isLoggedIn = false;
vm.logMeOut = function() {
Auth.signOut();
vm.checkBand();
};
vm.checkBand = function() {
if ($window.localStorage.bandName == undefined) {
vm.isLoggedIn = false;
} else if ($window.localStorage.bandName != 'null') {
vm.isLoggedIn = true;
} else {
vm.isLoggedIn = false;
}
};
vm.submitSignIn = function(band) {
Auth.signIn(band, function() {
$location.path('/');
vm.checkBand();
});
};
}]);
};
|
/******************* 사전지식 ********************/
/*
function a() {
}
function b() {
return "B";
}
var fnA = a();
var fnB = b();
console.log(fnA, fnB);
var css = {"position": "absolute", "top": "50%", "transform": "translateY(-50%)", "font-size": "5rem", "z-index": 900, "color": "#fff"};
var $btLeft = $('<i class="bt-lt fa fa-angle-left"></i>').appendTo(".main-wrap").css(css);
var $btRight = $('<i class="bt-rt fa fa-angle-right"></i>').appendTo(".main-wrap").css(css);
$btLeft.css("left", "2rem");
$btRight.css("right", "2rem");
*/
/******************* 전역설정 ********************/
mainSlide(".main-wrap");
/******************* 사용자 함수 ********************/
function mainSlide(container) {
var now = 0;
var $container = $(container).addClass("slide-wrap");
var $slide = $container.children("*").addClass("slide").css("transition", "0.5s");
var $btPrev = $('<div class="bt bt-prev"></div>').appendTo($container).click(onPrev);
var $btNext = $('<div class="bt bt-next"></div>').appendTo($container).click(onNext);
// console.log($slide);
var last = $slide.length - 1;
function init() {
$btPrev.show();
$btNext.show();
$container.children(".slide").remove();
$($slide[now]).appendTo($container);
}
function ani() {
$($slide[now]).appendTo($container).css({"opacity": 0, "transform": "scale(1.2)"});
setTimeout(function(){
$container.children(".slide").eq(0).css({"opacity": 0, "transform": "scale(0.7)"});
$container.children(".slide").eq(1).css({"opacity": 1, "transform": "scale(1)"});
setTimeout(init, 500);
}, 0);
}
function onPrev() {
$(this).hide();
now = (now == 0) ? now = last : now - 1;
ani();
}
function onNext() {
$(this).hide();
now = (now == 2) ? now = 0 : now + 1;
ani();
}
init();
}
/******************* 이벤트 함수 ********************/
function onResize() {
this.wid = $(this).innerWidth();
this.hei = $(this).innerHeight();
}
function onScroll() {
this.scTop = $(this).scrollTop();
if(scTop > hei) {
$(".header").css({"top": 0, "bottom": "auto", "position": "fixed"});
}
else {
$(".header").css({"top": "auto", "bottom": 0, "position": "absolute"});
}
}
/******************* 이벤트 설정 ********************/
$(window).resize(onResize).trigger("resize");
$(window).scroll(onScroll).trigger("scroll"); |
{
"results": [{
"serving_weight": 226.8,
"serving_qty": 1,
"ndb_no": 1253,
"serving_unit": "cup",
"tier": 1,
"nutrients": [{
"attr_id": 255,
"value": 89.83548,
"unit": "g",
"name": "Water",
"usda_tag": "WATER"
}, {
"attr_id": 208,
"value": 841.428,
"unit": "kcal",
"name": "Energy",
"usda_tag": "ENERC_KCAL"
}, {
"attr_id": 268,
"value": 3522.204,
"unit": "kJ",
"name": "Energy",
"usda_tag": "ENERC_KJ"
}, {
"attr_id": 203,
"value": 41.11884,
"unit": "g",
"name": "Protein",
"usda_tag": "PROCNT"
}, {
"attr_id": 204,
"value": 72.09972,
"unit": "g",
"name": "Total lipid (fat)",
"usda_tag": "FAT"
}, {
"attr_id": 207,
"value": 15.377040000000003,
"unit": "g",
"name": "Ash",
"usda_tag": "ASH"
}, {
"attr_id": 205,
"value": 8.391600000000002,
"unit": "g",
"name": "Carbohydrate, by difference",
"usda_tag": "CHOCDF"
}, {
"attr_id": 291,
"value": 0,
"unit": "g",
"name": "Fiber, total dietary",
"usda_tag": "FIBTG"
}, {
"attr_id": 269,
"value": 5.12568,
"unit": "g",
"name": "Sugars, total",
"usda_tag": "SUGAR"
}, {
"attr_id": 210,
"value": 0,
"unit": "g",
"name": "Sucrose",
"usda_tag": "SUCS"
}, {
"attr_id": 211,
"value": 0,
"unit": "g",
"name": "Glucose (dextrose)",
"usda_tag": "GLUS"
}, {
"attr_id": 212,
"value": 0,
"unit": "g",
"name": "Fructose",
"usda_tag": "FRUS"
}, {
"attr_id": 213,
"value": 4.8762,
"unit": "g",
"name": "Lactose",
"usda_tag": "LACS"
}, {
"attr_id": 214,
"value": 0,
"unit": "g",
"name": "Maltose",
"usda_tag": "MALS"
}, {
"attr_id": 287,
"value": 0.24948000000000004,
"unit": "g",
"name": "Galactose",
"usda_tag": "GALS"
}, {
"attr_id": 301,
"value": 2370.06,
"unit": "mg",
"name": "Calcium, Ca",
"usda_tag": "CA"
}, {
"attr_id": 303,
"value": 1.42884,
"unit": "mg",
"name": "Iron, Fe",
"usda_tag": "FE"
}, {
"attr_id": 304,
"value": 58.968,
"unit": "mg",
"name": "Magnesium, Mg",
"usda_tag": "MG"
}, {
"attr_id": 305,
"value": 1453.788,
"unit": "mg",
"name": "Phosphorus, P",
"usda_tag": "P"
}, {
"attr_id": 306,
"value": 299.376,
"unit": "mg",
"name": "Potassium, K",
"usda_tag": "K"
}, {
"attr_id": 307,
"value": 3789.8280000000004,
"unit": "mg",
"name": "Sodium, Na",
"usda_tag": "NA"
}, {
"attr_id": 309,
"value": 5.647320000000001,
"unit": "mg",
"name": "Zinc, Zn",
"usda_tag": "ZN"
}, {
"attr_id": 312,
"value": 0.104328,
"unit": "mg",
"name": "Copper, Cu",
"usda_tag": "CU"
}, {
"attr_id": 315,
"value": 0.09298800000000002,
"unit": "mg",
"name": "Manganese, Mn",
"usda_tag": "MN"
}, {
"attr_id": 317,
"value": 45.8136,
"unit": "µg",
"name": "Selenium, Se",
"usda_tag": "SE"
}, {
"attr_id": 313,
"value": 79.38,
"unit": "µg",
"name": "Fluoride, F",
"usda_tag": "FLD"
}, {
"attr_id": 401,
"value": 0,
"unit": "mg",
"name": "Vitamin C, total ascorbic acid",
"usda_tag": "VITC"
}, {
"attr_id": 404,
"value": 0.03402,
"unit": "mg",
"name": "Thiamin",
"usda_tag": "THIA"
}, {
"attr_id": 405,
"value": 0.5307120000000001,
"unit": "mg",
"name": "Riboflavin",
"usda_tag": "RIBF"
}, {
"attr_id": 406,
"value": 0.172368,
"unit": "mg",
"name": "Niacin",
"usda_tag": "NIA"
}, {
"attr_id": 410,
"value": 0.9140040000000001,
"unit": "mg",
"name": "Pantothenic acid",
"usda_tag": "PANTAC"
}, {
"attr_id": 415,
"value": 0.12247200000000001,
"unit": "mg",
"name": "Vitamin B-6",
"usda_tag": "VITB6A"
}, {
"attr_id": 417,
"value": 18.144000000000002,
"unit": "µg",
"name": "Folate, total",
"usda_tag": "FOL"
}, {
"attr_id": 431,
"value": 0,
"unit": "µg",
"name": "Folic acid",
"usda_tag": "FOLAC"
}, {
"attr_id": 432,
"value": 18.144000000000002,
"unit": "µg",
"name": "Folate, food",
"usda_tag": "FOLFD"
}, {
"attr_id": 435,
"value": 18.144000000000002,
"unit": "µg",
"name": "Folate, DFE",
"usda_tag": "FOLDFE"
}, {
"attr_id": 421,
"value": 82.1016,
"unit": "mg",
"name": "Choline, total",
"usda_tag": "CHOLN"
}, {
"attr_id": 418,
"value": 3.402,
"unit": "µg",
"name": "Vitamin B-12",
"usda_tag": "VITB12"
}, {
"attr_id": 320,
"value": 567,
"unit": "µg",
"name": "Vitamin A, RAE",
"usda_tag": "VITA_RAE"
}, {
"attr_id": 319,
"value": 551.124,
"unit": "µg",
"name": "Retinol",
"usda_tag": "RETOL"
}, {
"attr_id": 321,
"value": 181.44,
"unit": "µg",
"name": "Carotene, beta",
"usda_tag": "CARTB"
}, {
"attr_id": 322,
"value": 0,
"unit": "µg",
"name": "Carotene, alpha",
"usda_tag": "CARTA"
}, {
"attr_id": 334,
"value": 0,
"unit": "µg",
"name": "Cryptoxanthin, beta",
"usda_tag": "CRYPX"
}, {
"attr_id": 318,
"value": 2143.26,
"unit": "IU",
"name": "Vitamin A, IU",
"usda_tag": "VITA_IU"
}, {
"attr_id": 337,
"value": 0,
"unit": "µg",
"name": "Lycopene",
"usda_tag": "LYCPN"
}, {
"attr_id": 338,
"value": 0,
"unit": "µg",
"name": "Lutein + zeaxanthin",
"usda_tag": "LUT+ZEA"
}, {
"attr_id": 323,
"value": 1.8144000000000002,
"unit": "mg",
"name": "Vitamin E (alpha-tocopherol)",
"usda_tag": "TOCPHA"
}, {
"attr_id": 341,
"value": 0,
"unit": "mg",
"name": "Tocopherol, beta",
"usda_tag": "TOCPHB"
}, {
"attr_id": 342,
"value": 0.29484,
"unit": "mg",
"name": "Tocopherol, gamma",
"usda_tag": "TOCPHG"
}, {
"attr_id": 343,
"value": 0.09072000000000001,
"unit": "mg",
"name": "Tocopherol, delta",
"usda_tag": "TOCPHD"
}, {
"attr_id": 344,
"value": 0.045360000000000004,
"unit": "mg",
"name": "Tocotrienol, alpha",
"usda_tag": "TOCTRA"
}, {
"attr_id": 345,
"value": 0.045360000000000004,
"unit": "mg",
"name": "Tocotrienol, beta",
"usda_tag": "TOCTRB"
}, {
"attr_id": 346,
"value": 0.06804,
"unit": "mg",
"name": "Tocotrienol, gamma",
"usda_tag": "TOCTRG"
}, {
"attr_id": 347,
"value": 0.18144000000000002,
"unit": "mg",
"name": "Tocotrienol, delta",
"usda_tag": "TOCTRD"
}, {
"attr_id": 328,
"value": 1.3608,
"unit": "µg",
"name": "Vitamin D (D2 + D3)",
"usda_tag": "VITD"
}, {
"attr_id": 325,
"value": 0,
"unit": "µg",
"name": "Vitamin D2 (ergocalciferol)",
"usda_tag": "ERGCAL"
}, {
"attr_id": 326,
"value": 1.3608,
"unit": "µg",
"name": "Vitamin D3 (cholecalciferol)",
"usda_tag": "CHOCAL"
}, {
"attr_id": 324,
"value": 52.164,
"unit": "IU",
"name": "Vitamin D",
"usda_tag": "VITD"
}, {
"attr_id": 430,
"value": 5.896800000000001,
"unit": "µg",
"name": "Vitamin K (phylloquinone)",
"usda_tag": "VITK1"
}, {
"attr_id": 606,
"value": 40.953275999999995,
"unit": "g",
"name": "Fatty acids, total saturated",
"usda_tag": "FASAT"
}, {
"attr_id": 607,
"value": 1.3948200000000002,
"unit": "g",
"name": "4:0",
"usda_tag": "F4D0"
}, {
"attr_id": 608,
"value": 1.154412,
"unit": "g",
"name": "6:0",
"usda_tag": "F6D0"
}, {
"attr_id": 609,
"value": 0.7529760000000001,
"unit": "g",
"name": "8:0",
"usda_tag": "F8D0"
}, {
"attr_id": 610,
"value": 1.8189360000000003,
"unit": "g",
"name": "10:0",
"usda_tag": "F10D0"
}, {
"attr_id": 611,
"value": 2.004912,
"unit": "g",
"name": "12:0",
"usda_tag": "F12D0"
}, {
"attr_id": 612,
"value": 6.661116,
"unit": "g",
"name": "14:0",
"usda_tag": "F14D0"
}, {
"attr_id": 652,
"value": 0.705348,
"unit": "g",
"name": "15:0",
"usda_tag": "F15D0"
}, {
"attr_id": 613,
"value": 18.509148,
"unit": "g",
"name": "16:0",
"usda_tag": "F16D0"
}, {
"attr_id": 653,
"value": 0.43092,
"unit": "g",
"name": "17:0",
"usda_tag": "F17D0"
}, {
"attr_id": 614,
"value": 7.307496,
"unit": "g",
"name": "18:0",
"usda_tag": "F18D0"
}, {
"attr_id": 615,
"value": 0.10659600000000001,
"unit": "g",
"name": "20:0",
"usda_tag": "F20D0"
}, {
"attr_id": 624,
"value": 0.047628000000000004,
"unit": "g",
"name": "22:0",
"usda_tag": "F22D0"
}, {
"attr_id": 654,
"value": 0.020412,
"unit": "g",
"name": "24:0",
"usda_tag": "F24D0"
}, {
"attr_id": 645,
"value": 18.679248000000005,
"unit": "g",
"name": "Fatty acids, total monounsaturated",
"usda_tag": "FAMS"
}, {
"attr_id": 625,
"value": 0.55566,
"unit": "g",
"name": "14:1",
"usda_tag": "F14D1"
}, {
"attr_id": 697,
"value": 0,
"unit": "g",
"name": "15:1",
"usda_tag": "F15D1"
}, {
"attr_id": 626,
"value": 1.1340000000000001,
"unit": "g",
"name": "16:1 undifferentiated",
"usda_tag": "F16D1"
}, {
"attr_id": 673,
"value": 0.893592,
"unit": "g",
"name": "16:1 c",
"usda_tag": "F16D1C"
}, {
"attr_id": 662,
"value": 0.240408,
"unit": "g",
"name": "16:1 t",
"usda_tag": "F16D1T"
}, {
"attr_id": 687,
"value": 0.138348,
"unit": "g",
"name": "17:1",
"usda_tag": "F17D1"
}, {
"attr_id": 617,
"value": 16.338672000000003,
"unit": "g",
"name": "18:1 undifferentiated",
"usda_tag": "F18D1"
}, {
"attr_id": 674,
"value": 14.42448,
"unit": "g",
"name": "18:1 c",
"usda_tag": "F18D1C"
}, {
"attr_id": 663,
"value": 1.914192,
"unit": "g",
"name": "18:1 t",
"usda_tag": "F18D1T"
}, {
"attr_id": 628,
"value": 0.508032,
"unit": "g",
"name": "20:1",
"usda_tag": "F20D1"
}, {
"attr_id": 630,
"value": 0.002268,
"unit": "g",
"name": "22:1 undifferentiated",
"usda_tag": "F22D1"
}, {
"attr_id": 676,
"value": 0.002268,
"unit": "g",
"name": "22:1 c",
"usda_tag": "F22D1C"
}, {
"attr_id": 664,
"value": 0,
"unit": "g",
"name": "22:1 t",
"usda_tag": "F22D1T"
}, {
"attr_id": 671,
"value": 0.002268,
"unit": "g",
"name": "24:1 c",
"usda_tag": "F24D1C"
}, {
"attr_id": 646,
"value": 2.9166480000000004,
"unit": "g",
"name": "Fatty acids, total polyunsaturated",
"usda_tag": "FAPU"
}, {
"attr_id": 618,
"value": 2.2748039999999996,
"unit": "g",
"name": "18:2 undifferentiated",
"usda_tag": "F18D2"
}, {
"attr_id": 675,
"value": 1.7917200000000002,
"unit": "g",
"name": "18:2 n-6 c,c",
"usda_tag": "F18D2CN6"
}, {
"attr_id": 670,
"value": 0.040824,
"unit": "g",
"name": "18:2 CLAs",
"usda_tag": "F18D2CLA"
}, {
"attr_id": 619,
"value": 0.31298400000000004,
"unit": "g",
"name": "18:3 undifferentiated",
"usda_tag": "F18D3"
}, {
"attr_id": 851,
"value": 0.31071600000000005,
"unit": "g",
"name": "18:3 n-3 c,c,c (ALA)",
"usda_tag": "F18D3CN3"
}, {
"attr_id": 685,
"value": 0.002268,
"unit": "g",
"name": "18:3 n-6 c,c,c",
"usda_tag": "F18D3CN6"
}, {
"attr_id": 627,
"value": 0.015876,
"unit": "g",
"name": "18:4",
"usda_tag": "F18D4"
}, {
"attr_id": 672,
"value": 0.020412,
"unit": "g",
"name": "20:2 n-6 c,c",
"usda_tag": "F20D2CN6"
}, {
"attr_id": 689,
"value": 0.07711200000000001,
"unit": "g",
"name": "20:3 undifferentiated",
"usda_tag": "F20D3"
}, {
"attr_id": 852,
"value": 0.002268,
"unit": "g",
"name": "20:3 n-3",
"usda_tag": "F20D3N3"
}, {
"attr_id": 853,
"value": 0.07484400000000001,
"unit": "g",
"name": "20:3 n-6",
"usda_tag": "F20D3N6"
}, {
"attr_id": 620,
"value": 0.10206,
"unit": "g",
"name": "20:4 undifferentiated",
"usda_tag": "F20D4"
}, {
"attr_id": 629,
"value": 0.027216000000000004,
"unit": "g",
"name": "20:5 n-3 (EPA)",
"usda_tag": "F20D5"
}, {
"attr_id": 858,
"value": 0.018144,
"unit": "g",
"name": "22:4",
"usda_tag": "F22D4"
}, {
"attr_id": 631,
"value": 0.047628000000000004,
"unit": "g",
"name": "22:5 n-3 (DPA)",
"usda_tag": "F22D5"
}, {
"attr_id": 621,
"value": 0.013608000000000002,
"unit": "g",
"name": "22:6 n-3 (DHA)",
"usda_tag": "F22D6"
}, {
"attr_id": 605,
"value": 2.594592,
"unit": "g",
"name": "Fatty acids, total trans",
"usda_tag": "FATRN"
}, {
"attr_id": 693,
"value": 2.1546,
"unit": "g",
"name": "Fatty acids, total trans-monoenoic",
"usda_tag": "FATRNM"
}, {
"attr_id": 695,
"value": 0.43999200000000005,
"unit": "g",
"name": "Fatty acids, total trans-polyenoic",
"usda_tag": "FATRNP"
}, {
"attr_id": 601,
"value": 226.8,
"unit": "mg",
"name": "Cholesterol",
"usda_tag": "CHOLE"
}, {
"attr_id": 501,
"value": 0.526176,
"unit": "g",
"name": "Tryptophan",
"usda_tag": "TRP_G"
}, {
"attr_id": 502,
"value": 1.750896,
"unit": "g",
"name": "Threonine",
"usda_tag": "THR_G"
}, {
"attr_id": 503,
"value": 2.1273839999999997,
"unit": "g",
"name": "Isoleucine",
"usda_tag": "ILE_G"
}, {
"attr_id": 504,
"value": 3.891888,
"unit": "g",
"name": "Leucine",
"usda_tag": "LEU_G"
}, {
"attr_id": 505,
"value": 3.438288,
"unit": "g",
"name": "Lysine",
"usda_tag": "LYS_G"
}, {
"attr_id": 506,
"value": 1.0773,
"unit": "g",
"name": "Methionine",
"usda_tag": "MET_G"
}, {
"attr_id": 507,
"value": 0.24948000000000004,
"unit": "g",
"name": "Cystine",
"usda_tag": "CYS_G"
}, {
"attr_id": 508,
"value": 2.1296519999999997,
"unit": "g",
"name": "Phenylalanine",
"usda_tag": "PHE_G"
}, {
"attr_id": 509,
"value": 2.0774880000000002,
"unit": "g",
"name": "Tyrosine",
"usda_tag": "TYR_G"
}, {
"attr_id": 510,
"value": 2.6921160000000004,
"unit": "g",
"name": "Valine",
"usda_tag": "VAL_G"
}, {
"attr_id": 511,
"value": 1.174824,
"unit": "g",
"name": "Arginine",
"usda_tag": "ARG_G"
}, {
"attr_id": 512,
"value": 1.238328,
"unit": "g",
"name": "Histidine",
"usda_tag": "HISTN_G"
}, {
"attr_id": 513,
"value": 1.390284,
"unit": "g",
"name": "Alanine",
"usda_tag": "ALA_G"
}, {
"attr_id": 514,
"value": 3.517668,
"unit": "g",
"name": "Aspartic acid",
"usda_tag": "ASP_G"
}, {
"attr_id": 515,
"value": 9.237564,
"unit": "g",
"name": "Glutamic acid",
"usda_tag": "GLU_G"
}, {
"attr_id": 516,
"value": 0.814212,
"unit": "g",
"name": "Glycine",
"usda_tag": "GLY_G"
}, {
"attr_id": 517,
"value": 4.055184000000001,
"unit": "g",
"name": "Proline",
"usda_tag": "PRO_G"
}, {
"attr_id": 518,
"value": 2.478924,
"unit": "g",
"name": "Serine",
"usda_tag": "SER_G"
}, {
"attr_id": 221,
"value": 0,
"unit": "g",
"name": "Alcohol, ethyl",
"usda_tag": "ALC"
}, {
"attr_id": 262,
"value": 0,
"unit": "mg",
"name": "Caffeine",
"usda_tag": "CAFFN"
}, {
"attr_id": 263,
"value": 0,
"unit": "mg",
"name": "Theobromine",
"usda_tag": "THEBRN"
}],
"parsed_query": {
"qty": 1,
"unit": "cup",
"food": "cheese",
"query": "1 cup cheese "
},
"idx": 0
}, {
"serving_weight": 20,
"serving_qty": 20,
"ndb_no": 11529,
"serving_unit": "g",
"tier": 1,
"nutrients": [{
"attr_id": 255,
"value": 18.904,
"unit": "g",
"name": "Water",
"usda_tag": "WATER"
}, {
"attr_id": 208,
"value": 3.6,
"unit": "kcal",
"name": "Energy",
"usda_tag": "ENERC_KCAL"
}, {
"attr_id": 268,
"value": 14.8,
"unit": "kJ",
"name": "Energy",
"usda_tag": "ENERC_KJ"
}, {
"attr_id": 203,
"value": 0.17600000000000002,
"unit": "g",
"name": "Protein",
"usda_tag": "PROCNT"
}, {
"attr_id": 204,
"value": 0.04000000000000001,
"unit": "g",
"name": "Total lipid (fat)",
"usda_tag": "FAT"
}, {
"attr_id": 207,
"value": 0.1,
"unit": "g",
"name": "Ash",
"usda_tag": "ASH"
}, {
"attr_id": 205,
"value": 0.778,
"unit": "g",
"name": "Carbohydrate, by difference",
"usda_tag": "CHOCDF"
}, {
"attr_id": 291,
"value": 0.24,
"unit": "g",
"name": "Fiber, total dietary",
"usda_tag": "FIBTG"
}, {
"attr_id": 269,
"value": 0.526,
"unit": "g",
"name": "Sugars, total",
"usda_tag": "SUGAR"
}, {
"attr_id": 210,
"value": 0,
"unit": "g",
"name": "Sucrose",
"usda_tag": "SUCS"
}, {
"attr_id": 211,
"value": 0.25,
"unit": "g",
"name": "Glucose (dextrose)",
"usda_tag": "GLUS"
}, {
"attr_id": 212,
"value": 0.274,
"unit": "g",
"name": "Fructose",
"usda_tag": "FRUS"
}, {
"attr_id": 213,
"value": 0,
"unit": "g",
"name": "Lactose",
"usda_tag": "LACS"
}, {
"attr_id": 214,
"value": 0,
"unit": "g",
"name": "Maltose",
"usda_tag": "MALS"
}, {
"attr_id": 287,
"value": 0,
"unit": "g",
"name": "Galactose",
"usda_tag": "GALS"
}, {
"attr_id": 209,
"value": 0,
"unit": "g",
"name": "Starch",
"usda_tag": "STARCH"
}, {
"attr_id": 301,
"value": 2,
"unit": "mg",
"name": "Calcium, Ca",
"usda_tag": "CA"
}, {
"attr_id": 303,
"value": 0.054000000000000006,
"unit": "mg",
"name": "Iron, Fe",
"usda_tag": "FE"
}, {
"attr_id": 304,
"value": 2.2,
"unit": "mg",
"name": "Magnesium, Mg",
"usda_tag": "MG"
}, {
"attr_id": 305,
"value": 4.800000000000001,
"unit": "mg",
"name": "Phosphorus, P",
"usda_tag": "P"
}, {
"attr_id": 306,
"value": 47.400000000000006,
"unit": "mg",
"name": "Potassium, K",
"usda_tag": "K"
}, {
"attr_id": 307,
"value": 1,
"unit": "mg",
"name": "Sodium, Na",
"usda_tag": "NA"
}, {
"attr_id": 309,
"value": 0.034,
"unit": "mg",
"name": "Zinc, Zn",
"usda_tag": "ZN"
}, {
"attr_id": 312,
"value": 0.0118,
"unit": "mg",
"name": "Copper, Cu",
"usda_tag": "CU"
}, {
"attr_id": 315,
"value": 0.0228,
"unit": "mg",
"name": "Manganese, Mn",
"usda_tag": "MN"
}, {
"attr_id": 317,
"value": 0,
"unit": "µg",
"name": "Selenium, Se",
"usda_tag": "SE"
}, {
"attr_id": 313,
"value": 0.45999999999999996,
"unit": "µg",
"name": "Fluoride, F",
"usda_tag": "FLD"
}, {
"attr_id": 401,
"value": 2.74,
"unit": "mg",
"name": "Vitamin C, total ascorbic acid",
"usda_tag": "VITC"
}, {
"attr_id": 404,
"value": 0.0074,
"unit": "mg",
"name": "Thiamin",
"usda_tag": "THIA"
}, {
"attr_id": 405,
"value": 0.0038,
"unit": "mg",
"name": "Riboflavin",
"usda_tag": "RIBF"
}, {
"attr_id": 406,
"value": 0.1188,
"unit": "mg",
"name": "Niacin",
"usda_tag": "NIA"
}, {
"attr_id": 410,
"value": 0.0178,
"unit": "mg",
"name": "Pantothenic acid",
"usda_tag": "PANTAC"
}, {
"attr_id": 415,
"value": 0.016,
"unit": "mg",
"name": "Vitamin B-6",
"usda_tag": "VITB6A"
}, {
"attr_id": 417,
"value": 3,
"unit": "µg",
"name": "Folate, total",
"usda_tag": "FOL"
}, {
"attr_id": 431,
"value": 0,
"unit": "µg",
"name": "Folic acid",
"usda_tag": "FOLAC"
}, {
"attr_id": 432,
"value": 3,
"unit": "µg",
"name": "Folate, food",
"usda_tag": "FOLFD"
}, {
"attr_id": 435,
"value": 3,
"unit": "µg",
"name": "Folate, DFE",
"usda_tag": "FOLDFE"
}, {
"attr_id": 421,
"value": 1.34,
"unit": "mg",
"name": "Choline, total",
"usda_tag": "CHOLN"
}, {
"attr_id": 454,
"value": 0.020000000000000004,
"unit": "mg",
"name": "Betaine",
"usda_tag": "BETN"
}, {
"attr_id": 418,
"value": 0,
"unit": "µg",
"name": "Vitamin B-12",
"usda_tag": "VITB12"
}, {
"attr_id": 320,
"value": 8.4,
"unit": "µg",
"name": "Vitamin A, RAE",
"usda_tag": "VITA_RAE"
}, {
"attr_id": 319,
"value": 0,
"unit": "µg",
"name": "Retinol",
"usda_tag": "RETOL"
}, {
"attr_id": 321,
"value": 89.80000000000001,
"unit": "µg",
"name": "Carotene, beta",
"usda_tag": "CARTB"
}, {
"attr_id": 322,
"value": 20.200000000000003,
"unit": "µg",
"name": "Carotene, alpha",
"usda_tag": "CARTA"
}, {
"attr_id": 334,
"value": 0,
"unit": "µg",
"name": "Cryptoxanthin, beta",
"usda_tag": "CRYPX"
}, {
"attr_id": 318,
"value": 166.60000000000002,
"unit": "IU",
"name": "Vitamin A, IU",
"usda_tag": "VITA_IU"
}, {
"attr_id": 337,
"value": 514.6,
"unit": "µg",
"name": "Lycopene",
"usda_tag": "LYCPN"
}, {
"attr_id": 338,
"value": 24.6,
"unit": "µg",
"name": "Lutein + zeaxanthin",
"usda_tag": "LUT+ZEA"
}, {
"attr_id": 323,
"value": 0.10800000000000001,
"unit": "mg",
"name": "Vitamin E (alpha-tocopherol)",
"usda_tag": "TOCPHA"
}, {
"attr_id": 341,
"value": 0.002,
"unit": "mg",
"name": "Tocopherol, beta",
"usda_tag": "TOCPHB"
}, {
"attr_id": 342,
"value": 0.024,
"unit": "mg",
"name": "Tocopherol, gamma",
"usda_tag": "TOCPHG"
}, {
"attr_id": 343,
"value": 0,
"unit": "mg",
"name": "Tocopherol, delta",
"usda_tag": "TOCPHD"
}, {
"attr_id": 344,
"value": 0.002,
"unit": "mg",
"name": "Tocotrienol, alpha",
"usda_tag": "TOCTRA"
}, {
"attr_id": 345,
"value": 0,
"unit": "mg",
"name": "Tocotrienol, beta",
"usda_tag": "TOCTRB"
}, {
"attr_id": 346,
"value": 0,
"unit": "mg",
"name": "Tocotrienol, gamma",
"usda_tag": "TOCTRG"
}, {
"attr_id": 347,
"value": 0,
"unit": "mg",
"name": "Tocotrienol, delta",
"usda_tag": "TOCTRD"
}, {
"attr_id": 328,
"value": 0,
"unit": "µg",
"name": "Vitamin D (D2 + D3)",
"usda_tag": "VITD"
}, {
"attr_id": 324,
"value": 0,
"unit": "IU",
"name": "Vitamin D",
"usda_tag": "VITD"
}, {
"attr_id": 430,
"value": 1.58,
"unit": "µg",
"name": "Vitamin K (phylloquinone)",
"usda_tag": "VITK1"
}, {
"attr_id": 429,
"value": 0,
"unit": "µg",
"name": "Dihydrophylloquinone",
"usda_tag": "VITK1D"
}, {
"attr_id": 606,
"value": 0.005600000000000001,
"unit": "g",
"name": "Fatty acids, total saturated",
"usda_tag": "FASAT"
}, {
"attr_id": 607,
"value": 0,
"unit": "g",
"name": "4:0",
"usda_tag": "F4D0"
}, {
"attr_id": 608,
"value": 0,
"unit": "g",
"name": "6:0",
"usda_tag": "F6D0"
}, {
"attr_id": 609,
"value": 0,
"unit": "g",
"name": "8:0",
"usda_tag": "F8D0"
}, {
"attr_id": 610,
"value": 0,
"unit": "g",
"name": "10:0",
"usda_tag": "F10D0"
}, {
"attr_id": 611,
"value": 0,
"unit": "g",
"name": "12:0",
"usda_tag": "F12D0"
}, {
"attr_id": 612,
"value": 0,
"unit": "g",
"name": "14:0",
"usda_tag": "F14D0"
}, {
"attr_id": 613,
"value": 0.004,
"unit": "g",
"name": "16:0",
"usda_tag": "F16D0"
}, {
"attr_id": 614,
"value": 0.0016,
"unit": "g",
"name": "18:0",
"usda_tag": "F18D0"
}, {
"attr_id": 645,
"value": 0.006200000000000001,
"unit": "g",
"name": "Fatty acids, total monounsaturated",
"usda_tag": "FAMS"
}, {
"attr_id": 626,
"value": 0.0002,
"unit": "g",
"name": "16:1 undifferentiated",
"usda_tag": "F16D1"
}, {
"attr_id": 617,
"value": 0.006,
"unit": "g",
"name": "18:1 undifferentiated",
"usda_tag": "F18D1"
}, {
"attr_id": 628,
"value": 0,
"unit": "g",
"name": "20:1",
"usda_tag": "F20D1"
}, {
"attr_id": 630,
"value": 0,
"unit": "g",
"name": "22:1 undifferentiated",
"usda_tag": "F22D1"
}, {
"attr_id": 646,
"value": 0.0166,
"unit": "g",
"name": "Fatty acids, total polyunsaturated",
"usda_tag": "FAPU"
}, {
"attr_id": 618,
"value": 0.016,
"unit": "g",
"name": "18:2 undifferentiated",
"usda_tag": "F18D2"
}, {
"attr_id": 619,
"value": 0.0006000000000000001,
"unit": "g",
"name": "18:3 undifferentiated",
"usda_tag": "F18D3"
}, {
"attr_id": 627,
"value": 0,
"unit": "g",
"name": "18:4",
"usda_tag": "F18D4"
}, {
"attr_id": 620,
"value": 0,
"unit": "g",
"name": "20:4 undifferentiated",
"usda_tag": "F20D4"
}, {
"attr_id": 629,
"value": 0,
"unit": "g",
"name": "20:5 n-3 (EPA)",
"usda_tag": "F20D5"
}, {
"attr_id": 631,
"value": 0,
"unit": "g",
"name": "22:5 n-3 (DPA)",
"usda_tag": "F22D5"
}, {
"attr_id": 621,
"value": 0,
"unit": "g",
"name": "22:6 n-3 (DHA)",
"usda_tag": "F22D6"
}, {
"attr_id": 601,
"value": 0,
"unit": "mg",
"name": "Cholesterol",
"usda_tag": "CHOLE"
}, {
"attr_id": 636,
"value": 1.4000000000000001,
"unit": "mg",
"name": "Phytosterols",
"usda_tag": "PHYSTR"
}, {
"attr_id": 501,
"value": 0.0012000000000000001,
"unit": "g",
"name": "Tryptophan",
"usda_tag": "TRP_G"
}, {
"attr_id": 502,
"value": 0.0054,
"unit": "g",
"name": "Threonine",
"usda_tag": "THR_G"
}, {
"attr_id": 503,
"value": 0.0036,
"unit": "g",
"name": "Isoleucine",
"usda_tag": "ILE_G"
}, {
"attr_id": 504,
"value": 0.005000000000000001,
"unit": "g",
"name": "Leucine",
"usda_tag": "LEU_G"
}, {
"attr_id": 505,
"value": 0.0054,
"unit": "g",
"name": "Lysine",
"usda_tag": "LYS_G"
}, {
"attr_id": 506,
"value": 0.0012000000000000001,
"unit": "g",
"name": "Methionine",
"usda_tag": "MET_G"
}, {
"attr_id": 507,
"value": 0.0018,
"unit": "g",
"name": "Cystine",
"usda_tag": "CYS_G"
}, {
"attr_id": 508,
"value": 0.0054,
"unit": "g",
"name": "Phenylalanine",
"usda_tag": "PHE_G"
}, {
"attr_id": 509,
"value": 0.0028000000000000004,
"unit": "g",
"name": "Tyrosine",
"usda_tag": "TYR_G"
}, {
"attr_id": 510,
"value": 0.0036,
"unit": "g",
"name": "Valine",
"usda_tag": "VAL_G"
}, {
"attr_id": 511,
"value": 0.004200000000000001,
"unit": "g",
"name": "Arginine",
"usda_tag": "ARG_G"
}, {
"attr_id": 512,
"value": 0.0028000000000000004,
"unit": "g",
"name": "Histidine",
"usda_tag": "HISTN_G"
}, {
"attr_id": 513,
"value": 0.0054,
"unit": "g",
"name": "Alanine",
"usda_tag": "ALA_G"
}, {
"attr_id": 514,
"value": 0.027000000000000003,
"unit": "g",
"name": "Aspartic acid",
"usda_tag": "ASP_G"
}, {
"attr_id": 515,
"value": 0.0862,
"unit": "g",
"name": "Glutamic acid",
"usda_tag": "GLU_G"
}, {
"attr_id": 516,
"value": 0.0038,
"unit": "g",
"name": "Glycine",
"usda_tag": "GLY_G"
}, {
"attr_id": 517,
"value": 0.003,
"unit": "g",
"name": "Proline",
"usda_tag": "PRO_G"
}, {
"attr_id": 518,
"value": 0.0052,
"unit": "g",
"name": "Serine",
"usda_tag": "SER_G"
}, {
"attr_id": 221,
"value": 0,
"unit": "g",
"name": "Alcohol, ethyl",
"usda_tag": "ALC"
}, {
"attr_id": 262,
"value": 0,
"unit": "mg",
"name": "Caffeine",
"usda_tag": "CAFFN"
}, {
"attr_id": 263,
"value": 0,
"unit": "mg",
"name": "Theobromine",
"usda_tag": "THEBRN"
}],
"parsed_query": {
"qty": 1,
"unit": null,
"food": "tomato",
"query": "1 tomato"
},
"idx": 1
}],
"total": {
"nutrients": [{
"name": "Protein",
"unit": "g",
"usda_tag": "PROCNT",
"attr_id": 203,
"value": 41.29484
}, {
"name": "Total lipid (fat)",
"unit": "g",
"usda_tag": "FAT",
"attr_id": 204,
"value": 72.13972000000001
}, {
"name": "Carbohydrate, by difference",
"unit": "g",
"usda_tag": "CHOCDF",
"attr_id": 205,
"value": 9.169600000000003
}, {
"name": "Ash",
"unit": "g",
"usda_tag": "ASH",
"attr_id": 207,
"value": 15.477040000000002
}, {
"name": "Energy",
"unit": "kcal",
"usda_tag": "ENERC_KCAL",
"attr_id": 208,
"value": 845.028
}, {
"name": "Starch",
"unit": "g",
"usda_tag": "STARCH",
"attr_id": 209,
"value": 0
}, {
"name": "Sucrose",
"unit": "g",
"usda_tag": "SUCS",
"attr_id": 210,
"value": 0
}, {
"name": "Glucose (dextrose)",
"unit": "g",
"usda_tag": "GLUS",
"attr_id": 211,
"value": 0.25
}, {
"name": "Fructose",
"unit": "g",
"usda_tag": "FRUS",
"attr_id": 212,
"value": 0.274
}, {
"name": "Lactose",
"unit": "g",
"usda_tag": "LACS",
"attr_id": 213,
"value": 4.8762
}, {
"name": "Maltose",
"unit": "g",
"usda_tag": "MALS",
"attr_id": 214,
"value": 0
}, {
"name": "Alcohol, ethyl",
"unit": "g",
"usda_tag": "ALC",
"attr_id": 221,
"value": 0
}, {
"name": "Water",
"unit": "g",
"usda_tag": "WATER",
"attr_id": 255,
"value": 108.73948
}, {
"name": "Caffeine",
"unit": "mg",
"usda_tag": "CAFFN",
"attr_id": 262,
"value": 0
}, {
"name": "Theobromine",
"unit": "mg",
"usda_tag": "THEBRN",
"attr_id": 263,
"value": 0
}, {
"name": "Energy",
"unit": "kJ",
"usda_tag": "ENERC_KJ",
"attr_id": 268,
"value": 3537.0040000000004
}, {
"name": "Sugars, total",
"unit": "g",
"usda_tag": "SUGAR",
"attr_id": 269,
"value": 5.65168
}, {
"name": "Galactose",
"unit": "g",
"usda_tag": "GALS",
"attr_id": 287,
"value": 0.24948000000000004
}, {
"name": "Fiber, total dietary",
"unit": "g",
"usda_tag": "FIBTG",
"attr_id": 291,
"value": 0.24
}, {
"name": "Calcium, Ca",
"unit": "mg",
"usda_tag": "CA",
"attr_id": 301,
"value": 2372.06
}, {
"name": "Iron, Fe",
"unit": "mg",
"usda_tag": "FE",
"attr_id": 303,
"value": 1.4828400000000002
}, {
"name": "Magnesium, Mg",
"unit": "mg",
"usda_tag": "MG",
"attr_id": 304,
"value": 61.168000000000006
}, {
"name": "Phosphorus, P",
"unit": "mg",
"usda_tag": "P",
"attr_id": 305,
"value": 1458.588
}, {
"name": "Potassium, K",
"unit": "mg",
"usda_tag": "K",
"attr_id": 306,
"value": 346.77599999999995
}, {
"name": "Sodium, Na",
"unit": "mg",
"usda_tag": "NA",
"attr_id": 307,
"value": 3790.8280000000004
}, {
"name": "Zinc, Zn",
"unit": "mg",
"usda_tag": "ZN",
"attr_id": 309,
"value": 5.68132
}, {
"name": "Copper, Cu",
"unit": "mg",
"usda_tag": "CU",
"attr_id": 312,
"value": 0.11612800000000001
}, {
"name": "Fluoride, F",
"unit": "µg",
"usda_tag": "FLD",
"attr_id": 313,
"value": 79.83999999999999
}, {
"name": "Manganese, Mn",
"unit": "mg",
"usda_tag": "MN",
"attr_id": 315,
"value": 0.11578800000000002
}, {
"name": "Selenium, Se",
"unit": "µg",
"usda_tag": "SE",
"attr_id": 317,
"value": 45.8136
}, {
"name": "Vitamin A, IU",
"unit": "IU",
"usda_tag": "VITA_IU",
"attr_id": 318,
"value": 2309.86
}, {
"name": "Retinol",
"unit": "µg",
"usda_tag": "RETOL",
"attr_id": 319,
"value": 551.124
}, {
"name": "Vitamin A, RAE",
"unit": "µg",
"usda_tag": "VITA_RAE",
"attr_id": 320,
"value": 575.4
}, {
"name": "Carotene, beta",
"unit": "µg",
"usda_tag": "CARTB",
"attr_id": 321,
"value": 271.24
}, {
"name": "Carotene, alpha",
"unit": "µg",
"usda_tag": "CARTA",
"attr_id": 322,
"value": 20.200000000000003
}, {
"name": "Vitamin E (alpha-tocopherol)",
"unit": "mg",
"usda_tag": "TOCPHA",
"attr_id": 323,
"value": 1.9224000000000003
}, {
"name": "Vitamin D",
"unit": "IU",
"usda_tag": "VITD",
"attr_id": 324,
"value": 52.164
}, {
"name": "Vitamin D2 (ergocalciferol)",
"unit": "µg",
"usda_tag": "ERGCAL",
"attr_id": 325,
"value": 0
}, {
"name": "Vitamin D3 (cholecalciferol)",
"unit": "µg",
"usda_tag": "CHOCAL",
"attr_id": 326,
"value": 1.3608
}, {
"name": "Vitamin D (D2 + D3)",
"unit": "µg",
"usda_tag": "VITD",
"attr_id": 328,
"value": 1.3608
}, {
"name": "Cryptoxanthin, beta",
"unit": "µg",
"usda_tag": "CRYPX",
"attr_id": 334,
"value": 0
}, {
"name": "Lycopene",
"unit": "µg",
"usda_tag": "LYCPN",
"attr_id": 337,
"value": 514.6
}, {
"name": "Lutein + zeaxanthin",
"unit": "µg",
"usda_tag": "LUT+ZEA",
"attr_id": 338,
"value": 24.6
}, {
"name": "Tocopherol, beta",
"unit": "mg",
"usda_tag": "TOCPHB",
"attr_id": 341,
"value": 0.002
}, {
"name": "Tocopherol, gamma",
"unit": "mg",
"usda_tag": "TOCPHG",
"attr_id": 342,
"value": 0.31884
}, {
"name": "Tocopherol, delta",
"unit": "mg",
"usda_tag": "TOCPHD",
"attr_id": 343,
"value": 0.09072000000000001
}, {
"name": "Tocotrienol, alpha",
"unit": "mg",
"usda_tag": "TOCTRA",
"attr_id": 344,
"value": 0.047360000000000006
}, {
"name": "Tocotrienol, beta",
"unit": "mg",
"usda_tag": "TOCTRB",
"attr_id": 345,
"value": 0.045360000000000004
}, {
"name": "Tocotrienol, gamma",
"unit": "mg",
"usda_tag": "TOCTRG",
"attr_id": 346,
"value": 0.06804
}, {
"name": "Tocotrienol, delta",
"unit": "mg",
"usda_tag": "TOCTRD",
"attr_id": 347,
"value": 0.18144000000000002
}, {
"name": "Vitamin C, total ascorbic acid",
"unit": "mg",
"usda_tag": "VITC",
"attr_id": 401,
"value": 2.74
}, {
"name": "Thiamin",
"unit": "mg",
"usda_tag": "THIA",
"attr_id": 404,
"value": 0.04142
}, {
"name": "Riboflavin",
"unit": "mg",
"usda_tag": "RIBF",
"attr_id": 405,
"value": 0.5345120000000001
}, {
"name": "Niacin",
"unit": "mg",
"usda_tag": "NIA",
"attr_id": 406,
"value": 0.291168
}, {
"name": "Pantothenic acid",
"unit": "mg",
"usda_tag": "PANTAC",
"attr_id": 410,
"value": 0.9318040000000002
}, {
"name": "Vitamin B-6",
"unit": "mg",
"usda_tag": "VITB6A",
"attr_id": 415,
"value": 0.138472
}, {
"name": "Folate, total",
"unit": "µg",
"usda_tag": "FOL",
"attr_id": 417,
"value": 21.144000000000002
}, {
"name": "Vitamin B-12",
"unit": "µg",
"usda_tag": "VITB12",
"attr_id": 418,
"value": 3.402
}, {
"name": "Choline, total",
"unit": "mg",
"usda_tag": "CHOLN",
"attr_id": 421,
"value": 83.44160000000001
}, {
"name": "Dihydrophylloquinone",
"unit": "µg",
"usda_tag": "VITK1D",
"attr_id": 429,
"value": 0
}, {
"name": "Vitamin K (phylloquinone)",
"unit": "µg",
"usda_tag": "VITK1",
"attr_id": 430,
"value": 7.476800000000001
}, {
"name": "Folic acid",
"unit": "µg",
"usda_tag": "FOLAC",
"attr_id": 431,
"value": 0
}, {
"name": "Folate, food",
"unit": "µg",
"usda_tag": "FOLFD",
"attr_id": 432,
"value": 21.144000000000002
}, {
"name": "Folate, DFE",
"unit": "µg",
"usda_tag": "FOLDFE",
"attr_id": 435,
"value": 21.144000000000002
}, {
"name": "Betaine",
"unit": "mg",
"usda_tag": "BETN",
"attr_id": 454,
"value": 0.020000000000000004
}, {
"name": "Tryptophan",
"unit": "g",
"usda_tag": "TRP_G",
"attr_id": 501,
"value": 0.527376
}, {
"name": "Threonine",
"unit": "g",
"usda_tag": "THR_G",
"attr_id": 502,
"value": 1.756296
}, {
"name": "Isoleucine",
"unit": "g",
"usda_tag": "ILE_G",
"attr_id": 503,
"value": 2.1309839999999998
}, {
"name": "Leucine",
"unit": "g",
"usda_tag": "LEU_G",
"attr_id": 504,
"value": 3.8968879999999997
}, {
"name": "Lysine",
"unit": "g",
"usda_tag": "LYS_G",
"attr_id": 505,
"value": 3.443688
}, {
"name": "Methionine",
"unit": "g",
"usda_tag": "MET_G",
"attr_id": 506,
"value": 1.0785
}, {
"name": "Cystine",
"unit": "g",
"usda_tag": "CYS_G",
"attr_id": 507,
"value": 0.25128000000000006
}, {
"name": "Phenylalanine",
"unit": "g",
"usda_tag": "PHE_G",
"attr_id": 508,
"value": 2.1350519999999995
}, {
"name": "Tyrosine",
"unit": "g",
"usda_tag": "TYR_G",
"attr_id": 509,
"value": 2.0802880000000004
}, {
"name": "Valine",
"unit": "g",
"usda_tag": "VAL_G",
"attr_id": 510,
"value": 2.6957160000000004
}, {
"name": "Arginine",
"unit": "g",
"usda_tag": "ARG_G",
"attr_id": 511,
"value": 1.179024
}, {
"name": "Histidine",
"unit": "g",
"usda_tag": "HISTN_G",
"attr_id": 512,
"value": 1.241128
}, {
"name": "Alanine",
"unit": "g",
"usda_tag": "ALA_G",
"attr_id": 513,
"value": 1.3956840000000001
}, {
"name": "Aspartic acid",
"unit": "g",
"usda_tag": "ASP_G",
"attr_id": 514,
"value": 3.544668
}, {
"name": "Glutamic acid",
"unit": "g",
"usda_tag": "GLU_G",
"attr_id": 515,
"value": 9.323764
}, {
"name": "Glycine",
"unit": "g",
"usda_tag": "GLY_G",
"attr_id": 516,
"value": 0.8180120000000001
}, {
"name": "Proline",
"unit": "g",
"usda_tag": "PRO_G",
"attr_id": 517,
"value": 4.058184000000001
}, {
"name": "Serine",
"unit": "g",
"usda_tag": "SER_G",
"attr_id": 518,
"value": 2.484124
}, {
"name": "Cholesterol",
"unit": "mg",
"usda_tag": "CHOLE",
"attr_id": 601,
"value": 226.8
}, {
"name": "Fatty acids, total trans",
"unit": "g",
"usda_tag": "FATRN",
"attr_id": 605,
"value": 2.594592
}, {
"name": "Fatty acids, total saturated",
"unit": "g",
"usda_tag": "FASAT",
"attr_id": 606,
"value": 40.958876
}, {
"name": "4:0",
"unit": "g",
"usda_tag": "F4D0",
"attr_id": 607,
"value": 1.3948200000000002
}, {
"name": "6:0",
"unit": "g",
"usda_tag": "F6D0",
"attr_id": 608,
"value": 1.154412
}, {
"name": "8:0",
"unit": "g",
"usda_tag": "F8D0",
"attr_id": 609,
"value": 0.7529760000000001
}, {
"name": "10:0",
"unit": "g",
"usda_tag": "F10D0",
"attr_id": 610,
"value": 1.8189360000000003
}, {
"name": "12:0",
"unit": "g",
"usda_tag": "F12D0",
"attr_id": 611,
"value": 2.004912
}, {
"name": "14:0",
"unit": "g",
"usda_tag": "F14D0",
"attr_id": 612,
"value": 6.661116
}, {
"name": "16:0",
"unit": "g",
"usda_tag": "F16D0",
"attr_id": 613,
"value": 18.513148
}, {
"name": "18:0",
"unit": "g",
"usda_tag": "F18D0",
"attr_id": 614,
"value": 7.309096
}, {
"name": "20:0",
"unit": "g",
"usda_tag": "F20D0",
"attr_id": 615,
"value": 0.10659600000000001
}, {
"name": "18:1 undifferentiated",
"unit": "g",
"usda_tag": "F18D1",
"attr_id": 617,
"value": 16.344672000000003
}, {
"name": "18:2 undifferentiated",
"unit": "g",
"usda_tag": "F18D2",
"attr_id": 618,
"value": 2.2908039999999996
}, {
"name": "18:3 undifferentiated",
"unit": "g",
"usda_tag": "F18D3",
"attr_id": 619,
"value": 0.31358400000000003
}, {
"name": "20:4 undifferentiated",
"unit": "g",
"usda_tag": "F20D4",
"attr_id": 620,
"value": 0.10206
}, {
"name": "22:6 n-3 (DHA)",
"unit": "g",
"usda_tag": "F22D6",
"attr_id": 621,
"value": 0.013608000000000002
}, {
"name": "22:0",
"unit": "g",
"usda_tag": "F22D0",
"attr_id": 624,
"value": 0.047628000000000004
}, {
"name": "14:1",
"unit": "g",
"usda_tag": "F14D1",
"attr_id": 625,
"value": 0.55566
}, {
"name": "16:1 undifferentiated",
"unit": "g",
"usda_tag": "F16D1",
"attr_id": 626,
"value": 1.1342
}, {
"name": "18:4",
"unit": "g",
"usda_tag": "F18D4",
"attr_id": 627,
"value": 0.015876
}, {
"name": "20:1",
"unit": "g",
"usda_tag": "F20D1",
"attr_id": 628,
"value": 0.508032
}, {
"name": "20:5 n-3 (EPA)",
"unit": "g",
"usda_tag": "F20D5",
"attr_id": 629,
"value": 0.027216000000000004
}, {
"name": "22:1 undifferentiated",
"unit": "g",
"usda_tag": "F22D1",
"attr_id": 630,
"value": 0.002268
}, {
"name": "22:5 n-3 (DPA)",
"unit": "g",
"usda_tag": "F22D5",
"attr_id": 631,
"value": 0.047628000000000004
}, {
"name": "Phytosterols",
"unit": "mg",
"usda_tag": "PHYSTR",
"attr_id": 636,
"value": 1.4000000000000001
}, {
"name": "Fatty acids, total monounsaturated",
"unit": "g",
"usda_tag": "FAMS",
"attr_id": 645,
"value": 18.685448000000004
}, {
"name": "Fatty acids, total polyunsaturated",
"unit": "g",
"usda_tag": "FAPU",
"attr_id": 646,
"value": 2.9332480000000003
}, {
"name": "15:0",
"unit": "g",
"usda_tag": "F15D0",
"attr_id": 652,
"value": 0.705348
}, {
"name": "17:0",
"unit": "g",
"usda_tag": "F17D0",
"attr_id": 653,
"value": 0.43092
}, {
"name": "24:0",
"unit": "g",
"usda_tag": "F24D0",
"attr_id": 654,
"value": 0.020412
}, {
"name": "16:1 t",
"unit": "g",
"usda_tag": "F16D1T",
"attr_id": 662,
"value": 0.240408
}, {
"name": "18:1 t",
"unit": "g",
"usda_tag": "F18D1T",
"attr_id": 663,
"value": 1.914192
}, {
"name": "22:1 t",
"unit": "g",
"usda_tag": "F22D1T",
"attr_id": 664,
"value": 0
}, {
"name": "18:2 CLAs",
"unit": "g",
"usda_tag": "F18D2CLA",
"attr_id": 670,
"value": 0.040824
}, {
"name": "24:1 c",
"unit": "g",
"usda_tag": "F24D1C",
"attr_id": 671,
"value": 0.002268
}, {
"name": "20:2 n-6 c,c",
"unit": "g",
"usda_tag": "F20D2CN6",
"attr_id": 672,
"value": 0.020412
}, {
"name": "16:1 c",
"unit": "g",
"usda_tag": "F16D1C",
"attr_id": 673,
"value": 0.893592
}, {
"name": "18:1 c",
"unit": "g",
"usda_tag": "F18D1C",
"attr_id": 674,
"value": 14.42448
}, {
"name": "18:2 n-6 c,c",
"unit": "g",
"usda_tag": "F18D2CN6",
"attr_id": 675,
"value": 1.7917200000000002
}, {
"name": "22:1 c",
"unit": "g",
"usda_tag": "F22D1C",
"attr_id": 676,
"value": 0.002268
}, {
"name": "18:3 n-6 c,c,c",
"unit": "g",
"usda_tag": "F18D3CN6",
"attr_id": 685,
"value": 0.002268
}, {
"name": "17:1",
"unit": "g",
"usda_tag": "F17D1",
"attr_id": 687,
"value": 0.138348
}, {
"name": "20:3 undifferentiated",
"unit": "g",
"usda_tag": "F20D3",
"attr_id": 689,
"value": 0.07711200000000001
}, {
"name": "Fatty acids, total trans-monoenoic",
"unit": "g",
"usda_tag": "FATRNM",
"attr_id": 693,
"value": 2.1546
}, {
"name": "Fatty acids, total trans-polyenoic",
"unit": "g",
"usda_tag": "FATRNP",
"attr_id": 695,
"value": 0.43999200000000005
}, {
"name": "15:1",
"unit": "g",
"usda_tag": "F15D1",
"attr_id": 697,
"value": 0
}, {
"name": "18:3 n-3 c,c,c (ALA)",
"unit": "g",
"usda_tag": "F18D3CN3",
"attr_id": 851,
"value": 0.31071600000000005
}, {
"name": "20:3 n-3",
"unit": "g",
"usda_tag": "F20D3N3",
"attr_id": 852,
"value": 0.002268
}, {
"name": "20:3 n-6",
"unit": "g",
"usda_tag": "F20D3N6",
"attr_id": 853,
"value": 0.07484400000000001
}, {
"name": "22:4",
"unit": "g",
"usda_tag": "F22D4",
"attr_id": 858,
"value": 0.018144
}],
"serving_weight_grams": 246.8
},
"errors": null
}
|
import { createStore, combineReducers } from "redux";
import moviesReducers from "../Reducers/MoviesReducers";
const configurationStore = () => {
const store = createStore(
combineReducers({
moviesname: moviesReducers,
})
);
return store;
};
export default configurationStore;
|
import React from 'react';
import { headerMap } from './headerMap';
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table';
const makeTable = (type, rowObjs, headerWhitelist, editButtonCreationFunction, rowTapFunction) => {
// rowObjs is something like an organizationLocations
// headerWhitelist is the fields to be rendered: ['called', 'address']
// editButtonCreationFunction (if exists) is a function returning a jsx (react) component that will edit a particular row
const renderedHeaders = headerWhitelist.map((header, index) => {
return (
<TableHeaderColumn key={index}>{headerMap[header]}</TableHeaderColumn>
);
});
const renderedRows = rowObjs ? rowObjs.map((row, rowIndex) => {
const renderedColumns = headerWhitelist.map((header, headerIndex) => {
let cellContents = row[header];
switch (header) {
case 'fullName':
cellContents = (<a href={`/#/${type}/${row['_id']}`}>{row['givenName'] + ' ' + row['surName']}</a>);
break;
case 'lastInteraction':
cellContents = row['interactions'] && row['interactions'].length ? row['interactions'][row['interactions'].length - 1] : '';
break;
case 'countOfInteraction':
cellContents = row['interactions'] ? row['interactions'].length : 0;
break;
case 'countOfContactOrganization':
cellContents = row['organization_contacts'] ? row['organization_contacts'].length : 0;
break;
case 'countOfContactPerson':
cellContents = row['person_contacts'] ? row['person_contacts'].length : 0;
break;
case 'classifiers':
cellContents = row['classifiers'] ? row['classifiers'].length : 0;
break;
case 'contactNameOfPerson':
cellContents = row['forPerson'] ? row['forPerson']['called'] : '';
break;
case 'addDetailsDelete':
return null;
case 'action':
return null;
default:
break;
}
if(typeof cellContents === 'undefined') {
// return null;
cellContents = '';
}
if(Array.isArray(row[header]) && row[header][0]) {
cellContents = row[header].map(obj=>obj.called).join(', ');
} else if (row[header] && row[header].called) {
cellContents = row[header].called;
}
return (<TableRowColumn key={headerIndex}>{cellContents}</TableRowColumn>)
});
return (
<TableRow
key={rowIndex}
onTouchTap={rowTapFunction ? rowTapFunction(row):null}
style={{ background: rowIndex % 2 ? 'rgba(33, 92, 103, 0.1)' : 'white' }}
>
{renderedColumns}
{editButtonCreationFunction(row)}
</TableRow>
);
}) : null;
return (
<Table
fixedHeader={true}
>
<TableHeader
adjustForCheckbox={false}
displaySelectAll={false}
>
<TableRow>
{renderedHeaders}
</TableRow>
</TableHeader>
<TableBody
displayRowCheckbox={false}>
{renderedRows}
</TableBody>
</Table>
);
}
export { makeTable };
|
Page({
data: {
isBOrZ: 0,
introduction: "",
objective: "",
requirement: "",
subjectRequirement: "",
loreAndAbility: "",
internship: "",
careerCredentials: "",
famousScholar: ""
},
onLoad: function onLoad(options) {
var that = this;
var isBOrZ = options.isborz;
var temData = {};
switch (parseInt(isBOrZ)) {
case 0:
that.selectComponent("#navigationcustom").setNavigationAll("培养目标、培养要求、学科要求", true);
temData.famousScholar = options.famousScholar;
temData.introduction = options.introduction;
temData.objective = options.objective;
temData.requirement = options.requirement;
temData.subjectRequirement = options.subjectRequirement;
temData.loreAndAbility = options.loreAndAbility;
temData.isBOrZ = isBOrZ;
that.setData(temData);
break;
case 1:
that.selectComponent("#navigationcustom").setNavigationAll("主要职能、实习实训、学科内容", true);
temData.objective = options.objective;
temData.loreAndAbility = options.loreAndAbility;
temData.internship = options.internship;
temData.careerCredentials = options.careerCredentials;
temData.isBOrZ = isBOrZ;
that.setData(temData);
break;
}
}
}); |
import React,{Component} from 'react'
import axios from 'axios';
import ShowWords from './ShowWords';
//This component gets all the words for a user
//and displays them using ShowWords Component
class WordsForUser extends Component
{
constructor(props)
{
super(props)
this.state={
data:[],
length:0
}
}
//At the start, the data is collected from the database
componentDidMount()
{
axios.get('http://localhost:8080/users/words/'+this.props.userid)
.then(
response => {
this.setState(
{
data:response.data,
length:response.data.length
})
}
)
.catch(error =>{
alert('Unable to fetch data')
})
}
//Whenever a learnt word is removed or added
//the state is updated, and this method gathers the data again
async componentDidUpdate()
{
axios.get('http://localhost:8080/users/words/'+this.props.userid)
.then(
response => {
this.setState(
{
data:response.data,
length:response.data.length
})
}
)
.catch(error =>{
alert('Unable to fetch data')
})
}
render()
{
var flags=[false,false,false,false,false]
return(
<div>
<h1>You have learnt {this.state.data.length} word(s).</h1>
<br/>
<ShowWords data={this.state.data} len={this.state.length} flag="UserWords" flags={flags} userid={this.props.userid}/>
</div>
)
}
}
export default WordsForUser; |
var mongoose = require('mongoose'),
Favourite = mongoose.model('Favourite');
exports.clear = function () {
Favourite.remove({}, function (err) {
if (err) {
console.log(err);
} else {
console.log('Favourite collection dropped');
}
return;
})
}
exports.all = function (callback) {
Favourite.find(function (err, favourites) {
if (err) {
console.log(err);
return;
} else {
console.log('Favourites found: ' + favourites);
callback(favourites);
}
});
};
exports.find = function (queryData, callback) {
var query = queryBuilder(queryData);
Favourite.find(query, function (err, favourites) {
if (err) {
console.log(err);
callback(null);
} else if (favourites.length <= 0) {
console.log('No favourites found');
callback(null);
} else {
console.log('Favourites found: ' + favourites);
callback(favourites);
}
});
};
function queryBuilder(queryData) {
var query = {};
query.userId = queryData.userId;
if (queryData.productId) {
query.productId = queryData.productId;
}
return query;
}
exports.insert = function (favouriteData, callback) {
Favourite.create({
userId: favouriteData.userId,
productId: favouriteData.productId
},
function (err, favourite) {
if (err) {
console.log(err);
} else {
//console.log("Favourite created: " + favourite);
callback();
}
})
}
exports.delete = function (favouriteData, callback) {
Favourite.remove({
userId: favouriteData.userId,
productId: favouriteData.productId
},
function (err, favourite) {
if (err) {
console.log(err);
} else {
//console.log("Favourite deleted: " + favourite);
callback();
}
})
} |
$(document).ready(function () {
$('#show_pitch_form_button').on('click', function (event) {
event.preventDefault();
$('#add_pitch_form_container').removeClass('hide');
$(this).addClass('hide');
});
$('#new_pitch').on('submit', '.btn', function (event) {
var $form = $(this)
event.preventDefault();
$.ajax({
url: $form.attr('action'),
method: $form.attr('method'),
data: $form.serialize()
});
});
$('.datepicker').pickadate({
selectMonths: true, // Creates a dropdown to control month
selectYears: 15 // Creates a dropdown of 15 years to control year
});
}); |
var Service_TypeController = require('../controllers/Service_TypeController');
module.exports = function (app) {
app.post('/service_type/getServiceBy', function (req, res) {
Service_TypeController.getService_TypeBy(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/service_type/getService_TypeByService_TypeCode', function (req, res) {
Service_TypeController.getService_TypeByService_TypeCode(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/service_type/insertService_Type', function (req, res) {
Service_TypeController.insertService_Type(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/service_type/updateService_TypeByService_TypeCode', function (req, res) {
Service_TypeController.updateService_TypeByService_TypeCode(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/service_type/deleteService_TypeByService_TypeCode', function (req, res) {
Service_TypeController.deleteService_TypeByService_TypeCode(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
} |
module.exports = {
projects: [
'<rootDir>/apps/next',
'<rootDir>/libs/simple-components',
'<rootDir>/libs/graphql',
'<rootDir>/libs/theme',
],
}
|
extend(Array.prototype, function(){
function each(fn, context){
var self = this
, index = 0
, length = self.length
for(;index < length; index++) fn.call(context, self[index], index, self)
return self
}
function collect(fn, context){
var self = this
, mapped = Array(self.length)
, index = 0
, length = self.length
for(;index < length; index++) mapped[index] = fn.call(context, self[index], index, self)
return mapped
}
function select (fn, context){
var self = this
, filtered = []
, index = 0
, length = self.length
for(;index < length; index++) if(fn.call(context, self[index], index, self)) filtered.push(self[index])
return filtered
}
function fold(fn, initial){
var self = this
, hasInit = arguments.length != 1
, reduced = hasInit ? initial : self[0]
, index = hasInit ? 0 : 1
, length = self.length
for(;index < length; index++) reduced = fn(reduced, self[index], index, self)
return reduced
}
function find(search, start){
var self = this
, index = start || 0
, length = self.length
for(;index < length; index++) if(self[index] === search) return index
return -1
}
function contains(value){
return !!~this.find(value)
}
function pluck(property){
var self = this
, plucked = Array(self.length)
, index = 0
, length = self.length
for(;index < length; index++) plucked[index] = self[index][property]
return plucked
}
function isEmpty(){
var self = this
, index = 0
, length = self.length
for(;index < length; index++) return false
return true
}
function clone(){
return this.concat()
}
function clean(){
var self = this
, cleaned = []
, index = 0
, length = self.length
, item
for(;index < length; index++) {
item = self[index]
if(typeof item != "number" && !item) continue
if(typeof item == "object" && item.length === 0) continue
cleaned.push(item)
}
return cleaned
}
function intersect(values){
var self = this
, result = []
, index = 0
, length = self.length
, item
for(;index < length; index++) {
item = self[index]
if(values.contains(item)) result.push(item)
}
return result
}
function difference(values){
var self = this
, result = []
, index = 0
, length = self.length
, item
for(;index < length; index++) {
item = self[index]
if(!values.contains(item)) result.push(item)
}
return result
}
function invoke(fn){
var self = this
, index = 0
, length = self.length
, args = toArray(arguments, 1)
, result = []
for(;index < length; index++) result[index] = (typeOf(fn) == "string" ? Element.methods[fn] : fn).apply($(self[index]), args)
return result
}
function group(){
return this.fold(function(a,b){ return a.concat(b) }, [])
}
return {
each: each,
clone: clone,
collect: collect,
select: select,
fold: fold,
group: group,
find: find,
contains: contains,
pluck: pluck,
isEmpty: isEmpty,
invoke: invoke,
clean: clean,
intersect: intersect,
difference: difference
}
}) |
import React, { Component, PureComponent } from 'react';
import Token from './services/token';
import Feeds from './Feeds';
import Tags from './Tags';
import Tabs, {YOUR_FEED_UNI_ID, GLOBAL_FEED_UNI_ID} from './Tabs';
class Home extends PureComponent {
constructor(props) {
super(props);
this.token = Token.get();
this.state = {
activeFeed: this.token ? YOUR_FEED_UNI_ID : GLOBAL_FEED_UNI_ID
};
this.handleTagClick = this.handleTagClick.bind(this);
}
handleTagClick (activeFeed) {
this.setState({
activeFeed
});
}
render() {
return (
<div className="home-page">
{
!this.token &&
<div className="banner">
<div className="container">
<h1 className="logo-font">conduit</h1>
<p>A place to share your knowledge.</p>
</div>
</div>
}
<div className="container page">
<div className="row">
<div className="col-md-9">
<Tabs activeFeed={this.state.activeFeed} handleTabClick={this.handleTagClick}/>
<Feeds activeFeed={this.state.activeFeed}/>
</div>
<Tags handleTagClick={this.handleTagClick}/>
</div>
</div>
</div>
);
}
}
export default Home;
|
var logicRouter = require('./logic/__init__.js')(),
renderRouter = require('./render/__init__.js')();
module.exports = function(e, preHandle, callback){
var logicFunc = logicRouter(e.request.url),
renderFunc = renderRouter(e.request.url);
if(!logicFunc) return callback(400);
preHandle(logicFunc)(e, function(err, result){
// (err, result) corresponds to the parameter for each handler.
if(302 == err || 418 == err) return callback(err, result);
if(401 == err){
return callback(
302,
'/authenticate/?' + $.nodejs.querystring.stringify({
'redirect': result,
})
);
};
if(!renderFunc) return callback(null, JSON.stringify(result));
return callback(null, renderFunc(result));
});
};
|
var endereco;
$(function () {
initMasks();
validaDadosCliente();
buildCardEnderecos();
validaNewEndereco();
buildCompletes();
$('#cadNewEndCep').mask("99999-999");
$('#titleEnderecos').hide();
$('#msgSemEndereco').hide();
});
function validateAndSaveAddress(event) {
event.preventDefault();
}
function buildEndereco(callback) {
let idEstado = $('#cadNewEndEstado').val().split(" ");
let idCidade = $('#cadNewEndCidade').val().split(" ");
endereco = new Endereco(
$('#cadNewEndCod').val() != '' ? $('#cadNewEndCod').val() : null,
$('#cadNewEndRua').val(),
$('#cadNewEndBairro').val(),
$('#cadNewEndNro').val(),
null,
null,
removeSimbolos($('#cadNewEndCep').val()),
$('#cadNewEndTipo').val()
);
findObjectsEstadoAndCidade(idEstado[0], idCidade[0], function (complete) {
if (complete) {
callback(complete);
}
});
}
function findObjectsEstadoAndCidade(idEstado, idCidade, onComplete) {
$.get(`http://localhost:8025/fornecedor/estado/${idEstado}`, function (estado) {
endereco.estado = estado;
$.get(`http://localhost:8025/fornecedor/cidade/${idCidade}`, function (cidade) {
endereco.cidade = cidade;
onComplete(true);
});
});
}
function saveEndereco() {
buildEndereco(function (callback) {
if (callback) {
if (endereco.id != null) {
enderecosList.forEach((enderecoo, index) => {
if (enderecoo.id == Number(endereco.id)) {
console.log(index);
enderecosList.splice(index, 1);
}
});
}
enderecosList.push(endereco);
save();
}
});
}
function save() {
$.ajax({
type: 'POST',
url: `/cliente/endereco/save/${$('#usuario').text()}`,
data: JSON.stringify(enderecosList),
contentType: "application/json; charset=utf-8",
success: function (data) {
swal({
title: 'Salvo!',
text: 'Registro salvo com sucesso!',
type: 'success'
}, function () {
clearForm();
window.location = '/cliente/endereco';
});
}, error: function (data) {
console.log(data);
swal(
'Atenção!',
'Ocorreu um erro ao salvar o registro. Por favor, tente novamente!',
'error'
);
}
});
}
function excluir(id) {
$.ajax({
type: 'DELETE',
url: `/cliente/endereco/delete/${$('#usuario').text()}/${id}`,
contentType: "application/json; charset=utf-8",
success: function (data) {
swal({
title: 'Removido!',
text: 'Registro removido com sucesso!',
type: 'success'
}, function () {
window.location = '/cliente/endereco';
});
}, error: function (data) {
console.log(data);
swal(
'Atenção!',
'Ocorreu um erro ao remover o registro. Por favor, tente novamente!',
'error'
);
}
});
}
function edit(id) {
enderecosList.forEach(endereco => {
if (endereco.id == id) {
$('#cadNewEndCod').val(endereco.id),
$('#cadNewEndRua').val(endereco.endereco),
$('#cadNewEndBairro').val(endereco.bairro),
$('#cadNewEndCep').val(endereco.cep),
$('#cadNewEndNro').val(endereco.nro),
$('#cadNewEndCidade').val(endereco.cidade.id),
$('#cadNewEndTipo').val(endereco.tipoEndereco),
$('#cadNewEndEstado').val(endereco.estado.id)
}
});
findDadosOnEdit();
}
function buildCardEnderecos() {
findEnderecos(function (callback) {
if (callback) {
dropListEnderecos();
if (enderecosList != null) {
$('#titleEnderecos').show();
enderecosList.forEach(endereco => {
if (endereco.tipoEndereco == 'P') {
$('#enderecos').append(`
<div id="card-endereco" class="card my-2 card-endereco">
<div class="card-header">
<div class="d-flex justify-content-between">
<h6 class="font-weight-bolder">${getTipoEndereco(endereco.tipoEndereco)}</h6>
</div>
</div>
<div class="card-body" style="height: auto;">
<p><strong>Rua: </strong>${endereco.endereco}</p>
<p><strong>Bairro: </strong>${endereco.bairro}</p>
<p><strong>Cidade: </strong>${endereco.cidade.nome}</p>
<p><strong>Estado: </strong>${endereco.estado.nome}</p>
<p><strong>Número: </strong>${endereco.nro}</p>
</div>
</div>
`);
} else {
$('#enderecos').append(`
<div id="card-endereco" class="card my-2 card-endereco">
<div class="card-header">
<div class="d-flex justify-content-between">
<h6 class="font-weight-bolder">${getTipoEndereco(endereco.tipoEndereco)}</h6>
<div>
<i class="fa fa-pencil pointer mx-2" onclick="edit(${endereco.id})"></i>
<i class="fa fa-trash pointer" onclick="excluir(${endereco.id})"></i>
</div>
</div>
</div>
<div class="card-body" style="height: auto;">
<p><strong>Rua: </strong>${endereco.endereco}</p>
<p><strong>Bairro: </strong>${endereco.bairro}</p>
<p><strong>Cidade: </strong>${endereco.cidade.nome}</p>
<p><strong>Estado: </strong>${endereco.estado.nome}</p>
<p><strong>Número: </strong>${endereco.nro}</p>
</div>
</div>
`);
}
});
} else {
$('#msgSemEndereco').show();
}
}
});
}
function dropListEnderecos() {
$('div#card-endereco').remove();
}
function clearForm() {
$('#formNewEndereco')[0].reset();
}
function buildCompletes() {
$("#cadNewEndEstado").autocomplete({
source: function (request, response) {
$.ajax({
url: 'http://localhost:8025/fornecedor/estado/complete',
type: 'GET',
dataType: 'json',
data: {
'texto': request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.nome,
value: item.id + " - " + item.nome,
}
}));
}
});
}, select(event, ui) {
habilitaCidade();
}
});
$("#cadNewEndCidade").autocomplete({
source: function (request, response) {
var idEstado = $('#cadNewEndEstado').val().split(" ");
idEstado = idEstado[0];
$.ajax({
url: `http://localhost:8025/fornecedor/cidade/complete/${idEstado}`,
type: 'GET',
dataType: 'json',
data: {
'texto': request.term
}
, success: function (data) {
response($.map(data, function (item) {
return {
label: item.nome,
value: item.id + " - " + item.nome
}
}));
}
});
}
});
}
function findDadosOnEdit() {
let cidade = $('#cadNewEndCidade').val();
let estado = $('#cadNewEndEstado').val();
if (cidade != null && cidade !== "" &&
estado != null && estado !== "") {
$.get(`http://localhost:8025/fornecedor/estado/${$('#cadNewEndEstado').val()}`, function (data) {
if (data != null) {
$('#cadNewEndEstado').val(data.id + " - " + data.nome);
}
});
$.get(`http://localhost:8025/fornecedor/cidade/${$('#cadNewEndCidade').val()}`, function (data) {
if (data != null) {
$('#cadNewEndCidade').val(data.id + " - " + data.nome);
}
});
}
} |
import React from 'react'
// 返回一个对象
//下面这个对象上有两个属性
const ThemeContext = React.createContext({
theme: 'aqua',
toggleTheme: () => {
}
})
class Context1 extends React.Component {
constructor() {
super();
this.handleToggleBlue = () => {
this.setState(state => {
return {
theme: 'blue'
}
})
}
this.state = {
theme: 'aqua',
handleToggleBlue: this.handleToggleBlue
}
}
// state = {}放外面 是 static(静态) 属性 则下面不能用this访问
handleToggleTheme = () => {
this.setState({
theme: 'red'
})
}
// handleToggleBlue = () => {
// this.setState({
// theme: 'blue'
// })
// }
render() {
const msgs = ['msg1','msg2','msg3']
return (
<ThemeContext.Provider value={ this.state }>
<button onClick={this.handleToggleTheme}>切换主题</button>
<button onClick={this.handleToggleBule}>切换蓝色主题</button>
{
msgs.map((msg,i) => {
return <Message key={i} text={msg} />
})
}
</ThemeContext.Provider>
)
}
}
class Message extends React.Component {
shouldComponentUpdate() {
return false
}
render() {
return (
<div>
{ this.props.text }
<MyButton>delete?</MyButton>
</div>
)
}
}
class MyButton extends React.Component {
render() {
return (
<ThemeContext.Consumer>
{
(value) => {
return (
<button style={ {backgroundColor: value.theme} } onClick={ value.handleToggleBlue }>
{ this.props.children }
</button>
)
}
}
</ThemeContext.Consumer>
)
}
}
export default Context1 |
function get_file() {
const category_id = "{{ lab_object.category.id }}";
var request = new XMLHttpRequest();
function reqReadyStateChange() {
if (request.readyState == 4 && request.status == 200)
location.reload();
}
request.open("GET", "{% url 'inc_download_category' %}?" + `category=${category_id}&lab={{ lab_object.id }}`);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.onreadystatechange = reqReadyStateChange;
request.send();
window.location.href = '{{ lab_object.file.url }}';
}
function add_reputation(){
alert({{ user.get_fullname }})
}
function sub_reputation(){
} |
/**
* @author v.lugovsky
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.emergency', [])
.config(routeConfig);
/** @ngInject */
function routeConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('emergency', {
url: '/emergency',
template : '<ui-view autoscroll="true" autoscroll-body-top></ui-view>',
abstract: true,
// controller: 'LawsPageCtrl',
title: '风险应急管理',
sidebarMeta: {
icon: 'ion-battery-charging',
order: 1300,
},
}).state('emergency.sys', {
url: '/sys',
// templateUrl: 'app/pages/laws/nationLaws/nationLaws.html',
title: '应急体系',
sidebarMeta: {
order: 0,
},
}).state('emergency.staff', {
url: '/staff',
templateUrl: 'app/pages/laws/nationLaws/nationLaws.html',
title: '应急资源',
sidebarMeta: {
order: 100,
},
}).state('emergency.plan', {
url: '/plan',
// templateUrl: 'app/pages/laws/nationLaws/nationLaws.html',
title: '应急预案',
sidebarMeta: {
order: 101,
},
}).state('emergency.practice', {
url: '/practice',
// templateUrl: 'app/pages/laws/nationLaws/nationLaws.html',
title: '救援演练',
sidebarMeta: {
order: 101,
},
}).state('emergency.fireAlert', {
url: '/fireAlert',
templateUrl: 'app/pages/emergency/fireAlert/fireAlert.html',
controller: 'fireAlertPageCtrl',
title: '火灾报警管理',
sidebarMeta: {
order: 101,
},
});
// 默认显示
$urlRouterProvider.when('/emergency','/emergency/sys');
}
})();
|
const USER_NAME = "user";
export const setUser = (user) => {
localStorage.setItem(USER_NAME, JSON.stringify(user));
};
export const getUser = () => {
return localStorage.getItem(USER_NAME);
};
export const scrollToTop = () => window.scrollTo(0, 0);
export function checkTextFormat(string, lengthLimit, setErrorMessages) {
if (string.length > lengthLimit + 1) {
setErrorMessages(`長度最多 ${lengthLimit} 個字元`);
return false;
}
if (string.match(/[\s]/g) !== null) {
setErrorMessages('不得含空白字元');
return false;
}
return true;
}
|
const { Joi } = require('celebrate');
const create = {
body: Joi.object({
title: Joi.string()
.required(),
}).unknown()
.required(),
};
const update = {
params: Joi.object({
todoID: Joi.number()
.required(),
}),
body: Joi.object({
title: Joi.string()
.required(),
}).unknown()
.required(),
};
const getByID = {
params: Joi.object({
todoID: Joi.number()
.required(),
}),
};
const get = {
query: Joi.object({
pageNumber: Joi.number()
.required(),
pageLength: Joi.number()
.min(10)
.max(100)
.default(50),
}),
};
const markDone = {
params: Joi.object({
todoID: Joi.number()
.required(),
}),
};
module.exports = {
create,
update,
getByID,
get,
markDone,
};
|
import React from 'react';
import './style.css';
import {
IoIosStar,
IoIosCheckmarkCircle,
} from 'react-icons/io';
import { generatePublicUrl } from '../../../urlConfig';
const ReviewItem = (props) => {
const { review } = props;
const formatDate = (date) => {
if(date){
const d = new Date(date);
return `${d.getDate()}/${d.getMonth() + 1}/${d.getFullYear()}`
}
return "";
};
return (
<div className="productReviewContainer">
<div className="ratingReview">
<span >{review.rating}</span>
<IoIosStar />
</div>
<div className="flexRow" style={{ margin: "12px 0", alignItems: 'center', fontSize: 14 }}>
{review.review}
</div>
<div className="flexRow">
{review.productPictures.map((image, index) => (
<div key={index} className="thumbnail">
<img src={generatePublicUrl(image.img)} alt={image.img} />
</div>
))}
</div>
<div className="flexRow">
<p style={{ color: 'rgb(138, 138, 138)', fontSize: 12, fontWeight: 'bold' }}>{review.firstName} {review.lastName}</p>
<div style={{ display: 'flex', alignItems: 'center', marginLeft: 10 }}>
<IoIosCheckmarkCircle color='rgb(138, 138, 138)' />
<span style={{ color: 'rgb(138, 138, 138)', fontSize: 12, textAlign: 'center', marginLeft: 4 }}>Certified buyer at {formatDate(review.createdAt)}</span>
</div>
</div>
</div>
)
}
export default ReviewItem
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const express_1 = __importDefault(require("express"));
const body_parser_1 = __importDefault(require("body-parser"));
const user_1 = __importDefault(require("./routes/user/user"));
const contacts_1 = __importDefault(require("./routes/contact/contacts"));
const auth_1 = __importDefault(require("./routes/auth/auth"));
const connection_1 = __importDefault(require("./database/connection"));
const cors_1 = __importDefault(require("cors"));
const path_1 = __importDefault(require("path"));
const app = express_1.default();
const port = parseInt(process.env.PORT || "8080");
//connecting the database
connection_1.default();
//middleware
app.use(body_parser_1.default.urlencoded({ extended: true }));
app.use(body_parser_1.default.json());
app.use(cors_1.default());
// Route Setup
app.use("/api/user", user_1.default);
app.use("/api/contact", contacts_1.default);
app.use("/api/auth", auth_1.default);
if (process.env.NODE_ENV === "production") {
app.use(express_1.default.static("client/build"));
app.get("*", (request, response) => {
response.sendfile(path_1.default.resolve(__dirname, "client", "build", "index.html"));
});
}
app.listen(port, error => {
console.log(`server running at port ${port}`);
if (error) {
console.log(error);
}
});
|
import { Dlg } from '@/assets/dialog/fm.dialog.min.js'
export default {
data () {
return {
}
},
mounted () {
},
methods: {
mixShowDlg (content) {
Dlg.msg({
content: content,
msgType: 'inverse'
})
}
}
}
|
const express = require('express');
const app = express();
app.use('/api/appareils', (req, res, next) => {
appareils = [
{
id: 'abc12345',
name: 'Refregirateur',
status: 'éteint'
},
{
id: 'zer12345',
name: 'Télévision',
status: 'allumé'
},
{
id: 'fre78956',
name: 'Ordinateur',
status: 'éteint'
}
];
res.status(200).json({
message: 'Requete réussie !',
appareils: appareils
});
});
app.use((req, res, next)=> {
console.log('Hello Premier midleware !');
next();
});
app.use((req, res, next)=> {
res.end('Message from express !!!');
});
module.export = app;
|
/* al presionar el botón mostrar 10 repeticiones con números ASCENDENTE, desde el 1 al 10.
*/
function mostrar()
{
for (var i = 1; i < 11 ; i++)
{
document.write (i);
}
} |
import Vue from 'vue'
import Vuetify from 'vuetify/lib'
Vue.use(Vuetify)
export default new Vuetify({
theme: {
dark: true,
themes: {
dark: {
primary: '#51D6FF',
secondary: '#2F9C95',
accent: '#B4ADEA',
anchor: '#8c9eff',
success: '#37FF8B',
warning: '#FFFD82',
error: '#E84855',
},
},
},
})
|
import SingletonAxios from "../utils/SingletonAxios";
import Client from "../client";
import ConstantType from "../constant/ConstantType";
export default {
baseUrl() {
return Client.getInstance().openApiUrl
},
/**
* 获取用户所在所有群组及群成员
*/
queryGroupByUser() {
return SingletonAxios.getInstance()({
url: this.baseUrl() + "/im/group/queryGroupByUser",
method: "get",
params: {
imUid: Client.getInstance().account,
groupName: ""
}
})
},
/**
* 获取群成员信息
* @param {string} groupId
*/
queryUserGroupByGroup(groupId) {
return SingletonAxios.getInstance()({
url: this.baseUrl() + "/im/group/queryUserGroupByGroup",
method: "get",
params: {
groupId: groupId
}
});
},
/**
* 获取消息已读详情
* @param {Long} sequenceId
*/
getReadState(sequenceId) {
return SingletonAxios.getInstance()({
url: this.baseUrl() + "/im/chat/getReadState/" + sequenceId.toString(),
method: "get"
});
},
/**
* 查询所有联系人
*/
findAllUserByCurUser() {
return SingletonAxios.getInstance()({
url: this.baseUrl() + "/im/user/findAllUserByCurUser",
method: "get"
});
},
/**
* 根据Id查询用户信息
* @param {Number} imUid
*/
findUserById(imUid) {
return SingletonAxios.getInstance()({
url: this.baseUrl() + "/im/user/findById",
method: "get",
params: {
imUid: imUid
}
});
},
/**
* 根据Id查询用户信息
* @param {Number} imUid
*/
getPublicAccountAll() {
return SingletonAxios.getInstance()({
url: this.baseUrl() + "/im/publicaccount/getList",
method: "post",
data: {}
});
},
/**
* 获取OSS STS
*/
getOssSTS() {
return SingletonAxios.getInstance()({
url: this.baseUrl() + "/user/getOssSTS",
method: "get"
});
},
/**
* 获取转译后的群名称
*/
getEscapeGroupName(groupName) {
return SingletonAxios.getInstance()({
url: this.baseUrl() + "/im/group/getEscapeGroupName",
method: "get",
params: {
groupName: groupName
}
});
}
}
|
export default {
label: 'Good Citizen',
id: 'good-citizen',
list: [
{
id: 'reading',
type: 'passage',
label: 'Good Citizen - Passage',
data: {
title: 'Good Citizen',
text: `Man is a social animal. Human beings are bestowed with senses. Human beings think and act using their senses. They are born free but bound in the social web. They cannot live alone. They need social and emotional support. To live in the society they need to develop some good values.
We are born with few values and rights. These values are further polished in educational institutions. The aim of education is to change a person into a valuable person.
Good values are the qualities of a person that keep society running. These qualities can be developed by all. The term ‘civic’ relates to people or civilian or citizen of a country. People should live together in unity.
Living together in harmony despite all the disparities is a significant value. Helping others is also an important value. There should be no disparity among people and all are one. Today’s children are tomorrow’s citizens of the nation. Moral and good values have to be grown among children so that they may become valuable citizens.
# Personal values
Personal value is the basic value for every individual. We must bring out the hidden values of a person that they acquire from their experiences. This leads to their overall development.
# Cultural values
To become well mannered or cultured is an essence of the society. Irrespective of language and religion people live together in harmony. This help to maintain cultural values.
# Social values
We can maintain good values in public places by following the points given below.
1. Maintain good relations with people
2. Respect elders
3. Respect nature
4. Be tolerant
5. Maintain friendship
# Disciplinary values
Punctuality, involvement, treating everyone as equal, doing work on time, holding your morals, doing duties without fail, etc. are disciplinary values.
# Constitutional values:
1. Safeguard the public properties
2. Maintain the unity and integrity of the nation
3. Develop scientific attitude
4. Protect the natural resources
5. Care for the environment
6. Honour the national symbols
7. Respect martyrs and their sacrifices
8. Preserve our culture and heritage
9. Develop patriotism
A citizen is a person who is a member of a particular country and enjoys various rights and executes his duties. A sovereign state provides Citizenship to its people. Right to live, right to vote, right to work and reside anywhere in the country are the other rights enjoyed by the citizens.
There are some negative factors that affect our values:
1. Extreme faith in religion leads to communalism.
2. Don’t break the queue / rules.
3. Spitting and dumping garbage anywhere.
4. Polluting land and water.
Factors that enriches good values are:
1. Literacy
2. Creating awareness and interests
3. Trying hard till success
4. One’s own evaluation
5. Acceptance
6. Self confidence
One main feature of good value is to preserve hygiene. Each person should be taught to be hygienic and follow the routine below.
1. Wakeup early
2. Brush your teeth
3. Have a bath
4. Wear clean clothes
5. Wear slippers / shoes
6. Trim hair and cut the nails
7. Wash hands before and after meals.`
}
/*
Sambhar Salt Lake in Rajasthan is one of the important inland salt water lake in India.*/
},
{
id: 'mcq',
label: 'Multiple Choice Questions',
type: 'mcq',
data: {
editable: true,
title: 'Multiple Choice Questions',
questions: [
{
qText: 'Man is a ______ animal.',
options: 'social, mathematical, scientific'
},
{
qText: `The love for one's country is known as _____.`,
options: 'patriotism, criticism, communism'
},
{
qText: 'Which of the following are considered as bad values?',
options:
'* Polluting land and water, Self Confidence, Trying hard till success, * Breaking the queue'
},
{
qText: 'Which of the following helps in protecting nature?',
options:
'Reducing the use of plastic paper, Respecting elders, Treating everyone as equal'
},
{
qText:
'What should we do while living with people from different cultural background? ',
options: `Showing respect to different religions and languages.
Have different types of foods from various cultural background.
Learn atleast four different languages.`
}
]
}
},
{
label: 'True or False',
id: 'truefalse',
type: 'classifySentence',
data: {
title: 'Classify the below sentences as True or False.',
types: [
{
name: 'True',
text: `We are born with values and rights.
Honouring national symbol is a constitutional value.`
},
{
name: 'False',
text: `Human beings can live alone in this world.
Being punctual is a social value.
We are born with values, and it cannot be modified.`
}
]
}
},
{
label: 'Personal vs Social Values',
type: 'group',
id: 'group',
data: {
title: 'Classify the below as Personal or Social Values.',
types: [
{
name: 'Social Value',
text: 'respect elders, respect nature, tolerance'
},
{
name: 'Personal Value',
text: 'punctuality, hardwork, hygiene'
}
]
}
},
{
type: 'match',
label: 'Match ',
id: 'match',
data: {
title: 'Match the related words.',
text: `Literacy, Education
Punctuality, Time
Plastic, Pollution
Country, Citizen
Elders, Respect
Cultural, Tolerance`
}
},
{
label: 'Fill Up',
id: 'fillup',
type: 'matchByDragDrop',
data: {
isPractice: false,
title: 'Drag and drop the words at proper places.',
styles: {
dashWidth: 80
},
text: `We show *love* to all living beings. Help the poor with *generosity*. *honesty* is the best policy. The best relationship is *friendship*.
We show *hospitality* to our guests. We show *mercy* to those who suffer. Always speak the *truth*. We must maintain *peace* in public.`
}
},
{
type: 'rightOne',
id: 'spell',
label: 'Right Spelling',
data: {
title: 'Pick the word with the right spelling',
noCaps: true,
text: `pollution, pollusion, pollucion
education, etucation, edukation
society, socaity, sosaity
cultural, caltural, culturel
tolerance, toleranse, tolarance
hygiene, hygene, hygine
hospitality, haspitality, haspitelity
generosity, generocity, ganerosity
significant, significent, signeficant`
}
},
{
type: 'match',
label: 'Match - 2 ',
id: 'match-2',
data: {
title: 'Match the related words.',
text: `Public Property, Bus
National Symbol, Tricolor Flag
Environment, Tree
Different Languages, Harmony
Education, Empowerment`
}
},
{
type: 'match',
label: 'Match - 3',
id: 'match-3',
data: {
title: 'Match the related words.',
text: `Personal character,Punctuality
Culture, Language
Society,Tolerance
Duty,Good value
Unemployment, Affecting factor`
}
}
]
};
|
export const disenoApp = {
/* SEO */
titleSEO: 'Desarrollo de aplicaciones móviles',
descriptionSEO: 'Desarrollamos su aplicación móvil para ayudar a aumentar la presencia en línea de su empresa, tenemos cientos de clientes satisfechos ¡Comienza ahora!',
/* ** */
startWith: 'A PARTIR DE:',
list: ['Fideliza a tus clientes', 'Aumenta la visibilidad de tu empresa', 'Ofrece otro canal de venta y contacto', 'Fortalece tu marca', 'Adáptate a posibles nuevos clientes. '],
title: 'Aplicación para Móviles',
description: `Desarrollar una aplicación móvil ayuda a aumentar la presencia en línea de tu empresa y conectarse con los usuarios a través de una nueva plataforma digital.`,
shortDescription: `Desarrolla una aplicación móvil para ayudar a aumentar la presencia en línea de su empresa y conectarse con los usuarios a través de una nueva plataforma digital`,
icon: '/icons/app.svg',
whatWeOffer: [
{
title: 'ORIGINAL',
description: 'Diseño Gráfico, Estructura, Navegación y funcionalidades conformes a los resultados que desea lograr.',
icon: '/icons/logo-unico-original.svg'
}, {
title: 'GARANTIA DE CONFORMIDAD',
description: 'Conceptos y perfeccionamientos hasta su entera aprobación',
icon: '/icons/garantia-de-conformidad.svg'
}, {
title: 'VERSATILIDAD',
description: 'Gracias a las múltiples integraciones su app puede ser escalable a las necesidades de su negocio',
icon: '/images/pages/app/versatilidad.svg'
}, {
title: 'INTEGRACIÓN',
description: 'Vinculamos la app con su web, con algún gestor de contenido o api.',
icon: '/images/pages/app/integracion.svg'
}, {
title: 'EQUIPO INTERDISCIPLINARIO',
description: 'Su proyecto en manos de nuestros expertos en diseño, publicidad y programación.',
icon: '/icons/equipo-interidisciplinario.svg'
}, {
title: 'PUBLICACIÓN PARA MÚLTIPLES DISPOSITIVOS',
description: 'Su app estará disponible para la descarga en la play store y apple store.',
icon: '/images/pages/app/multiples-dispositivos.svg'
}
],
whatYouGet: {
noCarrito: true,
noMaxWidth: true,
notShowPrice: true,
img: '/images/pages/app/bonorum.jpg',
color: 'black',
columns: [
[
{
title: 'APLICACIÓN MOVIL',
description: 'Aplicación móvil lista para ser instalada en cualquier dispositivo Android y/o Ios, diseñada y desarrollada bajo un estricto proceso de planificación que se centra en las necesidades del usuario y garantiza que su experiencia móvil sea atractiva y conducente al logro de sus objetivos comerciales. ',
items: ['Instalador de la aplicación (.APK)', 'Disponible en para descarga en play store y iTunes', 'Código fuente para el mantenimiento y crecimiento de su app', 'Manual de uso e implementación', 'Garantía de entera conformidad y confidencialidad', 'Soporte postventa por 2 años.'],
icon: '/icons/app.svg'
}
]
]
},
topSliderHeight: '590px',
topSliderStylesXS: {
mt: '',
mh: ''
},
topSliderStylesSM: {
mt: '',
mh: ''
},
arrowsTop: '',
topSliderBgSize: '',
topSlider: [
{
url: '/images/pages/app/rocabike.jpg',
color: '#c8171f'
},
{
url: '/images/pages/app/extremadura.jpg',
color: '#7FC670'
},
{
url: '/images/pages/app/aixo-hotel.jpg',
color: '#003995'
},
{
url: '/images/pages/app/movil-market.jpg',
color: '#003995'
},
{
url: '/images/pages/app/univiajes-express.jpg',
color: '#7FC670'
},
{
url: '/images/pages/app/omkel.jpg',
color: '#E59E8F'
}
],
creativeProcess: [
{
src: '/images/carousels/creative-process/1.jpg',
alt: 'desarrollo de aplicacion'
},
{
src: '/images/carousels/creative-process/2.jpg',
alt: 'desarrollo de app'
},
{
src: '/images/carousels/creative-process/3.jpg',
alt: 'desarrollo de app'
}
],
steps: [
{
title: '1. Brief e investigación',
color: '#323c9e',
icon: '/icons/creative-process-1.svg',
description: 'Todas las aplicaciones comienzan con una idea. En esta etapa se refina esa idea en una base sólida para su app. Se asegura de que su análisis inicial incluya preferencias de diseño, funcionalidades básicas y objetivos.',
alt: 'brief-y-selector'
},
{
title: '2. Diseño de conceptos',
color: '#1d8127',
icon: '/icons/creative-process-2.svg',
description: 'En este paso se diseñan en detalle y se organizan todos los componentes, se crea una hoja de ruta o un guion gráfico para describir la relación entre las interfaces y se define la navegabilidad a través de la aplicación.',
alt: 'conceptos'
},
{
title: '3. Desarrollo y despliegue',
color: '#c3953f',
icon: '/icons/creative-process-3.svg',
description: 'La fase de desarrollo generalmente comienza bastante temprano. De hecho, una vez que una idea adquiere cierta madurez en la etapa de diseño, se desarrolla un prototipo que valida la funcionalidad y suposiciones ayudando a comprender el alcance del proyecto. Al terminar las pruebas la aplicación estará lista para su lanzamiento.',
alt: 'entrega-y-documentacion'
}
],
carousel: {
items1: [
{ img: '/images/services-carousel/app/app-comer_c.jpg' },
{ img: '/images/services-carousel/app/app-flyvel_c.jpg' },
{ img: '/images/services-carousel/app/app-logitrans_c.jpg' },
{ img: '/images/services-carousel/app/app-pio-chikens_c.jpg' },
{ img: '/images/services-carousel/app/app-rentum_c.jpg' },
{ img: '/images/services-carousel/app/app-stem-medic_c.jpg' },
{ img: '/images/services-carousel/app/divino-alchemy_c.jpg' }
]
},
packs: {
title: 'Aprovecha nuestros pack',
first: {
image: '/images/pages/packs/addons-logo+pack-de-identidad.png',
title: 'LOGO A MEDIDA + PACK DE IDENTIDAD DE 6 PIEZA + LOGO ANIMADO',
subtitle: 'LLEVA 6 PIEZAS AL PRECIO DE 2',
url: '/nuestros-servicios/imagen-corporativa',
brief: '/nuestros-servicios/imagen-corporativa/brief/disenos'
},
last: {
image: '/images/pages/packs/addons-logo+web.png',
title: 'LOGO + WEB',
subtitle: '50% OFF EN DISEÑO DE LOGO',
url: '/nuestros-servicios/logo-y-pagina-web',
brief: '/nuestros-servicios/logo-y-pagina-web/brief/disenos'
}
}
}
|
const Crypto = require('../utils/crypto');
module.exports = (req, res, next) => {
let sign = req.body;
if (Crypto.Verify(sign)) {
req.body = JSON.parse(sign.msg);
req.body.pubKeyHash = Crypto.Hash(sign.pubKey);
if (req.body.header) {
if (new Date() - new Date(req.body.time) >= DURATION) {
return res.end('Signature timeout');
}
}
next();
} else {
res.end('Invalid signature');
}
}; |
module.exports = {
globDirectory: "public",
globIgnores: [
"service-worker/**/*.*",
"service-worker/*.*",
],
globPatterns: [
"**/*.{png,ico,html,js,svg,css}",
],
injectionPointRegexp: new RegExp("(const precacheManifest = )\\[\\](;)"),
swDest: "public/sw.js",
swSrc: "src/service-worker/index.js",
};
|
const gulp = require('gulp');
const sass = require('gulp-sass');
const autoprefixer = require('gulp-autoprefixer');
const uglify = require('gulp-uglify');
const saveLicense = require('uglify-save-license');
const babel = require('gulp-babel');
const through = require('through2');
const path = require('path');
const argv = require('yargs').argv;
gulp.task('js', () => {
return gulp.src(['./src/js/*.js'])
.pipe(babel(
{
presets: [
[
'@babel/preset-env',
{
modules: false
}
]
]
}
))
.pipe(argv.dev ? through.obj() : uglify({
output: {
comments: saveLicense
}
}))
.pipe(gulp.dest('./demo/'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('scss', () => {
return gulp.src(['./src/scss/*.scss', '!./src/scss/demo.scss'])
.pipe(sass({
'includePaths': ['node_modules'],
'outputStyle': argv.dev ? 'development' : 'compressed'
}).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(gulp.dest('./dist/'));
});
gulp.task('demo', () => {
return gulp.src(['./src/scss/demo.scss'])
.pipe(sass({
'includePaths': ['node_modules'],
'outputStyle': argv.dev ? 'development' : 'compressed'
}).on('error', sass.logError))
.pipe(autoprefixer())
.pipe(gulp.dest('./demo/'));
});
gulp.task('default', ['js', 'scss', 'demo'], () => {});
gulp.task('watch', ['default'], () => {
gulp.watch(['./src/js/*.js'], ['js']);
gulp.watch(['./src/scss/*.scss'], ['scss', 'demo']);
}); |
'use strict'
//importar librerias
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const cors = require('cors');
//uso de librerias
const app = express();
require('dotenv').config();
//Middlewares
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());
app.use(cors());
//conexion a mongodb
mongoose.connect(process.env.DATABASE,{
useNewUrlParser:true,
useCreateIndex:true,
useUnifiedTopology:true
}).then( ()=>{console.log('Conexion a base de datos:....... OK!')} );
//Routes
app.use('/jmautos/carros', require('./routes/rutas.carros'));
app.use('/jmautos/contactos', require('./routes/rutas.contactos'));
app.use('/jmautos/session', require('./routes/ruta.session'));
//Listen port
const port = process.env.PORT;
app.listen(port, () => {
console.log('Estado de servidor:........OK!');
});
|
$("select#departamentoSelect").change(function() {
let departamentoValue = $("#departamentoSelect").val();
$.ajax({
url: '/municipios?id=' + departamentoValue,
method: 'GET',
}).done(
function (municipios) {
let stateSelect = $('#municipioSelect');
let ceSelect = $('#institucionSelect')
ceSelect.find('option').remove()
ceSelect.append("<option value=0 > - Seleccione una institucion - </option>")
stateSelect.find('option').remove();
stateSelect.append("<option value=0 > - Seleccione un municipio - </option>")
let municipioValue = $("#municipioSelect").val()
for (let i = 0; i < municipios.length; i++) {
if( municipioValue != municipios[i].idMunicipio){
stateSelect.append("<option value=" + municipios[i].idMunicipio + " >" + municipios[i].nombre + "</option>")
}
}
}).fail(
function() {
alert('error inesperado');
}
)
})
$("select#municipioSelect").change(function() {
let munValue = $("#municipioSelect").val();
console.log("MUN-CAMBIO")
$.ajax({
url: '/instituciones?id=' + munValue,
method: 'GET',
}).done(
function (institucion) {
let stateSelect = $('#institucionSelect');
stateSelect.find('option').remove();
stateSelect.append("<option value=0 > - Seleccione una institucion - </option>")
let municipioValue = $("#institucionSelect").val()
for (let i = 0; i < institucion.length; i++) {
if( municipioValue != institucion[i].idCentroEscolar){
stateSelect.append("<option value=" + institucion[i].idCentroEscolar + " >" + institucion[i].nombre + "</option>")
}
}
}).fail(
function() {
alert('error inesperado');
}
)
}) |
class Score {
constructor() {
this.points = 0;
this.positionX = 30;
this.delay = 0;
this.isStoped = false;
}
loop() {
this.display();
this.update();
}
display() {
fill(255);
textSize(50);
text(this.points, width - this.positionX, 50);
}
update() {
if(this.isStoped) return;
if(this.delay == 2) {
this.points++;
this.delay = 0;
}
let decimals = (this.points + '').length;
if((decimals*30)+0 > this.positionX) {
this.positionX += 30;
}
this.delay++;
}
toggleStop() {
this.isStoped = true;
}
} |
import React from 'react'
import styled from 'styled-components';
import ImgSlider from './ImgSlider';
import Movies from './Movies';
import Viewers from './Viewers';
function Home() {
return (
<Container>
<ImgSlider/>
<Viewers/>
<Movies/>
</Container>
)
}
export default Home
const Container = styled.main`
min-height: calc(100vh - 70px);
padding: 0 calc(3.5vw + 5px);
position: relative;
overflow-x: hidden;
&:before{
background: url("/home-background.png") center center/ cover no-repeat fixed;
content: "";
position: absolute;
top:0;
left:0;
right:0;
bottom:0;
z-index:-1;
}
` |
'use strict';
var <%= modelName %> = require('<%= modelPath %>');
module.exports = function (router) {
var model = new <%= modelName %>();
router.get('/', function (req, res) {
<% if (templateModule) { %>
<% if (useJson) { %>
res.format({
json: function () {
res.json(model);
},
html: function () {
res.render('<%= name %>', model);
}
});<% } else { %>
res.render('<%= name %>', model);
<% } %>
<% } else { %>
res.send('<code><pre>' + JSON.stringify(model, null, 2) + '</pre></code>');
<% } %>
});
};
|
const searchTable = document.querySelector('.search-display table');
const checkCells = document.querySelectorAll('.search-display table > tbody tr input[type=checkbox]');
const loader = document.querySelector('.ui.segment');
const removeBtn = document.querySelector('#remove');
const userID = document.querySelector('#userID');
const userRole = document.querySelector('#userRole');
let checkedCells = 0;
const handleServiceBtnsActive = (numOfEntites) => {
if (numOfEntites > 0) {
removeBtn.classList.remove('disabled');
} else {
removeBtn.classList.add('disabled');
}
}
const resetTableHandler = () => {
checkCells.forEach(cell => {
cell.checked = false;
checkedCells = 0;
});
document.querySelectorAll('.search-display table > tbody tr').forEach(ele => {
ele.classList.remove('checked');
})
document.querySelector('#checkAll').checked = false;
handleServiceBtnsActive(checkedCells);
}
if (searchTable) {
searchTable.addEventListener('change', function (e) {
if (e.target.checked && e.target.parentElement.nodeName !== 'TD') {
checkCells.forEach(cell => {
cell.checked = true
checkedCells = checkCells.length;
});
document.querySelectorAll('.search-display table > tbody tr').forEach(ele => {
ele.classList.add('checked');
})
} else if (e.target.checked && e.target.parentElement.nodeName === 'TD') {
e.target.checked = true;
e.target.parentElement.parentElement.classList.add('checked');
checkedCells++;
} else if (!e.target.checked && e.target.parentElement.nodeName === 'TD') {
e.target.checked = false;
e.target.parentElement.parentElement.classList.remove('checked');
checkedCells--;
} else {
checkCells.forEach(cell => {
cell.checked = false;
checkedCells = 0;
});
document.querySelectorAll('.search-display table > tbody tr').forEach(ele => {
ele.classList.remove('checked');
})
}
;
handleServiceBtnsActive(checkedCells);
})
}
document.querySelector('.reset-action ').addEventListener('click', function (e) {
e.preventDefault();
document.querySelector('.container.left #owner').value = '';
document.querySelector('#petName').value = '';
document.querySelector('#breed').value = '';
document.querySelector('#periodTo').value = '';
})
const updateLogs = async (bookings, logURI) => {
await fetch(`http://localhost:3000/PRJ321_REST/logs/bookings/${logURI}/${userID.value}`, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include",
body: JSON.stringify(bookings)
})
.then(response => {
return response.json();
})
.catch(err => {
setTimeout(() => {
iziToast.error({
title: 'Error',
message: 'Log(s) Can\'t Be Updated !!',
});
}, 50);
});
}
const removeBookings = async () => {
const checkedRows = searchTable.querySelectorAll('tr.checked');
const deletedBookings = Array.from(checkedRows).map(row => {
return row.querySelector('[data-label=ID]').getAttribute('data-tooltip');
});
loader.classList.add('active');
await updateLogs(deletedBookings, "remove");
fetch('http://localhost:3000/PRJ321_REST/bookings/delete', {
method: 'DELETE', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include",
body: JSON.stringify(deletedBookings),
headers: {
"Content-Type": 'application/json'
}
})
.then(response => response.json())
.then(data => {
setTimeout(() => {
iziToast.success({
title: 'OK',
timeout: 3000,
message: 'Booking(s) Remove Successfully ! The Page will reload in 3 seconds for changes to take effect',
onClosing: function () {
window.location.replace(window.location.href.split('?')[0]);
}
});
}, 50);
})
.catch(err => {
setTimeout(() => {
iziToast.error({
title: 'Error',
message: 'Booking(s) Can\'t Be Removed !!',
});
}, 50);
});
loader.classList.remove('active');
resetTableHandler();
}
if (removeBtn) {
removeBtn.addEventListener('click', function () {
iziToast.show({
theme: 'dark',
overlay: true,
displayMode: 'once',
title: 'Hey',
message: 'Are you sure ?',
position: 'center', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: 'rgb(0, 255, 184)',
buttons: [
['<button>Ok</button>', function (instance, toast) {
instance.hide({
transitionOut: 'fadeOutUp',
}, toast);
removeBookings();
}], // true to focus
['<button>Close</button>', function (instance, toast) {
instance.hide({
transitionOut: 'fadeOutUp',
}, toast);
}]
],
});
});
}
function s2ab(s) {
var buf = new ArrayBuffer(s.length); //convert s to arrayBuffer
var view = new Uint8Array(buf); //create uint8array as viewer
for (var i = 0; i < s.length; i++)
view[i] = s.charCodeAt(i) & 0xFF; //convert to octet
return buf;
}
const createExcelSheet = (sheetName, worksheet_data) => {
const workBook = XLSX.utils.book_new();
workBook.Props = {
Title: 'bookings_Report',
Subject: 'Booking Detail File',
Author: 'ViruSs',
CreatedDate: new Date()
}
workBook.SheetNames.push(sheetName);
const worksheet = XLSX.utils.aoa_to_sheet(worksheet_data);
workBook.Sheets[sheetName] = worksheet;
return XLSX.write(workBook, {bookType: 'xlsx', type: 'binary'});
}
$("#export-to-excel").click(async () => {
try {
$("#export-to-excel").addClass("loading");
let BASE_URL = 'http://localhost:3000/PRJ321_REST/bookings';
if (userRole.value === 'pet owner') {
BASE_URL += `/${userID.value}`;
}
const response = await fetch(BASE_URL, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: "include",
headers: {
"Content-Type": 'application/json'
}
});
const bookings = await response.json();
console.log(bookings);
const header = ["Id", "Owner", "Pet", "Arrival", "Departure", "Notes", "Employee Notes", "Status", "Cancellation Notes", "Total Fee", "Receipt", "Extra Services", "Created At", "Updated At"];
const worksheet_data = [header];
for (let booking of bookings) {
const row_data = [];
row_data.push(booking.id);
row_data.push(booking.userID);
row_data.push(booking.petId);
row_data.push(new Date(booking.arrival).toLocaleString());
row_data.push(new Date(booking.departure).toLocaleString());
row_data.push(booking.ownerNotes.trim());
row_data.push(booking.managerNotes.trim());
row_data.push(booking.status);
row_data.push(booking.cancelNotes.trim());
row_data.push(`$${booking.fee}`);
if (booking.receipt) {
row_data.push(`${booking.receipt}`);
} else {
row_data.push("");
}
if (booking.extraServices) {
row_data.push("Yes");
} else {
row_data.push("No");
}
row_data.push(new Date(booking.createdAt).toLocaleString());
if (booking.updatedAt) {
row_data.push(new Date(booking.updatedAt).toLocaleString());
} else {
row_data.push("");
}
worksheet_data.push(row_data);
}
console.log(worksheet_data);
await saveAs(new Blob([s2ab(createExcelSheet("Booking_Report Sheet", worksheet_data))], {type: "application/octet-stream"}), 'booking.xlsx');
} catch (err) {
iziToast.error({
title: 'Error',
message: 'Export Bookings To Excel Failed!',
});
return ;
}
iziToast.success({
title: 'OK',
message: 'Export Bookings To Excel Successfully!',
})
$("#export-to-excel").removeClass("loading");
});
$('#createdAt').datetimepicker();
$('#createdTo').datetimepicker();
$('#periodTo').datetimepicker();
$('#periodAt').datetimepicker();
|
/**
* spawnQueue: creepConfig[] which is a priority-sorted list of CreepConfigs
* --pop(): returns the next highest-priority spawn and removes it from the queue
* --peek(): returns ref to the next highest-priority spawn
*/
class CivReport {
constructor(debug, phase) {
this.debug = debug;
this.counts = {'hostiles' : 0};
this.phase = phase;
}
config() {
return {
"cattle": { "priority": 6, "count": 1},
"colonizer": { "priority": 8, "count": 1},
"missionary": { "priority": 7, "count": 1},
"conquerer": { "priority": 9, "count": 1}
};
}
/**
* Tallies all creep roles in a village for processing.
* Returns a creep role
* @param {creep} creep
* @param {Village} village
*/
report(creep, village) {
let myRole = village.colonization.civCreeps[creep.name].role;
if (creep.my && myRole) {
if (this.counts[myRole]) {
this.counts[myRole]++;
} else {
this.counts[myRole] = 1;
}
return myRole;
} else {
this.counts.hostiles++;
return 'enemy';
}
}
read() {
_.forOwn(this.counts, function(value, key) { console.log(`${key}: ${value}`) } );
console.log(`DangerPresent: ${this.dangerPresent()}`);
}
process(village) {
if (this.phase == 2) {
return [];
}
//village.debugMessage.append(`\t [CreepReport] BEGIN processing for ${village.villageName}`);
//console.log(`\t [CreepReport] BEGIN processing for ${village.villageName} lv ${village.level}`);
let config = this.config();
//console.log(this.level)
// return the first role by priority that isn't filled out
// for each role
let priorityList = Object.keys(config).sort(function(a, b) {
if (config[a].priority < config[b].priority) {
return 1;
} else {
return -1;
}
});
let that = this;
//console.log(`\t\t [CreepReport] priority list: ${priorityList}`);
//village.debugMessage.append(`\t\t [CreepReport] priority list: ${priorityList}`);
var spawnQueue = [];
//console.log("------STARTING")
_.forEach(priorityList, function(role) {
// Calculate differently for remote roles
let adjustedCount = config[role].count;
switch(role) {
case 'conquerer':
if (village.colonization.civRoom) { // if I've claimed the controller
adjustedCount = 0;
}
break;
case 'missionary':
case 'colonizer':
case 'cattle':
if (village.Villages[village.colonization.civVillageName].level > 2) {
adjustedCount = 0;
}
break;
}
//console.log(`\t\t [CreepReport] Required for role ${role}: ${config[role].count}`);
//console.log(`\t\t [CreepReport] Have: ${that.counts[role]}`);
//village.debugMessage.append(`\t\t [CreepReport] Required for role ${config[role]}: ${config[role].count}`);
//village.debugMessage.append(`\t\t [CreepReport] Have: ${that.counts[role]}`);
if (!that.counts[role] || that.counts[role] < adjustedCount) { // TODO: scale up and down
//console.log("--> We have 0 or fewer than necessary of role " + role);
let creepCount = that.counts[role] ? adjustedCount - that.counts[role] : adjustedCount;
_.times(creepCount, function() {
spawnQueue.push(role);
})
}
});
village.debugMessage.append(`\t\t [CreepReport] COMPLETE -- SpawnQueue for ${village.villageName}: ${spawnQueue}`);
//console.log( " QUEUE: " +spawnQueue + ':' + spawnQueue.forEach(x=>console.log(x)))
//console.log("------FINISHED")
return spawnQueue;
}
}
module.exports = CivReport; |
import React from 'react';
import { Text } from 'react-native';
import firebase from 'firebase';
import { Scene, Router, Actions } from 'react-native-router-flux';
import InitialScreen from './components/InitialScreen';
import LoginForm from './components/LoginForm';
import Home from './components/Home';
import ExampleList from './ExampleList';
import GatePass from './components/GatePass';
const TabIcon = ({ selected, title }) => {
return(
<Text style={{ color: selected? '#F04E45' : 'black', fontSize: 12, fontFamily: 'Helvetica-Light' }}>{title}</Text>
);
};
const RouterComponent = () => {
return (
<Router
navigationBarStyle={styles.navBar}
titleStyle={{ color: '#FFFFFF' }}
>
<Scene
key='initializeApp'
component={InitialScreen}
hideNavBar
title='Chalkpad'
initial
/>
<Scene key='login'>
<Scene
key='loginUser'
component={LoginForm}
title='Chalkpad Login'
hideNavBar={false}
initial
sceneStyle={{ paddingTop: 65 }}
/>
</Scene>
<Scene
key='tabbar'
tabs
tabBarStyle={{ backgroundColor: '#FFFFFF' }}
>
<Scene key='tab1' title='Home' icon={TabIcon}>
<Scene
key='home'
component={Home}
title='Home'
hideNavBar={false}
sceneStyle={{ paddingTop: 65 }}
initial
renderBackButton={() => (null)}
rightTitle='Logout'
onRight={() => {
firebase.auth().signOut();
Actions.initializeApp({ type: 'reset' });
}}
rightButtonTextStyle={{ color: '#FFFFFF' }}
/>
</Scene>
<Scene key='tab4' title='Attendance' icon={TabIcon}>
<Scene
key='attendance'
component={Home}
title='Attendance'
sceneStyle={{ paddingTop: 65 }}
renderBackButton={() => (null)}
/>
</Scene>
<Scene key='tab2' title='Gate Pass' icon={TabIcon}>
<Scene
key='gatepass'
component={GatePass}
title='Gate Pass'
hideNavBar={false}
sceneStyle={{ paddingTop: 65 }}
renderBackButton={() => (null)}
/>
</Scene>
<Scene key='tab3' title='Marks' icon={TabIcon}>
<Scene
key='marks'
component={Home}
title='Marks'
sceneStyle={{ paddingTop: 65 }}
renderBackButton={() =>( null)}
/>
</Scene>
<Scene key='tab5' title='Developer' icon={TabIcon}>
<Scene
key='initial7'
component={ExampleList}
title='About Developer'
sceneStyle={{ paddingTop: 65 }}
renderBackButton={() => (null)}
/>
</Scene>
</Scene>
</Router>
);
};
const styles = {
navBar: {
backgroundColor: '#F04E45',
},
barButtonTextStyle: {
color: '#FFFFFF'
},
barButtonIconStyle: {
tintColor: 'rgb(255,255,255)'
}
};
export default RouterComponent;
|
//Init material and dropdown.
$.material.init();
//Resize my final canvas.
function resizeCanvas(canvasItem){
canvasItem.outerHeight( $(window).height() -
canvasItem.offset().top -
Math.abs(
canvasItem.outerHeight(true) -
canvasItem.outerHeight()
)
);
}
//Call resize canvas on resize windows event.
$(document).ready(function(){
resizeCanvas($("#myCanvasDownload"));
$(window).on("resize", function(){
resizeCanvas($("#myCanvasDownload"));
});
});
//Create option list for country.
var $selectContry = $('#countryOption').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: country,
create: false,
//Check GDG list on every change of countryOption
onChange: function(value) { downloadGDGList(value); }
});
//Get from GDGx the list of GDG per country.
function downloadGDGList(country){
$.ajax( { url: "https://hub.gdgx.io/api/v1/chapters/country/" + country + "?perpage=999&fields=_id,name&asc=-1",
type: "GET",
dataType: "jsonp",
async: true,
success: function(result){
var gdgList = result.items;
var $selectGDG = $('#gdgOption').selectize({
valueField: 'name',
labelField: 'name',
searchField: 'name',
options: gdgList,
create: false,
});
},
error: function(error){
console.log(error);
}
}
);
}
document.getElementById("uploadimage").addEventListener("change", draw, false);
document.getElementById('download').addEventListener('click', function() {
downloadCanvas(this, 'myCanvasDownload', 'image.png');
}, false);
function downloadCanvas(link, canvasId, filename) {
link.href = document.getElementById(canvasId).toDataURL();
link.download = filename;
}
var logo = new Image();
logo.crossOrigin='anonymous';
var logoWtm = new Image();
logoWtm.crossOrigin = 'anonymous';
logoWtm.src = "img/wtm.png";
logoWtm.onload = function() { console.log("Caricato"); };
var canvas = document.createElement('canvas');
function draw(ev) {
//console.log(ev);
var ctx = canvas.getContext('2d');
img = new Image();
f = document.getElementById("uploadimage").files[0];
url = window.URL || window.webkitURL;
src = url.createObjectURL(f);
img.src = src;
img.onload = function() {
if(document.getElementById("squareCrop").checked){
canvas.width=500;
canvas.height=500;
var sourceX = 500;
var sourceY = 0;
var sourceWidth = 500;
var sourceHeight = 500;
var destWidth = sourceWidth;
var destHeight = sourceHeight;
var destX = canvas.width / 2 - destWidth / 2;
var destY = canvas.height / 2 - destHeight / 2;
ctx.drawImage(img, sourceX, sourceY, sourceWidth, sourceHeight, destX, destY, destWidth, destHeight);
}
else if(img.width > 500){
canvas.width=500;
canvas.height=img.height / img.width * 500;
ctx.drawImage(img,0,0,500,img.height / img.width * 500);
}
else{
canvas.width=img.width;
canvas.height=img.height;
ctx.drawImage(img,0,0);
}
if(document.getElementById("colorSet").checked){
var imageData = ctx.getImageData(0, 0, img.width, img.height);
var data = imageData.data;
for(var i = 0; i < data.length; i += 4) {
var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
// red
data[i] = brightness;
// green
data[i + 1] = brightness;
// blue
data[i + 2] = brightness;
}
// overwrite original image
ctx.putImageData(imageData, 0, 0);
}
logo.src = "img/logo.png";
logo.onload = start;
url.revokeObjectURL(src);
};
}
function start(){
applyText(canvas, $("#gdgOption option:selected").text() );
}
function applyText(canvas,text){
var tempCanvas = document.createElement('canvas');
var tempCtx = tempCanvas.getContext('2d');
var cw,ch;
cw = tempCanvas.width = canvas.width;
ch = tempCanvas.height = canvas.height;
tempCtx.drawImage(canvas,0,0);
tempCtx.font = "30px verdana";
var textWidth = tempCtx.measureText(text).width;
tempCtx.fillStyle = 'white';
tempCtx.fillText(text,cw-textWidth-10, 30);
var new_height = logo.height / logo.width * cw;
tempCtx.drawImage(logo,0,ch-new_height,cw,new_height);
if(document.getElementById("wtm").checked){
var widthWMT = 100;
var new_height = logoWtm.height / logoWtm.width * widthWMT;
tempCtx.drawImage(logoWtm,0,0,widthWMT,new_height);
}
if(document.getElementById('myCanvasDownload'))
document.getElementById('myImage').removeChild(document.getElementById('myCanvasDownload'));
tempCanvas.setAttribute('id','myCanvasDownload');
document.getElementById('myImage').appendChild(tempCanvas);
}
|
var homePage = require("../pageObjects/homepage.js");
var restaurantSearchPage = require("../pageObjects/restaurantsearchpage.js");
beforeEach(async() => {
browser.maximizeWindow();
await browser.url('/');
});
describe('Offers & Discounts', function () {
it('Test1: Verify Offers page is displayed on clicking offers button', function(){
homePage.setSearchLocation('chennai');
restaurantSearchPage.offersButton.waitForDisplayed(6000);
restaurantSearchPage.clickOffersButton();
restaurantSearchPage.offers.waitForDisplayed(6000);
try {
expect(restaurantSearchPage.offersText).to.equal("Offers for you");
console.log("Offers Page is displayed successfully");
} catch(err) {
console.log("Exception: " + err);
assert.fail();
}
});
}); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const react_native_1 = require("@storybook/react-native");
function importStories(components) {
components.forEach(component => {
require(`../components/${component}/stories/${component}.native.stories.tsx`);
});
}
// import stories
react_native_1.configure(() => {
importStories(['button']);
}, module);
// Refer to https://github.com/storybookjs/storybook/tree/master/app/react-native#start-command-parameters
// To find allowed options for getStorybookUI
const App = react_native_1.getStorybookUI({});
exports.default = App;
|
import styled from "styled-components";
const StyledListContainer = styled.div`
margin: 0 -8px;
${(props) => props.relative && "position: relative;"}
`;
export {StyledListContainer};
|
const firebaseConfig = {
apiKey: "AIzaSyBwx7K1CdnQjA2UB2rCZzTlRR0M0WpW2YY",
authDomain: "form-login-74002.firebaseapp.com",
projectId: "form-login-74002",
storageBucket: "form-login-74002.appspot.com",
messagingSenderId: "1045293905476",
appId: "1:1045293905476:web:ef3b7694d054e2ae846e11"
};
export default firebaseConfig; |
var book = require('../models/Book.js');
//GET ALL
exports.findAll = function(req, res) {
book.find(function(error, bookList) {
if(error) { return res.status(500).send(error.message); }
// Layout is the name of the view thath render the inf
return res.render('index', {
bookList: bookList
});
return res.status(200).jsonp(bookList);
});
};
//GET
exports.findById = function(req, res) {
var id = req.params.id;
console.log('Book: ' + id);
book.findById(req.params.id, function(error, found) {
if(error) { return res.status(500).send(console.error.message); }
return res.render('edit_book', {
book: found
});
return res.status(200).json(found);
});
};
//PUT
exports.updateBook = function(req, res) {
var id = req.params.book_id;
book.findById(id, function(error, selectedBook) {
if(error) { return res.status(500).send(console.error.message); }
//updateinfo
selectedBook.Title = req.body.title;
selectedBook.Descripton = req.body.description;
selectedBook.ISBN = req.body.isbn;
selectedBook.Author = req.body.author;
//save the book
selectedBook.save(function(error) {
if(error) { return res.status(500).send(console.error.message); }
book.find(function(error, bookList) {
if(error) { return res.status(500).send(error.message); }
return res.render('index', {
bookList: bookList
});
return res.status(200).jsonp(bookList);
});
});
});
};
//POST
exports.addBook = function(req, res) {
console.log(req.body)
//Create a new instane of the book model
var newBook = new book({
//bookId = req.body.bookId,
Title: req.body.title,
Descripton: req.body.description,
ISBN: req.body.isbn,
Author: req.body.author
});
//Save the book and heck for errors
newBook.save(function (error) {
if(error) { return res.status(500).send(error.message); }
book.find(function(error, bookList) {
if(error) { return res.status(500).send(error.message); }
return res.render('index', {
bookList: bookList
});
return res.status(200).jsonp(bookList);
});
});
};
//DELETE
exports.deleteBook = function(req, res) {
book.remove({ _id: req.params.book_id }, function(error, selectedBook) {
if(error) { return res.status(500).send(error.message); }
book.find(function(error, bookList) {
if(error) { return res.status(500).send(error.message); }
return res.render('index', {
book: bookList
});
return res.status(200).jsonp(bookList);
});
});
};
|
import React, { useState } from "react";
import { useSelector } from "react-redux";
import { Button, Input } from "antd";
import { PhoneOutlined, MailOutlined, CheckOutlined } from "@ant-design/icons";
import {
UserBoxContainer,
AvatarContainer,
DetailsContainer,
ContactContainer,
MessageContainer,
} from "./style";
import sendNewMessage from "../../../utils/sendNewMessage";
import Avatar from "../../avatar";
const { TextArea } = Input;
const index = ({ user, location, postId, phone, email }) => {
const [isContact, setIsContact] = useState(false);
const [message, setMessage] = useState("");
const [isSending, setSending] = useState(false);
const [sendButtonText, setSendButtonText] = useState("Send Message");
const currentUser = useSelector((state) => state.auth.user);
const sendMessage = async () => {
if (message.length > 0) {
try {
setSending(true);
await sendNewMessage(
"post",
postId,
currentUser.username,
user._id,
message
);
setMessage("");
setSending(false);
setSendButtonText("Message Sent!");
} catch (err) {
setSending(false);
setSendButtonText("Couldn't Send Message");
}
}
};
return (
<UserBoxContainer>
<AvatarContainer>
<Avatar
profileImage={user.profileImage}
userId={user._id}
username={user.username}
size={45}
/>
</AvatarContainer>
<DetailsContainer>
<strong style={{ fontSize: "20px", lineHeight: "20px" }}>
{user.username}
</strong>
<div>{location.city + ", " + location.state}</div>
</DetailsContainer>
<ContactContainer>
{!isContact && (
<Button type='primary' onClick={() => setIsContact(!isContact)}>
Contact
</Button>
)}
{isContact && (
<div>
<PhoneOutlined /> {phone ? phone : "n/a"}
<br />
<MailOutlined /> {email ? email : "n/a"}
</div>
)}
</ContactContainer>
{isContact && (
<MessageContainer>
<TextArea
rows={4}
value={message}
onChange={(e) => {
setMessage(e.target.value);
setSendButtonText("Send Message");
}}
placeholder={"Send " + user.username + " a message..."}
style={{ marginBottom: "10px" }}
/>
{currentUser ? (
<Button
type='primary'
disabled={currentUser._id === user._id}
loading={isSending}
block
onClick={sendMessage}
>
{sendButtonText === "Message Sent!" && (
<CheckOutlined style={{ color: "white" }} />
)}
{sendButtonText}
</Button>
) : (
<Button type='primary' block disabled>
Login to send messages
</Button>
)}
</MessageContainer>
)}
</UserBoxContainer>
);
};
export default index;
|
import styled from "styled-components";
const StyledTextBlock = styled.span`
border-radius: 5px;
padding: 3px;
position: relative;
border: dashed 1px #e8e8e8;
transition: border-color 0.3s ease-out, background-color 0.3s ease-out;
margin: 0 5px;
&:hover {
border: dashed 1px #b5b5b5;
}
.variantControlWrapper {
/* pointer-events: none; */
display: inline-block;
/* opacity: 0; */
position: relative;
width: 0px;
}
.variantControl {
position: absolute;
width: 60px;
display: flex;
position: relative;
top: -14px;
left: -60px;
background-color: #b5b5b5;
border-radius: 5px;
align-items: center;
justify-content: center;
}
.variantControlArrow {
color: #fff;
padding: 8px;
.MuiIconButton-label {
width: 0.25rem;
height: 0.25rem;
}
svg {
width: 0.375rem;
}
}
.variantControlAmount {
color: #fff;
width: 16px;
height: 16px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 0.55em;
z-index: 9;
padding: 0 3px;
}
&:hover {
background-color: #fce8fa;
cursor: pointer;
}
`;
export {StyledTextBlock};
|
const object = (text) => (text ? JSON.stringify(text) : '');
export default object;
|
function createC02(YEARS, YEARMARKINGS, WIDTH, HEIGHT) {
} |
import 'styles/salonathome.scss';
import React from 'react';
import {render} from 'react-dom';
import {Router, Route, browserHistory} from 'react-router';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware, compose} from 'redux';
import thunk from 'redux-thunk';
import reducers from './reducers';
import App from './components/Main';
import AddAddress from './components/AddAddress';
import AddressList from './components/AddressList';
import Base from './components/base/Base';
import BookingConfirm from './components/BookingConfirm';
import Cancel from './components/Cancel';
import FullCart from './components/FullCart';
import Gallery from './components/Gallery';
import InviteAndEarn from './components/InviteAndEarn';
import Login from './components/Login';
import OrderConfirm from './components/OrderConfirm';
import OTPConfirm from './components/OTPConfirm';
import Offers from './components/Offers';
import Reschedule from './components/Reschedule';
import RegisterUser from './components/RegisterUser';
import ThankYou from './components/ThankYou';
import ErrorPage from './components/ErrorPage';
import FooterPage from './components/FooterPage';
import Appointments from './components/AppointmentList';
import {getItems, getUserDetails} from './actions';
export default class Index extends React.Component {
constructor(props) {
super(props);
this.store = createStore(reducers, compose(applyMiddleware(thunk), window.devToolsExtension ? window.devToolsExtension() : f => f));
}
componentWillMount() {
this.store.dispatch(getItems());
this.store.dispatch(getUserDetails());
}
render() {
return (
<Provider store={this.store}>
<Router history = { browserHistory } onEnter = { Base.routerInvoked() }>
<Route path = { '/' } component = { App } />
<Route path = { 'salon-at-home' } component = { App } />
<Route path = { 'beauty-at-home.html' } component = { App } />
<Route path = { 'salon-at-home/in/delhi' } component = { App } />
<Route path = { 'salon-at-home/in/gurgaon' } component = { App } />
<Route path = { 'salon-at-home/in/noida' } component = { App } />
<Route path = { 'salon-at-home/in/indirapuram' } component = { App } />
<Route path = { 'face' } component = { App } />
<Route path = { 'body' } component = { App } />
<Route path = { 'hair' } component = { App } />
<Route path = { 'makeup' } component = { App } />
<Route path = { 'packages' } component = { App } />
<Route path = { 'salon-at-home/face' } component = { App } />
<Route path = { 'salon-at-home/body' } component = { App } />
<Route path = { 'salon-at-home/hair' } component = { App } />
<Route path = { 'salon-at-home/makeup' } component = { App } />
<Route path = { 'salon-at-home/packages' } component = { App } />
<Route path = { 'address' } component = { AddressList } />
<Route path = { 'address/add' } component = { AddAddress } />
<Route path = { 'appointments' } component = { Appointments } />
<Route path = { 'booking/confirm' } component = { BookingConfirm } />
<Route path = { 'booking/confirmed' } component = { ThankYou } />
<Route path = { 'cart' } component = { FullCart } />
<Route path = { 'cancel' } component = { Cancel } />
<Route path = { 'reschedule' } component = { Reschedule } />
<Route path = { 'salon-at-home/gallery/bridal' } component = { Gallery } />
<Route path = { 'salon-at-home/referearn' } component = { InviteAndEarn } />
<Route path = { 'login' } component = { Login } />
<Route path = { 'register' } component = { RegisterUser } />
<Route path = { 'order/details' } component = { OrderConfirm } />
<Route path = { 'otp/confirm' } component = { OTPConfirm } />
<Route path = { 'salon-at-home/offers' } component = { Offers } />
<Route path = { 'about-us' } component = { FooterPage } />
<Route path = { 'contact-us' } component = { FooterPage } />
<Route path = { 'privacy-policy' } component = { FooterPage } />
<Route path = { 'refund-policy' } component = { FooterPage } />
<Route path = { 'terms-of-service' } component = { FooterPage } />
<Route path = { 'salon-at-home/*' } component = { App } />
<Route path = { '*' } component = { App } />
</Router>
</Provider>
)
}
}
render( <Index />, document.getElementById('app'));
|
import React, { Component } from 'react';
import * as actions from '../../actions/categories';
import { connect } from 'react-redux';
import { Link } from 'react-router';
class CategoryList extends Component {
componentWillMount() {
this.props.fetchCategories();
this.user = JSON.parse(localStorage.getItem('user'));
}
// renderCategories(categories) {
// return categories.map((c) => {
// c = c.trim();
// return (
// <Link to={"filter/" + c} key={c} className="list-group-item-text">{" " + c + " "}</Link>
// );
// });
// }
renderCategories() {
const categories = this.props.categories || [];
return categories.map((category, i) => {
return
<Link style={{color:'black'}} to={"categories/" + category._id}>
<li key={i}>{ category.description }</li>
</Link>
})
}
render() {
return (
<div className="content users">
<h1>Hello { this.user.firstname }</h1>
<p>Here are auth protected categories! :)</p>
<ul>
{ this.renderCategories() }
</ul>
</div>
)
}
}
function mapStateToProps(state) {
return { categories: state.category.list };
}
export default connect(mapStateToProps, actions)(CategoryList); |
import React from 'react'
import Menu from '../menu'
import st from './index.css'
class Header extends React.Component {
render() {
return (
<div className={st.outerHeader}>
<div className={st.header}>
<div className={[st.container, st.headerAlign].join(' ')}>
<div className={st.headerPrimary}>
{<this.props.logo />}
</div>
<Menu />
</div>
</div>
</div>
)
}
}
export default Header
|
import React from 'react';
import { Link } from 'react-router'
import Header from '../../components/header/header.js'
import SeniorForm from '../../components/senior-form/senior-form.js'
import './home.scss'
const Home = () => {
return (
<div>
<Header />
<Link to="/sign-up">Create An Account</Link>
{/* <SeniorForm /> */}
{/* BM - Removed this so that the home page can be autonomous and insead you are linked to the form. */}
</div>
);
}
export default Home;
|
const Customer = require('../../models/customer');
const jwt = require('jsonwebtoken')
var regpan = /^([a-zA-Z]){5}([0-9]){4}([a-zA-Z]){1}?$/;
//for converting Date string to Date Object
const toDate = (dateStr) => {
const [year, month, day] = dateStr.split("/")
return new Date(year, month - 1, day)
}
//function for creating customer information
module.exports.createCustomer = async function(req,res){
const date = toDate(req.body.DateOfBirth)
console.log('this is date',date);
try{
if(regpan.test(req.body.panNumber)==false){
return res.json(100, {
status: 100,
message: 'Invalid Pan Number'
})
}
let customer = await Customer.create({
firstName : req.body.firstName,
panNumber : req.body.panNumber,
DateOfBirth : date,
Gender : req.body.Gender,
email : req.body.email,
avatar : req.body.avatar
});
console.log('Customer registered successfully');
return res.json(200, {
message : 'success',
data : {
jwtToken: jwt.sign(customer.toJSON(), 'customerapi', { expiresIn: '400000' })
}
});
}catch(err){
console.log('Error', err);
return res.json(500, {
status: 500,
message: 'Internal Server Error'
})
}
}
//function for showing customer infromation
module.exports.showCustomer = async function(req,res){
try{
let pan = req.params.panNumber;
let customer = await Customer.findOne({panNumber:pan});
console.log(customer.panNumber)
if(customer)
{
return res.status(200).json({
message : "Here is your customer information",
customer_info : customer
});
}else{
return res.json(300,{
message : "No customer with the given pan number"
})
}
}catch(err){
console.log(err);
return res.json(500, {
status: 500,
message: 'Internal Server Error'
})
}
}
|
import React, {Component} from 'react';
export default class Dashboard extends Component {
constructor(){
super();
this.state = {
imageUrl: '',
productName : '',
price: ''
}
}
handleImageUrlChange = (e) => {
this.setState({imageUrl: e.target.value});
}
handleProductNameChange = (e) => {
this.setState({productName: e.target.value});
}
handlePriceChange = (e) => {
this.setState({price: e.target.value});
}
clearInput = () => {
this.setState({
imageUrl: '',
productName: '',
price: ''
})
}
render(){
return(
<div className='Form'>
<input value={this.state.imageUrl} onChange={ this.handleImageUrlChange } type='text' />
<input value={this.state.productName} onChange= { this.handleProductNameChange } type='text'/>
<input value={this.state.price} onChange={ this.handlePriceChange } type='text'/>
<button onClick={this.clearInput}>Cancel</button>
<button>Add to Inventory</button>
</div>
)
}
} |
import React from "react";
import { Link } from "@reach/router";
const languages = {
en: "English",
si: "සිංහල",
ta: "தமிழ்"
};
function LangSelector({ lang, time }) {
return (
<ul className="nav navbar-nav navbar-right">
{Object.keys(languages).map(l => (
<li key={l} className={lang === l ? "langs active" : "menuitem"}>
<Link className="menuitem" to={"/" + l}>
{languages[l]}
</Link>
</li>
))}
</ul>
);
}
export default LangSelector;
|
export function helpFather() {
return 'father';
} |
var myMusic = [
{
"artist": "Billy Joel",
"title": "Piano Man",
"release_year": 1973,
"formats": [
"CD",
"8T",
"LP"
],
"gold": true
}
// Add a record here
,{
"artist": "Derek Pope",
"title": "Epochs",
"release_year": 2020,
"formats": [
"SoundCloud",
"Spotify",
"YouTube Music"]
}
];
|
import React from 'react';
import './Project.css';
import CarRepair from '../image/CarRepairing.png';
import FoodApp from '../image/foodapp.png';
import RideShare from '../image/rideshare.png';
import FootballLeague from '../image/footballLeague.png';
import Ecommerce from '../image/ecommerce.png';
import Landingpage from '../image/landingpage.png';
const Projects = () => {
return (
<section className="projects" style={{backgroundColor:''}}>
<div className="d-flex justify-content-center">
<h1 style={{marginTop:'50px'}}>MY PROJECTS</h1>
</div>
<div className="container" style={{marginTop:'20px'}}>
<div className="row">
<div className="col-md-4 col-sm-12">
<div class="card">
<img class="card-img-top" src={CarRepair} alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">Car repair website</h4>
<p class="card-text">Use Mongodb, firebase, react, node</p>
<button type="button" class="btn btn-outline-dark">View</button>
</div>
</div>
</div>
<div className="col-md-4 col-sm-12">
<div class="card" >
<img class="card-img-top" src={FoodApp} alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">Food Application</h4>
<p class="card-text">Use Mongodb, firebase, react, node</p>
<button type="button" class="btn btn-outline-dark">View</button>
</div>
</div>
</div>
<div className="col-md-4 col-sm-12">
<div class="card" >
<img class="card-img-top" src={RideShare} alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">Ride Sharing App</h4>
<p class="card-text">Use Mongodb, firebase, react, node</p>
<button type="button" class="btn btn-outline-dark">View</button>
</div>
</div>
</div>
</div>
</div>
<div className="container">
<div className="row">
<div className="container" style={{marginTop:'40px'}}>
<div className="row">
<div className="col-md-4 col-sm-12" >
<div class="card">
<img class="card-img-top" src={FootballLeague} alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">All Football League</h4>
<p class="card-text">Use Mongodb, firebase, react, node</p>
<button type="button" class="btn btn-outline-dark">View</button>
</div>
</div>
</div>
<div className="col-md-4 col-sm-12">
<div class="card" >
<img class="card-img-top" src={Ecommerce} alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">E-commerce website</h4>
<p class="card-text">Use Mongodb, firebase, react, node</p>
<button type="button" class="btn btn-outline-dark">View</button>
</div>
</div>
</div>
<div className="col-md-4 col-sm-12">
<div class="card" >
<img class="card-img-top" src={Landingpage} alt="Card image cap"/>
<div class="card-body">
<h4 class="card-title">Responsive Templates</h4>
<p class="card-text">Use Mongodb, firebase, react, node</p>
<button type="button" class="btn btn-outline-dark">View</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</section>
);
};
export default Projects; |
'use strict';
angular.module('oneWorldApp')
.directive('livechatbar', () => ({
templateUrl: 'components/liveChatbar/liveChatbar.html',
restrict: 'E',
controller: 'LiveChatbarCtrl',
controllerAs: 'chat',
replace: true
}));
|
import React from 'react';
import './NotFound.css';
const NotFound = () => {
return (
<section className='not-found'>
<div className='container'>
<div className='row'>
<div className='col-lg-6 mx-auto text-center'>
<h1>404</h1>
<p>Page not found 😭</p>
</div>
</div>
</div>
</section>
);
};
export default NotFound;
|
// Review component; makes up the send to view.
class Review extends React.Component {
render() {
return (
<div>
<Completion
deathRecord={this.props.deathRecord}
currentUser={this.props.currentUser}
updateStep={this.props.updateStep}
requestEdits={this.props.requestEdits}
/>
<Validation deathRecord={this.props.deathRecord} />
<SendTo deathRecord={this.props.deathRecord} updateStep={this.props.updateStep} />
</div>
);
}
}
|
describe('BambooHR', function () {
it('Fill all days', function () {
cy.visit('/login.php')
cy.get('.normal-login-link-container').click()
cy.get('#lemail').type(Cypress.env('username'))
cy.get('#password').type(Cypress.env('password'))
cy.get('form').submit()
cy.get('.TimeTrackingWidget__summary-link').click()
const selector =
'.TimesheetSlat:not(.TimesheetSlat--disabled):not(.js-timesheet-showWeekends):not(.TimesheetSlat--future):not(.TimesheetSlat--expanded):not(.TimesheetSlat--expandable)'
cy.get(selector).each(() => {
cy.get(`${selector} .TimesheetSlat__addEntryLink`)
.first()
.click()
.then(() => {
cy.get('.SimpleModal').within(() => {
cy.get('ba-select > input')
.last()
.then(($elem) => {
$elem.val('PM')
})
cy.get('.ClockField__formInput')
.first()
.type(Cypress.env('enterTime'))
cy.get('.ClockField__formInput')
.last()
.type(Cypress.env('exitTime'))
cy.get('.SimpleModal__footer > .btnAction').click()
cy.wait(3000)
})
})
})
})
})
|
import React from "react";
import youtube from "../api/youtube";
import CssBaseline from "@material-ui/core/CssBaseline";
import MainAppBar from "./MainAppBar";
import VideoList from "./VideoList";
import VideoDetail from "./VideoDetail";
import PropTypes from "prop-types";
import { withStyles } from "@material-ui/core/styles";
import Grid from "@material-ui/core/Grid";
const styles = theme => ({
root: {
flexGrow: 1
},
container: {},
paper: {
padding: theme.spacing.unit * 2,
textAlign: "center",
color: theme.palette.text.secondary
}
});
class App extends React.Component {
state = { videos: [], selectedVideo: null };
componendDidMount() {
this.handleSubmit("buildings");
}
handleSubmit = async query => {
const response = await youtube.get("/search", {
params: {
q: query
}
});
this.setState({
videos: response.data.items,
selectedVideo: response.data.items[0]
});
};
handleVideoSelect = video => {
this.setState({
selectedVideo: video
});
};
render() {
const { classes } = this.props;
return (
<div className={classes.root}>
<CssBaseline />
<MainAppBar handleSubmit={this.handleSubmit} />
<Grid container spacing={24}>
<Grid item md={8} xs={12}>
<VideoDetail video={this.state.selectedVideo} />
</Grid>
<Grid item md={4} xs={12}>
<VideoList
videos={this.state.videos}
handleVideoSelect={this.handleVideoSelect}
/>
</Grid>
</Grid>
</div>
);
}
}
App.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(App);
|
/* global define */
'use strict';
define([
'-/logger/index.js'
], logger => function plugin() {
return (err, req, res, next) => {
logger.error('generic error', { err });
res.status(500);
next();
};
});
|
import { MoreArticles } from "../components/template/MoreArticles";
import { getAllPostsFrontMatter } from "../lib/posts";
import { PER_PAGE } from "../lib/constants";
import { SEO } from "../components/organisms/SEO";
export default function Home({ posts, totalPosts }) {
return (
<>
<SEO />
<MoreArticles posts={posts} totalPosts={totalPosts} currentPage={1} />
</>
);
}
export function getStaticProps() {
const allPosts = getAllPostsFrontMatter();
const posts = allPosts.slice(0, PER_PAGE);
return {
props: { posts, totalPosts: allPosts.length },
};
}
Home.isHome = true;
|
/**
* @type {HTMLCanvasElement} canvas
*/
var canvas = document.getElementById("mycanvas");
/**
* @type {WebGLRenderingContext} gl
*/
var gl = canvas.getContext("webgl");
// Definisi Titik
let vertices = [
-0.5,
0.5,
0.0,
0.83,
1.0, //titik A
0.5,
0.5,
0.0,
0.81,
0.73, //titik B
0.5,
-0.5,
0.0,
0.01,
0.26, //titik C
-0.5,
-0.5,
0.0,
0.0,
1.0, //titik D
];
// Membuat linkedlist untuk simpan data vertex
let buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Membuat Vertex Shader
let vertexShaderCode = `
attribute vec2 aPosition;
attribute vec3 aColor;
varying vec3 vColor;
uniform float uChange;
void main(){
gl_Position = vec4(aPosition + uChange, 0.0, 1.0);
vColor = aColor;
}
`;
let vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vertexShaderCode);
gl.compileShader(vertexShader);
// Membuat Fragment Shader
let fragmentShaderCode = `
precision mediump float;
varying vec3 vColor;
void main(){
gl_FragColor = vec4(vColor, 1.0);
}
`;
let fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fragmentShaderCode);
gl.compileShader(fragmentShader);
// Menautkan titik dan warna dalam program -> Compile shader ke program -> file.exe
let shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertexShader);
gl.attachShader(shaderProgram, fragmentShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
let aPosition = gl.getAttribLocation(shaderProgram, "aPosition");
let aColor = gl.getAttribLocation(shaderProgram, "aColor");
gl.vertexAttribPointer(
aPosition,
2,
gl.FLOAT,
false,
5 * Float32Array.BYTES_PER_ELEMENT,
0
);
gl.vertexAttribPointer(
aColor,
3,
gl.FLOAT,
false,
5 * Float32Array.BYTES_PER_ELEMENT,
2 * Float32Array.BYTES_PER_ELEMENT
);
gl.enableVertexAttribArray(aPosition);
gl.enableVertexAttribArray(aColor);
//Elemen interasktif
let freeze = false;
function onMouseClick(e) {
freeze = !freeze;
}
document.addEventListener("click", onMouseClick, false);
function onKeyDown(e) {
if (e.keyCode == 32) freeze = true;
}
function onKeyUp(e) {
if (e.keyCode == 32) freeze = false;
}
document.addEventListener("keydown", onKeyDown, false);
document.addEventListener("keyup", onKeyUp, false);
// Kecepatan animasi
let speed = 0.005;
let change = 0;
let uChange = gl.getUniformLocation(shaderProgram, "uChange");
// =============== Cara 1: menggunakan setInterval(function,fps) ==================
// function render() {
// if (change >= 0.5 || change < -0.5) speed = -speed;
// change += speed;
// gl.uniform1f(uChange, change);
// gl.clearColor(0.0, 0.1, 0.15, 1.0);
// gl.clear(gl.COLOR_BUFFER_BIT);
// gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
// }
// setInterval(render, 1000 / 60);
// ============== Cara 2: menggunakan setTimeOut(function,fps) ===================
function render() {
setTimeout(function () {
if (change < -0.5 || change >= 0.5) speed = -speed;
if (!freeze) change += speed;
gl.uniform1f(uChange, change);
gl.clearColor(0.0, 0.1, 0.15, 1.0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLE_FAN, 0, 4);
render();
}, 1000 / 60);
}
render();
|
import styled from 'styled-components';
import backgroundImage from './snow.jpg';
export const StyledApp = styled.div`
background: url("${backgroundImage}") center;
background-size: cover;
height: 100vh;
`;
|
import FirebaseApi from "./FirebaseApi";
import User from "./User";
class PollProvider {
static create() {
return FirebaseApi.push('polls');
}
static load(pollId, callback) {
return FirebaseApi.subscribe('polls/' + pollId, (data) => {
this.countResults(data, callback)
});
}
static update(pollId, data) {
const currentUser = User.getCurrentId();
return FirebaseApi.set('polls/' + pollId + '/' + currentUser, {
...data,
userName: User.getName(),
updateTime: Date.now()
});
}
static countResults(data, callback) {
const currentUser = User.getCurrentId();
let results = {};
let userCount = 0;
for (const userId in data) {
if (data.hasOwnProperty(userId) && data[userId].votes) {
userCount++;
const userName = data[userId].userName || '';
const votes = data[userId].votes;
votes.forEach(voteId => {
if (results[voteId]) {
results[voteId].count++;
results[voteId].users.push(userName);
} else {
results[voteId] = { count: 1, selected: false, users: [userName] };
}
});
}
}
if (data && data[currentUser] && data[currentUser].votes) {
data[currentUser].votes.forEach(voteId => {
results[voteId] = {
...results[voteId],
selected: true
}
});
}
callback(results, userCount);
};
}
export default PollProvider; |
// access_a_property.js
var o = {a: 1, b: 2};
o.__proto__ = {b: 3, c: 4};
// the full prototype chain looks like:
// {a: 1, b: 2} ---> {b: 3, c: 4} ---> null
console.log(o.a); // => 1
console.log(o.b); // => 2
console.log(o.c); // => 4
console.log(o.d); // => undefined |
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
const iD = {
name: "Instructional Designer",
rate: 120,
1: .45,
2: .35,
3: .3
};
const prog = {
name: "Programmer",
rate: 110,
1: .4,
2: .4,
3: .43
};
const gA = {
name: "Graphic Artist",
rate: 120,
1: 0,
2: .09,
3: .12
};
const aV = {
name: "Audio/Visual Producer",
rate: 115,
1: .05,
2: .06,
3: .06
};
const eM = {
name: "Engagement Manager",
rate: 135,
1: .05,
2: .05,
3: .05
};
const pM = {
name: "Project Manager",
rate: 117,
1: .05,
2: .05,
3: .05
};
const data = {
1: {
1: 48, 2: 127, 3: 217
},
2: {
1: 100, 2: 150, 3: 350
},
3: {
1: 180, 2: 230, 3: 550
},
4: {
1: 217, 2: 267, 3: 716
}
};
class TotalAmount extends React.Component {
render () {
const { graphicLevel, seatTime, IDLevel } = this.props
const calcEconomyOfSale = (cost) => {
if (seatTime <= 10) {
cost = cost - (cost * .05);
} else if (seatTime >= 11 && seatTime <= 19) {
cost = cost - (cost * .1);
} else if (seatTime >= 20 && seatTime <= 29) {
cost = cost - (cost * .15);
} else if (seatTime >= 30) {
cost = cost - (cost * .2);
}
return cost;
}
const find_range = (total) => {
let min = total - 2500;
let max = total + 2500;
min = Math.round(min/1000)*1000
max = Math.round(max/1000)*1000
min = min.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
max = max.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,');
return `${min} - $${max}`;
}
const totalValue = () => {
var hours = data[IDLevel][graphicLevel] * seatTime
var cost =
iD.rate * (iD[graphicLevel] * hours)
+ prog.rate * (prog[graphicLevel] * hours)
+ gA.rate * (gA[graphicLevel] * hours)
+ aV.rate * (aV[graphicLevel] * hours)
+ eM.rate * (eM[graphicLevel] * hours)
+ pM.rate * (pM[graphicLevel] * hours);
var finalCost = calcEconomyOfSale(cost);
return find_range(finalCost)
}
return (
<div className='total value'> Total: ${totalValue()} </div>
)
}
}
TotalAmount.PropTypes = {
graphicLevel: PropTypes.number.isRequired,
IDLevel: PropTypes.number.isRequired,
seatTime: PropTypes.number.isRequired,
}
const mapStateToProps = (state) => ({
graphicLevel: state.graphicLevel,
IDLevel: state.IDLevel,
seatTime: state.seatTime,
})
export default connect(
mapStateToProps
)(TotalAmount)
const format_id = (id) => {
switch(id) {
case 1:
var ID = "very low"
break;
case 2:
var ID = "low"
break;
case 3:
var ID = "medium"
break;
case 4:
var ID = "High"
}
return ID;
}
const format_range = (total) => {
if (total < 10000) {
console.log("$5,000 - $10,000")
} else if (total < 15000) {
console.log("$10,000 - $15,000")
}
}
const find_range = (total) => {
let min = total - 2500;
let max = total + 2500;
min = Math.round(min/1000)*1000
max = Math.round(max/1000)*1000
return `${min} - ${max}`;
} |
import React, { Fragment } from "react";
import PropTypes from 'prop-types';
import { MDBInput } from 'mdbreact';
const Input = ({word, handleInput, showResult}) => {
return (
<Fragment>
<form onSubmit={showResult}>
<p className="h5 text-center mb-4 mt-5">Type your word here..</p>
<div className="grey-text">
<MDBInput label="Your word.." icon="edit" onChange={handleInput} name="word" value={word}/>
</div>
</form>
</Fragment>
);
};
Input.propTypes = {
word: PropTypes.string,
handleInput: PropTypes.func,
showResult: PropTypes.func
};
export default Input; |
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var gulp_1 = require("gulp");
var changed = require("gulp-changed");
var filter = require("gulp-filter");
var gulp_ttf2woff_1 = __importDefault(require("gulp-ttf2woff"));
var gulp_ttf2woff2_1 = __importDefault(require("gulp-ttf2woff2"));
function default_1(config) {
function createWoffFromTtf() {
return gulp_1.src(config.src)
.pipe(filter(function (file) { return /ttf$/.test(file.path); }))
.pipe(gulp_ttf2woff_1.default())
.pipe(gulp_1.dest(config.srcPath));
}
function createWoff2FromTtf() {
return gulp_1.src(config.src)
.pipe(filter(function (file) { return /ttf$/.test(file.path); }))
.pipe(gulp_ttf2woff2_1.default())
.pipe(gulp_1.dest(config.srcPath));
}
function copyFonts() {
return gulp_1.src(config.src)
.pipe(filter(function (file) { return /(woff|woff2)$/.test(file.path); }))
.pipe(changed(config.dest))
.pipe(gulp_1.dest(config.dest));
}
return gulp_1.series(gulp_1.parallel(createWoffFromTtf, createWoff2FromTtf), copyFonts);
}
exports.default = default_1;
|
import {
getAlbums,
getAlbum,
getFavoriteAlbums,
getFavoriteAlbum,
addToFavorites,
deleteFromFavorites
} from '../../helpers/albums';
export const Types = {
ALBUMS_REQUEST: 'ALBUMS_REQUEST',
ALBUMS_SUCCESS: 'ALBUMS_SUCCESS',
ALBUMS_FAILURE: 'ALBUMS_FAILURE',
ALBUM_REQUEST: 'ALBUM_REQUEST',
ALBUM_SUCCESS: 'ALBUM_SUCCESS',
ALBUM_FAILURE: 'ALBUM_FAILURE',
FAVORITE_ALBUMS_REQUEST: 'FAVORITE_ALBUMS_REQUEST',
FAVORITE_ALBUMS_SUCCESS: 'FAVORITE_ALBUMS_SUCCESS',
FAVORITE_ALBUMS_FAILURE: 'FAVORITE_ALBUMS_FAILURE',
FAVORITE_ALBUM_REQUEST: 'FAVORITE_ALBUM_REQUEST',
FAVORITE_ALBUM_SUCCESS: 'FAVORITE_ALBUM_SUCCESS',
FAVORITE_ALBUM_FAILURE: 'FAVORITE_ALBUM_FAILURE',
ADD_TO_FAVORITES_REQUEST: 'ADD_TO_FAVORITES_REQUEST',
ADD_TO_FAVORITES_SUCCESS: 'ADD_TO_FAVORITES_SUCCESS',
ADD_TO_FAVORITES_FAILURE: 'ADD_TO_FAVORITES_FAILURE',
DELETE_FROM_FAVORITES_REQUEST: 'DELETE_FROM_FAVORITES_REQUEST',
DELETE_FROM_FAVORITES_SUCCESS: 'DELETE_FROM_FAVORITES_SUCCESS',
DELETE_FROM_FAVORITES_FAILURE: 'DELETE_FROM_FAVORITES_FAILURE',
SET_ID_FOR_ALBUM: 'SET_ID_FOR_ALBUM',
CLEAR_TOAST_MESSAGES: 'CLEAR_TOAST_MESSAGES',
};
export const getAlbumsRequest = () => {
return dispatch => {
dispatch(startAlbumsRequest());
getAlbums()
.then(res => {
if (res && res.status === 200) {
dispatch(getAlbumsSuccess(res.data));
} else {
dispatch(getAlbumsFailure(res));
}
});
};
};
export const getFavoriteAlbumsRequest = email => {
return dispatch => {
dispatch(startFavoriteAlbumsRequest());
getFavoriteAlbums(email)
.then(res => {
if (res && res.status === 200) {
dispatch(getFavoriteAlbumsSuccess(res.data));
} else {
dispatch(getFavoriteAlbumsFailure(res));
}
});
};
};
export const addToFavoritesRequest = data => {
return dispatch => {
dispatch(startAddToFavoritesRequest());
addToFavorites(data)
.then(res => {
if (res.status === 201) {
dispatch(addToFavoritesSuccess(res.data.message));
} else {
dispatch(addToFavoritesFailure(res));
}
});
};
};
export const deleteFromFavoritesRequest = id => {
return dispatch => {
dispatch(startDeleteFromFavoritesRequest());
deleteFromFavorites(id)
.then(res => {
if (res.status === 200) {
dispatch(deleteFromFavoritesSuccess(res.data.message));
} else {
dispatch(deleteFromFavoritesFailure(res));
}
});
};
};
export const getAlbumRequest = id => {
return dispatch => {
dispatch(startAlbumRequest());
getAlbum(id)
.then(res => {
if (res && res.status === 200) {
dispatch(getAlbumSuccess(res.data));
} else {
dispatch(getAlbumFailure(res));
}
});
};
};
export const getFavoriteAlbumRequest = id => {
return dispatch => {
dispatch(startFavoriteAlbumRequest());
getFavoriteAlbum(id)
.then(res => {
if (res.status === 200) {
dispatch(getFavoriteAlbumSuccess(res.data));
} else {
dispatch(getFavoriteAlbumFailure(res));
}
});
};
};
export const setIdForAlbum = id => {
return setId(id);
};
export const clearToastMessages = () => {
return clearToast();
};
const startDeleteFromFavoritesRequest = () => ({
type: Types.DELETE_FROM_FAVORITES_REQUEST
});
const deleteFromFavoritesSuccess = payload => ({
type: Types.DELETE_FROM_FAVORITES_SUCCESS,
payload
});
const deleteFromFavoritesFailure = error => ({
type: Types.DELETE_FROM_FAVORITES_FAILURE,
payload: error
});
const startAddToFavoritesRequest = () => ({
type: Types.ADD_TO_FAVORITES_REQUEST
});
const addToFavoritesSuccess = payload => ({
type: Types.ADD_TO_FAVORITES_SUCCESS,
payload
});
const addToFavoritesFailure = error => ({
type: Types.ADD_TO_FAVORITES_FAILURE,
payload: error
});
const startAlbumsRequest = () => ({
type: Types.ALBUMS_REQUEST
});
const getAlbumsSuccess = payload => ({
type: Types.ALBUMS_SUCCESS,
payload
});
const getAlbumsFailure = error => ({
type: Types.ALBUMS_FAILURE,
payload: { error }
});
const startFavoriteAlbumsRequest = () => ({
type: Types.FAVORITE_ALBUMS_REQUEST
});
const getFavoriteAlbumsSuccess = payload => ({
type: Types.FAVORITE_ALBUMS_SUCCESS,
payload
});
const getFavoriteAlbumsFailure = error => ({
type: Types.FAVORITE_ALBUMS_FAILURE,
payload: { error }
});
const startAlbumRequest = () => ({
type: Types.ALBUM_REQUEST
});
const getAlbumSuccess = payload => ({
type: Types.ALBUM_SUCCESS,
payload
});
const getAlbumFailure = error => ({
type: Types.ALBUM_FAILURE,
payload: { error }
});
const startFavoriteAlbumRequest = () => ({
type: Types.FAVORITE_ALBUM_REQUEST
});
const getFavoriteAlbumSuccess = payload => ({
type: Types.FAVORITE_ALBUM_SUCCESS,
payload
});
const getFavoriteAlbumFailure = error => ({
type: Types.FAVORITE_ALBUM_FAILURE,
payload: { error }
});
const setId = payload => ({
type: Types.SET_ID_FOR_ALBUM,
payload
});
const clearToast = () => ({
type: Types.CLEAR_TOAST_MESSAGES
});
|
/**
* Email Prefrences Page
*/
import React, { Component } from 'react';
import Switch from 'react-toggle-switch';
import Button from '@material-ui/core/Button';
import { FormGroup, Input } from 'reactstrap';
import { NotificationManager } from 'react-notifications';
import CircularProgress from '@material-ui/core/CircularProgress';
// intl messages
import IntlMessages from 'Util/IntlMessages';
export default class EmailPrefrences extends Component {
state = {
'Features & Announcements': true,
'Tips & Recommendations': true,
'Inbox': false,
'Community Activity': false,
'Research': true,
'Newsletter': false,
loading: false
}
// toggle switch
toggleSwitch = (key) => {
this.setState({ [key]: !this.state[key] });
}
// on save changes
onSaveChanges() {
this.setState({ loading: true });
let self = this;
setTimeout(() => {
self.setState({ loading: false });
NotificationManager.success('Changes Save Successfully!');
}, 1500);
}
render() {
return (
<div className="prefrences-wrapper">
<div className="row">
<div className="col-sm-12 col-md-8">
<div className="search-filter p-0 mb-50">
<form>
<h2 className="heading"><IntlMessages id="widgets.updateYourEmailAddress" /></h2>
<FormGroup className="mb-0 w-40">
<Input type="search" className="input-lg" name="search" placeholder="info@example.com" />
</FormGroup>
<Button variant="raised" color="primary" className="text-white btn-lg">
<IntlMessages id="button.save" />
</Button>
</form>
</div>
<ul className="list-unstyled">
<li className="d-flex justify-content-between">
<div className="">
<h5>Features & Announcements</h5>
<p>New products and feature updates, as well as occasional company announcements.</p>
</div>
<Switch
onClick={() => this.toggleSwitch('Features & Announcements')}
on={this.state['Features & Announcements']}
/>
</li>
<li className="d-flex justify-content-between">
<div className="">
<h5>Tips & Recommendations</h5>
<p>Timely advice to help you make the most of our features.</p>
</div>
<Switch
onClick={() => this.toggleSwitch('Tips & Recommendations')}
on={this.state['Tips & Recommendations']}
/>
</li>
<li className="d-flex justify-content-between">
<div className="">
<h5>Inbox</h5>
<p>Answers to your questions, comments, chat notifications and more.</p>
</div>
<Switch
onClick={() => this.toggleSwitch('Inbox')}
on={this.state['Inbox']}
/>
</li>
<li className="d-flex justify-content-between">
<div className="">
<h5>Community Activity</h5>
<p>Notifications about upcoming events & community activity.</p>
</div>
<Switch
onClick={() => this.toggleSwitch('Community Activity')}
on={this.state['Community Activity']}
/>
</li>
<li className="d-flex justify-content-between">
<div className="">
<h5>Research</h5>
<p>Invitations to participate in surveys, usability tests and more. Only a few per year.</p>
</div>
<Switch
onClick={() => this.toggleSwitch('Research')}
on={this.state['Research']}
/>
</li>
<li className="d-flex justify-content-between">
<div className="">
<h5>Newsletter</h5>
<p>Our best community content of the week/month</p>
</div>
<Switch
onClick={() => this.toggleSwitch('Newsletter')}
on={this.state['Newsletter']}
/>
</li>
</ul>
{this.state.loading ?
<CircularProgress />
: <Button variant="raised" color="primary" className="text-white btn-lg" onClick={() => this.onSaveChanges()}><IntlMessages id="button.saveChanges" /></Button>
}
</div>
</div>
</div>
);
}
}
|
import React from 'react'
import TodolistShowTile from "../components/TodolistShowTile"
import TodolistFormContainer from "./TodolistFormContainer"
class TodolistShowContainer extends React.Component {
constructor(props){
super(props)
this.state = {
todolist: {}
}
this.handleDelete = this.handleDelete.bind(this)
}
componentDidMount(){
fetch(`http://127.0.0.1:8000/api/${this.props.match.params.id}`)
.then(response => response.json())
.then(res => {
this.setState({todolist: res})
})
}
handleDelete(event){
fetch(`http://127.0.0.1:8000/api/${this.props.match.params.id}`, {
credentials: 'same-origin',
headers: { 'Accept': 'application/json','Content-Type': 'application/json' },
method: 'DELETE'
})
.then(response => this.props.history.push('/'))
}
render() {
return (
<div>
<h1> Detailed ToDo-Lists </h1>
<TodolistShowTile
key={this.state.todolist.id}
title={this.state.todolist.title}
body={this.state.todolist.body}
created_at={this.state.todolist.created_at}
/>
<br/>
<hr/>
<h3> Update Todolist </h3>
<TodolistFormContainer
requestType='put'
todolistId={this.state.todolist.id + '/'}
btn="Update Todolist"
/>
<button type="submit" value="submit" onClick={this.handleDelete}> Delete Todolist </button>
</div>
)
}
}
export default TodolistShowContainer
|
var request = require('superagent');
var SignupService = {
userSignupRequest: function(
firstName,
lastName,
userName,
password,
gender,
email,
dob,
phone,
callback) {
// Build the request
request
.post('/GroupDirectServices/SignupService.svc/usersignuprequest')
.send({
userSignupRequest: {
FirstName: firstName,
LastName: lastName,
UserName: userName,
Password: password,
Gender: gender,
EmailAddress: email,
DOB: dob,
Phone: phone
}
})
// Submit the request
.end(callback);
},
activateUserSignupRequest: function(
email,
activationCode,
callback){
// Build the request
request
.post('/GroupDirectServices/SignupService.svc/activateusersignuprequest')
.send({
email: email,
code: activationCode
})
// Submit the request
.end(callback);
},
companySignupRequest: function(
firstName,
lastName,
userName,
password,
email,
newCompanyName,
newCompanyEmail,
newCompanyAddrLine1,
newCompanyAddrLine2,
newCompanyCity,
newCompanyState,
newCompanyCountry,
newCompanyZip,
callback) {
// Build the request
request
.post('/GroupDirectServices/CompanySignupService.svc/docompanysignuprequest')
.send({
signUpModel: {
FirstName: firstName,
LastName: lastName,
UserName: userName,
Password: password,
EmailAddress: email,
CompanyName: newCompanyName,
CompanyEmail: newCompanyEmail,
CompanyAddress1: newCompanyAddrLine1,
CompanyAddress2: newCompanyAddrLine2,
CompanyCity: newCompanyCity,
CompanyState: newCompanyState,
CompanyCountry: 221,
CompanyZip: newCompanyZip
}
})
// Submit the request
.end(callback);
},
signupForExistingCompany: function(
firstName,
lastName,
userName,
email,
password,
invitationCode,
callback){
// Build the request
request
.post('/GroupDirectServices/CompanySignupService.svc/dousersignupforexistingcompany')
.send({
signUpModel: {
FirstName: firstName,
LastName: lastName,
UserName: userName,
Password: password,
EmailAddress: email
},
invitationCode: invitationCode
})
// Submit the request
.end(callback);
}
};
module.exports = SignupService;
|
import React from 'react';
import DisplayActivitiesContainer from './containers/DisplayActivitiesContainer'
const CreateEvent = props => {
const routePage = (path) => {
props.history.push(path)
}
return (
<DisplayActivitiesContainer
openModal={props.openModal}
eventId={props.eventId}
handleRoutePage={routePage}
/>
)
}
CreateEvent.defaultProps = {
event: ''
}
export default CreateEvent |
import * as fs from "fs/promises";
import { resolve } from "path";
import { isAccessible } from "./utils/accessible.js";
import { handleError } from "./utils/handleerror.js";
import SortFiles from "./module/sort.js";
import program from "./utils/commander.js";
import createDirnameAndFileName from "./utils/dirname.js";
const { __dirname } = createDirnameAndFileName(import.meta.url);
program.parse(process.argv);
const output = program.opts().output;
if (!(await isAccessible(output))) {
await fs.mkdir(output);
}
try {
const sorting = new SortFiles(output);
await sorting.readFolder(resolve(__dirname, program.opts().folder));
console.log("Done. We can delete source folder");
} catch (error) {
handleError(error);
}
|
/*global Backbone */
var App = App || {};
(function () {
// Create Search result list
App.Views.SearchResult = Backbone.View.extend({
// Cache common element use in this view.
element: {
searchBtn: $('#searchBtn'),
searchKey: $('#searchfield'),
searchformAlert: $('#searchformAlert')
},
initialize: function() {
var self = this;
this.element.searchBtn.on('click', function(e){
e.preventDefault();
// Preparing the keyword
var keyword = $.trim(self.element.searchKey.val()).toLowerCase();
// Check if user provide a keyword or not
if (!keyword) {
self.element.searchformAlert.text('Please insert search keyword.');
return;
}
// Remove the message that tell user to type a keyword
self.element.searchformAlert.text('');
// Firing an AJAX request
self.getAJAX(keyword);
});
},
getAJAX: function(keyword){
var self = this;
var searchUL = $('.search-result');
searchUL.html('<p>Now Loading...</p>');
$.ajax({
type: 'GET',
dataType: 'json',
cache: true,
url: 'https://api.nutritionix.com/v1_1/search/' + keyword +'?results=0%3A10&cal_min=0&cal_max=50000&fields=item_name%2Cbrand_name%2Cnf_calories&appId=13503f28&appKey=3daab5653ab630e12e2f2aa9e1cecf8e'
}).done(function(data) {
var food;
var addBtn = $('#foodSubmit');
var searchItemHTML = '';
// If no food found then tell the user.
if (data.hits.length <= 0) {
var seachNotfound = '<p>Not found any food from keyword: ' + keyword + '</p>';
searchUL.html(seachNotfound);
return;
}
// Iterate through each food object and get the data from it
for (var i = 0; i < data.hits.length; i++) {
searchItemHTML += '<li class="searchItem"><span class="searchName">' + data.hits[i].fields.item_name + ', ' + data.hits[i].fields.brand_name + '</span> <span class="searchCal">' + Math.round(data.hits[i].fields.nf_calories) + ' Cal. </span></li>';
}
// Insert to the DOM.
searchUL.html(searchItemHTML);
var searchItem = $('.searchItem');
// Listen to an event. If user clicked on the targeted element then get the element's value
searchItem.on('click', function(){
addBtn.prop('disabled', false);
var name = $(this).find('.searchName').text();
var cal = $(this).find('.searchCal').text();
$('#FoodName').text(name);
$('#FoodCal').text(cal);
return;
});
}).fail(function(){
// If AJAX request is fail then tell the user.
searchUL.html('<p>There\'re some error getting food information. Please try again later.</p>');
});
}
});
})(); |
/**
* @name VenueType
* @author Oleg Kaplya
* @overview VenueType model.
*/
'use strict';
module.exports = function(sequelize, DataTypes) {
var VenueType = sequelize.define('venue_type', {
title: DataTypes.STRING,
layout: DataTypes.TEXT
}, {
underscored: true
});
return VenueType;
};
|
/**
* Date Author Des
*----------------------------------------------
* 2019/12/20 gongtiexin 服务详情
* */
import React, { Component } from 'react';
import { inject, observer } from 'mobx-react';
import qs from 'query-string';
import { Descriptions, Table } from 'antd';
import PropTypes from 'prop-types';
import { CONFIG_TYPE_ENUM } from '../../constants';
@inject(({ store: { configStore } }) => ({ configStore }))
@observer
export default class Detail extends Component {
static propTypes = {
configStore: PropTypes.object.isRequired,
};
componentDidMount() {
this.props.configStore.getConfig(qs.parse(window.location.search));
}
componentWillUnmount() {
this.props.configStore.setConfig();
}
render() {
const {
configStore: { config },
} = this.props;
return (
<Descriptions column={1}>
<Descriptions.Item label="Namespace">{config.namespace}</Descriptions.Item>
<Descriptions.Item label="Data Id">{config.dataId}</Descriptions.Item>
<Descriptions.Item label="Group">{config.groupName}</Descriptions.Item>
<Descriptions.Item label="Type">
{CONFIG_TYPE_ENUM.properties[config.type]?.label}
</Descriptions.Item>
<Descriptions.Item label="content">{config.content}</Descriptions.Item>
</Descriptions>
);
}
}
|
var companyModel = require('../models/companyModel.js');
/**
* companyController.js
*
* @description :: Server-side logic for managing companys.
*/
module.exports = {
/**
* companyController.list()
*/
list: function (req, res) {
companyModel.find(function (err, companys) {
if (err) {
return res.status(500).json({
message: 'Error when getting company.',
error: err
});
}
return res.json(companys);
});
},
/**
* companyController.show()
*/
show: function (req, res) {
var id = req.params.id;
companyModel.findOne({id: id}, function (err, company) {
if (err) {
return res.status(500).json({
message: 'Error when getting company.',
error: err
});
}
if (!company) {
return res.status(404).json({
message: 'No such company'
});
}
return res.json(company);
});
},
/**
* companyController.create()
*/
create: function (req, res) {
companyModel(req.body).save();
return res.status(201).json(req.body);
},
/**
* companyController.update()
*/
update: function (req, res) {
var id = req.params.id;
companyModel.findOne({id: id}, function (err, company) {
if (err) {
return res.status(500).json({
message: 'Error when getting company',
error: err
});
}
if (!company) {
return res.status(404).json({
message: 'No such company'
});
}
company.name = req.body.name ? req.body.name : company.name;
company.location = req.body.location ? req.body.location : company.location;
company.save(function (err, company) {
if (err) {
return res.status(500).json({
message: 'Error when updating company.',
error: err
});
}
return res.json(company);
});
});
},
/**
* companyController.remove()
*/
remove: function (req, res) {
var id = req.params.id;
companyModel.findOneAndRemove({id:id}, function (err, company) {
if (err) {
return res.status(500).json({
message: 'Error when deleting the company.',
error: err
});
}
return res.status(204).json();
});
}
};
|
define(
['jquery', 'chai', 'sinon', 'viewcontrollers/aboutus'],
function($, chai, Sinon, AboutUs) {
var expect = chai.expect;
describe('About us ViewController', function() {
it('Provides the About us ViewController', function() {
expect(AboutUs.constructor).to.be.a('function');
});
});
}
);
|
const express = require('express');
const Joi = require('joi');
const app = express();
app.use(express.json());
app.get('/', (req, res) => {
return res.send('Hey there, looking for a villain? You\'ve come to the right place')
})
|
const request = require('supertest')
const app = require('../app')
// Setup a Test Database
const { setupDB } = require('./test-setup')
setupDB('endpoint-testing')
const Product = require('../models/product')
describe('GET /products', () => {
/**
* testing /GET endpoints on Customer resource
*/
it("should return a list", async () => {
const response = await request(app).get('/products')
expect(response.body).toEqual(expect.arrayContaining([]))
})
it("should check that data is valid", async () => {
const product = {
name: "Product 1",
description: "Description for Product 1",
amount: 120000
}
const data = await new Product(product).save()
expect(data.name).toBe(product.name)
})
it("should retrieve data for a particular product given its ID", async () => {
const _data = new Product({
name: "Product 1",
description: "Description for Product 1",
amount: 120000
})
const data = await _data.save()
const response = await request(app).get(`/products/${data.id}`)
expect(response.body._id).toEqual(data.id)
})
})
|
import * as firebase from "firebase/app";
import "firebase/auth";
const firebaseConfig = {
apiKey: "API_KEY",
authDomain: "AUTH_DOMAIN",
databaseURL: "DATABASE_URL",
projectId: "PROJECT_ID",
storageBucket: "STORAGE_BUCKET",
messagingSenderId: "MESSAGING_SENDER_ID",
appId: "APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
// firebase.analytics();
// export default firebaseConfig;
export default app;
|
import './Projects.css';
import ProjectCard from './ProjectCard';
import shrewed from '../assets/ecart.jpeg';
import greener from '../assets/greener.jpeg';
import spot from '../assets/spot.jpeg';
import fund from '../assets/fund.png';
import weather from '../assets/weather.jpeg';
import smart from '../assets/smart.jpeg';
function Projects(){
return(
<div className="container" id="projects">
<div className="row">
<div className="col">
<ProjectCard image={shrewed} title="Shrewd Cart" line1="Book Store Application" line2="React, Node, Express, MySQL" link="https://github.com/chandrakanth-c/webapp"/>
</div>
<div className="col">
<ProjectCard image={greener} title="Greener" line1="Eco-friendly store" line2="React, Node, Express, Mongo" link="https://github.com/chandrakanth-c/greener"/>
</div>
<div className="col">
<ProjectCard image={spot} title="Spotsteerer" line1="Job Portal" line2="Swift, Firebase" link="https://github.com/chandrakanth-c/spotsteerer"/>
</div>
</div>
<div className="row">
<div className="col">
<ProjectCard image={fund} title="Fundraiser" line1="Fund Raiser" line2="Java, Swing, Db4o" link="https://github.com/chandrakanth-c/fundraiser"/>
</div>
<div className="col">
<ProjectCard image={smart} title="Smartmanager" line1="Project Management Tool" line2="SpringMVC, Hiberante, MySQL" link="https://github.com/chandrakanth-c/smartmanager"/>
</div>
<div className="col">
<ProjectCard image={weather} title="RestFull API's" line1="CRUD operations" line2="Node JS & MongoDB" link="https://github.com/chittappac-su2020/Restful_API"/>
</div>
</div>
</div>
)
}
export default Projects;
|
// @flow
/* eslint no-bitwise: 0 */
/* **********************************************************
* File: actions/collectionActions.js
*
* Brief: Actions that span the entire app
*
* Authors: Craig Cheney
*
* 2017.09.19 CC - Document created
*
********************************************************* */
import { TimeSeries } from 'pondjs';
import type {
toggleCollectionStateActionType,
updateGraphSettingsActionType
} from '../types/collectionActionTypes';
import { bleWriteCharacteristic } from '../utils/BLE/bleFunctions';
// import { writeCharacteristic } from '../utils/mica/micaNobleDevices';
import { micaCharUuids } from '../utils/mica/micaConstants';
import {
resetDataBuffer,
resetStartTime,
getLastDataPointsDecimated
} from '../utils/dataStreams/graphBuffer';
import log from '../utils/loggingUtils';
import {
encodeStartPacket,
encodeStopPacket,
channelsToActiveNameList,
channelsToActiveIdList
} from '../utils/mica/parseDataPacket';
import type { idType, zeroT } from '../types/paramTypes';
import type { stateType, graphSettingsType } from '../types/stateTypes';
import type { thunkType } from '../types/functionTypes';
import type { updateZeroActionType } from '../types/actionTypes';
export const TOGGLE_COLLECTION_STATE = 'TOGGLE_COLLECTION_STATE';
export const UPDATE_GRAPH_SETTINGS = 'UPDATE_GRAPH_SETTINGS';
export const UPDATE_ZERO = 'UPDATE_ZERO';
/* Set the state whether or not the app is collecting data */
export function toggleCollectionState(newState: boolean): toggleCollectionStateActionType {
return {
type: TOGGLE_COLLECTION_STATE,
payload: {
newState
}
};
}
/* Gather the active sensor and start collecting data */
export function startCollecting(): thunkType {
/* Return a function for redux thunk */
return (dispatch: () => void, getState: () => stateType): void => {
/* get the new state */
const { devices, scanForDevices } = getState();
/* find all active devices */
const deviceIdList = Object.keys(devices);
/* Keep track of whether a sensor was started */
let sensorStarted = false;
/* Iterate over each device */
for (let i = 0; i < deviceIdList.length; i++) {
const deviceId = deviceIdList[i];
const device = devices[deviceId];
/* Ensure the device is active */
if (device.active) {
/* PLACE HOLDER SAMPLE RATE */
const sampleRate = 100;
const { sensors } = device.settings;
const startPacket = encodeStartPacket(sampleRate, sensors);
// const startPacket = [1, 3, 232, 1, 1, 0];
console.log('Start packet', startPacket);
/* Only write if there were active sensors */
if (startPacket.length) {
sensorStarted = true;
const result = bleWriteCharacteristic(
scanForDevices.method,
deviceId,
micaCharUuids.sensorCommands,
startPacket,
(dId, charUuid, err) => {
console.log('writeCharCallback:', dId, charUuid, err);
},
true
);
console.log('startCollecting: writeResult', result);
/* Reset the data buffer */
resetDataBuffer(deviceId);
/* Reset the start time of the data collection */
resetStartTime(deviceId);
}
}
}
/* Ensure that at least one sensor was started */
if (sensorStarted) {
/* Indicate that the device is being collected */
dispatch(toggleCollectionState(true));
}
};
}
/* Stop collecting data */
export function stopCollecting(): thunkType {
/* Return a function for redux thunk */
return (dispatch: () => void, getState: () => stateType): void => {
/* get the new state */
const { devices, scanForDevices } = getState();
/* find all active devices */
const deviceIdList = Object.keys(devices);
/* Iterate over each device */
for (let i = 0; i < deviceIdList.length; i++) {
const deviceId = deviceIdList[i];
const device = devices[deviceId];
/* Ensure the device is active */
if (device.active) {
/* Create the stop packet */
const stopPacket = encodeStopPacket(device.settings.sensors);
/* Write to the characteristic */
bleWriteCharacteristic(
scanForDevices.method,
deviceId,
micaCharUuids.sensorCommands,
stopPacket,
(dId, charUuid, err) => {
if (err) {
log.warn('writeCharCallback:', dId, charUuid, err);
}
},
true
);
}
}
/* Update the object */
dispatch(toggleCollectionState(false));
// /* get the new state */
// const state = getState();
// const { settings } = state.devices;
// /* find all active devices */
// const deviceKeys = Object.keys(settings);
// /* Iterate over each device */
// for (let i = 0; i < deviceKeys.length; i++) {
// const deviceId = deviceKeys[i];
// const device = settings[deviceId];
// /* See if the device is active */
// if (device.active) {
// const stopPacket = encodeStopPacket(device.sensors);
// writeCharacteristic(deviceId, micaCharUuids.sensorCommands, stopPacket);
// }
// }
// /* Update the object */
// dispatch(toggleCollectionState(false));
};
}
/* Update the graph settings */
export function updateGraphSettings(
graphSettings: graphSettingsType
): updateGraphSettingsActionType {
return {
type: UPDATE_GRAPH_SETTINGS,
payload: { ...graphSettings }
};
}
export function updateZero(
deviceId: idType,
sensorId: idType,
newZero: zeroT
): updateZeroActionType {
return {
type: UPDATE_ZERO,
payload: {
deviceId,
sensorId,
newZero,
}
};
}
export function zeroSensor(
deviceId: idType,
sensorId: idType
): thunkType {
/* Return a function for redux thunk */
return (dispatch: () => void, getState: () => stateType): void => {
/* get the new state */
const { devices } = getState();
const device = devices[deviceId];
const sensor = device.settings.sensors[parseInt(sensorId, 10)];
const { channels } = sensor;
const channelNames = channelsToActiveNameList(channels);
const channelIds = channelsToActiveIdList(channels);
/* find the channels */
const dataPoints = getLastDataPointsDecimated(deviceId, 25);
/* Create a time series */
const series = new TimeSeries({
name: 'zero',
events: dataPoints
});
/* zero obj */
const newZero: zeroT = {};
for (let i = 0; i < channelNames.length; i++) {
const channelName = channelNames[i];
const channelId = channelIds[i];
const avg = series.avg(channelName);
newZero[parseInt(channelId, 10)] = avg;
}
/* Dispatch the action */
dispatch(updateZero(deviceId, sensorId, newZero));
};
}
/* [] - END OF FILE */
|
var Store = require('flux/utils').Store;
var AppDispatcher = require('../dispatcher/dispatcher');
var IndexItemStore = new Store(AppDispatcher);
var BenchConstants = require('../constants/bench_constants');
var _hoveredBenchId = null;
IndexItemStore.__onDispatch = function(payload) {
switch (payload.actionType) {
case BenchConstants.RECEIVE_HOVERED_BENCH:
_hoveredBenchId = payload.benchId;
IndexItemStore.__emitChange();
break;
}
};
IndexItemStore.getHighlightedBenchId = function() {
console.log("Store function was called.")
return _hoveredBenchId;
};
module.exports = IndexItemStore;
|
module.exports = function(mongoose) {
// use mongoose to declare a user schema
var ReviewSchema = mongoose.Schema({
googleBooksId: String,
username: String,
comment: String,
dateAdded: { type: Date, default: Date.now }
}, {collection: 'project.review'});
return ReviewSchema;
};
|
//= require ./lib/_energize
//= require ./app/_toc
//= require ./app/_lang
$(function() {
loadToc($('#toc'), '.toc-link', '.toc-list-h2', 10);
setupLanguages($('body').data('languages'));
$('.content').imagesLoaded( function() {
window.recacheHeights();
window.refreshToc();
});
$('.asana-table').on('click', 'tr',function (e) {
var thisLevel = parseInt(this.className.substring(1));
// Check if this row has children
if ($(this).hasClass("has-children")) {
// Check if this row is already expanded
if ($(this).hasClass("expanded")) {
$(this).removeClass("expanded");
var arr = Array.apply(null, {length: thisLevel + 1}).map(Number.call, Number);
$(this).nextUntil('.c'+thisLevel, ':not(.c' + arr.join(',.') + ',.common-items-toggle)').addClass("hidden-row").removeClass("expanded");
} else {
$(this).addClass("expanded");
$(this).nextUntil('.c'+thisLevel, '.c' + (thisLevel + 1)).removeClass("hidden-row");
}
window.recacheHeights();
window.refreshToc();
return;
}
// Check if this row is the common expander
if ($(this).hasClass("common-items-toggle")) {
if ($(this).hasClass("expanded")) {
$(this).removeClass("expanded");
$(this).prevUntil(':not(.common-item)').addClass("hidden-row");
} else {
$(this).addClass("expanded");
$(this).prevUntil(':not(.common-item)').removeClass("hidden-row");
}
}
});
});
window.onpopstate = function() {
activateLanguage(getLanguageFromQueryString());
};
|
require("babel-register");
require("babel-polyfill");
const Koa = require("koa");
const config = require("./config");
const frame = require("./z-frame");
// const socket = require("./socket");
const router = require("./routers");
const { showBanner } = require("./utils/banner");
const app = new Koa();
showBanner(config.appName, config.version);
frame.attach(app, config);
// socket.attach(app);
app.use(router.routes());
app.listen(config.port, () => {
console.log(`${config.env} server started on port ${config.port}`);
});
|
import {h} from 'hyperapp'
import './style.css'
export const Box = ({top, bottom, class: className, ...rest}, children) => (
<div class={'box ' + className} {...rest}>
<div class="top">
{top}
</div>
{children.length > 0 && (
<div class="content">
{children}
</div>
)}
{bottom && (
<div class="bottom">
{bottom}
</div>
)}
</div>
)
|
'use strict';
angular.module('spaApp').factory('httpInterceptor', ['$q', '$window', '$location', '$rootScope', function httpInterceptor ($q, $window, $location, $rootScope) {
return function (promise) {
var success = function (response) {
return response;
};
var error = function (response) {
// TODO: Seems that in some time we don't get response.status
if (!response.status) {
console.log("Response undefined");
$location.url('/login');
}
if (response.status === 400 || response.status === 503 || response.status === 500) {
$rootScope.session_token = null;
console.log("Status 400 or 503");
$location.url('/login');
}
return $q.reject(response);
};
return promise.then(success, error);
};
}]);
|
import React from 'react'
export default props => (
<div className="form-group">
<input {...props.input} className="form-control" required={props.required} placeholder={props.placeholder} type={props.type} />
</div>
) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.