text stringlengths 7 3.69M |
|---|
import React from "react";
import {
HeaderNotificationAttentionLiner,
NotificationHeaderControlsLiner,
StyledNotificationSVG
} from "../../../layout/layout";
class NotificationItem extends React.Component {
render () {
return <NotificationHeaderControlsLiner>
<StyledNotificationSVG />
<HeaderNotificationAttentionLiner>
1
</HeaderNotificationAttentionLiner>
</NotificationHeaderControlsLiner>
}
}
export default NotificationItem |
import React, { useState, useCallback } from 'react';
import { useSelector } from 'react-redux';
import {
Modal,
ModalHeader,
basicStyle,
modalFooter
} from '../../public/style';
import { useRouter } from 'next/router';
import styled from '@emotion/styled';
import { LeftOutlined } from '@ant-design/icons';
import { Radio, message } from 'antd';
import customAxios from '../../utils/baseAxios';
import useCheckResult from '../../hooks/useCheckResult';
import useInputChangeHook from '../../hooks/useInputChangeHook';
const Container = styled.div`
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
& .join-content-detail {
width: 100%;
& .detail-q {
margin-top: 0.5rem;
//border: 1px solid blue;
}
& .detail-a {
//border: 1px solid green;
}
}
& .basic-info {
width: 90%;
${basicStyle}
& .subtitle {
font-weight: bold;
font-size: 1rem;
// border: 1px solid red;
margin-top: 1.5rem;
}
& input {
border: none;
width: 100%;
}
}
& .additional-info {
& input {
border: none;
border-bottom: 1px solid #000000;
}
& input[type='radio'] {
margin-top: 0.5rem;
width: 12px;
height: 12px;
}
& .radio-wrapper {
width: 33%;
display: inline;
}
}
`;
const ContainerHeader = styled(ModalHeader)`
line-height: 25px;
color: #ffffff;
background-color: #6055cd;
& .post-info {
height: 70px;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
& .user-name {
font-size: 12px;
}
& .group-info {
font-weight: bold;
font-size: 15px;
}
}
`;
const ContainerFooter = styled.button`
${modalFooter};
color: #ffffff;
background-color: #6055cd;
border: 1px solid #6055cd;
font-weight: bold;
margin-top: auto;
`;
const JoinGroup = ({ category, groupName, groupId, setShowingJoinModal }) => {
const { me } = useSelector(state => state.user);
const router = useRouter();
const year = new Date().getFullYear();
const [gender, setGender] = useState('');
const [portfolio, onChangePortfolio] = useInputChangeHook('');
const [activityPeriod, setActivityPeriod] = useState('3MonthOver');
const [toggleScreen, Screen] = useCheckResult({
title: '가입 지원',
content: '가입 지원 되었습니다.',
pushUrl: '/group'
});
const closeModal = useCallback(() => {
setShowingJoinModal(prev => !prev);
}, []);
const onChangeGender = useCallback(e => {
setGender(e.target.value);
}, []);
const onChangePeriod = useCallback(e => {
setActivityPeriod(e.target.value);
}, []);
const submitResult = useCallback(
async e => {
e.preventDefault();
const data = {
memberId: me.id,
groupId,
activityPeriod,
portfolio
};
try {
await customAxios.post(`/apply-group`, data);
toggleScreen();
} catch (err) {
console.log(err);
message.error('이미 지원한 모임입니다.');
// router.push('/');
}
},
[portfolio, groupId, me.id, activityPeriod]
);
return (
<Modal zIndex="3">
<Container>
<ContainerHeader>
<LeftOutlined onClick={closeModal} />
<div className="post-info">
<div className="user-name">{me.name}님의 모임 참여 신청</div>
<div className="group-info">
{groupName} | {category}
</div>
</div>
</ContainerHeader>
<main className="join-content">
<section className="basic-info">
<div className="subtitle">기본 정보</div>
<div className="join-content-detail">
<div className="join-content-detail-element">
<div className="detail-q">✦ 이름</div>
<div className="detail-a">{me.name}</div>
<div className="detail-q">✦ 나이</div>
<div className="detail-a">
{me.birthday && year - Number(me.birthday.split('-')[0]) + 1}
</div>
<div className="detail-q">✦ 성별</div>
<div className="detail-a">{me.gender ? '여성' : '남성'}</div>
{/* <input
type="text"
className="detail-a"
value={me.gender ? '여성' : '남성'}
readonly
/> */}
<div className="detail-q">✦ 이메일</div>
<div className="detail-a">{me.email}</div>
<div className="detail-q">✦ 연락처</div>
<div className="detail-a">{me.telephone}</div>
</div>
</div>
<div className="additional-info">
<div className="subtitle">추가 정보</div>
<div className="join-content-detail">
<div className="detail-q">✦ 예상 활동 기간</div>
<div className="radio-wrapper">
<input
id="3MonthUnder"
type="radio"
name="actMonth"
value="3MonthUnder"
onChange={onChangePeriod}
/>{' '}
<label htmlFor="3MonthUnder">3개월 미만 </label>
</div>
<div className="radio-wrapper">
<input
id="3MonthOver"
type="radio"
name="actMonth"
value="3MonthOver"
onChange={onChangePeriod}
/>{' '}
<label htmlFor="3MonthOver">3개월 이상 </label>
</div>
<div className="radio-wrapper">
<input
id="6MonthOver"
type="radio"
name="actMonth"
value="6MonthOver"
onChange={onChangePeriod}
/>{' '}
<label htmlFor="6MonthOver">6개월 이상 </label>
</div>
<div className="detail-q">✦ 요청사항</div>
<input
value={portfolio}
onChange={onChangePortfolio}
placeholder="요청사항을 입력해 보세요"
/>
</div>
</div>
</section>
</main>
<ContainerFooter onClick={submitResult}>제출하기</ContainerFooter>
</Container>
<Screen />
</Modal>
);
};
export default JoinGroup;
|
(function(addon) {
if(typeof define === "function" && define.amd) {
define("clique-grid", ["clique"], function() {
return addon(Clique);
});
}
if(!window.Clique) {
throw new Error("Clique.grid requires Clique.core");
}
if(window.Clique) {
addon(Clique);
}
})(function(_c) {
var $, grids;
$ = _c.$;
grids = [];
_c.component("rowMatchHeight", {
defaults: {
target: false,
row: true
},
boot: function() {
return _c.ready(function(context) {
return $("[data-row-match]", context).each(function() {
var grid, obj;
grid = $(this);
if(!grid.data("rowMatchHeight")) {
obj = _c.rowMatchHeight(grid, _c.utils.options(grid.attr("data-row-match")));
}
});
});
},
init: function() {
var $this;
$this = this;
this.columns = this.element.children();
this.elements = this.options.target ? this.find(this.options.target) : this.columns;
if(!this.columns.length) {
return;
}
_c.$win.on("load resize orientationchange", function() {
var fn;
fn = function() {
return $this.match();
};
_c.$(function() {
return fn();
});
return _c.utils.debounce(fn, 50);
}());
_c.$html.on("changed.clique.dom", function(e) {
$this.columns = $this.element.children();
$this.elements = $this.options.target ? $this.find($this.options.target) : $this.columns;
return $this.match();
});
this.on("display.clique.check", function(_this) {
return function(e) {
if(_this.element.is(":visible")) {
return _this.match();
}
};
}(this));
return grids.push(this);
},
match: function() {
var firstvisible, stacked;
firstvisible = this.columns.filter(":visible:first");
if(!firstvisible.length) {
return;
}
stacked = Math.ceil(100 * parseFloat(firstvisible.css("width")) / parseFloat(firstvisible.parent().css("width"))) >= 100;
if(stacked) {
this.revert();
} else {
_c.utils.matchHeights(this.elements, this.options);
}
return this;
},
revert: function() {
this.elements.css("min-height", "");
return this;
}
});
_c.component("rowMargin", {
defaults: {
cls: "row-margin"
},
boot: function() {
return _c.ready(function(context) {
return $("[data-row-margin]", context).each(function() {
var grid, obj;
grid = $(this);
if(!grid.data("rowMargin")) {
obj = _c.rowMargin(grid, _c.utils.options(grid.attr("data-row-margin")));
}
});
});
},
init: function() {
var firstChild = this.find("> *").first();
var leftSpacing = parseInt(firstChild.css("padding-left"), 10);
this.element.css("margin-bottom", -leftSpacing);
this.find("> *").css("margin-bottom", leftSpacing);
}
});
_c.utils.matchHeights = function(elements, options) {
var matchHeights;
elements = $(elements).css("min-height", "");
options = _c.$.extend({
row: true
}, options);
matchHeights = function(group) {
var max;
if(group.length < 2) {
return;
}
max = 0;
return group.each(function() {
max = Math.max(max, $(this).outerHeight());
}).each(function() {
return $(this).css("min-height", max);
});
};
if(options.row) {
elements.first().width();
return setTimeout(function() {
var group, lastoffset;
lastoffset = false;
group = [];
elements.each(function() {
var ele, offset;
ele = $(this);
offset = ele.offset().top;
if(offset !== lastoffset && group.length) {
matchHeights($(group));
group = [];
offset = ele.offset().top;
}
group.push(ele);
lastoffset = offset;
});
if(group.length) {
return matchHeights($(group));
}
}, 0);
} else {
return matchHeights(elements);
}
};
});
|
import React from 'react';
import { shallow } from 'enzyme';
import RaisedButton from 'material-ui/RaisedButton';
import Dialog from 'material-ui/Dialog';
import Auth from 'containers/Auth';
import CloseIcon from 'material-ui/svg-icons/content/clear';
import IconButton from 'material-ui/IconButton';
import GuestNav from '../GuestNav';
describe('Guest Nav Apperance', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(
<GuestNav />
);
});
it('should display two buttons', () => {
expect(wrapper.find(RaisedButton).length).toBe(2);
});
it('should contain the dialog', () => {
expect(wrapper.find(Dialog).length).toBe(1);
});
it('Auth should be inside the Dialog', () => {
expect(wrapper.find(Auth).length).toBe(1);
});
it('the dialog should be hidden', () => {
expect(wrapper.find(Dialog).props().open).toBe(false);
});
it('should have close button for the dialog', () => {
expect(wrapper.find(CloseIcon).length).toBe(1);
});
});
describe('Guest Nav Dialog test', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(
<GuestNav />
);
});
it('user click the login button, dialog show up', () => {
const LoginBtn = wrapper.find({ label: 'LOG IN' }).first();
LoginBtn.simulate('click', { preventDefault() {} });
expect(wrapper.find(Dialog).first().props().open).toBe(true);
expect(wrapper.state().authType).toEqual('Login');
});
it('user click the closeButton to close the dialog', () => {
const CloseBtn = wrapper.find(IconButton).first();
CloseBtn.simulate('click', { preventDefault() {} });
expect(wrapper.find(Dialog).first().props().open).toBe(false);
});
it('user click the signup button, dialog show up', () => {
const SignupBtn = wrapper.find({ label: 'SIGN UP' }).first();
SignupBtn.simulate('click', { preventDefault() {} });
expect(wrapper.find(Dialog).first().props().open).toBe(true);
expect(wrapper.state().authType).toEqual('Sign Up');
});
});
|
var mainCtrl = angular.module('mainCtrl', []);
mainCtrl.controller("mainCtrl", function ($scope, $http) {
$scope.visits = 0;
$http({
method: 'GET',
url: '/visits'
}).then(function successCallback(response) {
$scope.visits = response.data.visits;
});
$scope.addFav = function () {
if (window.sidebar && window.sidebar.addPanel) { // Mozilla Firefox Bookmark
window.sidebar.addPanel(document.title, window.location.href, '');
} else if (window.external && ('AddFavorite' in window.external)) { // IE Favorite
window.external.AddFavorite(location.href, document.title);
} else if (window.opera && window.print) { // Opera Hotlist
this.title = document.title;
return true;
} else { // webkit - safari/chrome
alert('Appuyer ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Command/Cmd' : 'CTRL') + ' + D pour ajouter dans votre favoris :)');
}
}
// general chart options
let percTooltip = {
callbacks: {
label: function (tooltipItem, data) {
let datasetIdx = [tooltipItem['datasetIndex']];
let label = data["datasets"][datasetIdx].label;
return (label === 'Létalité' || label === 'Nouveaux / total de la région') ?
label + ' : ' + data['datasets'][datasetIdx]['data'][tooltipItem['index']] + '%' :
label + ' : ' + data['datasets'][datasetIdx]['data'][tooltipItem['index']];
}
}
};
const optionLegend = { display: true, position: 'top', labels: { fontSize: 12, boxWidth: 12 } };
const elementStyles = { point: { radius: 4, borderWidth: 3, hitRadius: 10 } };
const limitXAxesTickScale = { xAxes: [{ ticks: { maxTicksLimit: screen.width / 30 } }] };
$scope.doughnutChartOptions = { legend: optionLegend, elements: elementStyles, maintainAspectRatio: false, tooltips: percTooltip };
$scope.chartOptions = { legend: optionLegend, elements: elementStyles, maintainAspectRatio: false, tooltips: percTooltip, scales: limitXAxesTickScale };
$scope.mergeObj = function (firstObj, secondObj) {
let objCopy = {};
let key;
for (key in firstObj) objCopy[key] = firstObj[key];
for (key in secondObj) objCopy[key] = secondObj[key];
return objCopy;
}
if (screen.width < 800) {
$scope.chartOptions.elements.point = { radius: 2, borderWidth: 2, hitRadius: 6 }
} else if (screen.width < 1200) {
$scope.chartOptions.elements.point = { radius: 3, borderWidth: 3, hitRadius: 8 }
}
window.addEventListener("resize", function(){
if ($scope.chartOptions.scales.xAxes[0].ticks.maxTicksLimit != screen.width / 25)
$scope.chartOptions.scales.xAxes[0].ticks.maxTicksLimit = screen.width / 25
if (screen.width < 800) {
$scope.chartOptions.elements.point = { radius: 2, borderWidth: 2, hitRadius: 6 }
} else if (screen.width < 1200) {
$scope.chartOptions.elements.point = { radius: 3, borderWidth: 3, hitRadius: 8 }
}
});
}); |
const graphql = require("graphql");
const _ = require("lodash");
const User = require("../model/user");
const {
GraphQLObjectType,
GraphQLString,
GraphQLSchema,
GraphQLID,
GraphQLNonNull,
GraphQLList
} = graphql;
const UserType = new GraphQLObjectType({
name: "User",
fields: () => ({
id: {
type: GraphQLID
},
fname: {
type: GraphQLString
},
lname: {
type: GraphQLString
},
email: {
type: GraphQLString
},
password: {
type: GraphQLString
}
})
});
const RootQuery = new GraphQLObjectType({
name: "RootQueryType",
fields: {
user: {
type: UserType,
args: {
email: {
type: GraphQLString
}
},
resolve(parent, args) {
//use args to fetch data from db
return User.findOne({email:args.email});
}
},
users: {
type: new GraphQLList(UserType),
resolve(parent, arg){
return User.find({});
}
}
}
});
const Mutation = new GraphQLObjectType({
name:"Mutation",
fields: {
addUser: {
type: UserType,
args:{ fname:{type:new GraphQLNonNull(GraphQLString)},
lname: {type:new GraphQLNonNull(GraphQLString)},
email: {type:new GraphQLNonNull(GraphQLString)},
password: {type:new GraphQLNonNull(GraphQLString)}},
resolve(parents, args){
let user = new User({
fname:args.fname,
lname:args.lname,
email:args.email,
password:args.password
});
return user.save();
}
}
}
})
module.exports = new GraphQLSchema({
query: RootQuery,
mutation:Mutation
});
|
var myApp = angular.module('myApp', []);
myApp.controller('AppCtrl', ['$scope', '$http', function($scope, $http) {
console.log("Hello World from controller");
$scope.content = 'first';
var refresh = function(){
$http.get('/HW5').then(function(response){
console.log("Got data!");
$scope.HW5 = response.data;
});
};
refresh();
$scope.addUser = function() {
console.log($scope.contact);
$http.post('/HW5', $scope.contact).then(function(response) {
console.log(response);
refresh();
});
};
$scope.remove = function(id) {
console.log(id);
$http.delete('/HW5/' + id).then(function(response) {
refresh();
});
};
$scope.edit = function(id) {
console.log(id);
$http.get('/HW5/' + id).then(function(response) {
$scope.contact = response.data;
});
};
$scope.update = function() {
console.log($scope.contact._id);
$http.put('/HW5/' + $scope.contact._id, $scope.contact).then(function(response) {
refresh();
})
};
$scope.complete = function(id) {
console.log(id);
$http.get('/HW5/' + id).then(function(response) {
response.data.statusProperty = "complete";
$scope.contact = response.data;
console.log(response);
$scope.update();
})
};
//junior
$scope.deselect = function() {
$scope.contact = "";
}
}]);
|
angular.module('todoApp', ['ui.router',
'ngAnimate',
'ngCookies',
'ngStorage',
'ui.bootstrap',
'angular-jwt',
'todoApp.todo',
'todoApp.security',
'todoApp.profile',
'todoApp.user'
]
);
angular.module('todoApp')
.constant("AccessLevels", {
anon: "anon",
user: "user",
admin: "admin"
});
angular.module('todoApp')
.run(['$rootScope', '$state', 'security', 'AccessLevels', '$location', '$window', function($rootScope, $state, security, AccessLevels, $location, $window) {
security.requestCurrentUser();
if(security.isAuthenticated()) {
$state.transitionTo('app.todo');
}
else {
$state.transitionTo('welcome.login');
}
$rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
var access = toState.data.access;
if(!security.isAuthorized(access)) {
event.preventDefault();
$state.go('welcome.login');
}
if((toState.name === 'welcome.login' || toState.name === 'welcome.register') && security.isAuthenticated()) {
event.preventDefault();
$state.go('app.todo');
}
});
$window.ga('create', 'UA-63408310-1', {
'cookieDomain': 'none'
});
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams) {
$window.ga('send', 'pageview', {
page: $location.path(),
title: toState.data.pageTitle
});
});
}]);
|
let API_HOST = "http://xxx.com/xxx";
let DEBUG = false;//��������
var Mock = require('mock.js')
function ajax(data = '', fn, method = "get", header = {}) {
if (!DEBUG) {
wx.request({
url: config.API_HOST + data,
method: method ? method : 'get',
data: {},
header: header ? header : { "Content-Type": "application/json" },
success: function (res) {
fn(res);
}
});
} else {
var res = Mock.mock({
'error_code': '',
'error_msg': '',
'data': {
'doctor': [{
'did': 1,
'doctor_image': 'doctor.jpg',
'doctor_name': '董广璐1',
'doctor_job': '主治医师',
'doctor_message':'暂无',
'doctor_price':20,
'doctor_place':'妇科',
'doctor_special':'肿瘤',
'doctor_number':20
}, {
'did': 2,
'doctor_image': 'doctor.jpg',
'doctor_name': '董广璐2',
'doctor_job': '主治医师',
'doctor_message':'暂无',
'doctor_price':20,
'doctor_place':'妇科',
'doctor_special':'肿瘤',
'doctor_number': 20
},{
'did': 3,
'doctor_image': 'doctor.jpg',
'doctor_name': '董广璐3',
'doctor_job': '主治医师',
'doctor_message':'暂无',
'doctor_price':20,
'doctor_place':'妇科',
'doctor_special':'肿瘤',
'doctor_number': 20
},{
'did': 4,
'doctor_image': 'doctor.jpg',
'doctor_name': '董广璐4',
'doctor_job': '主治医师',
'doctor_message':'暂无',
'doctor_price':20,
'doctor_place':'妇科',
'doctor_special':'肿瘤',
'doctor_number': 20
},{
'did': 5,
'doctor_image': 'doctor.jpg',
'doctor_name': '董广璐5',
'doctor_job': '主治医师',
'doctor_message':'暂无',
'doctor_price':20,
'doctor_place':'妇科',
'doctor_special':'肿瘤',
'doctor_number': 20
},{
'did': 6,
'doctor_image': 'doctor.jpg',
'doctor_name': '董广璐6',
'doctor_job': '主治医师',
'doctor_message':'暂无',
'doctor_price':20,
'doctor_place':'妇科',
'doctor_special':'肿瘤',
'doctor_number': 20
}
// {
// 'id|+1': 6,
// 'img': 'doctor.jpg',
// 'name': '董广璐',
// 'post': '教授'
// }
],
'article': [{
'aid': 1,
'article_id':10,
'article_title': '凉生我们可不可以不忧伤',
'writer': '马天宇1',
'article_class': '悲伤',
'article_content': '凉生,我们可不可以不忧伤是2014年新世界出版社、二十一世纪出版社出版的图书,作者是乐小米。凉生与姜生是一对伦理意义上的兄妹。惨淡的家境和生存的压力让妹妹姜生彻底的依赖与信任哥哥凉生,并不知不觉堕入了违背伦理道德的情感漩涡中。面对这样的爱情,作者的笔触是那么清丽、淡然,还夹着自嘲与绝望,甚至姜生觉得自己的感情是这个世界上最好笑的笑话。这是人世间所有人都渴望的爱情,纯粹、无悔、纤尘不染。'
},
{
'aid': 2,
'article_id':10,
'article_title': '凉生我们可不可以不忧伤',
'writer': '马天宇2',
'article_class': '悲伤',
'article_content': '凉生,我们可不可以不忧伤是2014年新世界出版社、二十一世纪出版社出版的图书,作者是乐小米。凉生与姜生是一对伦理意义上的兄妹。惨淡的家境和生存的压力让妹妹姜生彻底的依赖与信任哥哥凉生,并不知不觉堕入了违背伦理道德的情感漩涡中。面对这样的爱情,作者的笔触是那么清丽、淡然,还夹着自嘲与绝望,甚至姜生觉得自己的感情是这个世界上最好笑的笑话。这是人世间所有人都渴望的爱情,纯粹、无悔、纤尘不染。'
},
{
'aid': 3,
'article_id':10,
'article_title': '凉生我们可不可以不忧伤',
'writer': '马天宇3',
'article_class': '悲伤',
'article_content': '凉生,我们可不可以不忧伤是2014年新世界出版社、二十一世纪出版社出版的图书,作者是乐小米。凉生与姜生是一对伦理意义上的兄妹。惨淡的家境和生存的压力让妹妹姜生彻底的依赖与信任哥哥凉生,并不知不觉堕入了违背伦理道德的情感漩涡中。面对这样的爱情,作者的笔触是那么清丽、淡然,还夹着自嘲与绝望,甚至姜生觉得自己的感情是这个世界上最好笑的笑话。这是人世间所有人都渴望的爱情,纯粹、无悔、纤尘不染。'
},
{
'aid': 4,
'article_id':10,
'article_title': '凉生我们可不可以不忧伤',
'writer': '马天宇4',
'article_class': '悲伤',
'article_content': '凉生,我们可不可以不忧伤是2014年新世界出版社、二十一世纪出版社出版的图书,作者是乐小米。凉生与姜生是一对伦理意义上的兄妹。惨淡的家境和生存的压力让妹妹姜生彻底的依赖与信任哥哥凉生,并不知不觉堕入了违背伦理道德的情感漩涡中。面对这样的爱情,作者的笔触是那么清丽、淡然,还夹着自嘲与绝望,甚至姜生觉得自己的感情是这个世界上最好笑的笑话。这是人世间所有人都渴望的爱情,纯粹、无悔、纤尘不染。'
},
{
'aid': 5,
'article_id':10,
'article_title': '凉生我们可不可以不忧伤',
'writer': '马天宇5',
'article_class': '悲伤',
'article_content': '凉生,我们可不可以不忧伤是2014年新世界出版社、二十一世纪出版社出版的图书,作者是乐小米。凉生与姜生是一对伦理意义上的兄妹。惨淡的家境和生存的压力让妹妹姜生彻底的依赖与信任哥哥凉生,并不知不觉堕入了违背伦理道德的情感漩涡中。面对这样的爱情,作者的笔触是那么清丽、淡然,还夹着自嘲与绝望,甚至姜生觉得自己的感情是这个世界上最好笑的笑话。这是人世间所有人都渴望的爱情,纯粹、无悔、纤尘不染。'
}
],
'ill-class': [{
'iid|+1': 1,
'ill_title': '多囊卵巢综合征',
'ill_content': '多囊卵巢综合征(PCOS)是生育年龄妇女常见的一种复杂的内分泌及代谢异常所致的疾病,以慢性无排卵(排卵功能紊乱或丧失)和高雄激素血症(妇女体内男性激素产生过剩)为特征,主要临床表现为月经周期不规律、不孕、多毛和/或痤疮,是最常见的女性内分泌疾病。',
'contentSec': '1935年Stein和Leventhal归纳为闭经、多毛、肥胖及不孕四大病症,称之为Stein-Leventhal综合征(S-L综合征)。PCOS患者的卵巢增大、白膜增厚、多个不同发育阶段的卵泡,并伴有颗粒细胞黄素化。PCOS是II型糖尿病、心血管疾病、妊娠期糖尿病、妊娠高血压综合征以及子宫内膜癌的重要危险因素。PCOS的临床表型多样,目前病因不清,PCOS常表现家族群聚现象,提示有遗传因素的作用。患者常有同样月经不规律的母亲或者早秃的父亲;早秃是PCOS的男性表型,女性PCOS和男性早秃可能是由同一等位基因决定的;高雄激素血症和/或高胰岛素血症可能是多囊卵巢综合征患者家系成员同样患病的遗传特征;在不同诊断标准下作的家系分析研究经常提示PCOS遗传方式为常染色体显性遗传;而应用“单基因-变异表达模型”的研究却显示PCOS是由主基因变异并50%可遗传给后代。'
},
{
'iid|+1': 2,
'ill_title': '不孕症',
'ill_content': '不孕的医学定义为一年未采取任何避孕措施,性生活正常(每周两次及以上)而没有怀孕。主要分为原发不孕及继发不孕。原发不孕为从未受孕;继发不孕为曾经怀过孕。根据这种严格的定义,不孕是一种常见的问题,大约影响到至少10%~15%的育龄夫妇。引起不孕的发病原因分为男性不孕和女性不孕。',
'contentSec': ""
},
{
'iid|+1': 3,
'ill_title': '月经不调',
'ill_content': '月经失调也称月经不调,是妇科常见疾病,表现为月经周期或出血量的异常,可伴月经前、月经时的腹痛及其他的全身症状。病因可能是器质性病变或是功能失常。',
'contentSec': ""
},
{
'iid|+1': 4,
'ill_title': '盆腔炎性疾病',
'ill_content': '盆腔炎性疾病(pelvicinflammatorydisease,PID)指一组女性上生殖道的感染性疾病,主要包括子宫内膜炎、输卵管炎、输卵管卵巢脓肿(TOA)、盆腔腹膜炎。炎症可局限于一个部位,也可同时累及几个部位,最常见的是输卵管炎。',
'contentSec': ""
},
{
'iid|+1': 5,
'ill_title': '痛经',
'ill_content': '痛经(dysmenorrhea)为最常见的妇科症状之一,指行经前后或月经期出现下腹部疼痛、坠胀,伴有腰酸或其他不适,症状严重影响生活质量者。痛经分为原发性痛经和继发性两类,原发性痛经指生殖器官无器质性病变的痛经;继发性痛经指由盆腔器质性疾病,如子宫内膜异位症、子宫腺肌病等引起的痛经。',
'contentSec': "",
},
{
'iid|+1': 6,
'ill_title': '子宫内膜异位症',
'ill_content': '子宫内膜异位症(endometriosis)是指有活性的内膜细胞种植在子宫内膜以外的位置而形成的一种女性常见妇科疾病。内膜细胞本该生长在子宫腔内,但由于子宫腔通过输卵管与盆腔相通,因此使得内膜细胞可经由输卵管进入盆腔异位生长。目前对此病发病的机制有多种说法,其中被普遍认可的是子宫内膜种植学说。本病多发生于生育年龄的女性,青春期前不发病,绝经后异位病灶可逐渐萎缩退化。',
'contentSec': '子宫内膜异位症的主要病理变化为异位内膜周期性出血及其周围组织纤维化,形成异位结节,痛经、慢性盆腔痛、月经异常和不孕是其主要症状。病变可以波及所有的盆腔组织和器官,以卵巢、子宫直肠陷凹、宫骶韧带等部位最常见,也可发生于腹腔、胸腔、四肢等处。'
},
{
'iid|+1': 7,
'ill_title': '绝经期综合征',
'ill_content': '绝经期综合症是指归女绝经期,由于卵巢分泌功能缓慢减弱,植物性神经功能障碍,新陈代谢及营养障碍性出现的症状。如月经紊乱、头晕、心烦急躁、口干、潮热、舌尖红、脉细数等。',
'contentSec': ""
},
{
'iid|+1': 8,
'ill_title': '多发性流产',
'ill_content': '',
'contentSec': ""
},
{
'iid|+1': 9,
'ill_title': '',
'ill_content': '',
'contentSec': ""
}]
}
})
fn(res);
}
}
module.exports = {
ajax: ajax
}
|
(function () {
"use strict";
angular.module("vcas").controller("EventsCtrl", EventsCtrl);
/* @ngInject */
function EventsCtrl($filter, ContentsService, AlertsService, ContentModalService, EventService, ConfirmModalService, $modal, $state) {
var vm = this;
vm.removeEvents = removeEvents;
vm.openCreatePackageModal = openCreatePackageModal;
vm.confirmRemoveEvents = confirmRemoveEvents;
vm.editEvent = editEvent;
vm.viewPackagesFor = viewPackagesFor;
vm.addToPackages = addToPackages;
vm.setEvents = setEvents;
vm.isPPCEvent = isPPCEvent;
initialize();
//////////
function initialize() {
var dateFilter = _.partialRight($filter("date"), "M/d/yyyy - h:mm a");
vm.source = {
handler: ContentsService.getEvents,
args: [$state.params.networkId],
callback: vm.setEvents,
};
vm.columns = [{
label: "Event ID",
field: "smsEventId",
}, {
label: "Network Content Id",
field: "networkContentId",
}, {
label: "Content Id",
field: "smsContentId",
}, {
label: "Start Time",
field: "timePeriodRule.startTime",
filter: dateFilter,
}, {
label: "End Time",
field: "timePeriodRule.endTime",
filter: dateFilter,
}];
vm.bulkActions = [{
label: "Create Package",
handler: vm.openCreatePackageModal,
}, {
label: "Remove Events",
handler: vm.confirmRemoveEvents,
}];
vm.itemActions = [{
label: "Packages",
actions: [{
label: "View Packages",
handler: vm.viewPackagesFor,
}, {
label: "Add to Existing",
handler: vm.addToPackages,
}, {
label: "Create New",
handler: vm.openCreatePackageModal,
}],
}, {
actions: [{
label: "Edit Event",
handler: vm.editEvent,
isDisabled: vm.isPPCEvent,
}, {
label: "Remove Event",
handler: vm.confirmRemoveEvents,
}]
}];
}
function isPPCEvent (event) {
/**
* Determines if an event is a Pay Per Channel Event depending on the existence
* of a timePeriodRule
*
* @return {boolean}
*/
return !EventService.isPPV(event);
}
function setEvents(events) {
vm.events = parseResults(events);
}
function parseResults(results) {
var _results = [];
angular.forEach(results, function(result) {
var _result = {};
angular.forEach(result, function(value, key) {
var _params;
if (key == "eventParameters") {
_params = parseParams(result);
if (_params) {
_result[key] = _params;
}
} else {
_result[key] = value;
}
});
_results.push(_result);
});
return _results;
//////////
function parseParams(result) {
var params = null;
if (angular.isDefined(result.eventParameters) && angular.isArray(result.eventParameters.eventParameter)) {
params = {};
angular.forEach(result.eventParameters.eventParameter, parseParam);
}
return params;
/////
function parseParam(param) {
params[_.camelCase(param.key)] = {
name: param.key,
value: param.value.valueType == "NUMBER" ? parseInt(param.value.value, 10) : param.value.value,
valueType: param.value.valueType,
};
}
}
}
function confirmRemoveEvents (events) {
/**
* Open a confirmation modal to prompt the user before removing selected Event(s)
* @param {object|array} events The selected Event or Array of selected Events
*/
ConfirmModalService.openModal({message: "Are you sure you want to remove the Event(s)?"})
.then(function() {
removeEvents(events);
});
}
function removeEvents(events) {
if (!angular.isArray(events)) {
events = [events];
}
// Copy the collection of events to be removed so the content doesn't
// shift around on-screen (since we're changing properties before removal)
var _events = _.map(events, function(evt) {
return _.omit(evt, "networkContentId");
});
ContentsService.removeEvents(_events)
.then(function (response) {
var results = response.result || [],
success,
errors,
tally;
if (!angular.isArray(results)) {
results = [results];
}
tally = _.reduce(results, buildTally, {success: [], error: []});
success = tally.success;
errors = tally.error;
if (success.length) {
AlertsService.addSuccess("Successfully removed Events: " + success.join(", "));
angular.forEach(success, removeEvent);
}
if (errors.length) {
AlertsService.addErrors(_.map(errors, getError));
}
function getError(error) {
return "Could not remove Event: " + error.resultId + " - " + error.resultText + " (" + error.resultCode + ")";
}
function removeEvent(id) {
_.pullAt(vm.events, _.findIndex(vm.events, { smsEventId: id }));
}
function buildTally(tal, res) {
if (res.resultCode === "0") {
tal.success.push(res.resultId);
} else {
tal.error.push(res);
}
return tal;
}
});
}
function addToPackages(chosenEvent) {
openModal({
chosenEvent: chosenEvent,
resolveEvent: true,
templateName: "add_to_packages_modal",
controller: "AddToPackagesModalCtrl",
});
}
function openCreatePackageModal(chosenEvent) {
openModal({
chosenEvent: chosenEvent,
resolveEvent: true,
collection: vm.events,
templateName: "create_package_modal",
controller: "CreatePackageModalCtrl"
});
}
function editEvent(chosenEvent) {
$modal.open({
templateUrl: "app/networks/events/create_event_modal.html",
controller: "EditEventModalCtrl as vm",
size: "lg",
resolve: {
event: function() {
return chosenEvent;
},
content: function () {
return ContentsService.getEventContent(chosenEvent);
}
}
});
}
function viewPackagesFor(chosenEvent) {
openModal({
chosenEvent: chosenEvent,
resolveEvent: true,
templateName: "event_package_list_modal",
controller: "EventPackageListModalCtrl",
size: "md",
});
}
function openModal(opts) {
/**
* Helper function to hand off to the ContentModalService
* @function openModal
* @param opts {Object} The configuration necessary to open the ContentModal.
* @returns Promise The modal promise
*/
return ContentModalService.openModal(opts);
}
}
}());
|
var eventsStorage = localStorage.events;
var events = [];
if (eventsStorage) {
events = JSON.parse(eventsStorage);
}
$(function() {
$('#calendar').fullCalendar({
editable: true,
dayClick: dayClick,
eventClick: eventClick,
timeFormat: 'HH:mm',
displayEventEnd: true,
events: function(start, end, timezone, callback) {
callback(events);
},
eventRender: function(eventObj, $el) {
$el.popover({
title: eventObj.title,
content: eventObj.description,
trigger: 'hover',
placement: 'top',
container: 'body'
});
},
});
$('#start-picker').datetimepicker({
allowInputToggle: true,
format: 'HH:mm'
});
$('#end-picker').datetimepicker({
allowInputToggle: true,
format: 'HH:mm'
});
$("#form-time-start").inputmask({
alias: "datetime",
inputFormat: "HH:MM",
showMaskOnHover: false,
clearMaskOnLostFocus: false,
});
$("#form-time-end").inputmask({
alias: "datetime",
inputFormat: "HH:MM",
showMaskOnHover: false,
clearMaskOnLostFocus: false,
});
});
function getEvents() {
return events;
}
function dayClick(date, jsEvent, view) {
today = moment.utc().startOf('day');
if (date < today) {
return;
}
clearForm();
$('#form-id').val(null);
$('#form-date').val(date.format('YYYY-MM-DD'));
$('#event-modal-label').text("New appointment: " + date.format('MMMM Do YYYY'));
$('#confirm-delete-button').addClass('d-none');
$('#event-modal').modal('show');
}
function eventClick(calEvent, jsEvent, view) {
clearForm();
fillForm(calEvent);
$('#event-modal-label').text("Edit appointment: " + calEvent.start.format('MMMM Do YYYY'));
$('#confirm-delete-button').removeClass('d-none');
$('#event-modal').modal('show');
}
$('#event-form').on('submit', function(e) {
e.preventDefault();
var event = getEventData($('#event-form'));
if (!eventIsValid(event)) {
return;
}
// new event
if (!event.id) {
event.id = generateId();
} else {
// remove event to add updated event
events = events.filter(function(item) {
return item.id !== event.id;
});
}
events.push(event);
localStorage.events = JSON.stringify(events);
$('#calendar').fullCalendar('refetchEvents');
$('#event-modal').modal('hide');
});
$('#confirm-delete-button').on('click', function(){
$('#event-modal').modal('hide');
$('#confirm-delete-modal').modal('show');
});
$('#delete-button').on('click', function(){
$('#confirm-delete-modal').modal('hide');
var event = getEventData($('#event-form'));
deleteEvent(event);
});
$('#cancel-delete-button').on('click', function(){
$('#event-modal').modal('show');
});
function getEventData($form) {
var dataArray = $form.serializeArray();
var data = {};
jQuery.each(dataArray, function(i, item) {
data[item.name] = item.value;
})
return {
"id": data.id,
"title": data.title,
"description": data.description,
"start": data.date + 'T' + data.startTime + ':00',
"end": data.date + 'T' + data.endTime + ':00'
}
}
function deleteEvent(event) {
events = events.filter(function(item) {
return item.id !== event.id;
});
localStorage.events = JSON.stringify(events);
$('#calendar').fullCalendar('refetchEvents');
clearForm();
}
function eventIsValid(event) {
if (event.start > event.end) {
$('#form-alert-text').text('The End time must be greater than the Start time.');
$('#form-alert').removeClass('d-none');
return false;
}
var overlaps = events.filter(function(item){
// ignores comparition with himself
if (item.id === event.id) {
return false;
}
if (
(item.start <= event.start && item.end >= event.end) ||
(item.start >= event.start && item.start <= event.end) ||
(item.end >= event.start && item.end <= event.end)
) {
return true;
}
});
if (overlaps.length > 0) {
$('#form-alert-text').text('This appointment overlaps with another appointment.');
$('#form-alert').removeClass('d-none');
return false;
}
$('#form-alert').addClass('d-none');
return true;
}
function clearForm() {
document.getElementById("event-form").reset();
$('#form-alert').addClass('d-none');
}
function fillForm(event) {
$('#form-id').val(event.id);
$('#form-title').val(event.title);
$('#form-description').val(event.description);
$('#form-data').val(event.start.format('YYYY-MM-DD'));
$('#form-time-start').val(event.start.format('HH:mm'));
$('#form-time-end').val(event.end.format('HH:mm'));
}
function generateId(){
return Date.now().toString(36) + Math.random().toString(36).substr(2, 5) + Math.random().toString(36).substr(2, 5);
} |
import React, { Component } from 'react';
import { createStackNavigator } from 'react-navigation-stack'
import { createAppContainer } from 'react-navigation';
import TabScreen from './Components/AppTabNavigator/TabScreen';
import LoginScreen from './Components/Login/LoginScreen';
import AlarmScreen from './Components/Alarm/AlarmScreen';
import {combineReducers} from "redux";
import { createStore } from 'redux';
import { Provider } from 'react-redux'
import loginReducer from './Components/Login/LoginReducer'
const RootReducer = combineReducers({
loginReducer
});
const Store = createStore(RootReducer);
const AppStackNavigator = createStackNavigator({
Login: {
screen: LoginScreen,
navigationOptions: {
header: null,
},
},
Tab:{
screen: TabScreen
},
Alarm: {
screen: AlarmScreen,
navigationOptions: {
header: null,
}
}
});
class App extends Component {
render() {
const Layout = createAppContainer(AppStackNavigator);
return (
<Provider store={Store}>
<Layout />
</Provider>
);
}
}
export default App; |
const { query } = require('../src/common-publications');
const assert = require('chai').assert;
describe('common-publications', () => {
describe('query', () => {
it('simple match, 1 prop', () => {
const filter = query({ dept: 'a' });
assert.isTrue(filter({ dept: 'a' }));
assert.isFalse(filter({ dept: 'b' }));
});
it('simple match, 2 props', () => {
const filter = query({ dept: 'acct' });
assert.isTrue(filter({ name: 'john', dept: 'acct' }));
assert.isFalse(filter({ name: 'nick', dept: 'xacct' }));
});
});
}); |
import React, { Fragment, useState, useContext } from 'react';
import projectContext from '../../context/projects/projectContext';
const NewProject = () => {
// Get form's state
const projectsContext = useContext(projectContext);
const { form, errorForm, showForm, addProject, showError } = projectsContext;
// state
const [project, setProject] = useState({
name: ''
});
// Extract project's name
const { name } = project;
/**
* Read input's data
* @param {*} e
*/
const onChangeProject = e => {
setProject({
...project,
[e.target.name]: e.target.value
});
};
/**
* Save project in state
* @param {*} e
*/
const onSubmitProject = e => {
e.preventDefault();
// Validate project
if (name === '') {
showError();
return;
}
// Add to state
addProject(project);
// Restart form
setProject({
name: ''
});
};
/**
* Show form
*/
const onClickForm = () => {
showForm();
};
return (
<Fragment>
<button type="button" className="btn btn-block btn-primario" onClick={() => onClickForm()}>
Nuevo Proyecto
</button>
{form ? (
<form className="formulario-nuevo-proyecto" onSubmit={onSubmitProject}>
<input
type="text"
className="input-text"
placeholder="Nombre del Proyecto"
name="name"
value={name}
onChange={onChangeProject}
></input>
<input type="submit" className="btn btn-primario btn-block" value="Agregar Proyecto"></input>
</form>
) : null}
{errorForm ? <p className="mensaje error">El nombre es obligatorio</p> : null}
</Fragment>
);
};
export default NewProject;
|
export const isCorrect = (userAnswer) => {
if (userAnswer === 'yes') {
return true;
} else if (userAnswer === 'no'){
return false;
}
}; |
let events = require("events");
let eventEmitter = new events.EventEmitter();
let myFunct = function () {
console.log("Do Something!");
}
eventEmitter.on('Bump', myFunct);
eventEmitter.emit('Bump');
eventEmitter.emit('Bump');
eventEmitter.emit('Bump');
eventEmitter.emit('Bump');
eventEmitter.emit('Bump'); |
import swap from '../misc/swap_func.js'
export default function heap_sort_animations(arr){
let animations=[]
let n=arr.length
for (let i=Math.floor(n/2)-1;i>=0;i--){
heapify(arr,n,i,animations)
}
for (let i=n-1;i>0;i--)
{
swap(arr,0,i,animations)
heapify(arr,i,0,animations)
}
return animations
}
function heapify(arr,n,i,animations){
let smallest=i
let l=2*i+1
let r=2*i+2
if (l < n && arr[l] < arr[smallest]) smallest = l
if (r < n && arr[r] < arr[smallest]) smallest = r
if (smallest !== i) {
swap(arr,i,smallest,animations)
heapify(arr, n, smallest,animations)
}
}
|
import axios from "axios";
import HttpHelper from './HttpHelper';
class HttpRequestHandler {
constructor() {
this.httpHelper = new HttpHelper();
// this.headers = this.httpHelper.getHeader()
this.headers = { headers : {} };
}
async GET(url, success, error) {
try {
const response = await axios.get(url, this.headers);
if (success) {
success(await response);
}
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async POST(url, params, success, error, headers = {}) {
try {
const config = {
headers : headers
};
const response = await axios.post(url, params, config);
if (success) {
success(await response);
}
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async ALL(urls, token, success, error) {
try {
var requests = []
for( let i=0; i<urls.length; i++) {
requests.push(axios.get(urls[i], this.httpHelper.getHeader(token)));
}
await axios.all(requests).then(axios.spread((...responses) => {
success(responses);
}))
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async MIXED_REQUEST(urls, params, token, success, error) {
try {
var requests = []
for( let i=0; i<urls.length; i++) {
if (params[i].type === 'get') {
requests.push(axios.get(urls[i], this.httpHelper.getHeader(token)));
}
else if (params[i].type === 'post') {
requests.push(axios.post(urls[i], params[i].params, this.httpHelper.getHeader(token)));
}
}
await axios.all(requests).then(axios.spread((...responses) => {
success(responses);
}))
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async UPLOAD_ALL(urls, token, bodyParams, success, error) {
try {
var requests = []
for( let i=0; i<urls.length; i++) {
requests.push(axios.post(urls[i], bodyParams[i], this.httpHelper.getMultiPartHeader(token)));
}
await axios.all(requests).then(axios.spread((...responses) => {
success(responses);
}))
} catch (err) {
console.log(err);
if (error) {
error(await err.response);
}
}
}
async DOWNLOAD(url, token, params, success, error) {
try {
const response = await axios.post(url, params, this.httpHelper.getDownloadHeader(token));
if (success) {
success(await response);
}
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async UPLOAD(url, token, data, success, error) {
try {
const response = await axios.post(url, data, this.httpHelper.getMultiPartHeader(token));
if (success) {
success(await response);
}
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async PUT(url, params, success, error) {
try {
const response = await axios.put(url, params, this.headers);
if (success) {
success(await response);
}
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async POST_METHOD(url, params, success, error) {
try {
const response = await axios.post(url, params, this.headers);
if (success) {
success(await response);
}
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async PATCH(url, params, success, error) {
try {
const response = await axios.patch(url, params, this.headers);
if (success) {
success(await response);
}
} catch (err) {
if (error) {
error(await err.response);
}
}
}
async DELETE(url, token, params, success, error) {
try {
const config = this.httpHelper.getHeader(token);
if(params) {
config.data = {
userId: params.userId,
teamId: params.teamId
};
}
const response = await axios.delete(url, config);
if (success) {
success(await response);
}
} catch (err) {
if (error) {
error(await err.response);
}
}
}
}
export default HttpRequestHandler;
|
export const addValue = value => ({
type: 'ADD_VALUE',
value
})
export const removeFromHistory = value => ({
type: 'REMOVE_FROM_HISTORY',
value
}) |
define(['require', 'angular'], function (require, angular) {
'use strict';
var siteId, ngApp;
siteId = location.search.match('site=(.*)')[1];
ngApp = angular.module('app', ['ngSanitize', 'ui.bootstrap']);
ngApp.controller('ctrlMain', ['$scope', '$q', '$http', function ($scope, $q, $http) {
function listSubscription(page) {
var defer = $q.defer(),
url;
if (page === undefined) {
page = {
at: 1,
size: 10,
total: 0,
j: function () {
return 'page=' + this.at + '&size=' + this.size;
}
};
}
url = '/rest/site/fe/user/subscribe/list?site=' + siteId;
url += '&' + page.j();
$http.get(url).success(function (rsp) {
page.total = rsp.data.total;
defer.resolve({
matters: rsp.data.matters,
page: page
});
});
return defer.promise;
}
$scope.openMatter = function (matter) {
var url = location.protocol + '//' + location.host + '/rest/site/fe/matter';
if (/article|custom|channel/.test(matter.matter_type)) {
url += '?id=' + matter.matter_id + '&type=' + matter.matter_type + '&site=' + matter.siteid;
} else {
url += '/' + matter.matter_type + '?id=' + matter.matter_id + '&site=' + matter.siteid;
}
location.href = url;
};
$scope.moreMatters = function () {
$scope.page.at++;
listSubscription($scope.page).then(function (result) {
if (result.matters && result.matters.length) {
result.matters.forEach(function (matter) {
$scope.matters.push(matter);
});
}
});
};
$http.get('/rest/site/fe/get?site=' + siteId).success(function (rsp) {
$scope.site = rsp.data;
listSubscription().then(function (result) {
$scope.matters = result.matters;
$scope.page = result.page;
});
window.loading.finish();
});
}]);
/* bootstrap angular app */
require(['domReady!'], function (document) {
angular.bootstrap(document, ["app"]);
});
}); |
import {
GET_MARKET_CAP,
GET_GLOBAL_MARKET_CAP,
GET_BTC_PERCENTILE,
INIT_COINS,
GET_COIN_PRICE,
GET_WON_BY_DOLLAR,
GET_TRANSACTIONS,
GET_INFLATION,
GET_DCB_DATA,
GET_DDENGLE_DATA,
GET_COINPAN_DATA,
GET_CLIEN_DATA,
GET_REDDIT_DATA,
} from './types.js';
import * as api from '../utils/api';
// -------------------------- Market Actions --------------------------
export const getMarketCap = (coin) => dispatch => {
return api.getMarketCap(coin)
.then(data => dispatch({type: GET_MARKET_CAP, data}));
};
export const getGlobalMarketCap = () => dispatch => {
return api.getGlobalMarketCap()
.then(data => dispatch({type: GET_GLOBAL_MARKET_CAP, data}));
};
export const getBTCPercentile = () => dispatch => {
return api.getBTCPercentile()
.then(data => dispatch({type: GET_BTC_PERCENTILE, data}));
};
export const initCoins = (coin) => dispatch => {
return dispatch({
type: INIT_COINS,
name: coin.name,
symbolBig: coin.symbolBig,
symbolSmall: coin.symbolSmall,
img: coin.img,
coin
});
};
export const getCoinPrice = (coin) => dispatch => {
api.marketBithumb(coin.symbolBig)
.then(data => dispatch({type: GET_COIN_PRICE, bithumbPrice: data, coin}))
api.marketUpbit(coin.symbolBig)
.then(data => dispatch({type: GET_COIN_PRICE, upbitPrice: data, coin}))
api.marketBittrex(coin.symbolSmall)
.then(data => dispatch({type: GET_COIN_PRICE, bittrexPrice: data, coin}))
api.marketBitfinex(coin.symbolSmall)
.then(data => dispatch({type: GET_COIN_PRICE, bitfinexPrice: data, coin}))
}
export const getWonByDollar = () => dispatch => {
return api.getWonByDollar()
.then(data => dispatch({type: GET_WON_BY_DOLLAR, data}))
}
// -------------------- Bubble Actions -------------------------
export const getTransactions = () => dispatch => {
return api.getTransactions()
.then(data => dispatch({type: GET_TRANSACTIONS, data}))
}
export const getInflation = (value, year) => dispatch => {
return api.getInflation(value, year)
.then(data => dispatch({type: GET_INFLATION, data}))
}
// -------------------- COMMUNITIES Actions -----------------------
export const getDCBData = () => dispatch => {
return api.loadDCB()
.then(data => dispatch({type: GET_DCB_DATA, data}))
}
export const getDdengleData = () => dispatch => {
return api.loadDdengle()
.then(data => dispatch({type: GET_DDENGLE_DATA, data}))
}
export const getCoinpanData = () => dispatch => {
return api.loadCoinpan()
.then(data => dispatch({type: GET_COINPAN_DATA, data}))
}
export const getClienData = () => dispatch => {
return api.loadClien()
.then(data => dispatch({type: GET_CLIEN_DATA, data}))
}
export const getRedditData = () => dispatch => {
return api.loadReddit()
.then(data => dispatch({type: GET_REDDIT_DATA, data}))
}
|
import { determineEmojiSupportLevel } from '../../../src/picker/utils/determineEmojiSupportLevel'
import { versionsAndTestEmoji } from '../../../bin/versionsAndTestEmoji'
import { setSimulateCanvasError, setSimulateOldBrowser } from '../../../src/picker/utils/testColorEmojiSupported'
describe('emoji support', () => {
test('returns latest emoji', () => {
const version = determineEmojiSupportLevel()
expect(version).toEqual(Math.max(...Object.values(versionsAndTestEmoji)))
})
describe('canvas error', () => {
beforeEach(() => {
setSimulateCanvasError(true)
})
afterEach(() => {
setSimulateCanvasError(false)
})
test('returns latest emoji when there is a canvas error', () => {
const version = determineEmojiSupportLevel()
expect(version).toEqual(Math.max(...Object.values(versionsAndTestEmoji)))
})
})
describe('old browser', () => {
beforeEach(() => {
setSimulateOldBrowser(true)
})
afterEach(() => {
setSimulateOldBrowser(false)
})
test('returns older emoji version for older browser', () => {
const version = determineEmojiSupportLevel()
expect(version).toEqual(11)
})
})
})
|
//function to go here on create an logo on a case
//rousseau jeremie 22/04/2016
//on selectionne uen case vide un bâtiment ou une unité
//via son Id et sa classe
// Irajouter parId dans calss move et peut être gogo[itrGogoT][0]gogo[itrGogoT][1]
function Select(ParId){
var getCase = Id(ParId).className;
//faire quelque chsoe en fonctionde l'idée det de la class
switch(getCase){
case "empty":
GoHere(ParId);
break;
case "unit":
selectUnit(ParId);
break;
}
}
//function si c'est vide
function GoHere(ParId){
if( TkHere === 0 ){
Id(ParId).className = "Here";
TkHere = 1;
XY(ParId);
stopXstopY();
if(TokengXY > 0){
console.log(TokengXY+"a");
start();
}
}else{
//remove the first point
goStop = document.getElementsByClassName("Here")[0];
goStop.className = "empty";
TkHere = 0;
//create a loop to avoid double clicking
GoHere(ParId);
}
}
// variable nbr for gogo[gXY][X][Y];
var TokengXY = 0;
function selectUnit(ParId){
Id(ParId).className = "selected_unit";
XY( ParId );
TokengXY += 1;
unitXY( TokengXY );
}
function XY( numXY ){
var NumXY = numXY;
Mxy = NumXY.match(/\d+/g);
//undefined if no group selected
return Mxy;
//return an string Mxy[0]
}
gogo = [];
gogo[0] = [];
gogo[0][0] = 0;
gogo[0][1] = 0;
gogo[0][2] = [];
var diffPath = [];
//let's this line in place if not that create an little bug
diffPath.push( gogo[0][0] + v + gogo[0][1] );
function unitXY(s){
X = parseInt(Mxy[0]);
Y = parseInt(Mxy[1]);
gogo[s] = [];
gogo[s][0] = X;
gogo[s][1] = Y;
gogo[0][2] = [];
//diffPath.push( gogo[s][0] + v + gogo[s][1] );
}
function stopXstopY(){
stopX = parseInt(Mxy[0]);
stopY = parseInt(Mxy[1]);
}
function start(){
console.log("ARRAY" + diffPath);
gogoInterval = setInterval( function timerB() {
for( var itrGogo = 1 ; itrGogo < gogo.length; itrGogo++){
(function(){
//very important to let as this.
var itrGogoT = itrGogo;
//console.log(gogo[itrGogoT][0] == stopX && gogo[itrGogoT][1] == stopY );
if( gogo[itrGogoT][0] == stopX && gogo[itrGogoT][1] == stopY ){
console.log("stop");
clearInterval(gogoInterval);
}
setTimeout( function timer(){
//let empty the case where was the unit
Id( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] ).className = "floor";
//clear the case's array to let' empty the position
index = diffPath.indexOf((gogo[itrGogoT][0] + v + gogo[itrGogoT][1]));
if (index > -1) {
diffPath.splice(index, 1);
}
//to avoid to take two time the same direction per one seconde
needle = false;
if ( gogo[itrGogoT][1] < stopY && gogo[itrGogoT][0] < stopX && needle === false ) {
//console.log(" goDiaUpRight");
gogo[itrGogoT][0] += 1;
gogo[itrGogoT][1] += 1;
if ( diffPath.indexOf( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] ) >= 0) {
gogo[itrGogoT][0] -= 1;
gogo[itrGogoT][1] -= 1;
}
if ( gogo[itrGogoT][0] > SIZE && gogo[itrGogoT][1] ) {
gogo[itrGogoT][0] -= 1;
gogo[itrGogoT][1] -= 1;
}
needle = true;
}
if ( gogo[itrGogoT][1] > stopY && gogo[itrGogoT][0] < stopX && needle === false ) {
//console.log(" goDiaDownRight");
gogo[itrGogoT][0] += 1;
gogo[itrGogoT][1] -= 1;
if ( diffPath.indexOf( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] ) >= 0) {
gogo[itrGogoT][0] -= 1;
gogo[itrGogoT][1] += 1;
}
if ( gogo[itrGogoT][0] > SIZE && gogo[itrGogoT][1] < 1 ){
gogo[itrGogoT][0] -= 1;
gogo[itrGogoT][1] += 1;
}
needle = true;
}
if ( gogo[itrGogoT][1] < stopY && gogo[itrGogoT][0] > stopX && needle === false ) {
console.log("//goDiaUpLeft");
gogo[itrGogoT][0] -= 1;
gogo[itrGogoT][1] += 1;
if ( diffPath.indexOf( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] ) >= 0) {
gogo[itrGogoT][0] += 1;
gogo[itrGogoT][1] -= 1;
}
needle = true;
}
if ( gogo[itrGogoT][1] > stopY && gogo[itrGogoT][0] > stopX && needle === false ) {
//goDiaDownLeft
gogo[itrGogoT][0] -= 1;
gogo[itrGogoT][1] -= 1;
if ( diffPath.indexOf( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] ) >= 0) {
gogo[itrGogoT][0] += 1;
gogo[itrGogoT][1] += 1;
}
if (gogo[itrGogoT][0] < 1 && gogo[itrGogoT][1] < 1) {
gogo[itrGogoT][0] += 1;
gogo[itrGogoT][1] += 1;
}
needle = true;
}
if ( gogo[itrGogoT][0] < stopX && needle === false ) {
//console.log("right");
//right
gogo[itrGogoT][0] += 1;
gogo[itrGogoT][1] += 0;
if ( diffPath.indexOf( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] ) >= 0 ) {
gogo[itrGogoT][0] -= 1;
gogo[itrGogoT][1] += 0;
}
if ( gogo[itrGogoT][0] > SIZE ) {
gogo[itrGogoT][0] -= 1;
}
needle = true;
}
if ( gogo[itrGogoT][0] > stopX && needle === false ){
//console.log("left");
//left
gogo[itrGogoT][0] -= 1;
gogo[itrGogoT][1] += 0;
if ( diffPath.indexOf( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] ) >= 0) {
gogo[itrGogoT][0] += 1;
gogo[itrGogoT][1] += 0;
}
if ( gogo[itrGogoT][0] === 0 ) {
gogo[itrGogoT][1] += 1;
}
needle = true;
}
if ( gogo[itrGogoT][1] > stopY && needle === false ){
//console.log("down");
//down
gogo[itrGogoT][0] += 0;
gogo[itrGogoT][1] -= 1;
if ( diffPath.indexOf( gogo[itrGogoT][0] + v + gogo[itrGogoT][1]) >= 0) {
gogo[itrGogoT][0] += 0;
gogo[itrGogoT][1] += 1;
}
if ( gogo[itrGogoT][1] === 0 ) {
gogo[itrGogoT][1] += 1;
}
needle = true;
}
if ( gogo[itrGogoT][1] < stopY && needle === false ){
//console.log("up");
//up
gogo[itrGogoT][0] += 0;
gogo[itrGogoT][1] += 1;
if ( diffPath.indexOf( gogo[itrGogoT][0] + v + gogo[itrGogoT][1]) >= 0) {
gogo[itrGogoT][0] += 0;
gogo[itrGogoT][1] -= 1;
}
if( gogo[itrGogoT][1] >= SIZE ){
gogo[itrGogoT][1] -= 1;
}
needle = true;
}
diffPath.push( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] );
Id( gogo[itrGogoT][0] + v + gogo[itrGogoT][1] ).className = "unit";
//areaOfTarget = (gogo[itrGogoT][0] += 3 );
//console.log(areaOfTarget);
//
}, itrGogoT*1000);
}());
}
console.log("A");
}, 1000);
} |
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
configureWebpack: config => {
if (process.env.NODE_ENV === 'production') {
return {
plugins:[
new CopyWebpackPlugin([{
from:'node_modules/@aspnet/signalr/dist/browser/signalr.min.js',
to:'dist'
},{
from:'node_modules/abp-web-resources/Abp/Framework/scripts/libs/abp.signalr-client.js',
to:'dist'
},{
from:'src/lib/abp.js',
to:'dist'
}])
]
}
} else {
return {
plugins:[
new CopyWebpackPlugin([{
from:'node_modules/@aspnet/signalr/dist/browser/signalr.min.js',
to:'dist'
},{
from:'node_modules/abp-web-resources/Abp/Framework/scripts/libs/abp.signalr-client.js',
to:'dist'
},{
from:'src/lib/abp.js',
to:'dist'
}])
]
}
}
}
} |
import { defineProtoFunc } from "./defineProtoFunc.js";
const typedArrays = [
Int8Array,
Uint8Array,
Uint8ClampedArray,
Int16Array,
Uint16Array,
Int32Array,
Uint32Array,
Float32Array
];
for (const typedArray of typedArrays) {
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/fill#polyfill
defineProtoFunc(typedArray, "fill", Array.prototype.fill);
defineProtoFunc(typedArray, "join", Array.prototype.join);
}
|
function sleep(milliseconds) {
var start = Date.now();
while ((Date.now() - start) < milliseconds);
}
let video1downloaded = new Promise((resolve,reject) =>{
sleep(5000);
console.log("Video1 downloaded.");
})
let video2downloaded = new Promise((resolve,reject) =>{
sleep(7000);
console.log("Video2 downloaded.")
})
let video3downloaded = new Promise((resolve,reject) =>{
sleep(2000);
console.log("Video3 downloaded.")
})
//wait till all promises are fullfilled
// Promise.all([video1downloaded,
// video2downloaded,
// video3downloaded]).then((msg) =>{
// console.log(msg);
// })
console.log("I am done1");
//executed as soon as any promise is fullfilled
Promise.race([video1downloaded,
video2downloaded,
video3downloaded]).then((msg) =>{
console.log(msg);
})
console.log("I am done2"); |
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from './components/App/App.js';
import { createStore, combineReducers, applyMiddleware } from 'redux';
// Provider allows us to use redux within our react app
import { Provider } from 'react-redux';
import logger from 'redux-logger';
import createSagaMiddleware from 'redux-saga';
import { takeEvery, put } from 'redux-saga/effects';
import axios from 'axios';
//ROOT saga here
function* rootSaga() {
yield takeEvery('FETCH_GIFS', getGifsSaga);
yield takeEvery('FAVORITE_GIF', favoriteSaga);
yield takeEvery('GET_FAVORITES', getFavorites);
yield takeEvery('GET_CATEGORIES', getCategorySaga);
}
//GET saga here
function* getGifsSaga(action) {
try {
const receivedGifs = yield axios.get(`/api/search/${action.payload}`);
console.log(receivedGifs);
yield put({ type: 'GET_GIFS', payload: receivedGifs.data.data });
} catch (error) {
console.log('error fetching gifs', error);
}
}
function* getCategorySaga(action) {
try {
const receivedCategories = yield axios.get(`/api/category/`);
yield put({ type: 'SET_CATEGORIES', payload: receivedCategories.data });
} catch (error) {
console.log('error fetching categories', error);
}
}
//POST saga
function* favoriteSaga(action) {
try {
yield axios.post('/api/favorite', action.payload)
yield put({ type: 'GET_GIFS' })
}
catch (error) {
console.log('error posting gif', error);
}
}
//GET favorites saga
function* getFavorites(action) {
try {
const favoriteGifs = yield axios.get('/api/favorite')
console.log(favoriteGifs);
yield put({ type: 'FAVORITES_REDUCER', payload: favoriteGifs.data})
}
catch (error) {
console.log('error posting gif', error);
}
}
// Create saga middleware
const sagaMiddleware = createSagaMiddleware();
// Reducer that holds our results
const fetchNewGifs = (state = [], action) => {
if (action.type === 'GET_GIFS') {
return action.payload;
}
return state;
}
const fetchFavoriteGifs = (state = [], action) => {
if (action.type === 'FAVORITES_REDUCER') {
return action.payload;
}
return state;
}
const fetchCategories = (state = [], action) => {
if (action.type === 'SET_CATEGORIES') {
return action.payload;
}
return state;
}
// Create one store that all components can use
const storeInstance = createStore(
combineReducers({
fetchNewGifs,
fetchFavoriteGifs,
fetchCategories,
}),
applyMiddleware(logger, sagaMiddleware),
);
sagaMiddleware.run(rootSaga);
ReactDOM.render(<Provider store={storeInstance}><App /></Provider>,
document.getElementById('react-root'));
|
import BinaryTree from "binary_tree_lib";
export default class BinarySearchTree extends BinaryTree {
insert( value ) {
if (value < this.value) {
this.left.insert(value);
} else if (value > this.value) {
this.right.insert(value);
}
}
toString() {
return this.left.toString() + ", " + this.value + ", " + this.right.toString();
}
toArray() {
return [...this.left.toArray(), this.value, ...this.right.toArray()];
}
has( value ) {
if (typeof this.value == 'undefined') {
return false;
}
if (value == this.value) {
return true;
}
if (value < this.value) {
return this.left.has(value);
} else if (value > this.value) {
return this.right.has(value);
}
}
}
|
import * as React from 'react'
import {
View,
StyleSheet,
ActivityIndicator,
Text,
AsyncStorage
} from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#B12D30',
justifyContent: 'center',
alignItems: 'center',
},
loadingText: {
fontSize: 18,
color: '#FFF',
fontWeight: 'bold',
marginTop: 15,
},
});
class Loading extends React.Component {
async componentDidMount() {
const username = await AsyncStorage.getItem('username');
if (username) {
this.props.navigation.navigate('Home')
} else {
this.props.navigation.navigate('Login')
}
}
render() {
return (
<View style={styles.container}>
<ActivityIndicator size="large" color="#FFF" />
<Text style={styles.loadingText}>Carregando...</Text>
</View>
);
}
}
export default Loading; |
const { query } = require('express-validator')
const withValidationErrorHandler = require('./withValidationErrorHandler')
const utils = require('../utils')
const getEntriesValidators = withValidationErrorHandler([
query('date').optional().isISO8601().withMessage('date param format must be YYYY-DD-MM'),
query('client_tz').optional().custom((value, { req }) => utils.isValidTimeZone(value))
])
module.exports = {
getEntriesValidators
}
|
var mn = mn || {};
mn.components = mn.components || {};
mn.components.MnXDCRDeleteReference =
(function (Rx) {
"use strict";
mn.core.extend(MnXDCRDeleteReference, mn.core.MnEventableComponent);
MnXDCRDeleteReference.annotations = [
new ng.core.Component({
templateUrl: "app-new/mn-xdcr-delete-reference.html",
changeDetection: ng.core.ChangeDetectionStrategy.OnPush,
inputs: [
"reference"
]
})
];
MnXDCRDeleteReference.parameters = [
ngb.NgbActiveModal,
mn.services.MnXDCR,
mn.services.MnForm
];
return MnXDCRDeleteReference;
function MnXDCRDeleteReference(activeModal, mnXDCRService, mnFormService) {
mn.core.MnEventableComponent.call(this);
this.form = mnFormService.create(this)
.setPackPipe(Rx.operators.map(function () {
return this.reference.name
}.bind(this)))
.setPostRequest(mnXDCRService.stream.deleteRemoteClusters)
.successMessage("Replication deleted successfully!")
.success(function () {
activeModal.close();
mnXDCRService.stream.updateRemoteClusters.next();
});
this.activeModal = activeModal;
}
})(window.rxjs);
|
$(document).ready(function(){
$(".panel").mouseup(function(e){
$(e.target).parents(".panel-title").find(".arrowCollapsed").addClass("hideArrow");
$(e.target).parents(".panel-title").find(".arrowExpaned").removeClass("hideArrow");
});
$(".panel-group").mouseup(function(e){
panelCollapsed = $(e.target).parents(".panel").find(".collapse").hasClass("in");
if (panelCollapsed) {
$(e.target).parents(".panel-title").find(".arrowCollapsed").removeClass("hideArrow");
$(e.target).parents(".panel-title").find(".arrowExpaned").addClass("hideArrow");
} else {
$(".arrowCollapsed").removeClass("hideArrow");
$(".arrowExpaned").addClass("hideArrow");
$(e.target).parents(".panel-title").find(".arrowCollapsed").addClass("hideArrow");
$(e.target).parents(".panel-title").find(".arrowExpaned").removeClass("hideArrow");
}
});
$('.closeEditModal').click(function () {
location.reload();
});
var form = null;
mask(".PrjShort", (/[\\~@#$%^<>\]\[&*=|/}{]+/ig), 149);
mask(".PrjFull", (/[\\~@#$%^<>\]\[&*=|/}{]+/ig), 1000);
mask(".TeamTask", (/[\\~@#$%^<>\]\[&*=|/}{]+/ig), 50);
mask(".TeamWork", (/[\\~@#$%^<>\]\[&*=|/}{]+/ig), 600);
$("#editProjectForm").validate({
submitHandler: function (editproject) {
console.log("validation ok");
form = editproject;
$('#readyConfirm').removeClass('hide');
$('#readyConfirm').modal('show');
}
});
$('#saveButton').click(function () {
$('.textField').each(function () {
$(this).rules('add', {
required: true,
messages: {
required: "Это обязательное поле",
}
});
});
});
$("#cancelButton").click(function () {
$('#closeConfirm').removeClass('hide');
$('#closeConfirm').modal('show');
});
$(".confirm_modal_btn").click(function () { //Сохранить изменения? НЕТ
$('#readyConfirm').addClass('hide');
});
$(".submit_btn").click(function () { // Сохранить изменения? ДА
if ($("#editProjectForm").valid()) {
RenewProject();
window.location.reload();
}
});
$(".submit_btn_edit").click(function () { // Сохранить изменения? ДА
if ($("#editProjectForm").valid()) {
console.log("validation ok");
form.submit();
}
});
$(".close_btn_modal").click(function () { //Выйти без изменений? НЕТ
$('#closeConfirm').addClass('hide');
})
$(".close_modal_btn").click(function () { //Выйти без изменений? ДА
$('#closeConfirm').addClass('hide');
$('#closeConfirm').modal('hide');
$('#readyConfirm').modal('hide');
HideReviewForm();
});
function HideReviewForm() {
// $('#projectEditModal').addClass('hide')
$('#projectEditModal').modal('hide');
};
function RenewProject() {
console.log("Ajax sent")
var data = {};
projectId = "projectId887"; //для проверки локально, потом закомментировать
//projectId = $('input[name="ProjectId"]').val(); // раскомментировать. Или не ProjectId, но что-то по чему идентифицируется проект
data.project = projectId;
data.projectShortDesc = $('textarea[name="projectShortDescription"]').val();
data.projectFullDesc = $('textarea[name="pojectFullDescription"]').val();
data.teamTask = $('textarea[name="teamTask"]').val();
data.teamWorkDesription = $('textarea[name="teamWorkDesription"]').val();
var json = JSON.stringify(data);
console.log(json);
$('#readyConfirm').addClass('hide'); //для проверки локально, потом закомментировать
$('#readyConfirm').modal('hide'); //повторяет строки внутри success
$.ajax({
type: 'POST',
url: '/Mentor/Review', // изменить ссылку
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
// PLACE FOR CALLBACK
console.log("ok Ajax");
$('#readyConfirm').addClass('hide');
$('#readyConfirm').modal('hide');
//window.location.href = "http://www.it-academy.by/" // заменить ссылку (move to the project page that we’ve just created)
},
error: function (data, error, mess) {
console.log("error: " + data + " " + error + " " + mess);
}
});
};
}); |
// @flow
import * as React from 'react';
import ShallowRenderer from 'react-test-renderer/shallow';
const renderer = new ShallowRenderer();
import { BoardingPassPdf } from '../BoardingPassPdf';
jest.mock('rn-fetch-blob');
const getWrapper = (
bookingId: number = 123456,
BoardingPassUrl: string = 'https://somedomain.com/folder/subfolder/file.pdf',
flightNumber: string = '123_321',
) =>
renderer.render(
<BoardingPassPdf
bookingId={bookingId}
boardingPassUrl={BoardingPassUrl}
flightNumber={flightNumber}
/>,
);
describe('BoardingPassPdf', () => {
it('renders', () => {
const wrapper = getWrapper();
expect(wrapper).toMatchInlineSnapshot(`
<PdfViewAndStore
fileName="boardingPasses/123456/123_321.pdf"
overwriteExisting={false}
url="https://somedomain.com/folder/subfolder/file.pdf"
/>
`);
});
it('show error if bookingId is missing', () => {
// $FlowExpectedError: Intentionally testing what happens with null value
const wrapper = getWrapper(null);
expect(wrapper).toMatchInlineSnapshot(`
<GeneralError
errorMessage={
<Translation
id="mmb.boarding_passes.not_available"
/>
}
/>
`);
});
it('show error if boardingPassUrl is missing', () => {
// $FlowExpectedError: Intentionally testing what happens with null value
const wrapper = getWrapper(123, null);
expect(wrapper).toMatchInlineSnapshot(`
<GeneralError
errorMessage={
<Translation
id="mmb.boarding_passes.not_available"
/>
}
/>
`);
});
it('show error if flightNumber is missing', () => {
// $FlowExpectedError: Intentionally testing what happens with null value
const wrapper = getWrapper(123, 'test', null);
expect(wrapper).toMatchInlineSnapshot(`
<GeneralError
errorMessage={
<Translation
id="mmb.boarding_passes.not_available"
/>
}
/>
`);
});
});
|
import * as types from '../constants/ActionTypes'
import { ERROR_CONNECTION_REFUSED, FETCHING, INIT, READY } from '../constants/Status'
const initialState = {
items: {},
selectedPost: {},
status: INIT
}
const posts = (state = initialState, action) => {
switch (action.type) {
case types.DECREASE_COMMENT_COUNT:
return {
...state,
selectedPost: {
...state.selectedPost,
commentCount: --state.selectedPost.commentCount
}
}
case types.FAIL_REQUEST_POSTS:
return {
...state,
status: ERROR_CONNECTION_REFUSED
}
case types.HANDLE_ERROR:
return {
...state,
status: action.status
}
case types.INCREASE_COMMENT_COUNT:
return {
...state,
selectedPost: {
...state.selectedPost,
commentCount: ++state.selectedPost.commentCount
}
}
case types.INIT_POST:
return {
...state,
status: INIT
}
case types.RECEIVE_ADD_POST :
return {
...state,
items: {
...state.items,
[action.post.id]: action.post
},
status: READY
}
case types.RECEIVE_GET_POST :
return {
...state,
selectedPost: action.post,
status: READY
}
case types.RECEIVE_GET_POSTS :
return {
...state,
items: action.posts,
status: READY
}
case types.RECEIVE_DELETE_POST :
case types.RECEIVE_DOWNVOTE_POST :
case types.RECEIVE_UPDATE_POST :
case types.RECEIVE_UPVOTE_POST :
return {
...state,
items: {
...state.items,
[action.post.id]: action.post
},
selectedPost: state.selectedPost.id ? action.post : {},
status: READY
}
case types.REQUEST_ADD_POST :
case types.REQUEST_DELETE_POST :
case types.REQUEST_DOWNVOTE_POST :
case types.REQUEST_GET_POST :
case types.REQUEST_GET_POSTS :
case types.REQUEST_UPDATE_POST :
case types.REQUEST_UPVOTE_POST :
return {
...state,
status: FETCHING
}
case types.SELECT_POST :
return {
...state,
selectedPost: state.items[action.postId],
status: READY
}
case types.UNSELECT_POST :
return {
...state,
selectedPost: {},
status: INIT
}
default:
return state
}
}
export default posts
|
/*
* inventoryApi.js
*
* Copyright (c) 2016 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
(function () {
angular.module('productMaintenanceUiApp').factory('InventoryFactory', inventoryFactory);
inventoryFactory.$inject = ['urlBase', '$resource'];
/**
* Creates a factory to create methods to contact product maintenance's inventory API.
*
* Supported methods:
* queryStoreInventory: Will return total inventory of a product across all stores. Pass in a parameter
* of productId.
*
* @param urlBase The base URL to use to contact the backend.
* @param $resource Angular $resource used to construct the client to the REST service.
* @returns {*} The inventory API factory.
*/
function inventoryFactory(urlBase, $resource) {
return $resource(urlBase + '/pm/inventory/:productId', null, {
'queryStoreInventory': {
method: 'GET',
url: urlBase + '/pm/inventory/store',
isArray: false
},
"queryPurchaseOrders": {
method: 'GET',
url: urlBase + '/pm/inventory/purchaseOrders',
isArray: false
},
'queryVendorInventory': {
method: 'GET',
url: urlBase + '/pm/inventory/vendor',
isArray: false
}
});
}
})();
|
import React from 'react';
// import DatePicker from "react-datepicker";
// import "react-datepicker/dist/react-datepicker.css";
// import en from 'date-fns/locale/en-GB';
import MaskedInput from 'react-text-mask'
// registerLocale('en', en)
import ArrowBlue from '../../assets/arrow-blue.svg';
import ArrowWhite from '../../assets/arrow-white.svg';
// const DateField = props => {
// const placeholderText = props.placeholderText;
// var textColor = props.lightText ? '#FFF' : '#090039';
// // const calendar = useRef(null)
// const [startDate, setStartDate] = useState(new Date());
// const handleSetStartDate = (date) => {
// setStartDate(date);
// props.onChange(date);
// }
// return (
//
// <div className="datefield" style={{color:textColor}}>
// <div className="datefield__toptext">
// <span>{props.topText}</span>
// </div>
// <div className="datefield__content">
// <form>
// <label className="datefield__container">
// <DatePicker
// selected={startDate}
// onChange={handleSetStartDate}
// className="datefield__textinput"
// shouldCloseOnSelect={true}
// locale={en}
// placeholderText="dd/mm/yy"
// dateFormat="MMMM d, yyyy"
// // ref={calendar}
// />
// {/* <span className="datefield__textfield"></span> */}
// </label>
// </form>
// {props.arrow === true ? <img className="datefield__arrow" src={
// props.lightText === true ? ArrowWhite: ArrowBlue} alt="->"/>
// : null
// }
//
// </div>
// {props.lightText ? <div className="datefield__line" style={{backgroundColor:'#E1E1EF'}}/> : <div className="datefield__line"/>}
//
// </div>
// );
// };
//
// export default DateField;
const DateField = props => {
var textColor = props.lightText ? '#FFF' : '#090039';
// const calendar = useRef(null)
// const [startDate, setStartDate] = useState(new Date());
const handleSetStartDate = (date) => {
// console.log(date.target.value);
// console.log(date);
// setStartDate(date.target.value);
props.onChange(date.target.value);
}
return (
<div className="datefield" style={{color:textColor}}>
<div className="datefield__toptext">
<span>{props.topText}</span>
</div>
<div className="datefield__content">
<form autoComplete="off">
<label className="datefield__container">
<MaskedInput
mask={[/[0-9]/, /\d/, '/' , /\d/, /\d/, '/', "2020"]}
placeholder="dd/mm/2020"
className="datefield__textinput"
onChange={handleSetStartDate}
// value={props.value}
kind={'datetime'}
options={{
format: 'DD-MM-YYYY'
}}
/>
</label>
</form>
{props.arrow === true ? <img className="datefield__arrow" src={
props.lightText === true ? ArrowWhite: ArrowBlue} alt="->"/>
: null
}
</div>
{props.lightText ? <div className="datefield__line" style={{backgroundColor:'#E1E1EF'}}/> : <div className="datefield__line"/>}
</div>
);
};
export default DateField;
|
const width = 28;
const grid = document.querySelector('.grid');
const scoreDisplay = document.querySelector('#score');
let squares=[];
let score = 0;
//28*28
// 0 - pac-dots
// 1 - wall
// 2 - ghost-lair
// 3 - power-pellet
// 4 - empty
const layout= [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,3,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,3,1,
1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,4,4,4,4,4,4,4,4,4,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,1,1,1,2,2,1,1,1,4,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,1,2,2,2,2,2,2,1,4,1,1,0,1,1,1,1,1,1,
4,4,4,4,4,4,0,0,0,4,1,2,2,2,2,2,2,1,4,0,0,0,4,4,4,4,4,4,
1,1,1,1,1,1,0,1,1,4,1,2,2,2,2,2,2,1,4,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,1,1,1,1,1,1,1,1,4,1,1,0,1,1,1,1,1,1,
1,1,1,1,1,1,0,1,1,4,1,1,1,1,1,1,1,1,4,1,1,0,1,1,1,1,1,1,
1,0,0,0,0,0,0,0,0,4,4,4,4,4,4,4,4,4,4,0,0,0,0,0,0,0,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,0,1,1,1,1,0,1,1,1,1,1,0,1,1,0,1,1,1,1,1,0,1,1,1,1,0,1,
1,3,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,3,1,
1,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1,
1,1,1,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,0,1,1,0,1,1,0,1,1,1,
1,0,0,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,1,1,0,0,0,0,0,0,1,
1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,
1,0,1,1,1,1,1,1,1,1,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1
]
//create board
function createBoard(){
for (let i = 0; i <layout.length; i++){
const square = document.createElement('div');
grid.appendChild(square);
squares.push(square);
if(layout[i] === 0){
squares[i].classList.add('pac-dot');
}else if(layout[i]===1){
squares[i].classList.add('wall');
}else if(layout[i]===3){
squares[i].classList.add('power-pellet')
}
}
}
createBoard();
//starting position of pacman
let pacmanCurrentIndex = 490;
squares[pacmanCurrentIndex].classList.add('pac-man')
function control(e){
// if(e.keyCode === 40){
// console.log('down pressed')
// } else if(e.keyCode === 38){
// console.log('up')
// }else if(e.keyCode === 37){
// console.log('left')
// }else if(e.keyCode===39){
// console.log('right')
// }
squares[pacmanCurrentIndex].classList.remove('pac-man');
switch(e.keyCode){
case 40:
if(pacmanCurrentIndex + width <= layout.length && squares[pacmanCurrentIndex + width].className !== 'wall' ){
pacmanCurrentIndex += width;
removeDot();
}
break
case 38:
if(pacmanCurrentIndex - width >= 0 && squares[pacmanCurrentIndex - width].className !== 'wall'){
pacmanCurrentIndex -= width;
removeDot();
}
break
case 37:
if(pacmanCurrentIndex % width !== 0 && squares[pacmanCurrentIndex - 1].className !== 'wall'){
pacmanCurrentIndex--;
removeDot()
}
break
case 39:
if(pacmanCurrentIndex % width !== width-1 && squares[pacmanCurrentIndex + 1].className !== 'wall'){
pacmanCurrentIndex++;
removeDot();
}
break
}
squares[pacmanCurrentIndex].classList.add('pac-man')
}
function removeDot(){
if(squares[pacmanCurrentIndex].className === 'pac-dot'){
console.log("DOTTT")
squares[pacmanCurrentIndex].classList.remove('pac-dot');
score ++;
scoreDisplay.textContent = score;
}
}
document.addEventListener('keyup', control) |
const API = require("./data");
const PRINTINFO = require("./insertToDom");
API.getUsers().then(users => users.forEach(user => PRINTINFO.toDom(user))); |
import React, { Component } from 'react';
import Countdown from './Countdown.js';
import { I18n } from 'react-i18next'
import Navbar from './Navbar'
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<I18n ns="translations">
{
(t, { i18n }) => (
<div className="App">
<Navbar />
<Countdown date={'2022-02-05T00:00:00'} />
</div>
)
}
</I18n>
)
}
}
export default App;
|
const toCamelCase = (str) => {
return str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map((x) => x.toLowerCase())
.join(" ")
.replace(/\s(.)/g, ($1) => {
return $1.toUpperCase();
})
.replace(/\s/g, "")
.replace(/^(.)/, ($1) => {
return $1.toLowerCase();
});
};
const toPascalCase = (str) => {
return str
.match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)
.map((x) =>
x.toLowerCase().replace(/^(.)/, ($1) => {
return $1.toUpperCase();
})
)
.join("");
};
const toSnakeCase = (str) => {
return (
str
.match(
/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
)
// .map(x => x.toLowerCase())
// .map(x => x.toUpperCase())
.join("_")
);
};
const toKebabCase = (str) => {
return (
str
.match(
/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
)
// .map(x => x.toLowerCase())
// .map(x => x.toUpperCase())
.join("-")
);
};
const toFlatCase = (str) => {
return (
str
.match(
/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
)
.map((x) => x.toLowerCase())
// .map(x => x.toUpperCase())
.join("")
);
};
const toInverseCase = (str) => {
return (
str
.match(
/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
)
.map((x) => {
if (x.toUpperCase() === x) return x.toLowerCase();
if (x.toLowerCase() === x) return x.toUpperCase();
})
// .map(x => x.toUpperCase())
.join("")
);
};
module.exports = {
toCamelCase,
toPascalCase,
toSnakeCase,
toKebabCase,
toFlatCase,
toInverseCase,
};
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ActivityIndicator, View, Platform } from 'react-native';
import VisibilitySensor from 'react-visibility-sensor';
import get from 'lodash.get';
import Catalogue from '../../components/catalogue/Catalogue';
import Loader from '../../components/loader/Loader';
import styles from './App.styles';
class App extends Component {
constructor(props) {
super(props);
this.state = {
isLoadingMore: false,
};
}
onChange = (isVisible) => {
if (isVisible) {
this.loadMore();
}
};
loadMore = () => {
this.setState({ isLoadingMore: true });
const remaining = get(this, 'props.catalogue.product.remaining', 0);
if (remaining <= 0) {
this.setState({ isLoadingMore: false });
return;
}
this.props.loadMore().then(() => {
this.setState({ isLoadingMore: false });
});
}
renderFooter = () => (
!this.state.isLoadingMore ?
<View /> :
<ActivityIndicator style={styles.loader} size="small" />
)
render() {
const { loading, catalogue } = this.props;
const remaining = get(catalogue, 'product.remaining', 0);
return (
<View style={styles.container}>
{
loading && <Loader />
}
{
!loading && catalogue &&
<Catalogue
catalogue={catalogue}
loadMore={this.loadMore}
isLoadingMore={this.state.isLoadingMore}
{...this.props}
/>
}
{
this.renderFooter()
}
{
Platform.OS === 'web' && !loading && !this.state.isLoadingMore && remaining >= 0 ?
<VisibilitySensor
onChange={this.onChange}
delayedCall
/> :
<View />
}
</View>
);
}
}
App.propTypes = {
catalogue: PropTypes.shape({
title: PropTypes.string,
}),
loading: PropTypes.bool,
loadMore: PropTypes.func,
};
App.defaultProps = {
catalogue: {
title: '',
},
loading: false,
loadMore: null,
};
export default App;
|
var net = require("net");
var relay = net.createServer(function(socket) {
socket.on('connect', function() {
console.log('Connected');
});
socket.on('data', function(data) {
data = data.toString().substring(2,data.length);
console.log(data.toString());
socket.write("hi");
socket.write("\r\n");
console.log("Wrote Hi");
});
});
relay.listen(8080);
var relay2 = net.createServer(function(socket) {
socket.on('connect', function() {
console.log('Connected');
});
socket.on('data', function(data) {
data = data.toString().substring(2,data.length);
console.log(data.toString());
socket.write("hi");
socket.write("\r\n");
console.log("Wrote Hi");
});
});
relay2.listen(8081);
|
import axios from "axios";
import axiosInstance from "./axiosInstance";
//import localStorageService from "./localStorageService";
import { GenericService } from "./GenericService";
// var { GenericService } = require("./GenericService");
class CompanyService extends GenericService {
constructor() {
super("/api/user");
}
adminLogin = (data) => this.post("/api/user/admin/login", data);
usersQuery = (query, id) =>
new Promise((resolve, reject) => {
axiosInstance
.post(this.endPoint + "/query/" + id, { query })
.then((res) => {
resolve(res.data);
})
.catch((res) => {
reject(res.data);
});
});
}
export default new CompanyService();
|
class Menu{
constructor(gameWidth, gameHeight){
this.gameWidth = gameWidth;
this.gameHeight = gameHeight;
}
update(deltaTime){
}
render(context){
context.fillStyle = "Black";
context.fillRect(0, 0, this.gameWidth, this.gameHeight);
context.fillStyle = "White";
context.fillRect(this.gameWidth/2 - 200, 100, 400, 50);
context.fillStyle = "Black";
context.font = "30px Sans serif";
context.fillText("Press Enter to play", this.gameWidth/2 - 150, 135);
}
} |
import React from "react";
import { Box } from "@chakra-ui/react";
import Home from "./Home";
import HowItWorks from "./HowItWorks";
import SignUp from "./SignUp";
import Enroll from "./Enroll";
import Feed from "./Feed";
import Login from "./Login";
import { Route } from "react-router-dom";
import Navbar from "../components/Layout/Header/Navbar";
function Main({ children }) {
return (
<Box id="content" margin="auto" maxWidth="1348px">
<Navbar />
<Route exact path="/">
<Home />
</Route>
<Route exact path="/tasks">
<Feed />
</Route>
<Route exact path="/how_it_works">
<HowItWorks />
</Route>
<Route exact path="/join">
<SignUp />
</Route>
<Route exact path="/enroll">
<Enroll />
</Route>
<Route exact path="/login">
<Login />
</Route>
</Box>
);
}
export default Main;
|
import React from 'react';
import { connect } from 'react-redux';
import axios from '../axios';
import './App.css';
import CardViewer from './CardViewer';
import Loading from './Loading';
import SearchBox from './SearchBox';
import history from '../history';
import Filter from './Filter';
import auth from '../auth/index';
import { setFilterData } from '../actions';
import Login from './Login';
import Modal from './Modal';
class Contents extends React.Component {
constructor(props) {
super(props);
this.state = {
recipes: null,
limit: 48,
loading: true,
user: null,
modal: false,
activeRecipe: null,
filteredRecipes: null
};
}
async componentDidMount() {
console.log(this.props.user);
console.log(this.props.search);
let recipes = null;
let first = false;
const user = await auth();
this.setState({ user });
recipes = await axios.get('/recipes');
this.setState({ recipes: recipes.data.filter((rec) => rec.title.toLowerCase().includes(this.props.search)) });
Object.keys(this.props.filters).map((key) => {
if (!this.props.filters[key]) {
first = true;
}
});
if (first) {
this.setState({ filteredRecipes: recipes.data, loading: false });
}
}
async componentDidUpdate(lastProps) {
let recipes = this.state.recipes;
if (lastProps.filters !== this.props.filters) {
recipes = this.handleFilterSearch(recipes);
console.log(recipes);
}
if (recipes) {
if (lastProps.search !== this.props.search) {
this.setState({
filteredRecipes: recipes.filter((rec) => rec.title.toLowerCase().includes(this.props.search)),
loading: false
});
} else {
if (lastProps.filters !== this.props.filters) {
this.setState({
filteredRecipes: recipes.filter((rec) => rec.title.toLowerCase().includes(this.props.search)),
loading: false
});
}
}
}
}
handleFilterSearch = (recipes) => {
let finalRecipes = recipes;
console.log(finalRecipes);
const filters = this.props.filters;
const keys = Object.keys(filters);
keys.map((key) => {
if (filters[key] === true) {
switch (key) {
case 'vegan':
finalRecipes = finalRecipes.filter((recipe) => recipe.restrictions.vegan);
console.log(finalRecipes);
break;
case 'vegetarian':
finalRecipes = finalRecipes.filter((recipe) => recipe.restrictions.vegetarian);
break;
case 'healthy':
finalRecipes = finalRecipes.filter((recipe) => recipe.restrictions.veryHealthy);
break;
case 'gluten':
finalRecipes = finalRecipes.filter((recipe) => recipe.restrictions.glutenFree);
break;
case 'dairyFree':
finalRecipes = finalRecipes.filter((recipe) => recipe.diets.includes('dairy free'));
break;
case 'pescatarian':
finalRecipes = finalRecipes.filter((recipe) => recipe.diets.includes('pescatarian'));
break;
default:
break;
}
}
if (filters['cost'] > 9) {
finalRecipes = finalRecipes.filter((rec) => rec.pricePerServing / 5 < filters['cost']);
}
});
console.log(finalRecipes);
return finalRecipes;
};
filterContents = (filter, cost) => {
const filters = this.props.filters;
switch (filter) {
case 'VEGETARIAN':
this.props.setFilterData({ ...filters, vegetarian: !filters.vegetarian });
break;
case 'VEGAN':
this.props.setFilterData({ ...filters, vegan: !filters.vegan });
break;
case 'PESCATARIAN':
this.props.setFilterData({ ...filters, pescatarian: !filters.pescatarian });
break;
case 'HEALTHY':
this.props.setFilterData({ ...filters, healthy: !filters.healthy });
break;
case 'DAIRY FREE':
this.props.setFilterData({ ...filters, dairyFree: !filters.dairyFree });
break;
case 'GLUTENFREE':
this.props.setFilterData({ ...filters, gluten: !filters.gluten });
break;
case 'COST':
this.props.setFilterData({ ...filters, cost: cost });
default:
break;
}
console.log(this.props.filters);
};
clickMore = () => {
console.log(this.state.limit);
this.setState({ limit: this.state.limit + 24 });
};
openModal = (recipe) => {
this.setState({ modal: true, activeRecipe: recipe });
};
modalDismiss = () => {
this.setState({ modal: false });
};
render() {
console.log(this.props.filters);
return !this.state.loading ? (
<div>
<div style={{ display: 'block' }}>
<SearchBox />
<Filter filterContents={this.filterContents} filters={this.state.filters} />
<CardViewer
clickMore={this.clickMore}
limit={this.state.limit}
recipes={this.state.filteredRecipes}
modal={this.openModal}
/>
{this.state.modal ? (
<Modal modalDismiss={this.modalDismiss} recipe={this.state.activeRecipe} />
) : (
''
)}
</div>
</div>
) : (
<Loading />
);
}
}
const mapStateToProps = (state) => {
console.log(state);
return { search: state.search, filters: state.filters, user: state.user };
};
export default connect(mapStateToProps, { setFilterData })(Contents);
|
/**
* @namespace
*/
var firebase = {};
/**
* @namespace
*/
var localStorage = {};
/**
* @namespace
*/
var hyperApp = {};
/** @function(evt: Event) */
function dispatchEvent(evt) {}
/** @function(evt: Event) */
function onpushstate(evt) {}
|
var models = {
Admin: require('./lib/admin'),
Masterclass: require('./lib/masterclass'),
User: require('./lib/user'),
Student: require('./lib/student'),
Teacher: require('./lib/teacher')
};
/**
* @typedef {{
* Admin: Admin,
* Masterclass: Masterclass,
* User: User,
* Student: Student,
* Teacher: Teacher
* }}
*/
var Models;
/**
* @type {Models}
*/
module.exports = models;
|
define(['jquery','common_mod','data_mod'],function($,com,aData)
{
var plugins;
plugins = {
thisWebUrl : function(){
var protocolFlag = ('http:' == document.location.protocol ? false : true);
if(protocolFlag)
{
return aData.webHttpsUrl;
}
else
{
return aData.webUrl;
}
},
selectWidget : function(){
/*
$("body").find(".js-selectlist").bind("DOMSubtreeModified DOMNodeInserted DOMNodeRemoved DOMNodeRemovedFromDocument DOMNodeInsertedIntoDocument DOMAttrModified DOMCharacterDataModified",
function(e)
{
var offsetTop = $(this).offset().top;
var offsetBottom = $("body").outerHeight() - offsetTop;
var lessHeight = $(this).outerHeight() - offsetBottom;
if(lessHeight > 0)
{
$(this).offset({'top':offsetTop-lessHeight,'bottom':''});
}
}
);
*/
$("body").on("click",".js-selectbox",function(event)
{
var _selectWidget = $(this);
if(com.browserCheck.isIE7())
{
$(this).parents(".plugins-select").css("z-index","100");
}
event.stopPropagation();
_selectWidget.next(".js-selectlist").show(0,function()
{
_selectWidget.addClass("plugins-select--has");
$(this).parent().on("click",".js-selectlist li",function(event)
//$(this).children("li").click(function(event)
{
if($(this).parent().prev(".js-selectbox").is("input"))
{
$(this).parent().prev(".js-selectbox").val($(this).text())
.attr("data-value",$(this).attr("data-value"));
}
else
{
$(this).parent().prev(".js-selectbox").text($(this).text())
.attr("data-value",$(this).attr("data-value"));
}
event.stopPropagation();
_selectWidget.next(".js-selectlist").hide(0);
_selectWidget.removeClass("plugins-select--has");
if(com.browserCheck.isIE7())
{
_selectWidget.parents(".plugins-select").css("z-index","0");
}
})
$(document).one("click",function ()
{
_selectWidget.next(".js-selectlist").hide();
_selectWidget.removeClass("plugins-select--has");
if(com.browserCheck.isIE7())
{
_selectWidget.parents(".plugins-select").css("z-index","0");
}
});
$(".js-selectbox").one("click",function ()
{
_selectWidget.next(".js-selectlist").hide();
_selectWidget.removeClass("plugins-select--has");
if(com.browserCheck.isIE7())
{
_selectWidget.parents(".plugins-select").css("z-index","0");
}
});
if(com.browserCheck.isIE6())
{
$(this).children("li").hover(function()
{
$(this).addClass("select");
$(this).siblings("li").removeClass("select");
})
}
});
var offsetTop = _selectWidget.next(".js-selectlist").offset().top;
var offsetBottom = $("body").outerHeight() - offsetTop;
var lessHeight = _selectWidget.next(".js-selectlist").outerHeight() - offsetBottom;
if(lessHeight > 0)
{
_selectWidget.next(".js-selectlist").offset({'top':offsetTop-lessHeight,'bottom':''});
}
})
},
radioWidget : function(){
$("body").on("click",".js-radiolabel",function()
{
var _name = $(this).attr("name");
if($(this).hasClass("plugins-radio--off"))
{
// $("label[name='" + _name + "']")
// .addClass("plugins-radio--off").removeClass("plugins-radio--on");
// $(this).addClass("plugins-radio--on").removeClass("plugins-radio--off");
// $("label[name='" + _name + "']").prev("input").removeAttr("checked");
// $(this).prev("input").attr("checked", true);
$("input[name='" + _name + "']").next("label")
.addClass("plugins-radio--off").removeClass("plugins-radio--on");
$(this).addClass("plugins-radio--on").removeClass("plugins-radio--off");
$("input[name='" + _name + "']").removeAttr("checked");
$(this).prev("input").attr("checked", true);
}
return false;
});
$("body").on("click",".js-radiominilabel",function()
{
var _name = $(this).attr("name");
if($(this).hasClass("plugins-miniradio--off"))
{
// $("input[name='" + _name + "']").next("label")
// .addClass("plugins-miniradio--off").removeClass("plugins-miniradio--on");
// $(this).addClass("plugins-miniradio--on").removeClass("plugins-miniradio--off");
// $("input[name='" + _name + "']").removeAttr("checked");
// $(this).prev("input").attr("checked", true);
$("label[name='" + _name + "']")
.addClass("plugins-miniradio--off").removeClass("plugins-miniradio--on");
$(this).addClass("plugins-miniradio--on").removeClass("plugins-miniradio--off");
$("label[name='" + _name + "']").prev("input").removeAttr("checked");
$(this).prev("input").attr("checked", true);
// $("input[name='" + _name + "']").next("label")
// .addClass("plugins-miniradio--off").removeClass("plugins-miniradio--on");
// $(this).addClass("plugins-miniradio--on").removeClass("plugins-miniradio--off");
// $("input[name='" + _name + "']").removeAttr("checked");
// $(this).prev("input").attr("checked", true);
}
return false;
});
},
checkBoxWidget : function(fn){
$("body").on("click",".js-checklabel",function(event)
{
event.stopPropagation();
if($(this).hasClass("plugins-checkbox--on"))
{
$(this).removeClass("plugins-checkbox--on").addClass("plugins-checkbox--off");
$(this).prev("input").removeAttr("checked");
}
else
{
$(this).addClass("plugins-checkbox--on").removeClass("plugins-checkbox--off");
$(this).prev("input").attr("checked", true);
}
});
$("body").on("click",".js-checkminilabel",function(event)
{
event.stopPropagation();
if($(this).hasClass("plugins-minicheckbox--on"))
{
$(this).removeClass("plugins-minicheckbox--on").addClass("plugins-minicheckbox--off");
$(this).prev("input").removeAttr("checked");
}
else
{
$(this).addClass("plugins-minicheckbox--on").removeClass("plugins-minicheckbox--off");
$(this).prev("input").attr("checked", true);
}
});
},
checkAll : function (targetItem,checkboxName)
{
targetItem.on("click",function(event)
{
if($(this).hasClass("plugins-checkbox--on"))
{
$('input[type=\'checkbox\'][name=\'' + checkboxName + '\']').each(function()
{
$(this).next("label").removeClass("plugins-checkbox--on").addClass("plugins-checkbox--off");
$(this).removeAttr("checked");
});
}
else
{
$('input[type=\'checkbox\'][name=\'' + checkboxName + '\']').each(function()
{
$(this).next("label").addClass("plugins-checkbox--on").removeClass("plugins-checkbox--off");
$(this).attr("checked", true);
});
}
})
$('input[type=\'checkbox\'][name=\'' + checkboxName + '\']').each(function()
{
$(this).next("label").on("click",function(){
if($(this).hasClass("plugins-checkbox--on"))
{
targetItem.removeClass("plugins-checkbox--on").addClass("plugins-checkbox--off");
targetItem.prev("input").removeAttr("checked");
}
else
{
var inputItem = $('input[type=\'checkbox\'][name=\'' + checkboxName + '\']');
var inputChecked = $('input[type=\'checkbox\'][name=\'' + checkboxName + '\']:checked');
if(inputItem.length - 1 == inputChecked.length)
{
targetItem.removeClass("plugins-checkbox--off").addClass("plugins-checkbox--on");
targetItem.prev("input").attr("checked", true);
}
}
})
})
},
/**
* flag : 1--只显示省;2--只显示市;3--只显示区;4--不显示省;
*/
nameforAddr : function(area,flag,type)
{
var areaNm = '';
if(!com.isillegal(area))
{
$.ajax({
type: "get",
async: false,
url: plugins.thisWebUrl() + "/component/plugins/area/allArea.js",
dataType: "json",
success: function (data) {
area.provinceName = area.provinceId ? data.province[area.provinceId] : '';
area.cityName = area.cityId ? data.city[area.provinceId][area.cityId] : '';
area.districtName = area.districtId ? data.county[area.cityId][area.districtId] : '';
var thisValueArr = [];
if(flag == '1')
{
thisValueArr = $.grep([area.provinceName],function(n,i){ return n != ''; });
}
else if(flag == '2')
{
thisValueArr = $.grep([area.cityName],function(n,i){ return n != ''; });
}
else if(flag == '3')
{
thisValueArr = $.grep([area.districtName],function(n,i){ return n != ''; });
}
else if(flag == '4')
{
thisValueArr = $.grep([area.cityName,area.districtName],function(n,i){ return n != ''; });
}
else
{
thisValueArr = $.grep([area.provinceName,area.cityName,area.districtName],function(n,i){ return n != ''; });
}
if(typeof type != 'undefined')
{
areaNm = thisValueArr.join(type);
}
else
{
areaNm = thisValueArr.join('-');
}
return areaNm;
},
error: function (err) {
return false;
}
});
}
else
{
return false;
}
return areaNm;
},
area : function()
{
window.plugins_area_id = 0;
window.plugins_area_lock = [];
var browserCheck =
{
isIE : function ()
{
return ("ActiveXObject" in window);
},
isIE6 : function ()
{
// ie6是不支持window.XMLHttpRequest的
return this.isIE() && !window.XMLHttpRequest;
},
isIE7 : function ()
{
//只有IE8+才支持document.documentMode
return this.isIE() && navigator.appName == "Microsoft Internet Explorer" && navigator.appVersion.split(";")[1].replace(/[ ]/g,"")=="MSIE7.0";
},
isIE8 : function ()
{
// alert(!-[1,])//->IE678返回NaN 所以!NaN为true 标准浏览器返回-1 所以!-1为false
return this.isIE() &&!-[1,]&&document.documentMode;
}
}
if($("input[type='plugins_area']").length > 0)
{
$("input[type='plugins_area']").each(function()
{
window.plugins_area_id ++;
if(browserCheck.isIE7 || browserCheck.isIE6)
{
$(this).addClass("plugins_area-input");
}
$(this).attr("readonly","readonly");
if(typeof $(this).data().provinceId != 'undefined' ||
typeof $(this).data().cityId != 'undefined' ||
typeof $(this).data().countyId != 'undefined')
{
var thisInput = $(this);
var area = {};
area.provinceId = $(this).data().provinceId || '';
area.cityId = $(this).data().cityId || '';
area.countyId = $(this).data().countyId || '';
$.ajax({
type: "get",
async: false,
url: plugins.thisWebUrl() + "/component/plugins/area/allArea.js",
dataType: "json",
success: function (data) {
area.provinceName = area.provinceId == '' ? '' : data.province[area.provinceId];
area.cityName = area.cityId == '' ? '' : data.city[area.provinceId][area.cityId];
area.countyName = area.countyId == '' ? '' : data.county[area.cityId][area.countyId];
area.areaId = window.plugins_area_id;
var thisValueArr = $.grep([area.provinceName,area.cityName,area.countyName],function(n,i){ return n != ''; });
thisInput.val(thisValueArr.join('-')).data(area);
},
error: function (err) {
}
});
}
$(this).attr("data-area-id",window.plugins_area_id);
})
}
$("body").on("click","input[type='plugins_area']",function()
{
var area = {};
area.id = $(this).attr("data-area-id");
$.each(window.plugins_area_lock,function(s,lock)
{
if(lock)
{
window.plugins_area_lock[s] = false;
}
})
//window.plugins_area_lock[area.id] = false;
area._getJson = function()
{
$.ajax({
type: "get",
async: false,
url: plugins.thisWebUrl() + "/component/plugins/area/queryAllProvinces.js",
dataType: "json",
success: function (data) {
area._province = data.province;
window.plugins_area_province = area._province;
},
error: function (err) {
}
});
$.ajax({
type: "get",
async: false,
url: plugins.thisWebUrl() + "/component/plugins/area/queryCities.js",
dataType: "json",
success: function (data) {
area._city = data.cities;
area.cityArr = {};
area.hotCity = '<div class="plugins-area-list js-arealist" data-tab="1">'
+ '<ul class="plugins-area-list-normal">';
$.each(area._city,function(s,a)
{
if(a.hotCity)
{
area.hotCity += '<li class="js-hotcity" data-province="' + a.provinceId + '" data-city="' + a.id + '">'
+ '<a class="plugins-area-list__text">'
+ '<i class="plugins-area-list__text--left"></i>'
+ '<span class="plugins-area-list__text--center js-name">' + a.name + '</span>'
+ '<i class="plugins-area-list__text--right"></i></a></li>';
}
if(typeof area.cityArr['province' + a.provinceId] == 'undefined')
{
area.cityArr['province' + a.provinceId] = [];
area.cityArr['province' + a.provinceId].push(area._city[s]);
}
else
{
area.cityArr['province' + a.provinceId].push(area._city[s]);
}
})
area.hotCity += '</ul></div>';
window.plugins_area_hotCity = area.hotCity;
window.plugins_area_cityArr = area.cityArr;
},
error: function (err) {
}
});
$.ajax({
type: "get",
async: false,
url: plugins.thisWebUrl() + "/component/plugins/area/queryAllAreas.js",
dataType: "json",
success: function (data) {
area._county = data.areas;
area.countyArr = {};
$.each(area._county,function(s,a)
{
if(typeof area.countyArr['city' + a.cityId] == 'undefined')
{
area.countyArr['city' + a.cityId] = [];
area.countyArr['city' + a.cityId].push(area._county[s]);
}
else
{
area.countyArr['city' + a.cityId].push(area._county[s]);
}
})
window.plugins_area_countyArr = area.countyArr;
},
error: function (err) {
}
});
}
area._position = function(aid)
{
var dom = $("input[type='plugins_area'][data-area-id='" + aid + "']");
var position = {};
position.top = dom.offset().top;
position.left = dom.offset().left;
position.height = dom.height();
position.width = dom.width();
return position;
}
area._showArea = function()
{
area.province = ' <div class="plugins-area-list js-arealist" style="display:block" data-tab="2">'
$.each(window.plugins_area_province,function(l,p)
{
area.province += '<div class="plugins-area-list-province">'
+ '<p class="plugins-area-list-lettersort">' + l + '</p><ul class="plugins-area-list-letter">';
$.each(p,function(s,a)
{
if(a.provinceName == '海外')
{
return true;
}
area.province += '<li class="js-province" data-province="' + a.id + '"><a class="plugins-area-list__text">'
+ '<i class="plugins-area-list__text--left"></i>'
+ '<span class="plugins-area-list__text--center js-name">' + a.provinceName + '</span>'
+ '<i class="plugins-area-list__text--right"></i>'
+ '</a></li>'
})
area.province += '</ul></div>';
})
area.province += '</div>';
area.hotCity = window.plugins_area_hotCity;
area.position = area._position(area.id);
area.areaList = '<div class="plugins-area" data-area-id="' + area.id + '"><div class="plugins-area-tab">'
+ ' <ul class="plugins-area-tablist js-tablist"><li data-tab="1">'
+ '<p class="plugins-area-tablist__text">常用</p><i class="plugins-area-tablist__cutline"></i></li>'
+ '<li class="choose" data-tab="2"><p class="plugins-area-tablist__text">省</p><i class="plugins-area-tablist__cutline"></i></li>'
+ '<li data-tab="3" class="disabled"><p class="plugins-area-tablist__text">市</p><i class="plugins-area-tablist__cutline"></i></li>'
+ '<li data-tab="4" class="disabled"><p class="plugins-area-tablist__text">区县</p></li></ul></div>'
+ area.hotCity
+ area.province
+ '<div class="plugins-area-list js-arealist" data-tab="3"></div>'
+ '<div class="plugins-area-list js-arealist" data-tab="4"></div>'
+ '</div>';
$("body").append(area.areaList);
$(".plugins-area[data-area-id='" + area.id + "']").css({
"top" : area.position.top + area.position.height + 3,
"left" : area.position.left
})
if(browserCheck.isIE7() || browserCheck.isIE6())
{
$(".plugins-area-list-letter,.plugins-area-list-normal").css("width","10000px");
$(".js-arealist").show();
$(".js-hotcity,.js-province").each(function(){
$(this).css("width",$(this).outerWidth());
})
$(".plugins-area-list-letter,.plugins-area-list-normal").removeAttr("style");
$(".js-arealist").hide();
$(".js-arealist[data-tab='2']").show();
}
if(typeof window.plugins_area_lock[area.id] == 'undefined')
{
window.plugins_area_lock[area.id] = false;
}
}
if($(".plugins-area[data-area-id='" + area.id + "']").length == 0)
{
if(typeof window.plugins_area_province == "undefined" ||
typeof window.plugins_area_cityArr == "undefined" ||
typeof window.plugins_area_countyArr == "undefined")
{
area._getJson();
}
area._showArea();
}
else
{
area.position = area._position(area.id);
$(".plugins-area[data-area-id='" + area.id + "']").css({
"top" : area.position.top + area.position.height + 3,
"left" : area.position.left
}).show();
}
})
$("html").click(function(event){
if(!$(event.target).is("input[type='plugins_area']"))
{
$.each(window.plugins_area_lock,function(s,lock)
{
if(!lock)
{
$(".plugins-area[data-area-id='" + s + "']").hide();
}
})
}
else{
var areaId = $(event.target).data('areaId');
$.each(window.plugins_area_lock,function(s,lock)
{
if(!lock && s != areaId)
{
$(".plugins-area[data-area-id='" + s + "']").hide();
}
})
}
});
$("body").on("mouseover",".plugins-area",function()
{
var area = {};
area.id = $(this).attr("data-area-id");
window.plugins_area_lock[area.id] = true;
})
$("body").on("mouseout",".plugins-area",function()
{
var area = {};
area.id = $(this).attr("data-area-id");
window.plugins_area_lock[area.id] = false;
})
$("body").on("click",".js-tablist li",function()
{
if($(this).hasClass("disabled"))
{
}
else
{
var tabId = $(this).attr("data-tab");
var pDom = $(this).parents(".plugins-area");
$(this).addClass("choose").siblings("li[data-tab]").removeClass("choose");
pDom.find(".js-arealist[data-tab='" + tabId + "']").show().siblings(".js-arealist[data-tab]").hide();
}
})
$("body").on("click",".js-province",function()
{
var pDom = $(this).parents(".plugins-area");
var province = {};
province.areaId = $(this).parents(".plugins-area").attr("data-area-id");
province.provinceId = $(this).attr('data-province');
province.provinceName = $(this).find(".js-name").text();
$("input[type='plugins_area'][data-area-id='" + province.areaId + "']")
.val(province.provinceName).removeData().data(province);
pDom.find(".js-province,.js-hotcity").removeClass("choose");
$(this).addClass("choose");
pDom.find(".js-tablist li[data-tab=3]").removeClass("disabled");
var cityList = '<ul class="plugins-area-list-normal">'
$.each(window.plugins_area_cityArr['province' + province.provinceId],function(s,a)
{
cityList += '<li class="js-city" '
+ 'data-province="' + a.provinceId + '" data-city="' + a.id + '" >'
+ '<a class="plugins-area-list__text"><i class="plugins-area-list__text--left"></i>'
+ '<span class="plugins-area-list__text--center js-name">' + a.name + '</span>'
+ '<i class="plugins-area-list__text--right"></i></a></li>'
})
cityList += '</ul>';
pDom.find(".js-arealist[data-tab=3]").empty().append(cityList);
pDom.find(".js-tablist li[data-tab=3]").trigger("click");
if(browserCheck.isIE7() || browserCheck.isIE6())
{
$(".js-arealist[data-tab=3] .plugins-area-list-normal").css("width","10000px");
$(".js-city").each(function(){
$(this).css("width",$(this).outerWidth());
})
$(".js-arealist[data-tab=3] .plugins-area-list-normal").removeAttr("style");
}
});
$("body").on("click",".js-hotcity,.js-city",function(event)
{
var pDom = $(this).parents(".plugins-area");
var hotCity = {};
hotCity.areaId = $(this).parents(".plugins-area").attr("data-area-id");
hotCity.provinceId = $(this).attr('data-province');
hotCity.cityId = $(this).attr('data-city');
$.each(window.plugins_area_province,function(l,p)
{
$.each(p,function(s,a)
{
if(hotCity.provinceId == a.id)
{
hotCity.provinceName = a.provinceName;
return false;
}
})
})
hotCity.cityName = $(this).find(".js-name").text();
$("input[type='plugins_area'][data-area-id='" + hotCity.areaId + "']")
.val(hotCity.provinceName + '-' + hotCity.cityName).removeData().data(hotCity);
$(this).addClass("choose").siblings("li").removeClass("choose");
pDom.find(".js-province[data-province='" + hotCity.provinceId + "']").addClass("choose")
pDom.find(".js-province[data-province!='" + hotCity.provinceId + "']").removeClass("choose");
pDom.find(".js-tablist li[data-tab=3]").removeClass("disabled");
pDom.find(".js-tablist li[data-tab=4]").removeClass("disabled");
if($(event.currentTarget).hasClass("js-hotcity"))
{
var cityList = '<ul class="plugins-area-list-normal">'
+ '<li class="js-city choose" data-province="' + hotCity.provinceId + '" data-city="' + hotCity.cityId + '">'
+ '<a class="plugins-area-list__text"><i class="plugins-area-list__text--left"></i>'
+ '<span class="plugins-area-list__text--center js-name">' + hotCity.cityName + '</span>'
+ '<i class="plugins-area-list__text--right"></i></a></li></ul>';
pDom.find(".js-arealist[data-tab=3]").empty().append(cityList);
}
else
{
if($(".js-hotcity[data-city='" + hotCity.cityId + "']").length == 0)
{
pDom.find(".js-hotcity").removeClass("choose");
}
else
{
pDom.find(".js-hotcity[data-city='" + hotCity.cityId + "']").addClass("choose").siblings("li").removeClass("choose");
}
}
var countyList = '<ul class="plugins-area-list-normal">'
$.each(window.plugins_area_countyArr['city' + hotCity.cityId],function(s,a)
{
countyList += '<li class="js-county" '
+ 'data-province="' + a.provinceId + '" data-city="' + a.cityId + '" data-county="' + a.id + '">'
+ '<a class="plugins-area-list__text"><i class="plugins-area-list__text--left"></i>'
+ '<span class="plugins-area-list__text--center js-name">' + a.areaName + '</span>'
+ '<i class="plugins-area-list__text--right"></i></a></li>'
})
countyList += '</ul>';
pDom.find(".js-arealist[data-tab=4]").empty().append(countyList);
pDom.find(".js-tablist li[data-tab=4]").trigger("click");
if(browserCheck.isIE7() || browserCheck.isIE6())
{
$(".js-arealist[data-tab=4] .plugins-area-list-normal").css("width","10000px");
$(".js-county").each(function(){
$(this).css("width",$(this).outerWidth());
})
$(".js-arealist[data-tab=4] .plugins-area-list-normal").removeAttr("style");
}
});
$("body").on("click",".js-county",function(event)
{
var pDom = $(this).parents(".plugins-area");
var county = {};
county.areaId = $(this).parents(".plugins-area").attr("data-area-id");
county.provinceId = $(this).attr('data-province');
county.cityId = $(this).attr('data-city');
county.countyId = $(this).attr('data-county');
$.each(window.plugins_area_province,function(l,p)
{
$.each(p,function(s,a)
{
if(county.provinceId == a.id)
{
county.provinceName = a.provinceName;
return false;
}
})
})
$.each(window.plugins_area_cityArr['province' + county.provinceId],function(s,a)
{
if(county.cityId == a.id)
{
county.cityName = a.name;
return false;
}
})
county.countyName = $(this).find(".js-name").text();
$("input[type='plugins_area'][data-area-id='" + county.areaId + "']")
.val(county.provinceName + '-' + county.cityName + '-' + county.countyName).removeData().data(county);
$(this).addClass("choose").siblings("li").removeClass("choose");
$(".plugins-area[data-area-id='" + county.areaId + "']").hide();
});
}
}
return plugins;
})
|
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
Email: String,
Username: String,
Displayname: String,
Password: String,
ProfileInfo: { type: mongoose.Types.ObjectId, ref: "ProfileInfo" },
BlockedUsers: [{ type: mongoose.Types.ObjectId, ref: "User" }],
UserType: Number,
LastLogin: String,
});
module.exports = mongoose.model("User", userSchema);
|
var express = require('express');
var app = express.createServer();
var blog = require("./blog.js");
var contact = require("./contact.js");
var twitter = require("./twitter.js");
var redirects = require("./redirects.js");
global.settings = {};
// Load static content
var oneYear = 1000 * 60 * 60 * 24 * 365; //ish
app.use(express.static(__dirname + '/static', { maxAge: oneYear }));
app.use(express.bodyParser());
app.set('views', __dirname + "/views");
// Handle 500 errors
app.error(function(err, req, res, next) {
console.error(err.message);
res.render("error", {
locals: {
title: "Error",
status: 500
}
});
});
// Load redirects
redirects.load(app);
// Init blog
blog.init(app);
// Init contact
contact.init(app);
// Init twitter stream
twitter.init(app);
// Export vhost server
if (process.argv[2]) {
app.listen(process.argv[2], '127.0.0.1');
console.log("Listening on port " + process.argv[2]);
}
exports.app = app; |
import {$, $$} from './bling.js';
export class Account {
constructor() {
this.submit = $('.account_submit');
this.optin = $$('.optin');
}
keyValues() {
const keyValues = this.optin.filter(item => item.checked).map(item => {
return {[item.dataset.key]: item.dataset.value}
});
return Object.assign({}, ...keyValues);
}
submitSettings() {
return new Promise((resolve, reject) => {
resolve(this.keyValues());
});
}
submitAjax(data) {
let xhr = new XMLHttpRequest();
xhr.open('POST', '/account');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
if (xhr.status === 200) {
window.location.href = '/account';
} else if (xhr.status !== 200) {
alert('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(JSON.stringify(data));
}
}
|
import React, {useEffect, useState} from 'react';
import {View, StyleSheet, Text, Image} from 'react-native';
import {getData} from '../utils';
export default function Header() {
const [name, setName] = useState('');
useEffect(() => {
getData('userProfile')
.then((res) => setName(res.data.fullname))
.catch((err) => console.log(err));
}, []);
return (
<View style={styles.header}>
<Image style={styles.img} source={require('../assets/me.png')} />
<View>
<Text style={styles.text}>{name}</Text>
<Text style={styles.kelas}>Teknik Informatika</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
header: {
height: 150,
backgroundColor: '#327fe3',
flexDirection: 'row',
alignItems: 'center',
},
img: {
height: 50,
width: 50,
marginLeft: 20,
},
text: {
color: 'white',
marginLeft: 18,
fontFamily: 'NunitoSemiBold',
},
kelas: {
color: 'white',
fontSize: 12,
marginLeft: 18,
fontFamily: 'NunitoLight',
},
});
|
var express = require("express");
var router = express.Router();
var auth = require("../middlewares/auth");
var Article = require("../models/article");
var Comment = require("../models/comment");
// New article form
router.get("/new", auth.verifyLoggedInUser, (req, res, next) => {
res.render("newArticleForm");
});
// create article
router.post("/", auth.verifyLoggedInUser, (req, res, next) => {
var tags = req.body.tags ? req.body.tags.split(",").map(tag => tag.trim()) : [];
req.body.tags = tags;
req.body.author = req.session.userId;
Article.create(req.body, (err, articleCreated) => {
if (err) return next(err);
res.redirect("/articles");
});
});
// all articles
router.get("/", (req, res, next) => {
Article.find({}).sort({ updatedAt : "descending" }).exec((err, articles) => {
if (err) return next(err);
res.render("articles", { articles });
});
});
// get one article
router.get("/:id", (req, res, next) => {
let id = req.params.id;
Article.findById(id).populate("author").populate({ path : "comments", populate : { path : "author" } }).exec((err, article) => {
if (err) return next(err);
////////////////////////
console.log(article);
///////////////////////
res.render("getArticle", { article });
});
});
// get update article form
router.get("/:id/update", auth.verifyLoggedInUser, (req, res, next) => {
Article.findById(req.params.id, (err, article) => {
if (err) return next(err);
res.render("articleUpdate", { article });
});
});
// update article
router.post("/:id", auth.verifyLoggedInUser, (req, res, next) => {
var tags = req.body.tags ? req.body.tags.split(",").map(tag => tag.trim()) : [];
req.body.tags = tags;
Article.findByIdAndUpdate(req.params.id, req.body, { new : true }, (err, updatedArticle) => {
if (err) return next(err);
res.redirect(`/articles/${req.params.id}`);
});
});
// delete article
router.get("/:id/delete", (req, res, next) => {
Article.findByIdAndDelete(req.params.id, (err, deletedArticle) => {
if (err) return next(err);
res.redirect("/articles");
});
});
// Add likes
router.get("/:id/claps", auth.verifyLoggedInUser, (req, res, next) => {
let userId = req.user.id;
let articleId = req.params.id;
Article.findById(articleId, (err, article) => {
if (err) return next(err);
if (article.claps.includes(userId)) {
Article.findByIdAndUpdate(articleId, { $pull : { claps : userId } }, (err, updatedArticle) => {
if (err) return next(err);
res.redirect("/articles/" + articleId);
});
} else {
Article.findByIdAndUpdate(articleId, { $push : { claps : userId } }, (err, updatedArticle) => {
if (err) return next(err);
res.redirect("/articles/" + articleId);
});
}
});
});
// create comment
router.post("/:articleId/comments", auth.verifyLoggedInUser, (req, res, next) => {
let articleId = req.params.articleId;
req.body.articleId = articleId;
let author = req.user._id;
req.body.author = author;
Comment.create(req.body, (err, comment) => {
if (err) return next(err);
Article.findByIdAndUpdate(articleId, { $push : { comments : comment._id }}, (err, article) => {
if (err) return next(err);
res.redirect("/articles/" + articleId );
});
});
});
// get comment edit page
router.get("/:articleId/comments/:commentId/edit", auth.verifyLoggedInUser, (req, res, next) => {
let commentId = req.params.commentId;
Comment.findById(commentId, (err, comment) => {
if (err) return next(err);
res.render("commentEdit", { comment });
});
});
// Update comment
router.post("/:articleId/comments/:commentId/edit", auth.verifyLoggedInUser, (req, res, next) => {
let commentId = req.params.commentId;
let articleId = req.params.articleId;
Comment.findByIdAndUpdate(commentId, req.body, (err, UpdatedComment) => {
if (err) return next(err);
res.redirect("/articles/" + articleId);
});
});
// delete comment
router.get("/:articleId/comments/:commentId/delete", auth.verifyLoggedInUser, (req, res, next) => {
let articleId = req.params.articleId;
let commentId = req.params.commentId;
Comment.findByIdAndDelete(commentId, (err, deletedComment) => {
if (err) return next(err);
res.redirect("/articles/" + articleId);
});
});
module.exports = router; |
var express = require('express');
var router = express.Router();
var path = require('path');
/* GET home page. */
router.get('/', function(req, res, next) {
debugger;
res.render('index', { title: 'Express' });
});
router.get('/abort', function(req, res, next) {
console.error("SOMETHING WENT WRONG!");
process.exit(1);
});
router.get('/minecraft', function(req, res, next){
res.sendFile(path.join(__dirname, '../public/minecraft.html'));
});
module.exports = router;
|
/*
* To run this test : livre/fiche/creation
*/
function livre_fiche_creation()
{
my = livre_fiche_creation
my.specs = "Test de la création complète d'une fiche, depuis la demande de création jusqu'à "+
"la construction de sa fiche sur la table de travail."
my.step_list = [
// ["Préparation du test de création des fiches", FicheCreation_Preparation],
// ["Vérification des méthodes/propriétés complexes utiles", FicheCreation_methodes_utiles],
// ["Construction du code HTML", FicheCreation_code_html_de_la_fiche],
// ["Construction de la fiche sur la table de travail", FicheCreation_Construction_de_la_fiche],
// ["Création de la fiche sur la table de travail", FicheCreation_Creation_de_la_fiche],
["Test du fonctionnement des observers", FicheCreation_Fonction_observers],
"Fin"
]
switch(my.step)
{
case "Fin":
break
default:
pending("Step '"+my.step+"' should be implanted")
}
}
function FicheCreation_Preparation() {
with(APP)
{
$('section#table').html('')
FICHES.list = {}
}
}
function FicheCreation_methodes_utiles() {
APP.ibook = new APP.Book()
var compprops = [
'create', 'build', 'save', 'html', 'html_recto', 'html_verso', 'observe'
]
L(compprops).each(function(prop){'ibook'.should.have.property(prop)})
}
function FicheCreation_code_html_de_la_fiche() {
APP.ipage = new APP.Page()
'ipage'.should.have.property('html')
'ipage.html'.should_not.be.null
'ipage.html'.should.contain('<fiche id="f-'+APP.ipage.id+'"')
'ipage.html'.should.contain('class="fiche page')
'ipage.html'.should.contain('<recto id="'+APP.ipage.dom_id+'-recto"')
'ipage.html'.should.contain('</recto>')
'ipage.html'.should.contain('<verso id="'+APP.ipage.dom_id+'-verso"')
'ipage.html'.should.contain('</verso>')
'ipage.html'.should.contain('</fiche>')
w("Les autres tests sont fait dans le test livre/fiche/display.js")
}
function FicheCreation_Construction_de_la_fiche() {
if(APP.ichap != undefined)
{
id_chap = APP.ichap.id
}
switch(my.stop_point)
{
case 1:
APP.ichap = new APP.Chapter()
var id_chap = APP.ichap.id
APP.ichap.dispatch({
top:200, left:600, ranged:false
})
if(APP.ichap.obj) APP.ichap.obj.remove()
APP.ichap.build // <-- TEST
my.wait.for( 1, "Construction (build) de la fiche…" ).and( NEXT_POINT )
break
case 2:
var ofiche = jq(APP.ichap.jid)
ofiche.should.exist
ofiche.should.be.visible
ofiche.should.be.at( 600, 200)
w("@note: build construit une fiche fermée")
ofiche.should_not.have.class('opened')
'ichap.opened'.should.be.false
my.wait.for(0)
break
}
}
// À la différence de la méthode `build', la méthode `create' va ouvrir
// la fiche.
function FicheCreation_Creation_de_la_fiche() {
APP.ichap = new APP.Chapter()
var id_chap = APP.ichap.id
APP.ichap.dispatch({
top:100, left:400, ranged:false
})
if(APP.ichap.obj) APP.ichap.obj.remove()
APP.ichap.create ; // <-- TEST
('FICHES.list['+APP.ichap.id+']').should.be.defined ;
('FICHES.list['+APP.ichap.id+'].class').should = "Fiche" ;
('FICHES.list['+APP.ichap.id+'].type').should = "chap" ;
var ofiche = jq(APP.ichap.jid)
ofiche.should.be.visible
ofiche.should.be.at( 400, 100)
'ichap.opened'.should.be.true
ofiche.should.have.class('opened')
}
function FicheCreation_Fonction_observers() {
switch(my.stop_point)
{
case 1:
specs("Ce test permet de savoir si les observers ont bien été placés sur la fiche."+
"\nLe test se fait sur tous les types de fiche.")
APP.ipage = new APP.Page({titre:"Titre au départ"})
var page = APP.ipage
page.create
page.deselect
w("La touche tabulation ne doit pas retourner la fiche")
Keyboard.press(APP.K_TAB)
jq(page.recto_jid).should.be.visible
jq(page.verso_jid).should_not.be.visible
'ipage.retourned'.should.be.false
blue("Cliquer sur la fiche doit la sélectionner")
jq(page.jid).click // <-- TEST
'ipage.selected'.should.be.true
jq(page.jid).should.have.class('selected')
blue("La sélection de la fiche doit avoir activé les raccourcis clavier propres")
w("On presse la touche tabulation pour retourner la fiche")
Keyboard.press(APP.K_TAB)
jq(page.recto_jid).should_not.be.visible
jq(page.verso_jid).should.be.visible
'ipage.retourned'.should.be.true
w("Tabulation à nouveau pour remettre la fiche au recto")
Keyboard.press(APP.K_TAB)
jq(page.recto_jid).should.be.visible
jq(page.verso_jid).should_not.be.visible
'ipage.retourned'.should.be.false
blue("Focusser dans le titre doit changer son style")
w("Le test ne peut pas être exécuté, car il faudrait basculer vers l'application")
jq(page.input_titre_jid).should_not.have.class('focused')
jq(page.input_titre_jid).obj.select() // <-- TEST
jq(page.input_titre_jid).should.have.class('focused')
jq(page.input_titre_jid).obj[0].blur() // <-- TEST
jq(page.input_titre_jid).should_not.have.class('focused')
blue("Modifier le titre doit changer le titre et mettre la fiche modifiée")
my.new_titre = "Un titre donné à " + Time.now()
jq(page.input_titre_jid).val(my.new_titre)
'ipage._titre'.should = my.new_titre
blue("Modifier le titre réel d'un livre doit modifier la fiche")
APP.ibook = new APP.Book({real_titre:"Le titre réel au départ"})
var book = APP.ibook
book.create
var new_real_titre = "Un nouveau titre réel à "+Time.now()
jq(book.real_titre_jid).val(new_real_titre)
'ibook._real_titre'.should = new_real_titre
blue("Focusser dans un champ d'édition doit régler la gestion propre des touches")
jq(page.input_titre_jid).obj.select() // <-- TEST
Keyboard.press({meta:true, key_code:APP.Key_F})
// TODO Implémenter la vérification
my.wait.for(0).and(NEXT_POINT)
break
case 2:
var page = APP.ipage
my.wait.for(0).and(NEXT_POINT)
break
case 3:
my.wait.for(0)
}
} |
const express = require('express')
const Route = express.Router()
const movies = require('./routes/movies')
const productionHouse = require('./routes/productionHouse')
Route
.use('/movies', movies)
.use('/productionHouse', productionHouse)
module.exports = Route |
let Bookmarks = require('../libs/Bookmarks.class');
class BookmarksManager {
constructor(){
this._createBookmarksHolder();
this._workingSet = null;
this._workingSet_type = null;
this._enums = {
wkset_type: {
all:0,
tag:1,
lookup:2
}
}
}
printWorkingSet(options,printPrefixFn,printFn){
if(options.lookup){
printPrefixFn('working with samples founded with latest lookup:');
if(!this._workingSet || this._workingSet.empty()) { printPrefixFn("no samples in the latest lookup."); return false; }
}else if(options.tag){
printPrefixFn('working with bookmarked samples under',options.tag);
if(!this._workingSet || this._workingSet.empty()) { printPrefixFn("no bookmarked samples under'"+options.tag+"'."); return false; }
}else{
printPrefixFn('working with all bookmarked samples');
if(!this._workingSet || this._workingSet.empty()) { printPrefixFn("no bookmarked samples."); return false; }
}
this._workingSet.printIndexedList(printFn);
//d$(this._workingSet);
return true;
}
workingSet(options){
this._workingSet = null;
this._workingSet_type = null;
options = _.merge({
all:false,
lookup:false,
tag:null
},options);
let bookmObj = DataMgr.get('bookmarks');
// LATEST LOOKUP
if(options.lookup===true){
let smp_obj = SamplesMgr.getLatestLookup();
if(!_.isObject(smp_obj) || smp_obj.empty()){
return null;
}
this._workingSet = new Bookmarks();
smp_obj.forEach((v)=>{
this._workingSet.add(v);
});
this._workingSet_type = this._enums.wkset_type.lookup;
return this._workingSet;
// TAGGED BOOKMARKS
}else if(_.isString(options.tag) && options.tag.length>0){
if(bookmObj.empty() || bookmObj.empty(options.tag)){
return null;
}
this._workingSet = bookmObj.cloneSubStructure(options.tag);
this._workingSet_type = this._enums.wkset_type.tag;
return this._workingSet;
// ALL BOOKMARKS
}else{
if(bookmObj.empty()){
return null;
}
this._workingSet = bookmObj.cloneStructure();
this._workingSet_type = this._enums.wkset_type.all;
return this._workingSet;
}
}
set(addIds, removeIds, label, showingTag){
let elmt;
let bookmObj = DataMgr.get('bookmarks');
let addElmts = [];
let removeElmts = [];
addIds.forEach((elmtIndex)=>{
elmt = this._workingSet.getByIndex(elmtIndex-1);
if(!elmt) return;
addElmts.push(elmt);
});
removeIds.forEach((elmtIndex)=>{
elmt = this._workingSet.getByIndex(elmtIndex-1);
if(!elmt) return;
removeElmts.push(elmt);
});
addElmts.forEach((elmt)=>{
if(this._workingSet_type === this._enums.wkset_type.all){
this._workingSet.add(elmt.smpobj,label);
}
bookmObj.add(elmt.smpobj,label);
});
removeElmts.forEach((elmt)=>{
if(this._workingSet_type === this._enums.wkset_type.all){
this._workingSet.remove(elmt.smpobj,elmt.label);
bookmObj.remove(elmt.smpobj,elmt.label);
}else if(this._workingSet_type === this._enums.wkset_type.lookup){
bookmObj.remove(elmt.smpobj,elmt.label);
}else if(_.isString(showingTag) && this._workingSet_type === this._enums.wkset_type.tag){
this._workingSet.remove(elmt.smpobj);
bookmObj.remove(elmt.smpobj,showingTag);
}
});
}
hasBookmarks(){
let bookmObj = DataMgr.get('bookmarks');
if(!_.isObject(bookmObj)) return false;
return (!bookmObj.empty());
}
forEach(cb){
let bookmObj = DataMgr.get('bookmarks');
if(!_.isObject(bookmObj) || bookmObj.empty()) return false;
bookmObj.forEach(cb);
}
save(){
DataMgr.save('bookmarks');
}
_createBookmarksHolder(){
return DataMgr.setHolder({
label:'bookmarks',
filePath:ConfigMgr.path('bookmarks'),
fileType:'json',
dataType:'object',
logErrorsFn:console.log,
preLoad:true,
// setFn:()=>{
// return __new_bookmObj();
// },
initFn:()=>{
return new Bookmarks();
},
loadFn:(fileData)=>{
d$('loading');
let bookmObj = new Bookmarks();
if(!_.isObject(fileData)){
return bookmObj;
}
bookmObj.fromJson(fileData);
bookmObj.sort();
return bookmObj;
},
saveFn:(bookmObj)=>{
bookmObj.sort();
return bookmObj.toJson();
}
});
}
}
module.exports = new BookmarksManager();
|
import React, { Component,Fragment } from 'react';
import {Col, Container, Row, Pagination, Button} from "react-bootstrap";
import JobIcon from './../../asset/images/jobs/jobsIcon.webp';
class careerAdvisor extends Component {
render() {
return (
<Fragment>
<div className="page__bg">
<Container>
<p className="pageSection__title pt-5">Trainings</p>
<p className="greyBar"></p>
<div className="jobCategory__checkBoxSection mt-4">
<Row>
<Col lg="4" md="4" sm="12">
<div className="p-4 jobCategory__checkBoxSection--responsive jobCategory__checkBoxSection--FirstSectionResponsive">
<input type="checkbox"/>
<label className="checkbox__label">Finance</label><br/>
<input type="checkbox"/>
<label className="checkbox__label"> Accounting </label><br/>
<input type="checkbox"/>
<label className="checkbox__label"> Supply Chain </label><br/>
</div>
</Col>
<Col lg="4" md="4" sm="12">
<div className="p-4 jobCategory__checkBoxSection--responsive">
<input type="checkbox"/>
<label className="checkbox__label"> Trade Marketing</label><br/>
<input type="checkbox"/>
<label className="checkbox__label"> Business Management </label><br/>
<input type="checkbox"/>
<label className="checkbox__label"> Marketing </label><br/>
</div>
</Col>
<Col lg="4" md="4" sm="12">
<div className="p-4 jobCategory__checkBoxSection--responsive">
<input type="checkbox"/>
<label className="checkbox__label"> Sales</label><br/>
<input type="checkbox"/>
<label className="checkbox__label"> HR </label><br/>
</div>
</Col>
</Row>
</div>
<Row className="mt-5">
<Col lg="4" md="6" sm="12">
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
</Col>
<Col lg="4" md="6" sm="12">
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
</Col>
<Col lg="4" md="6" sm="12">
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
<div className="avaiablejobs__jobCard">
<img className="avaiablejobs__jobIcon" src={JobIcon} alt="jobIcon"/>
<div className="avaiablejobs__jobDes">
<p className="availableJobs__jobTitle">Training Title</p>
<p className="availableJobs__jobCategory">Training Category</p>
<Button className="availableJobs__btn details__btn mt-2">View Details</Button>
</div>
</div>
</Col>
<Pagination className="talentTracker__pagination mt-5">
<Pagination.First />
<Pagination.Prev />
<Pagination.Item>{1}</Pagination.Item>
<Pagination.Ellipsis />
<Pagination.Item>{10}</Pagination.Item>
<Pagination.Item>{11}</Pagination.Item>
<Pagination.Item active>{12}</Pagination.Item>
<Pagination.Item>{13}</Pagination.Item>
<Pagination.Item disabled>{14}</Pagination.Item>
<Pagination.Ellipsis />
<Pagination.Item>{20}</Pagination.Item>
<Pagination.Next />
<Pagination.Last />
</Pagination>
</Row>
</Container>
</div>
</Fragment>
);
}
}
export default careerAdvisor; |
import React from 'react'
import { v4 as uuidv4} from 'uuid'
import ToDo from './ToDo'
const ToDoList = ({ toDoList, checkItem, deleteItem }) => {
return (
<div>
{toDoList.map(todo => {
let key = uuidv4()
return (
<ToDo todo={todo} checkItem={checkItem} deleteItem={deleteItem} key={key}/>
)
})}
</div>
)}
export default ToDoList |
"use strict";
module.exports = function(sequelize, DataTypes) {
var Vote = sequelize.define("Vote", {
up: DataTypes.BOOLEAN
});
Vote.associate = function(models) {
Vote.belongsTo(models.User, {
foreignKey: 'user_id',
targetKey: 'user_id'
})
Vote.belongsTo(models.Comment, {
})
}
Vote.add = function(area, category, id, user, db, up){
return db.Comment.find({
where:{
id: id
},
include: [
{
model: db.Category,
where: {id: category},
required:true,
include: [
{
model: db.Area,
required: true,
where: {name: area}
}
]
}
]
}).then(comment => {
return Vote.find({
where: {
user_id: user,
CommentUuid: comment.uuid
}
}).then(vote => {
if(vote){
Vote.upsert({
id: vote.id,
user_id: user,
CommentUuid: comment.uuid,
up
})
} else {
Vote.create({
user_id: user,
CommentUuid: comment.uuid,
up
})
}
})
})
}
return Vote;
};
|
import React, { useState } from "react";
import GmailLogo from "../assets/img/gmail.svg";
import MailchimpLogo from "../assets/img/mailchimp.svg";
const emailsInitial = {
gmail: {
id: "gmail",
title: "Gmail",
description: "These Gmail contacts will sync to MailChimp",
icon: GmailLogo,
contacts: ["Family", "Relatives", "Work", "Gym", "Bar"],
contactsSelection: [],
},
mailchimp: {
id: "mailchimp",
title: "Mailchimp",
description: "These Mailchimp contacts will sync to Gmail",
icon: MailchimpLogo,
contacts: ["Friends", "College"],
contactsSelection: [],
},
};
const initialState = {
emails: emailsInitial,
setEmails: () => {},
syncContacts: () => {},
};
export const EmailsContext = React.createContext(initialState);
const EmailsStore = ({ children }) => {
const [emails, setEmails] = useState(emailsInitial);
const syncContacts = () => {
const e = emails;
const gmailContactsSelected = e.gmail["contactsSelection"].filter((item) => item.selected).map((item) => item.label);
e.mailchimp.contacts = [...new Set(e.mailchimp.contacts.concat(gmailContactsSelected))];
const mailchimpContactsSelected = e.mailchimp["contactsSelection"].filter((item) => item.selected).map((item) => item.label);
e.gmail.contacts = [...new Set(e.gmail.contacts.concat(mailchimpContactsSelected))];
setEmails({ ...e });
};
return <EmailsContext.Provider value={{ emails, setEmails, syncContacts }}>{children}</EmailsContext.Provider>;
};
export default EmailsStore;
|
import React, { useState, useImperativeHandle } from 'react'
import PropTypes from 'prop-types'
import {
Box,
Button,
Collapsible
} from 'grommet'
const Togglable = React.forwardRef((props, ref) => {
const [visible, setVisible] = useState(false)
const toggleVisibility = () => {
setVisible(!visible)
}
useImperativeHandle(ref, () => {
return {
toggleVisibility
}
})
return (
<Box
align='center'
pad='medium'
>
<Collapsible open={visible}>
{props.children}
<Button onClick={toggleVisibility} label='cancel' />
</Collapsible>
{!visible && (
<Box width='small'>
<Button onClick={toggleVisibility} label={props.buttonLabel}/>
</Box>
)}
</Box>
)
})
Togglable.propTypes = {
buttonLabel: PropTypes.string.isRequired,
children: PropTypes.object.isRequired
}
Togglable.displayName = 'Togglable'
export default Togglable
|
var UnitInfo = function(res, grade, attack, attackInc, attackRange, splashRange, attackSpd, critical, moveSpd, type, attr, skill, skillCoolTime, isSplash, name, code, recKey, lev, exp, present, weaponName) {
this.res = res.split("_")[1];
this.grade = Number(grade);
this.attack = Number(attack);
this.attackInc = Number(attackInc);
this.attackRange = Number(attackRange);
this.splashRange = Number(splashRange);
this.attackSpd = Number(attackSpd);
this.critical = Number(critical);
this.moveSpd = Number(moveSpd);
this.type = Number(type);
this.attr = Number(attr);
this.skill = Number(skill);
this.skillCoolTime = Number(skillCoolTime);
this.isSplash = isSplash;
this.name = name;
this.code = code;
this.recKey = recKey;
this.lev = Number(lev);
this.exp = Number(exp);
this.present = String(present).split("|");
this.weaponName = weaponName;
this.check = false;
this.used = false;
for (var i = 0; i < this.exp; i++) {
this.attack = this.attack + Math.floor(this.attack * this.attackInc / 100);
}
};
UnitInfo.prototype.setCheck = function(_check) {
this.check = _check;
};
UnitInfo.prototype.getCheck = function() {
return this.check;
};
UnitInfo.prototype.setUsed = function(_used) {
this.used = _used;
};
UnitInfo.prototype.getUsed = function() {
return this.used;
};
UnitInfo.prototype.getGrade = function() {
return this.grade;
};
UnitInfo.prototype.getRes = function() {
return this.res;
};
UnitInfo.prototype.getAttack = function() {
return this.attack;
};
UnitInfo.prototype.getAttackInc = function() {
return this.attackInc;
};
UnitInfo.prototype.getAttackRange = function() {
return this.attackRange;
};
UnitInfo.prototype.getSplashRange = function() {
return this.splashRange;
};
UnitInfo.prototype.getAttackSpd = function() {
return this.attackSpd;
};
UnitInfo.prototype.getCritical = function() {
return this.critical;
};
UnitInfo.prototype.getMoveSpd = function() {
return this.moveSpd;
};
UnitInfo.prototype.getType = function() {
return this.type;
};
UnitInfo.prototype.getAttr = function() {
return this.attr;
};
UnitInfo.prototype.getSkill = function() {
return this.skill;
};
UnitInfo.prototype.getSkillCoolTime = function() {
return this.skillCoolTime;
};
UnitInfo.prototype.getIsSplash = function() {
return this.isSplash;
};
UnitInfo.prototype.getName = function() {
return this.name;
};
UnitInfo.prototype.getCode = function() {
return this.code;
};
UnitInfo.prototype.getRecKey = function() {
return this.recKey;
};
UnitInfo.prototype.isRankUp = function() {
return this.exp >= this.lev * 10 + 10;
};
UnitInfo.prototype.getExp = function() {
return this.exp + 1;
}
UnitInfo.prototype.getLev = function() {
return this.lev;
};
UnitInfo.prototype.getPresent = function() {
return this.present;
};
UnitInfo.prototype.getWeaponName = function() {
return this.weaponName;
}; |
import React from 'react';
import { Button } from 'reactstrap';
const LoadMoreButton = ({ onLoadMore }) => {
return (
<Button className='main-btn load-more-btn' onClick={() => onLoadMore()}>
Load More
</Button>
);
};
export default LoadMoreButton;
|
/**
* FeatureController
*
* @description :: Server-side actions for handling incoming requests.
* @help :: See https://sailsjs.com/docs/concepts/actions
*/
module.exports = {
add:function(req,res){
res.view('admin/addfeature')
},
getfeature : function(req,res){
Feature.findOne({game_id : req.param('game_id')}).exec(function(err, feature){
if(err){
return res.serverError(err);
}
else{
res.json(feature)
}
})
}
};
|
var ui = require('./yindex')
var insert = require('insert-css')
var cstyle = require('../see-style')
var master = new AudioContext
var sr = master.sampleRate
var beezy = require('../beezy')
var jsynth = require('../jsynth')
var $ = require('../polysynth/cheatcode')
var getids = require('getids')
var fs = require('fs')
var html = fs.readFileSync('./module.html', 'utf8')
var css = fs.readFileSync('./module.css', 'utf8')
insert(css)
document.body.innerHTML = html;
var model = document.querySelector('.module')
var env, dur = 1, del, start = false, fq
var ux = getids()
//iterate initial state ball and assign new interface element
//add option to drop down modules, which could be a parametrical element
//that switches style for large screen or mobile
//also save state between loads...
function init(config){
var elements = {}
for(x in config){
var el = document.createElement('div')
el.classList.add(config[x].type)
elements[config[x].name] = el
config[x]['el'] = el
}
return {config, elements}
}
// need to write a time-wubbing iir ****<---o--->**** for flawless transitions
var {config, elements} = init({
gain:
{ type: 'dial', value: .333, name: 'gain', mag: 5/10, min:0, max: 1},
amod:
{ type: 'dial', value: 1/3, step: 1/10, mag: 10},
xy: {type: 'xy', value: [3, 9], range:[-4,-24,4,24], name: 'ps'},
gain2:
{ type: 'dial', value: .4, name: 'gain', mag: 5/10, min:-3, max: 3, name: "jambosa"},
amod2:
{ type: 'dial', value: 1/3, step: 1/9, mag: 9, name:"mafoosa"},
f: { type: 'dial', value: 1/6, step: 1/9, mag: 10, name: 'f'},
g: { type: 'dial', value: 1/8, step: 1/10, mag: 10, name: 'g'},
a: {type: 'env', value: [[0,0],[0,2/2], [1,1]], name: 'athumb'},
s: {type: 'env', value: [[0,1],[1/2,1/4],[1,0]], name: 'sthumb'},
d: {type: 'env', value: [[0,0],[1/2, 1/2], [1,1]], name: 'dthumb'},
r: {type: 'bezier', value: [[0,1/2],[.25, 1],[.5, .5],[.75, 0], [1,1/2]], name: 'rthumb'},
e: {type: 'amod', value: [[0,1/2],[0,3/2], [1,1]], name: 'xthumb'}
})
for(e in elements) model.appendChild(elements[e])
cstyle.flex(model, {square: 3})
var st = ui(config, function(v, e){
//console.log(e, v)
am = {}
am.curves = v//st.state.amod
dur = am.dur = 1
// env = $.env([st.state.env2], [dur])
del = $.jdelay(1, .59, .9)
//console.log(st.state.env2)
//console.log('****************')
for(var x = 0; x <= 100; x++){
}
//console.log('****************')
// console.log(v,e, st.state, env(1))
fq = 440/2
if(!start){
start = true
}
bz = as(state.a, state.s, .1, 1/2) // refresh env
if(e==='ps')iir=$.iir(Math.abs(Math.floor(v[0])), Math.abs(Math.floor(v[1])))
})
var state = st.state
var beezmod = function(){
let pts = state.env2//[[0, 1/2], [.5, 1], [.5, .5], [.5, 0], [1, 1/2]]
let env = $.beezxy(pts)
pts = pts.reduce((a,e) => { a[0].push(e[0]); a[1].push(e[1]); return a }, [[],[]])
return function(c, t, f){
pts[0][2] = .5 + $.oz.sine(t, f * -state.g) / 2
var e = env((t * f) % 1, pts)
return e
}
}
//var tzmod = beezmod()
var rotate = (deg, xy)=>{
var c = Math.cos(deg*Math.PI/180)
var s = Math.sin(deg*Math.PI/180)
var tan = 1/Math.tan(deg*Math.PI/180)
return [(((xy[0]) * c) - ((xy[1]) * s)) + xy[1] * tan, ((xy[0]) * s) + (( xy[1]) * c)]
}
var zero = () => [0,0]
var as = function(a, s, ad, sd){
var ae = $.beezxy(a)
var se = $.beezxy(s)
a = a.reduce((a,e) => { a[0].push(e[0]); a[1].push(e[1]); return a }, [[],[]])
s = s.reduce((a,e) => { a[0].push(e[0]); a[1].push(e[1]); return a }, [[],[]])
var aalt = [ae,zero]
var salt = [se, zero]
var alt = [0,1] // don't get confused
var ez = [ae, se]
return function(t){
var tt = (t % (ad + sd)) / ad
var e = Math.floor(Math.min(tt, 1)) // should be zero if t < attack duration, else 1
var z = alt.map(i => i ^ e)
//if(t % 1 == .6) console.log(z)
//if(t % 1 == .1) console.log(t % ad, z, aalt[z[0]](t % ad, a))
return aalt[z[0]]((t % 1) * 1/ad, a)[1] + salt[z[1]](((t-ad) % 1) * 1/sd, s)[1]
}
}
var bz = as(state.a, state.s, .01, .99)//beezmod()
var bpm = 149.5
var iir = $.iir(4,12)
var dld, dl2d
var sampleRate = master.sampleRate
var dl = $.jdelay(dld = Math.floor(sampleRate * 60 / bpm / 15/2), .8, 1/2)
var dl2 = $.jdelay(dl2d = Math.floor(sampleRate * 60 / bpm * 3 / 2), .4, 1/2)
for(var x = 0; x < 1; x+=.01){
console.log(x, bz(x/1))
}
var synth = jsynth(master, function(t, s, i){
var e = bz(t)
//if(.2 > t % 1 > .1) console.log(e)
return $.oz.sine(t, 448) * e
var c = $.gtone(e[0], Math.PI * (113 - ((t*bpm/60) % 24)), $.amod(0, Math.E, e[0], 15), $.amod(Math.PI, Math.PI, e[0], -1/18), Math.E, 31, $.ph.sine, $.amod(0, 1/2, e[0], -state.amod2))
if(t%1==0) console.log(state.amod)
return (dl2(iir(dl(c * e[1])) * $.winfunk.planckt(t, 333,11), dl2d, $.amod(state.gain2, .4, e[0], -state.amod), 1/2)) * state.gain //(music(t, s, i))
},1024 )
var started = false
ux.play.onclick = function(e){
started = !started
if(started){
master.resume().then(() => {
synth.connect(master.destination)
})
}
else synth.disconnect(master)
}
|
/**
* Tractrix
*
* Imagine you have a rigid beam laid flat on the ground. Now imagine you pull the
* bottom of the rigid beam to the side and let the top drag behind. The path the
* top takes is a tractrix
*
* a(t) = (cos t + ln(tan(t / 2)), sin t)
* a'(t) = (-sin t + csc t, cos t)
*/
var SCALE = 100; // Pixels per unit
var PIXEL = 1.0 / SCALE;
var SPEED = 0.005;
/**
* Okay, really this is a half tractrix,
* but if we have 2 of them we can plot forwards
* and backwards at once
*/
function Tractrix(beam_length, dt) {
this.beam_length = beam_length;
this.dt = dt;
this.angle = HALF_PI;
this.tractrix = [];
this.update = function() {
if (0 < this.angle && this.angle < PI) {
this.angle += this.dt;
var new_point = this.curve_point(this.angle);
this.tractrix.push(new_point);
} else {
this.angle = HALF_PI;
this.tractrix = [];
}
}
this.ground_point = function(t) {
return createVector(log(tan(t / 2)), 0);
}
this.curve_point = function(t) {
return createVector(cos(t) + log(tan(t / 2)), sin(t));
}
this.render = function() {
stroke(255);
strokeWeight(2 * PIXEL);
// Draw the beam
var ground = this.ground_point(this.angle);
var curve = this.curve_point(this.angle);
line(ground.x, ground.y, curve.x, curve.y);
// Draw the curve
stroke(255, 0, 0);
strokeWeight(4 * PIXEL);
noFill();
beginShape();
for (var p of this.tractrix) {
vertex(p.x, p.y);
}
endShape();
};
}
var tractrices;
function setup() {
createCanvas(windowWidth, windowHeight);
tractrices = [
new Tractrix(2.0, SPEED),
new Tractrix(2.0, -SPEED)
];
}
function update() {
for (let tractrix of tractrices)
tractrix.update();
}
function draw() {
background(0);
push();
translate(width / 2, height / 2);
scale(SCALE, -SCALE);
for (let tractrix of tractrices)
tractrix.render();
pop();
update();
}
|
import { addZero } from './supScript.js';
export const videoPlayerInit = () => {
const videoPlayer = document.querySelector('.video-player'),
videoButtonPlay = document.querySelector('.video-button__play'),
videoTimePassed = document.querySelector('.video-time__passed'),
videoProgress = document.querySelector('.video-progress'),
videoTimeTotal = document.querySelector('.video-time__total'),
videoFullscreen = document.querySelector('.video-fullscreen'),
videoVolume = document.querySelector('.video-volume');
const toggleIcon = () => {
if (videoPlayer.paused) {
videoButtonPlay.classList.remove('fa-pause');
videoButtonPlay.classList.add('fa-play');
} else {
videoButtonPlay.classList.add('fa-pause');
videoButtonPlay.classList.remove('fa-play');
}
};
const togglePlay = () => {
if (videoPlayer.paused) {
videoPlayer.play();
} else {
videoPlayer.pause();
}
};
const stopPlay = () => {
videoPlayer.pause();
videoPlayer.currentTime = 0;
};
const toggleTime = () => {
const currentTime = videoPlayer.currentTime,
duration = videoPlayer.duration;
videoProgress.value = (currentTime / duration) * 100;
const minutePassed = Math.floor(currentTime / 60),
secondsPassed = Math.floor(currentTime % 60);
const minuteTottal = Math.floor(duration / 60),
secondsTottal = Math.floor(duration % 60);
videoTimePassed.textContent = `${addZero(minutePassed)}:${addZero(secondsPassed)}`;
videoTimeTotal.textContent = `${addZero(minuteTottal)}:${addZero(secondsTottal)}`;
};
const toggleProgress = () => {
const duration = videoPlayer.duration,
value = videoProgress.value;
videoPlayer.currentTime = (value * duration) / 100;
};
document.addEventListener('click', () => {
const target = event.target;
if (target.matches('.video-button__play') || target.matches('.video-player')) {
togglePlay();
}
if (target.matches('.video-button__stop')) {
stopPlay();
}
});
videoProgress.addEventListener('change', toggleProgress);
videoPlayer.addEventListener('play', toggleIcon);
videoPlayer.addEventListener('pause', toggleIcon);
videoPlayer.addEventListener('timeupdate', toggleTime);
videoFullscreen.addEventListener('click', () => {
videoPlayer.webkitEnterFullScreen();
});
videoVolume.addEventListener('input', () => {
videoPlayer.volume = videoVolume.value / 100;
});
videoVolume.value = videoPlayer.volume * 100;
videoPlayerInit.stop = () => {
if (!videoPlayer.paused) {
stopPlay();
}
};
};
|
import { takeEvery, takeLatest, select, put, delay, call, all, fork, cancel } from 'redux-saga/effects';
import { setCounter, setGameResult, setPicturesFetch, stopGame, setError } from '../actionCreators/gameState';
import { toggleAllCards, disableCard, setCards } from '../actionCreators/cards';
import { START_GAME, STOP_GAME, RESET_GAME, OPEN_CARD, SET_GAME_RESULT } from '../constants/actionTypes';
import { SETTINGS_SELECTOR, CARDS_SELECTOR, GAME_STATE_SELECTOR } from './selectors';
class Card {
constructor(cardImg) {
this.id = Math.floor(Math.random() * 100000000);
this.img = cardImg;
this.isOpen = false;
this.isDisable = false;
}
}
export function* rootSaga() {
yield takeLatest(START_GAME, startGameWorker);
yield takeEvery(OPEN_CARD, openCardWorker);
yield takeEvery(SET_GAME_RESULT, stopGameWorker);
yield takeLatest(STOP_GAME, stopGameWorker);
yield takeEvery(RESET_GAME, function*() {
yield put(toggleAllCards(false));
});
}
// start decrementing counter when the game has been started
function* counter(counterTime) {
yield put(setCounter(counterTime));
while(true) {
yield delay(1000);
yield put(setCounter());
const { counter } = yield select(GAME_STATE_SELECTOR);
if (counter <= 0) {
yield put(setGameResult(false));
break;
}
}
}
function* getRandomImage(density) {
return yield call(async () => await (await fetch(`https://picsum.photos/${600 / density}`)).url);
}
function* createCardsList() {
yield put(setPicturesFetch(true));
const { density } = yield select(SETTINGS_SELECTOR);
try {
const cardArr = yield all(
[ ...new Array(Math.pow(density, 2) / 2) ].map(() => getRandomImage(density))
);
const cards = [ ...cardArr, ...cardArr ].
map(card => new Card(card)).
sort(() => Math.random() - Math.random());
yield put(setCards(cards));
return true;
} catch(err) {
yield put(stopGame());
yield put(setError());
} finally {
yield put(setPicturesFetch(false));
}
};
// toogle cards when game has been started
function* showCards(hidingTime) {
yield put(toggleAllCards(true));
yield delay(hidingTime * 1000);
yield put(toggleAllCards(false));
}
// saga's workers
let forkedCounter, forkedToggleCards;
function* startGameWorker() {
const settings = yield select(SETTINGS_SELECTOR);
localStorage.setItem('settings', JSON.stringify(settings));
const success = yield createCardsList();
if (success) {
forkedCounter = yield fork(counter, settings.time);
forkedToggleCards = yield fork(showCards, settings.hidingTime);
}
}
function* openCardWorker() {
const cards = yield select(CARDS_SELECTOR);
const openedCards = cards.filter(({ isOpen, isDisable }) => isOpen && !isDisable);
if (openedCards.length > 1) {
const [ card1, card2 ] = openedCards;
if (card1.img === card2.img) {
yield all([ put(disableCard(card1.id)), put(disableCard(card2.id)) ]);
const updatedCards = yield select(CARDS_SELECTOR);
if (updatedCards.every(({ isDisable }) => isDisable)) return yield put(setGameResult(true));
}
yield delay(500);
yield put(toggleAllCards(false));
}
}
function* stopGameWorker() {
yield all([
cancel(forkedCounter),
cancel(forkedToggleCards)
]);
}
|
'use strict';
const cellref = require('cellref');
module.exports = class Translate {
constructor(ref) {
this._cellref = cellref(ref);
}
translate(x,y) {
let [,r,c] = this._cellref.split(/^R(\d+)C(\d+)$/);
c = parseInt(c) + x;
r = parseInt(r) + y;
if (c < 1) {
throw new Error('Invalid horizontal translation, would result in column index less than A');
}
if (r < 1) {
throw new Error('Invalid vertical translation, would result in row number less than 1');
}
this._cellref = `R${r}C${c}`;
return this;
}
get ref() {
return cellref(this._cellref);
}
get colNum() {
return parseInt(this._cellref.match(/C(\d+)/)[1]);
}
get col() {
return cellref(this._cellref).match(/[A-Z]+/)[0];
}
get row() {
return parseInt(this.ref.match(/\d+/)[0]);
}
set col(value) {
return this._cellref = cellref(`${value}${this.row}`);
}
set row(value) {
return this._cellref = cellref(`${this.col}${parseInt(value)}`);
}
};
|
(function () {
"use strict";
describe("EditDomainModalCtrl", function () {
var ctrl,
DomainMgmtService,
modal,
modalInstance,
AlertsService;
beforeEach(function () {
inject(function (_DomainMgmtService_, _$modal_, _AlertsService_) {
DomainMgmtService = _DomainMgmtService_;
modal = _$modal_;
AlertsService = _AlertsService_;
});
AlertsService.addSuccess = jasmine.createSpy();
AlertsService.addErrors = jasmine.createSpy();
modalInstance = modal.open({
template: "<div></div>",
});
var singleDomain = {
smsDomainId: "1",
maxDevices: "100",
timePeriodRule: {
startTime: "2015-03-23T20:28:13.000+00:00",
endTime: "2015-03-24T20:28:13.000+00:00",
},
domainAddress: "64",
};
ctrl = initializeCtrl(singleDomain);
});
describe("init", function() {
it("should have access to the Domain details passed to it", function() {
expect(ctrl.editFields.id).toBeDefined("1");
expect(ctrl.editFields.maxDevices).toBeDefined(100);
expect(ctrl.editFields.startTime).toBeDefined("2015-03-23T20:28:13.000+00:00");
expect(ctrl.editFields.endTime).toBeDefined("2015-03-24T20:28:13.000+00:00");
expect(ctrl.editFields.address).toBeDefined("64");
});
});
describe("Bulk Edit Domains", function() {
beforeEach(function() {
var bulkDomains = [
{
smsDomainId: "1",
maxDevices: "100",
timePeriodRule: {
startTime: "2015-03-23T20:28:13.000+00:00",
endTime: "2015-03-24T20:28:13.000+00:00",
},
domainAddress: "64",
},
{
smsDomainId: "2",
maxDevices: "200",
},
];
ctrl = initializeCtrl(bulkDomains);
spyOn(DomainMgmtService, "editDomain").and.callFake(function() {
return {then: function(cb) {
var mockResponse = {
result: {
resultCode: "0", // success
resultText: "Success",
}
};
cb(mockResponse);
}};
});
});
afterEach(function() {
var singleDomain = {
smsDomainId: "1",
maxDevices: "100",
timePeriodRule: {
startTime: "2015-03-23T20:28:13.000+00:00",
endTime: "2015-03-24T20:28:13.000+00:00",
},
domainAddress: "64",
};
ctrl = initializeCtrl(singleDomain);
});
describe("init", function() {
it("should set isBulk to true", function() {
expect(ctrl.isBulk).toBe(true);
});
});
describe("saveChanges", function() {
it("should edit all domains with the input from the editFields", function() {
ctrl.editFields = {
maxDevices: 300,
startTime: "2015-03-11T20:28:13.598Z",
endTime: "2015-03-12T20:28:13.598Z",
address: "22",
};
var newBulkDomains = [
{
id: "1",
maxDevices: 300,
startTime: "2015-03-11T20:28:13.598Z",
endTime: "2015-03-12T20:28:13.598Z",
address: "22",
},
{
id: "2",
maxDevices: 300,
startTime: "2015-03-11T20:28:13.598Z",
endTime: "2015-03-12T20:28:13.598Z",
address: "22",
},
];
ctrl.saveChanges(ctrl.editFields);
expect(DomainMgmtService.editDomain).toHaveBeenCalledWith(newBulkDomains[0]);
expect(DomainMgmtService.editDomain).toHaveBeenCalledWith(newBulkDomains[1]);
expect(DomainMgmtService.editDomain.calls.count()).toBe(2);
});
});
});
describe("saveChanges", function() {
it("should call the editDomain service and show the success alert", function() {
spyOn(DomainMgmtService, "editDomain").and.callFake(function() {
return {then: function(cb) {
var mockResponse = {
result: {
resultCode: "0", // success
resultText: "Success",
}
};
cb(mockResponse);
}};
});
ctrl.saveChanges();
expect(DomainMgmtService.editDomain).toHaveBeenCalled();
expect(AlertsService.addSuccess).toHaveBeenCalled();
});
});
//////////
function initializeCtrl(domains) {
return $controller("EditDomainModalCtrl", {
$modalInstance: modalInstance,
domains: domains,
});
}
});
}());
|
const getDateFormat = (days = 1, isOld = false) => {
const date = new Date().getTime() + days * 86400000;
return isOld ? new Date().getTime() - days * 86400000 : date;
};
const salesData = [
{
serialCode: 12,
name: "DELUXE COOKED HAM",
price: 50,
productId: "102",
status: "delivered",
catId: "A1",
productDate: getDateFormat(1, true)
},
{
serialCode: 212,
name: "DELUXE LOW-SODIUM WHOLE HAM",
price: 60,
productId: "105",
catId: "A2",
status: "delivered",
productDate: getDateFormat(15, true)
},
{
serialCode: 123,
name: "GAS STOVE",
price: 500,
productId: "1082",
status: "dispatch",
catId: "A3",
productDate: getDateFormat(7, true)
},
{
serialCode: 333,
name: "VEGTABLES",
price: 800,
productId: "1095",
status: "dispatch",
catId: "",
productDate: getDateFormat(16, true)
},
{
serialCode: 434,
name: "SMOKED VIRGINA HAM",
price: 70,
productId: "156",
status: "arrived",
catId: "2",
productDate: getDateFormat(32)
},
{
serialCode: 434,
name: "HONEY MAPLE HAM",
price: 80,
productId: "150",
status: "arrived",
catId: "A4",
productDate: getDateFormat(22)
},
{
serialCode: 44,
name: "HONEY MAPLE HAM 1/2",
price: 40,
productId: "151",
status: "ordered",
catId: "",
productDate: getDateFormat(7)
},
{
serialCode: 32,
name: "BAVARIAN SMOKED HAM",
price: 90,
productId: "166",
status: "delivered",
catId: "A5",
productDate: getDateFormat(8, true)
},
{
serialCode: 89,
name: "BLACK FOREST BEECHWOOD HAM L/S",
price: 50,
productId: "11005",
status: "ordered",
catId: "A22",
productDate: getDateFormat(17)
},
{
serialCode: 8,
name: "TAVERN SMOKED HAM",
price: 55,
productId: "158",
status: "ordered",
catId: "B2",
productDate: getDateFormat(45)
},
{
serialCode: 40,
name: "ROSEMARY HAM",
price: 51,
productId: "173",
status: "ordered",
catId: "C2",
productDate: getDateFormat(6)
},
{
serialCode: 345,
name: "PESTO PARMESAN HAM",
price: 100,
productId: "189",
catId: "C12",
status: "ordered",
productDate: getDateFormat(34)
},
{
serialCode: 787,
name: "DELI SWEET SLICE SMOKED HAM",
price: 49,
productId: "11018",
catId: "R2",
status: "ordered",
productDate: getDateFormat(5)
},
{
serialCode: 777,
name: "HABANERO HAM ",
price: 515,
productId: "11044",
status: "ordered",
catId: "R92",
productDate: getDateFormat(2)
},
{
serialCode: 3,
name: "ITALIAN RSTD HAM (PROSC COTTO)",
price: 579,
productId: "11022",
catId: "",
status: "ordered",
productDate: getDateFormat(8)
},
{
serialCode: 1,
name: "SUNDAY HOT HAM (SWEET SLICE)",
price: 39,
productId: "11018",
catId: "",
status: "shipped",
productDate: getDateFormat(4)
},
{
serialCode: 91,
name: "DELUXE ROAST BEEF TOP-ROUND",
price: 69,
productId: "235",
catId: "T12",
status: "ordered",
productDate: getDateFormat(7)
},
{
serialCode: 72,
name: "LONDONPORT ROAST BEEF",
price: 69,
productId: "915",
catId: "B42",
status: "delivered",
productDate: getDateFormat(13, true)
},
{
serialCode: 25,
name: "APPLE 11 PRO",
catId: "",
price: 140,
productId: "1222",
status: "shipped",
productDate: getDateFormat(9, true)
},
{
serialCode: 105,
name: "ONE PLUS 9",
price: 339,
productId: "1118",
catId: "",
status: "cancelled",
productDate: getDateFormat(6, true)
},
{
serialCode: 876,
name: "OFFICE CHAIR",
price: 500,
productId: "2235",
catId: "",
status: "ordered",
productDate: getDateFormat(0)
},
{
serialCode: 10,
name: "TYRE 100R",
price: 39,
productId: "1908",
catId: "Z2",
status: "delivered",
productDate: getDateFormat(2, true)
}
];
module.exports = salesData;
|
import {mapState, mapMutations, mapActions} from 'vuex'
export default {
computed: {
...mapState('play', ['volume', 'url', 'pause']),
...mapState('c_playlist', ['cycle']),
...mapState('lyrics', ['show']),
_volume: {
get() {
return this.volume
},
set(val) {
this.$store.commit('play/update', {
volume: val
})
localStorage.volume = val
}
}
},
methods: {
...mapMutations('c_playlist', ['cycleChange']),
...mapActions('c_playlist', ['last', 'next']),
pauseChange() {
if (this.url) {
this.$store.commit('play/pauseChange')
}
}
},
created() {
this.$ipc.on('tray-control-last', this.last)
this.$ipc.on('tray-control-next', () => {
console.log('next')
this.next()
})
this.$ipc.on('tray-control-pause', this.pauseChange)
}
}
|
// src/demo08.js
// 无参数 - 函数装饰器 - 执行顺序
function log(target, name, descriptor) {
console.log('log装饰器=>', name)
}
function needLogin(target, name, descriptor) {
console.log('needLogin装饰器=>', name)
}
function lockAsyncFunction(target, name, descriptor) {
console.log('lockAsyncFunction装饰器=>', name);
}
class App {
@log
@needLogin
@lockAsyncFunction
onClientList() {
console.log('App.onClientList');
}
@log
@needLogin
a() {
console.log('a函数');
}
@lockAsyncFunction
A() {
console.log('A函数');
}
}
const app = new App();
app.onClientList(); |
import './TTT.html';
import { Template } from 'meteor/templating';
import { ReactiveVar } from 'meteor/reactive-var';
Template.game.onCreated(function gameOnCreated() {
this.winner = new ReactiveVar("");
this.ID = new ReactiveVar(Math.floor(Math.random() * 100000)); //Replace this with ID of user account
this.gameID = new ReactiveVar(-1);
this.currentBoard = new ReactiveVar("---------");
this.ready = new ReactiveVar(0);
});
Template.game.helpers({
winner() {return Template.instance().winner.get();},
ID() {return Template.instance().ID.get();},
gameID() {return Template.instance().gameID.get();},
currentBoard() {return Template.instance().currentBoard.get();},
ready() {return Template.instance().ready.get();},
});
Template.game.events({
'click .btn-back': function () {
Session.set("currentView", "gameSelect");
return;
},
'click .btn-start'(event, instance) {
console.log("your user ID is: " + instance.ID.get());
if (Games.findOne({player2: -1}) === undefined){
console.log("creating a game");
instance.gameID.set(Meteor.apply("makeGame", [instance.ID.get()], {returnStubValue: true}));
console.log("gameID: " + instance.gameID.get());
}
else{
console.log("found a game");
console.log(Games.findOne({player2: -1}).player1);
instance.gameID.set(Games.findOne({player2: -1})._id);
Meteor.call("joinGame", Games.findOne({player2: -1})._id, instance.ID.get());
}
//Run any time Games updates
Games.find(instance.gameID.get()).observeChanges({
changed: function (id, fields) {
console.log("changed");
var game = Games.findOne(id);
//check if game is ready
if (instance.ready.get() === 0 && game.player2 > 0)
instance.ready.set(1);
//check if board has changed
if (game.board != instance.currentBoard.get()){
console.log("board has changed");
instance.currentBoard.set(game.board);
var i = 0;
for (; i <= 8; i++)
document.getElementById(i).innerText = game.board[i];
if (game.win > 0){
if (game.win == instance.ID.get())
instance.winner.set("You Win!");
else
instance.winner.set("You Lost");
}
}
},
});
return;
},
'click .grid-item'(event, instance) {
if (instance.ready.get())
Meteor.call("makeMove", instance.gameID.get(), instance.ID.get(), event.currentTarget.id);
return;
},
});
|
import Level from "./quickfacts/quickfacts";
import MiniGraph from "./minigraph/minigraph";
import moment from "moment";
import axios from "axios";
import DistrictCases from "../components/district/view-districts-cases-table"
import BurgerNavigation from "./navigation/burger-navigation"
import corona from "./images/corona.gif";
import corona2 from "./images/corona.jpg";
import washinghands from "./images/washing-hand.png";
import travel from "./images/backpack.png";
import firstaid from "./images/first-aid-kit.png";
import cough from "./images/cough.png";
import mask from "./images/medical-mask.png";
import sanitizer from "./images/hand-sanitizer.png";
import cough2 from "./images/cough2.png";
import clean from "./images/clean.png";
import spit from "./images/no-spit.png";
import handshake from "./images/partnership.png";
import headache from "./images/pain.png";
import fever from "./images/fever.png";
import sick from "./images/sick.gif";
import body from "./images/tumor.png";
import sorethroat from "./images/sore-throat.png";
import lung from "./images/lung.png";
import "./extra.css";
import {
mergeTimeseries,
preprocessTimeseries,
parseStateTimeseries,
parseStateTestTimeseries,
parseTotalTestTimeseries,
} from '../utils/common-functions';
import React, { useState } from 'react';
import { useEffectOnce } from 'react-use';
function Home(props) {
const [states, setStates] = useState(null);
const [timeseries, setTimeseries] = useState(null);
const [covidData, setCovidData] = useState(null);
useEffectOnce(() => {
getStates();
});
const getStates = async () => {
try {
const [
{ data: statesDailyResponse },
] = await Promise.all([
axios.get('https://api.nepalcovid19.org/states_daily.json'),
]);
const [
{ data: latest },
{ data: datatimeline },
{ data: covid },
{ data: stateTestData },
] = await Promise.all([
axios.get('https://nepalcorona.info/api/v1/data/nepal'),
axios.get('https://api.nepalcovid19.org/latest_data.json'),
axios.get("https://data.nepalcorona.info/api/v1/covid"),
// axios.get('https://api.nepalcovid19.org/latest_data.json'),
axios.get('https://api.nepalcovid19.org/state_test_data.json'),
]);
setStates(latest);
const ts = parseStateTimeseries(statesDailyResponse);
ts['TT'] = preprocessTimeseries(datatimeline.cases_time_series);
// Testing data timeseries
const testTs = parseStateTestTimeseries(stateTestData.states_tested_data);
testTs['TT'] = parseTotalTestTimeseries(datatimeline.tested);
// Merge
const tsMerged = mergeTimeseries(ts, testTs);
setTimeseries(tsMerged);
setCovidData(covid);
} catch (err) {
console.log(err);
}
};
//
return (
<div><BurgerNavigation />
<div>
<React.Fragment>
<div className="home-left">
<div>
<img src={corona} className="frontp" />
</div>
<div className="Home">
<div className="header fadeInUp" style={{ animationDelay: "1s" }}>
<div className="actions">
{covidData && <h5>Updated {moment(new Date(states.updated_at)).fromNow()}</h5>}
</div>
{states && <Level data={states} />}
{timeseries && <MiniGraph timeseries={timeseries['TT']} />}
</div>
<div className="user_card fadeInUp" style={{ animationDelay: "1s" }}>
<div className="row">
<div className="col-sm-6">
<div className="embed-responsive embed-responsive-4by3 ">
<iframe className="embed-responsive-item " src="https://www.youtube.com/embed/i0ZabxXmH4Y" allowfullscreen></iframe>
</div>
</div>
<div className="col-sm-6">
<div style={{ fontWeight: "bold", fontSize: "25px" }} className="text-success ">What is Coronavirus ?</div>
<div className="text-justify">Coronavirus disease (COVID-19) is an infectious disease caused by a newly discovered coronavirus.
Most people infected with the COVID-19 virus will experience mild to moderate respiratory illness and recover without requiring special treatment. Older people, and those with underlying medical problems like cardiovascular disease, diabetes, chronic respiratory disease, and cancer are more likely to develop serious illness.
The best way to prevent and slow down transmission is be well informed about the COVID-19 virus, the disease it causes and how it spreads. Protect yourself and others from infection by washing your hands or using an alcohol based rub frequently and not touching your face.
The COVID-19 virus spreads primarily through droplets of saliva or discharge from the nose when an infected person coughs or sneezes, so it’s important that you also practice respiratory etiquette (for example, by coughing into a flexed elbow).
At this time, there are no specific vaccines or treatments for COVID-19. However, there are many ongoing clinical trials evaluating potential treatments. WHO will continue to provide updated information as soon as clinical findings become available.
</div>
</div>
</div>
</div>
</div>
<div className="home-hospital">
<DistrictCases />
</div>
<div style={{background: "transparent" }}>
<hr/>
<div >
<h1 className="text-center">Preventive measures against Coronavirus</h1>
</div>
<div className="cardContainer center">
<div className="box">
<div className="content">
<img src={washinghands} alt="Corona img" width="100%" />
<p style={{ fontSize: "20px" }}>Washing hands frequently reduces the risk of being infected.</p>
</div>
</div>
<div className="box">
<div className="content">
<img src={cough} alt="first aid" />
<p style={{ fontSize: "20px" }}>When coughing and sneezing, everyone should cover their mouth.</p>
</div>
</div>
<div className="box">
<div className="content">
<img src={travel} alt="" />
<p style={{ fontSize: "20px" }}>Avoid travelling as much as possible.</p>
</div>
</div>
<div className="box">
<div className="content">
<img src={firstaid} alt="" />
<p style={{ fontSize: "20px" }}>Seek medical service if you have any symptoms.</p>
</div>
</div>
<div className="box">
<div className="content">
<img src={mask} alt="" />
<p style={{ fontSize: "20px" }}>Wearing mask is a good habit.</p>
</div>
</div>
<div className="box">
<div className="content">
<img src={sanitizer} alt="" />
<p style={{ fontSize: "20px" }}>Sanitize yourself after making contact with other individuals.</p>
</div>
</div>
<div className="box">
<div className="content">
<img src={clean} alt="" />
<p style={{ fontSize: "20px" }}>Clean and disinfect frequently touched surfaces daily.</p>
</div>
</div>
</div>
</div>
<hr/>
<div >
<h1 className="text-center font-weight-light">How corona virus actually spreads.</h1>
<h6 className="text-center text-success">Sanitize, distancing and mask</h6>
</div>
<div className="col-sm-12" >
<div className="row">
<div className="col-sm-12 col-md-6 col-lg-4">
<div className="containerCard">
<div className="col-sm-12 col-md-6 col-lg-4" >
<div className="cards">
<div className="face face1">
<div className="contents">
<img src={handshake} alt="card image" />
<h3>Direct human contact</h3>
</div>
</div>
<div className="face face2">
<div className="contents">
<p> It is suggested to avoid direct human contact and practice namaste instead of shaking hands.</p>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-6 col-lg-4" >
<div className="cards">
<div className="face face1">
<div className="contents">
<img src={spit} alt="card image" />
<h3>Droplet Transmission</h3>
</div>
</div>
<div className="face face2">
<div className="contents">
<p>There is high chance of sreading virus when a person sneezes or coughs.</p>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-6 col-lg-4" >
<div className="cards">
<div className="face face1">
<div className="contents">
<img src={cough2} alt="card image" />
<h3>Contaminated Objects</h3>
</div>
</div>
<div className="face face2">
<div className="contents">
<p>Virus can also be spreads via the contaminated object touched by infected person.</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr/>
<h3 className="text-center">Some symptoms of coronavirus.</h3>
<h6 className="text-center font-weight-light text-info"> It takes 2 to 14 days for symptoms to show up.
So, it is always good option to self isolate.</h6>
<img src={sick} className="rounded mx-auto d-block sizing" style={{ height: "200px", width: "auto" }} />
<div className="col-sm-12" >
<div className="row">
<div className="col-sm-12 col-md-4 " >
<div className="card bg-info text-white">
<div className="row">
<div className="col-sm-2">
<img className="card-img-top" style={{ width: "50px" }} src={headache} alt="Card image" />
</div>
<div className="col-sm-10">
<div style={{ fontWeight: "bold" }}>Headache</div>
<div class="col-sm-10" >
<p>
Infected person are prone to headache.
</p>
</div>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-4 " >
<div className="card bg-info text-white">
<div className="row">
<div className="col-sm-2">
<img className="card-img-top" style={{ width: "50px" }} src={body} alt="Card image" />
</div>
<div className="col-sm-10">
<div style={{ fontWeight: "bold" }}>Body ache</div>
<div class="col-sm-10" >
<p>
There may be pain all over the body.
</p>
</div>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-4 " >
<div class="card bg-info text-white">
<div className="row">
<div className="col-sm-2">
<img className="card-img-top" style={{ width: "50px" }} src={fever} alt="Card image" />
</div>
<div className="col-sm-10">
<div style={{ fontWeight: "bold" }}>Fever</div>
<div class="col-sm-10" >
<p>
High body temperature can also be noticed.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12 col-md-4 " >
<div className="card bg-info text-white">
<div className="row">
<div className="col-sm-2">
<img className="card-img-top" style={{ width: "50px" }} src={sorethroat} alt="Card image" />
</div>
<div className="col-sm-10">
<div style={{ fontWeight: "bold" }}>Sore throat</div>
<div class="col-sm-10" >
<p>Infected person can feel blockdage and difficulty in throat. </p>
</div>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-4 " >
<div className="card bg-info text-white">
<div className="row">
<div className="col-sm-2">
<img className="card-img-top" style={{ width: "50px" }} src={lung} alt="Card image" />
</div>
<div className="col-sm-10">
<div style={{ fontWeight: "bold" }}>Shortness of breathe</div>
<div class="col-sm-10" >
<p>
infected people experience difficulty in breathing.
</p>
</div>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-4 " >
<div class="card bg-info text-white">
<div className="row">
<div className="col-sm-2">
<img className="card-img-top" style={{ width: "50px" }} src={cough} alt="Card image" />
</div>
<div className="col-sm-10">
<div style={{ fontWeight: "bold" }}>Dry cough</div>
<div class="col-sm-10" >
<p>
Infected person may experience dry cough.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr/>
</React.Fragment>
</div>
</div >
);
}
export default Home;
|
var gulp = require('autotron')([
'at-Less',
'at-Sass',
'at-CompressCss',
'at-BuildStaticPages',
'at-Browserify',
'at-CompressJs',
'at-CompressJs',
'at-Revise',
'at-Replace',
'at-Webserver',
'at-Sitemap'
]);
gulp.task('less', ['at-Less']);
gulp.task('sass', ['at-Sass']);
gulp.task('compress-css', ['at-CompressCss']);
gulp.task('build-static-pages', ['at-BuildStaticPages']);
gulp.task('browserify', ['at-Browserify']);
gulp.task('compress-js', ['at-CompressJs']);
gulp.task('concat-js', ['at-ConcatJs']);
gulp.task('revise', ['at-Revise']);
gulp.task('replace', ['at-Replace']);
gulp.task('serve', ['at-Webserver']);
gulp.task('sitemap', ['at-Sitemap']);
|
import {createElement} from '../../create-element';
import './load-button.scss';
const loadButton = createElement('button', {
innerHTML: 'Show News',
className: ['btn', 'btn-danger', 'btn-shownews']
}
);
loadButton.addEventListener('click', loadNews);
const body = document.querySelector('body');
body.appendChild(loadButton);
async function loadNews() {
await import('../../common');
loadButton.remove();
}
|
const { registerBlockType } = wp.blocks
import Dropzone from '../components/Dropzone'
import Hero from '../components/Hero'
import Attachment from '../models/Attachment'
import { ReactComponent as BlockIcon } from '../../img/lnr-construction.svg'
registerBlockType(
'mwp/hero',
{
title: 'Hero',
category: 'mwp-gutenberg',
icon: {
src: BlockIcon
},
attributes: {
background: {
default: '',
type: 'string'
},
title: {
default: '',
type: 'string'
},
tagline: {
default: '',
type: 'string'
},
},
edit: (props) => {
const {
attributes: {
background,
title,
tagline
},
className
} = props
const onBackgroundChanged = ( value ) => {
const img = new Attachment(value)
props.setAttributes({ background: img.sizes.full.url })
}
if (props.isSelected) {
return (
<div className="mwp-gutenberg-form">
<h3 className="mwp-gutenberg-form__title">Hero</h3>
<div className="mwp-gutenberg-form__group">
<label className="mwp-gutenberg-form__label">Background Image</label>
{background &&
<div className="mwp-gutenberg-preview">
<img src={background} className="mwp-gutenberg-preview__thumbnail" />
<button
className="mwp-gutenberg-preview__remove dashicons dashicons-trash"
onClick={() => props.setAttributes({ background: null }) }
/>
</div>
}
{!background && <Dropzone onFileChanged={onBackgroundChanged} />}
</div>
<div className="mwp-gutenberg-form__group">
<label htmlFor="hero-title" className="mwp-gutenberg-form__label">Title</label>
<input
type="text"
id="hero-title"
className="mwp-gutenberg-form__input"
value={title}
placeholder="Hero Title"
onChange={(e) => props.setAttributes({ title: e.target.value })}
/>
</div>
<div className="mwp-gutenberg-form__group">
<label htmlFor="hero-tagline" className="mwp-gutenberg-form__label">Tagline</label>
<input
type="text"
id="hero-tagline"
className="mwp-gutenberg-form__input"
value={tagline}
placeholder="Lorem ipsum dolor sit amet, consectetur adipiscing elit"
onChange={(e) => props.setAttributes({ tagline: e.target.value })}
/>
</div>
</div>
)
} else {
return (
<Hero
classes={[className]}
style={{backgroundImage: `url('${background}')` }}
title={title}
tagline={tagline}
/>
)
}
},
save: (props) => {
const {
attributes: {
alignment,
background,
title,
tagline
}
} = props
return (
<Hero
style={{backgroundImage: `url('${background}')`, textAlign: alignment }}
title={title}
tagline={tagline}
/>
)
}
}
)
|
//BURGER MENU WORKING//
document
.querySelector("#burgermenuBtn")
.addEventListener("click", ShowBurgermenu);
function ShowBurgermenu() {
document.querySelector("#cos").classList.toggle("burgerContent");
document.querySelector("#cos").classList.toggle("burgerContentOpen");
console.log("show menu");
}
|
'use strict'
const express = require('express');
const app = express();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const expressJSDocSwagger = require('express-jsdoc-swagger');
const router = require('./router');
const port = process.env.PORT || 3000;
const swaggerOptions = {
info: {
description: 'Documentation for Node REST API',
title: 'NodeRESTAPI',
version: '1.0.0',
contact: {
name: 'Kevin Martínez',
email: 'kevinccbsg@gmail.com',
},
},
servers: [],
baseDir: __dirname,
filesPattern: './router/**.js',
};
mongoose.connect('mongodb://localhost:27017/beerlocker', (err) => {
if (err) { throw err; }
});
// Use the body-parser package in our app
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
expressJSDocSwagger(app)(swaggerOptions);
app.use('/api/1.0', router);
app.listen(port, () => {
console.log(`Listen on Port ${port}`);
});
|
export const setSelectedTodo = (todo) => {
return {
type: 'SET_SELECTED_TODO',
payload: todo
}
}
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPlayers } from './actions';
function mapStateToProps(state) {
return {boardStatus: state.boardStatus, players: state.players}
}
function mapDispatchToProps(dispatch){
return { fetchPlayers: () => dispatch(fetchPlayers()) }
}
class Leaderboard extends Component {
componentDidMount() {
this.props.fetchPlayers()
}
renderLeaderboardData(){
const sortedPlayerData = this.props.players.sort(function (a, b) { return b.score - a.score });
const leaderboardData = sortedPlayerData.map((player, index) => <tr><td>{index+1}.</td>
<td>{player.name}</td> <td>{player.score} Points</td></tr>);
return (
<table id='leaderboard'>
<tr><th>Rank</th><th>Name</th><th>Score</th></tr>
{leaderboardData}
</table>)
}
render() {
switch(this.props.boardStatus) {
case 'Success':
{
return this.renderLeaderboardData();
}
case 'Error':
{
if (this.props.players.length > 0) {
return (<>
{this.renderLeaderboardData()}
<div>Sorry. We had an error updating the leaderboard.</div>
</>)
} else {
return <div>Sorry. We had an error loading the leaderboard.</div>;
}
}
case 'Loading':
default:
{
return <div>Loading...</div>
}
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Leaderboard)
|
import InfoItem from "../InfoItem";
const CityItem = props => {
return <InfoItem navLink='/profile' title={props.title} value={props.city} />
}
export default CityItem |
//Var main elements
let tilemap;
let hero;
let livesEl;
let badboys = [];
//-----OBJECTS-----//
//TILEMAP CLASS//
class TileMap {
constructor() {
this.grid = new Array(); //create an array (of arrays) to interact with
for (let row = 0; row < 38; row++) {
//create the map
let line = new Array();
for (let col = 0; col < 18; col++) {
var tile = oxo.elements.createElement({
type: "div",
class: "tile",
styles: {
height: "40px",
width: "40px",
top: col * 40 + "px",
left: row * 40 + "px"
},
appendTo: ".map"
});
line.push(tile);
}
this.grid.push(line);
}
}
// method to get a tile (after burnTile or resetTile)
getTile(x, y) {
let valx = Math.round(x / 40);
let valy = Math.round(y / 40);
let line = this.grid[valx]; //line is the x axe
if (line == null) {
//security in case of outofindex
return null;
} else {
return line[valy];
}
}
//tile--burned
burnTile(x, y) {
let tile = this.getTile(x, y);
if (tile) {
//!null and !undefined (security)
if (!tile.classList.contains("tile--burned")) {
tile.classList.add("tile--burned");
}
}
}
//reset tile
resetTile(x, y) {
let tile = this.getTile(x, y);
if (tile && tile.classList.contains("tile--burned")) {
tile.classList.remove("tile--burned");
oxo.player.addToScore(100);
}
}
}
//HERO CLASS//
class Hero {
constructor() {
this.lives = 5;
this.oxoElement = oxo.elements.createElement({
type: "div",
class: "hero",
appendTo: ".map"
});
oxo.animation.moveElementWithArrowKeys(this.oxoElement, 20);
//method to target and shoot
document.querySelector(".contain").addEventListener("click", event => {
//fat arrow to stay in the correct scope
event.preventDefault(); //security to remove the click behaviour (select, etc.)
let oxo_position = oxo.animation.getPosition(this.oxoElement);
//choose in case of diagonal
let distanceX = Math.abs(oxo_position.x - event.clientX); //event.clientX return the cursor position (on X)
let distanceY = Math.abs(oxo_position.y - event.clientY); //event.clientY return the cursor position (on Y)
if (distanceX > distanceY) {
//decide between left and right
if (oxo_position.x < event.clientX) {
new Bullet(oxo_position.x, oxo_position.y, "right", false);
} else {
new Bullet(oxo_position.x, oxo_position.y, "left", false);
}
} else {
if (oxo_position.y < event.clientY) {
new Bullet(oxo_position.x, oxo_position.y, "down", false);
} else {
new Bullet(oxo_position.x, oxo_position.y, "up", false);
}
}
});
}
}
//BADBOY CLASS//
class BadBoy {
constructor() {
this.oxoElement = oxo.elements.createElement({
type: "div",
class: "badboy",
styles: {
transform:
"translate(" +
oxo.utils.getRandomNumber(0, window.innerWidth) +
"px, " +
oxo.utils.getRandomNumber(0, window.innerHeight) +
"px)"
},
appendTo: ".map"
});
badboys.push(this);
//Movement//
//initialize the direction, then randomize
this.direction = "none";
this.changeDirection();
//move every 100ms
this.moveInterval = setInterval(() => {
this.move();
}, 100);
//change the direction every 2000ms
this.changeDirectionInterval = setInterval(() => {
this.changeDirection();
}, 2000);
this.shootInterval = setInterval(() => {
this.shoot();
}, 4000);
//cause damage when colliding with hero
oxo.elements.onCollisionWithElement(
hero.oxoElement,
this.oxoElement,
function() {
displayLife(--hero.lives);
if (hero.lives === 0) {
oxo.screens.loadScreen("end", death);
}
}
);
}
//Move the enemy
move() {
if (this.direction != "none") {
//security
oxo.animation.move(this.oxoElement, this.direction, 5); // Move 5px
}
}
// Change the direction
changeDirection() {
const array = ["up", "down", "left", "right"];
this.direction = array[oxo.utils.getRandomNumber(0, array.length - 1)];
}
// shoot randomly
shoot() {
let oxo_position = oxo.animation.getPosition(this.oxoElement); //initial position
const array = ["up", "down", "left", "right"];
let dir = array[oxo.utils.getRandomNumber(0, array.length - 1)];
new Bullet(oxo_position.x, oxo_position.y, dir, true);
}
}
//BULLET CLASS - FIREBALL OR WATERBALL//
class Bullet {
constructor(posx, posy, direction, isFire) {
this.oxoElement = oxo.elements.createElement({
type: "div",
class: isFire ? "fireball" : "waterball",
styles: {
transform: "translate(" + posx + "px, " + posy + "px)"
},
appendTo: ".map"
});
this.direction = direction;
this.isFire = isFire;
//Target of the bullet
//Hero is touched
if (isFire) {
oxo.elements.onCollisionWithElement(
this.oxoElement,
hero.oxoElement,
function() {
displayLife(--hero.lives);
if (hero.lives === 0) {
oxo.screens.loadScreen("end", death);
}
}
);
//Badboy is dead
} else {
badboys.forEach(badboy => {
oxo.elements.onCollisionWithElement(
this.oxoElement,
badboy.oxoElement,
function() {
oxo.player.addToScore(150);
badboy.oxoElement.remove();
clearInterval(badboy.moveInterval); //do not forget to clear all intervals when destroying an object
clearInterval(badboy.changeDirectionInterval);
clearInterval(badboy.shootInterval);
badboy.oxoElement.remove(); //remove from HTML
destroyObj(this); //set it to null (end of code)
}
);
});
}
// Prevent infinite travel distance
this.traveldistance = 0;
this.moveInterval = setInterval(
() => {
this.move();
},
50,
true
); //50ms
}
move() {
// "movement" of the bullet
this.traveldistance += 10;
oxo.animation.move(this.oxoElement, this.direction, 10); //10px
let oxo_position = oxo.animation.getPosition(this.oxoElement);
if (this.isFire) tilemap.burnTile(oxo_position.x, oxo_position.y);
//interaction with the map
else tilemap.resetTile(oxo_position.x, oxo_position.y);
if (this.traveldistance > 500) {
//max distance is 500 px
this.killBullet();
}
}
killBullet() {
clearInterval(this.moveInterval);
this.oxoElement.remove();
destroyObj(this);
}
}
//-----FONCTIONS-----//
// Start the game when pressing enter
oxo.inputs.listenKey("enter", function() {
if (oxo.screens.getCurrentScreen() === "") {
oxo.screens.loadScreen("game", startGame);
}
});
//Game init
function startGame() {
tilemap = new TileMap();
hero = new Hero();
oxo.player.setScore(0);
setInterval(function() {
new BadBoy();
}, 3000); //a wild badboy appears every 3s
livesEl = document.querySelector(".lives");
displayLife(hero.lives);
//go back to menu
document
.querySelector(".info--menuBtn")
.addEventListener("click", function() {
oxo.screens.loadScreen("home", function() {
});
});
}
//life counter
function displayLife(lifeNumber) {
livesEl.innerHTML = "";
for (var i = 0; i < lifeNumber; i++) {
livesEl.innerHTML += '<div class="heart" />';
}
}
function setLinks() {
document.querySelector(".returnBtn").addEventListener("click", function() {
oxo.screens.loadScreen("home", function() {
});
});
}
//lose when the map is burned
var countTiliBurned = 0;
setInterval(function() {
countTiliBurned = document.querySelectorAll(".tile--burned").length;
if (countTiliBurned > 138) {
//20% of the map
death();
}
}, 5000);
function death() {
oxo.screens.loadScreen("end", setLinks);
oxo.player.getScore();
clearInterval(BadBoy.moveInterval);
clearInterval(BadBoy.changeDirectionInterval);
clearInterval(BadBoy.shootInterval);
BadBoy.oxoElement.remove();
destroyObj(BadBoy);
}
//SET objects to null
function destroyObj(obj) {
obj = null;
} |
function drawText(txt, x, y, size = '32px', font = 'Verdana', color = '#fff')
{
context.fillStyle = color;
context.font = size + " " + font;
context.fillText(txt, x, y);
}
function textCenter(txt, size)
{
var textWidth = context.measureText(txt).width;
var scale = size / 16;
return (canvas.width/2) - (textWidth/2 * scale);
}
function detectCollision(rect1, rect2)
{
if
(
rect1.x + rect1.width >= rect2.x && rect1.x <= rect2.x + rect2.width
&&
rect1.y + rect1.height >= rect2.y && rect1.y <= rect2.y + rect2.height
)
return true;
return false;
} |
// Dit is een script dat hoort bij het video-overzicht van de studio, waardoor automatisch links naar de bijbehorende video's op vimeo worden aangemaakt.
// link naar het spreadsheet document: https://docs.google.com/spreadsheets/d/1MSLz8dkZ2SqzEc20K1YAS2MhYub35hJfvG84-FSKrWs/edit#gid=0
function onEdit() {
var s = SpreadsheetApp.getActiveSheet();
var r = s.getActiveCell();
// woorden die moeten worden genegeerd in de zoekopdracht op Vimeo:
var ignore = ['locatieopname', 'locatie-opname','()', 'studioopname', 'studio-opname','studio','locatie', ' van ', ' de ', ' het ', ' op ', ' in ', ' voor ', 'PE ', 'PO ', 'APO ', 'CME ', 'LE ', 'TA ', 'FY ', 'HA ', 'SO ', 'PAOB ','AA '];
if( r.getColumn() != 0 ) { //checks the column
var row = r.getRow();
//Browser.msgBox(row);
var time = new Date();
var values = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var title =values[row-1][1];
title = title.replace('(',''); title = title.replace(')','');
title = deleter(title, ignore);
title = title.substring(1);
if (values[row-1][4] == "Montage" || values[row-1][4] == '') { SpreadsheetApp.getActiveSheet().getRange('I' + row.toString()).setValue('');} else {
var link = '=HYPERLINK("https://vimeo.com/manage/videos/search/'+encodeURI(title)+'"; "vimeo link")';
//time = Utilities.formatDate(time, "GMT+02:00", "dd/MM/yyyy, HH:mm:ss");
SpreadsheetApp.getActiveSheet().getRange('I' + row.toString()).setFormula(link);
SpreadsheetApp.getActiveSheet().getRange('I3').setValue('Vimeo link:');
SpreadsheetApp.getActiveSheet().getRange('I2').setValue('');
SpreadsheetApp.getActiveSheet().getRange('I1').setValue('');
};
};
};
function deleter(string, find) {
var replaceString = string;
for (var i = 0; i < find.length; i++) {
replaceString = replaceString.replace(find[i], ' ');
}
return replaceString;
}; |
function initialState() {
return {
entry: {
id: null,
first_name: '',
middle_name: '',
last_name: '',
created_at: '',
code_ds_gender: null,
dob: '',
married: null,
height: '',
minimum_income: '',
date_time: '',
email: null,
password: null,
size: '',
time: '',
multiple_file: [],
single_file: [],
multiple_photo: [],
single_photo: [],
belongs_to_id: null,
belongs_to_many: [],
text_area: '',
checkbox: false,
updated_at: '',
deleted_at: '',
owner_id: null
},
lists: {
code_ds_gender: [],
married: [],
belongs_to: [],
belongs_to_many: [],
owner: []
},
loading: false
}
}
const route = 'admissions'
const getters = {
entry: state => state.entry,
lists: state => state.lists,
loading: state => state.loading
}
const actions = {
storeData({ commit, state, dispatch }) {
commit('setLoading', true)
dispatch('Alert/resetState', null, { root: true })
return new Promise((resolve, reject) => {
let params = objectToFormData(state.entry, {
indices: true,
booleansAsIntegers: true
})
axios
.post(route, params)
.then(response => {
resolve(response)
})
.catch(error => {
let message = error.response.data.message || error.message
let errors = error.response.data.errors
dispatch(
'Alert/setAlert',
{ message: message, errors: errors, color: 'danger' },
{ root: true }
)
reject(error)
})
.finally(() => {
commit('setLoading', false)
})
})
},
updateData({ commit, state, dispatch }) {
commit('setLoading', true)
dispatch('Alert/resetState', null, { root: true })
return new Promise((resolve, reject) => {
let params = objectToFormData(state.entry, {
indices: true,
booleansAsIntegers: true
})
params.set('_method', 'PUT')
axios
.post(`${route}/${state.entry.id}`, params)
.then(response => {
resolve(response)
})
.catch(error => {
let message = error.response.data.message || error.message
let errors = error.response.data.errors
dispatch(
'Alert/setAlert',
{ message: message, errors: errors, color: 'danger' },
{ root: true }
)
reject(error)
})
.finally(() => {
commit('setLoading', false)
})
})
},
setFirstName({ commit }, value) {
commit('setFirstName', value)
},
setMiddleName({ commit }, value) {
commit('setMiddleName', value)
},
setLastName({ commit }, value) {
commit('setLastName', value)
},
setCreatedAt({ commit }, value) {
commit('setCreatedAt', value)
},
setCodeDsGender({ commit }, value) {
commit('setCodeDsGender', value)
},
setDob({ commit }, value) {
commit('setDob', value)
},
setMarried({ commit }, value) {
commit('setMarried', value)
},
setHeight({ commit }, value) {
commit('setHeight', value)
},
setMinimumIncome({ commit }, value) {
commit('setMinimumIncome', value)
},
setDateTime({ commit }, value) {
commit('setDateTime', value)
},
setEmail({ commit }, value) {
commit('setEmail', value)
},
setPassword({ commit }, value) {
commit('setPassword', value)
},
setSize({ commit }, value) {
commit('setSize', value)
},
setTime({ commit }, value) {
commit('setTime', value)
},
insertMultipleFileFile({ commit }, file) {
commit('insertMultipleFileFile', file)
},
removeMultipleFileFile({ commit }, file) {
commit('removeMultipleFileFile', file)
},
insertSingleFileFile({ commit }, file) {
commit('insertSingleFileFile', file)
},
removeSingleFileFile({ commit }, file) {
commit('removeSingleFileFile', file)
},
insertMultiplePhotoFile({ commit }, file) {
commit('insertMultiplePhotoFile', file)
},
removeMultiplePhotoFile({ commit }, file) {
commit('removeMultiplePhotoFile', file)
},
insertSinglePhotoFile({ commit }, file) {
commit('insertSinglePhotoFile', file)
},
removeSinglePhotoFile({ commit }, file) {
commit('removeSinglePhotoFile', file)
},
setBelongsTo({ commit }, value) {
commit('setBelongsTo', value)
},
setBelongsToMany({ commit }, value) {
commit('setBelongsToMany', value)
},
setTextArea({ commit }, value) {
commit('setTextArea', value)
},
setCheckbox({ commit }, value) {
commit('setCheckbox', value)
},
setUpdatedAt({ commit }, value) {
commit('setUpdatedAt', value)
},
setDeletedAt({ commit }, value) {
commit('setDeletedAt', value)
},
setOwner({ commit }, value) {
commit('setOwner', value)
},
fetchCreateData({ commit }) {
axios.get(`${route}/create`).then(response => {
commit('setLists', response.data.meta)
})
},
fetchEditData({ commit, dispatch }, id) {
axios.get(`${route}/${id}/edit`).then(response => {
commit('setEntry', response.data.data)
commit('setLists', response.data.meta)
})
},
fetchShowData({ commit, dispatch }, id) {
axios.get(`${route}/${id}`).then(response => {
commit('setEntry', response.data.data)
})
},
resetState({ commit }) {
commit('resetState')
}
}
const mutations = {
setEntry(state, entry) {
state.entry = entry
},
setFirstName(state, value) {
state.entry.first_name = value
},
setMiddleName(state, value) {
state.entry.middle_name = value
},
setLastName(state, value) {
state.entry.last_name = value
},
setCreatedAt(state, value) {
state.entry.created_at = value
},
setCodeDsGender(state, value) {
state.entry.code_ds_gender = value
},
setDob(state, value) {
state.entry.dob = value
},
setMarried(state, value) {
state.entry.married = value
},
setHeight(state, value) {
state.entry.height = value
},
setMinimumIncome(state, value) {
state.entry.minimum_income = value
},
setDateTime(state, value) {
state.entry.date_time = value
},
setEmail(state, value) {
state.entry.email = value
},
setPassword(state, value) {
state.entry.password = value
},
setSize(state, value) {
state.entry.size = value
},
setTime(state, value) {
state.entry.time = value
},
insertMultipleFileFile(state, file) {
state.entry.multiple_file.push(file)
},
removeMultipleFileFile(state, file) {
state.entry.multiple_file = state.entry.multiple_file.filter(item => {
return item.id !== file.id
})
},
insertSingleFileFile(state, file) {
state.entry.single_file.push(file)
},
removeSingleFileFile(state, file) {
state.entry.single_file = state.entry.single_file.filter(item => {
return item.id !== file.id
})
},
insertMultiplePhotoFile(state, file) {
state.entry.multiple_photo.push(file)
},
removeMultiplePhotoFile(state, file) {
state.entry.multiple_photo = state.entry.multiple_photo.filter(item => {
return item.id !== file.id
})
},
insertSinglePhotoFile(state, file) {
state.entry.single_photo.push(file)
},
removeSinglePhotoFile(state, file) {
state.entry.single_photo = state.entry.single_photo.filter(item => {
return item.id !== file.id
})
},
setBelongsTo(state, value) {
state.entry.belongs_to_id = value
},
setBelongsToMany(state, value) {
state.entry.belongs_to_many = value
},
setTextArea(state, value) {
state.entry.text_area = value
},
setCheckbox(state, value) {
state.entry.checkbox = value
},
setUpdatedAt(state, value) {
state.entry.updated_at = value
},
setDeletedAt(state, value) {
state.entry.deleted_at = value
},
setOwner(state, value) {
state.entry.owner_id = value
},
setLists(state, lists) {
state.lists = lists
},
setLoading(state, loading) {
state.loading = loading
},
resetState(state) {
state = Object.assign(state, initialState())
}
}
export default {
namespaced: true,
state: initialState,
getters,
actions,
mutations
}
|
import {
rhythm,
scale,
colors,
fonts
} from '../../../lib/traits'
export default {
root: {
fontFamily: fonts.display,
padding: rhythm(0),
backgroundColor: colors.maroon,
'@media screen and (min-width:80em)': {
padding: rhythm(1)
}
},
title: {
lineHeight: 1.25,
fontSize: scale(3),
color: colors.light,
textAlign: 'center',
padding: `${rhythm(1)} 0`,
'@media screen and (min-width:80em)': {
fontSize: scale(4.5)
}
},
leaderboards: {
maxWidth: '72rem',
margin: '0 auto',
padding: rhythm(1),
'@media (min-width: 50em)': {
display: 'flex',
justifyContent: 'center'
}
},
leaderboard: {
paddingTop: '2em',
width: '100%',
'@media (min-width: 50em)': {
width: '33.3%',
padding: rhythm(1),
':first-child': {
paddingLeft: 0
},
':last-child': {
paddingRight: 0
}
}
},
wrapper: {
backgroundColor: colors.light,
'ol': {
listStyle: 'none',
padding: rhythm(0.5)
}
}
}
|
"use strict";
/*
sudo apt-get update
sudo apt-get install software-properties-common
sudo apt-add-repository ppa:bitcoin/bitcoin
sudo apt-get update
sudo apt-get install bitcoind
bitcoind -datadir=/var/wif/bitcoin/datadir -rpcport=14545 -rpcuser=test -rpcpassword=test -conf=/var/wif/bitcoin/bitcoin.conf -deprecatedrpc=accounts -daemon
sudo apt update
sudo apt install redis-server
npm install fs -S
npm install bitcore-lib -S
npm install bitcoinjs-lib -S
npm install path -S
npm install colors -S
npm install request -S
npm install ws -S
npm install ioredis -S
*/
var fs = require('fs'),
bitcore = require('bitcore-lib');
var Bitcoin = require('bitcoinjs-lib');
const path = require('path');
var colors = require('colors');
var request = require('request');
var Redis = require('ioredis');
var redis = new Redis(6379,'127.0.0.1');
/*********************** REDIS *******************************/
/*
sudo apt update
sudo apt install redis-server
sudo nano /etc/redis/redis.conf
#change work patch
sudo systemctl restart redis.service
#if error need set patch
redis-cli
CONFIG SET dir /var/wif/redis
CONFIG SET dbfilename dump.rdb
#if error for save db
nano /etc/systemd/system/redis.service
#add in file
ReadWriteDirectories=-/var/wif/redis
sudo systemctl daemon-reload
sudo systemctl status redis.service
sudo systemctl restart redis-server.service
#Crear
#FLUSHDB - Removes data from your connection's CURRENT database.
#FLUSHALL - Removes data from ALL databases.
redis-cli
flushall
*/
try {
redis.ping()
.then(function(e) {
console.log('Connected REDIS!');
})
.catch(function(e) {
console.log('Error REDIS:'.red, e);
});
/*
redis.set('test1', 'Tesla Model S', function (err, result) {
console.log('Set Record: ', result);
});
redis.get('test1', function (err, result) {
console.log('Get Record:', result);
});
redis.del('test1', function (err, result) {
console.log('Delete Record:', result);
});
redis.get('test1', function (err, result) {
console.log('Get Deleted Record:', result);
});
redis.quit();
*/
}
catch (e) {
console.log('Error REDIS:', e);
}
/***************************** BLOCK READER *******************************/
function readVarInt(stream) {
var size = stream.read(1);
var sizeInt = size.readUInt8();
if (sizeInt < 253) {
return size;
}
var add;
if (sizeInt == 253) add = 2;
if (sizeInt == 254) add = 4;
if (sizeInt == 255) add = 8;
if (add) {
return Buffer.concat([size, stream.read(add)], 1 + add);
}
return -1;
}
function toInt(varInt) {
if (!varInt) {
return -1;
}
if (varInt[0] < 253) return varInt.readUInt8();
switch(varInt[0]) {
case 253: return varInt.readUIntLE(1, 2);
case 254: return varInt.readUIntLE(1, 4);
case 255: return varInt.readUIntLE(1, 8);
}
}
function getRawTx(reader) {
var txParts = [];
txParts.push(reader.read(4)); //Version
//Inputs
var inputCount = readVarInt(reader);
txParts.push(inputCount);
for(var i = toInt(inputCount) - 1; i >= 0; i--) {
txParts.push(reader.read(32)); //Previous tx
txParts.push(reader.read(4)); //Index
var scriptLength = readVarInt(reader);
txParts.push(scriptLength);
txParts.push(reader.read(toInt(scriptLength))); //Script Sig
txParts.push(reader.read(4)); //Sequence Number
}
//Outputs
var outputCount = readVarInt(reader);
txParts.push(outputCount);
for(i = toInt(outputCount) - 1; i >= 0; i--) {
txParts.push(reader.read(8)); //Value
var scriptLen = readVarInt(reader);
txParts.push(scriptLen);
txParts.push(reader.read(toInt(scriptLen))); //ScriptPubKey
}
txParts.push(reader.read(4)); //Lock time
return Buffer.concat(txParts);
}
function bufferReader(buffer) {
var index = 0;
return {
read: function read(bytes) {
if (index + bytes > buffer.length) {
return null;
}
var result = buffer.slice(index, index + bytes);
index += bytes;
return result;
}
}
}
function readHeader(reader) {
var version = reader.read(4);
if (version == null) {
return null;
}
if (version.toString('hex') == 'f9beb4d9') {
//It's actually the magic number of a different block (previous one was empty)
reader.read(4); //block size
return readHeader(reader);
}
return reader.read(76); //previous hash + merkle hash + time + bits + nonce
}
var fromBytesInt32=function(b) {
if(b == null) return null;
var result=0;
for (let i=3;i>=0;i--) {
result = (result << 8) | b[i];
}
return result;
};
var total = 0;
var totalStore = 0;
var okStore = 0;
var noStore = 0;
var txCount_ = 0;
var all = 0;
var time = Math.round(+new Date());
async function start_read_blocks(){
for(var b = min_block; b < max_block; b++) {
/*
blk00201.dat Nov 30, 2014 4:09:54 PM
*/
//var fileNumber = '01'+('000' + b).slice(-3),
var fileNumber = ('0000' + b).slice(-5),
data = fs.readFileSync( '/var/bitcoin/blocks/blk' + fileNumber + '.dat'),
reader = bufferReader(data),
magic = reader.read(4),
blockSize = reader.read(4),
blockHeader = readHeader(reader);
var block_Size = fromBytesInt32(blockSize);
//blk01508.dat
console.log('blockSize:'.yellow, block_Size, 'File:', 'blk'+fileNumber+'.dat');
while( blockHeader !== null ) {
var txCount = toInt(readVarInt(reader));
for(var j = 0; j < txCount; j++) {
var rawTx = getRawTx(reader);
var parsedTx = new bitcore.Transaction( rawTx );
var trx = parsedTx.toObject();
//var d = await store_address( trx.hash, 'hash', 0 );
//if( d ){ okStore++; totalStore++; }else{ noStore++; totalStore++; }
let tx = Bitcoin.Transaction.fromHex( rawTx );
for (var inp = 0; inp < tx.ins.length; inp++) {
let address;
try {
address = Bitcoin.address.fromOutputScript(tx.ins[inp].script);
} catch (e) {}
if ( address ){
//console.log('input address'.green, address, tx.ins[inp].value);
var d = await store_address( address, 'address', tx.ins[inp].value );
if( d ){ okStore++; totalStore++; }else{ noStore++; totalStore++; }
all++;
}
}
for (var out = 0; out < tx.outs.length; out++) {
let address;
try {
address = Bitcoin.address.fromOutputScript(tx.outs[out].script);
} catch (e) {}
if ( address ){
//console.log('input address'.green, address, tx.outs[out].value);
var d = await store_address( address, 'address', tx.outs[out].value );
if( d ){ okStore++; totalStore++; }else{ noStore++; totalStore++; }
all++;
}
}
// if( j > 30){ return; }
}
magic = reader.read(4);
blockSize = reader.read(4);
blockHeader = readHeader(reader);
var t = Math.round(+new Date());
if( ( t - time) > 5000 ){
console.log( 'blk'+fileNumber+'.dat', 'Block:'.yellow, txCount_ + ' trx, Done:',total.toString().green, 'Tolal:', totalStore.toString().yellow, 'OK:', okStore.toString().green, 'NO:', noStore.toString().red, 'P/S:'.bold.blue, all );
time = t;
txCount_ = 0;
okStore = 0;
noStore = 0;
all = 0;
}else{
txCount_ = txCount_ + txCount;
}
total = total + txCount;
}
}
return true;
}
/***********************************************************************/
// Bitcoin 700 blocks
var min_block = 5;
var max_block = 1400;
var min_satosh = 20000000;//0.20000000 BTC
var keysGoodFile = './goodKeys.json';
var arrGoodKeys = [];
fs.readFile( path.resolve(__dirname, keysGoodFile ), 'utf-8', function(err, buf) {
var arr = buf.toString();
arrGoodKeys = JSON.parse( arr );
console.log('loadGoodKeys'.green, arrGoodKeys.length);
start_read_blocks();
});
function storeGoodKeys( ){
fs.writeFileSync( path.resolve(__dirname, keysGoodFile ), JSON.stringify( arrGoodKeys, null, 4));
console.log('storeGoodKeys'.green);
}
var sets = '';
function rng () {
return Bitcoin.crypto.sha256(Buffer.from( sets ));
}
function store_address( source, type, amount ){
return new Promise(resolve => {
if( parseInt( amount ) < parseInt( min_satosh ) && type != 'hash' && type != 'mrklRoot' ){
return resolve( false );
}
if( typeof source == 'string' ){
if( typeof amount != 'string' && typeof amount != 'number' ){ amount = 0; }
//make privateKey and get address
sets = source;
const keyPair = Bitcoin.ECPair.makeRandom( /*{ rng : rng }*/ );
const { address } = Bitcoin.payments.p2pkh({ pubkey: keyPair.publicKey });
//console.log("address ", address);
var WIFkey = keyPair.toWIF();
//console.log("private key WIF ", WIFkey);
var res = 'WIFkey: '+WIFkey+' '+type.toUpperCase()+': '+source;
sets = '';
//try found WIF address on exist
//var find = arrKeys.filter(x => x.source === address);
var arrWIF = { address:address, WIFkey:WIFkey, amount:amount, source:source, type:type };
redis.get( address , function (err, result) {
if( result != null ){
console.log( 'Find WIF to ', arrWIF );
tg_notify( 'Find WIF to '+address );
arrGoodKeys.push( arrWIF );
storeGoodKeys( );
}
redis.set( source , amount, function (err, result) {
return resolve( true );
});
});
/*
redis.get( source , function (err, result) {
if( result == null ){
request.get( 'https://blockchain.info/q/addressbalance/'+source, { },
function (error, res, body) {
if (!error && res.statusCode == 200){
if( res.body > 100000 ){
redis.set( source , res.body , function (err, result) {
console.log( 'address:', source.toString().yellow, 'BTC'.bold.blue, res.body );
return resolve( true );
});
}else{
return resolve( false );
}
*/
/*
try{
var headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
'Content-Type' : 'application/x-www-form-urlencoded'
};
request.post( {headers: headers, url: 'https://api.omniwallet.org/v1/address/addr/', form: { addr:address }, method: 'POST'},
function (error, res, body) {
if (!error && res.statusCode == 200){
try{
var balance = JSON.parse( res.body );
balance = balance.balance;
for( var i = 0; i < balance.length; i++) {
if( balance[i].value > 100000 ){
redis.set( address , balance[i].value, function (err, result) {
console.log( 'address:', address.toString().yellow, 'OMNI_'+balance[i].symbol.toString().toUpperCase().bold.blue, balance[i].value );
});
}
}
return resolve( true );
}catch(e){
return resolve( false );
}
}else{
return resolve( false );
}
});
}catch(e){
return resolve( false );
}
*/
/*}else{*/
/*
try{
var headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
'Content-Type' : 'application/x-www-form-urlencoded'
};
request.post( {headers: headers, url: 'https://api.omniwallet.org/v1/address/addr/', form: { addr:address }, method: 'POST'},
function (error, res, body) {
if (!error && res.statusCode == 200){
try{
var balance = JSON.parse( res.body );
balance = balance.balance;
for( var i = 0; i < balance.length; i++) {
if( balance[i].value > 100000 ){
redis.set( address , balance[i].value, function (err, result) {
console.log( 'address:', address.toString().yellow, 'OMNI_'+balance[i].symbol.toString().toUpperCase().bold.blue, balance[i].value );
});
}
}
return resolve( true );
}catch(e){
return resolve( false );
}
}else{
return resolve( false );
}
});
}catch(e){
return resolve( false );
}
*/
/* return resolve( false );
}
});
}else{
return resolve( true );
}
});*/
}else{
return resolve( false );
}
});
}
/*********************** CHECK ONLINE BALANCE ****************/
function check_omni( address ){
return new Promise(resolve => {
try{
var headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36',
'Content-Type' : 'application/x-www-form-urlencoded'
};
request.post( {headers: headers, url: 'https://api.omniwallet.org/v1/address/addr/', form: { addr:address }, method: 'POST'},
function (error, res, body) {
if (!error && res.statusCode == 200){
try{
var balance = JSON.parse( res.body );
balance = balance.balance;
for( var i = 0; i < balance.length; i++) {
if( balance[i].value > 100000 ){
redis.set( address , balance[i].value, function (err, result) {
console.log( 'address:', address.toString().yellow, balance[i].symbol.toString().toUpperCase().bold.blue, balance[i].value );
});
}
}
return resolve( true );
}catch(e){
return resolve( false );
}
}else{
return resolve( false );
}
});
}catch(e){
return resolve( false );
}
});
}
function checkKeys( address, privKey, type, source, name ){
return new Promise(resolve => {
try{
/*
getreceivedbyaddress addressbalance
*/
request.get(
'https://blockchain.info/q/'+type+'/'+address,
{
/*
json: {
"json": true
}
*/
},
function (error, res, body) {
if (!error && res.statusCode == 200){
console.log('checkKeys'.yellow, address, type, res.body.toString().bgGreen.white.bold);
if( res.body > 0 ){
if( type == 'addressbalance' ){
console.log('checkKeys'.green, address+' / '+privKey+' : '+res.body.toString().bgGreen.white.bold );
arrKeys.push( { address:address, privKey:privKey, microBtc:res.body, source:source, name:name } );
storeKeys( );
}
return resolve( true );
}else{
return resolve( false );
}
}else{
console.log('checkKeys'.red);
return resolve( false );
}
});
}catch(e){ return resolve( false ); }
});
}
/*********************** NOTIFY ******************************/
function tg_notify( message, repeat ){
try{
var chatId = '@WIFrobots'; var token = '703397220:AAG-C-XyeCfS_GqENzrEmZlaKdD6cKsdvfI';
/*
WIFrobot
@ForecastCOFFE_bot
703397220:AAG-C-XyeCfS_GqENzrEmZlaKdD6cKsdvfI
*/
var mess = message.toString();
var headers = {
'Content-Type': 'application/json'
};
var url = 'https://api.telegram.org/bot'+token+'/sendMessage';
request.post(
{
headers: headers,
//proxy: 'http://95.164.74.27:32231',
url: url,
method: 'POST',
formData : {
chat_id: chatId,
text: mess
}
} ,
function (err, response) {
if (err) {
console.log( 'tg_notify', 'BAD'.red, err );
if( typeof repeat !== 'boolean' ){
tg_notify( message, true );
}else if( typeof repeat === 'boolean' && repeat === true ){
console.log( 'tg_notify', 'BAD'.red, repeat );
return;
}
}
try{
if( response.body ){
console.log( 'tg_notify', 'OK'.green, repeat );
}else{
if( typeof repeat !== 'boolean' ){
tg_notify( message, true );
}else if( typeof repeat === 'boolean' && repeat === true ){
console.log( 'tg_notify', 'BAD'.red, repeat );
return;
}
}
}catch(e){
if( typeof repeat !== 'boolean' ){
tg_notify( message, true );
}else if( typeof repeat === 'boolean' && repeat === true ){
console.log( 'tg_notify', 'BAD'.red, repeat );
return;
}
}
});
}catch(e){
console.log('tg_notify EXCEPTION'.red, e);
if( typeof repeat !== 'boolean' ){
tg_notify( message, true );
}else if( typeof repeat === 'boolean' && repeat === true ){
console.log( 'tg_notify', 'BAD'.red, repeat );
return;
}
}
} |
const supertest = require('supertest')
let app = supertest.agent(process.env.URLTEST || 'http://testing2.azarus.es/api/1.0')
require('./authorization.test')(app)
require('./companies.test')(app)
require('./linkAccounts.test')(app)
|
/**
* floating modal wrapped as a plugin
*/
'use strict';
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals
factory(jQuery);
}
}(function ($) {
var defaults = {
floating_icon_src: "/img/Setting-icon.png",
floating_top: "140px",
floating_modal_notshow: true,
float_position: "left",
float_range:20,
float_modal_url:"",
init_callback: null
};
$.fn.floating_modal = function (suppliedSettings, options) {
return this.each(function () {
var settings = $.extend(true, {}, defaults);
var $this = $(this);
if (typeof suppliedSettings === "object") {
$.extend(true, settings, suppliedSettings);
} else {
options = suppliedSettings;
}
/* attach modals to icons */
var loadfloating_modal =function (e) {
if (settings.float_position == "left"){
$(".floating_icon").find("img").after('<div style="vertical-align: top; float: left;"><div class="floating_modal" > </div></div>');
} else if (settings.float_position == "right"){
$(".floating_icon").find("img").after('<div style="vertical-align: top; float: right;"><div class="floating_modal" > </div></div>');
}
$.ajax({
url: e,
type: "GET"
}).done(function (data) {
$(".floating_modal").html(data);
if (settings.float_position == "left"){
$(".floating_icon").css({
left: - $(".floating_modal").width()
});
} else if (settings.float_position == "right"){
$(".floating_icon").css({
right: - $(".floating_modal").width()
});
}
});
}
/* active modals */
var call_floating_modal = function () {
if (settings.float_position == "left"){
if (settings.floating_modal_notshow){
$(".floating_icon").animate({
left: settings.float_range
}, 500, function() {
// Animation complete
});
settings.floating_modal_notshow = false;
} else {
$(".floating_icon").animate({
left: - $(".floating_modal").width()
}, 500, function() {
// Animation complete
});
settings.floating_modal_notshow = true;
}
} else if (settings.float_position == "right"){
if (settings.floating_modal_notshow){
$(".floating_icon").animate({
right: settings.float_range
}, 500, function() {
// Animation complete
});
settings.floating_modal_notshow = false;
} else {
$(".floating_icon").animate({
right: - $(".floating_modal").width()
}, 500, function() {
// Animation complete
});
settings.floating_modal_notshow = true;
}
}
}
/**
* plugin initialised
*/
var init = function () {
$this.append('<div class="floating_icon" style="cursor: pointer; position: absolute;z-index: 999;"><img style="background-color: transparent"></div>');
$("body").css("overflow-x","hidden");
$(".floating_icon").css({
top:settings.floating_top
});
$(".floating_icon").find("img").bind("click",function(){
call_floating_modal();
});
$(".floating_icon").find("img").attr({
src: settings.floating_icon_src
});
$(document).scroll(function() {
var currentpx = parseInt(settings.floating_top);
var scrolledpx = parseInt($(document).scrollTop());
var sum = currentpx+scrolledpx;
$( ".floating_icon" ).animate({
top: sum
}, 20, function() {
// Animation complete.
});
})
/* Call back function conditions */
if ($.isFunction(settings.init_callback) && !settings.float_modal_url) {
if (settings.float_position == "left"){
$(".floating_icon").css({
left: 45
});
} else if (settings.float_position == "right"){
$(".floating_icon").css({
right: 45
});
}
setTimeout(settings.init_callback, 0);
}else if ($.isFunction(settings.init_callback) && settings.float_modal_url){
setTimeout(settings.init_callback, 0);
loadfloating_modal(settings.float_modal_url);
}else if (settings.float_modal_url){
loadfloating_modal(settings.float_modal_url);
}
};
/* initialize */
init();
return $this;
})
};
})); |
import {dateFormat, getZoneDate} from './dateUtils.js'
export {dateFormat, getZoneDate}
export default function (name) {
console.log(name)
}
|
'use strict';
angular.module('events').controller('EventEditController', [
'$scope',
'EventsService',
'$stateParams',
function($scope, EventsService, $stateParams) {
EventsService.get({eventId: $stateParams.eventId}, function(data) {
$scope.event = data;
$scope.editForm = $scope.event;
}, function(error) {
$scope.alert = {
description: error,
type: 'error'
};
});
$scope.alert = false;
$scope.disabled = false;
$scope.submitEditForm = function () {
$scope.disabled = true;
EventsService.save({eventId: $stateParams.eventId}, $scope.editForm, function(data) {
$scope.alert = {
description: 'Edited event: ' + $scope.editForm.title,
type: 'success'
};
$scope.disabled = false;
}, function(error) {
$scope.alert = {
description: 'Something went wrong: ' + error,
type: 'error'
};
$scope.disabled = false;
});
};
}
]);
|
var sortArray = [];
var root = document.getElementById("root");
document.getElementById("bfs").addEventListener("click", function() {
sortArray = [];
bfs(root);
console.log(sortArray);
});
document.getElementById("btn1").addEventListener("click", function() {
if (flag === true) {
alert("正在执行");
return;
}
flag = true;
sortArray = [];
preSort(root);
render();
});
document.getElementById("btn2").addEventListener("click", function() {
sortArray = [];
midSort(root);
render();
});
document.getElementById("btn3").addEventListener("click", function() {
console.log(1);
if (flag === true) {
alert("正在执行");
return;
}
flag = true;
sortArray = [];
latSort(root);
console.log(sortArray);
render();
});
//该函数能不能解决问题,取决于左节点调用和有节点调用能否解决问题。
//代码有错不会改
//脑子不够用,不想写深度优先的代码
function preSort(root) {
sortArray.push(root);
if(root.firstElementChild != null) {
preSort(root.firstElementChild);
}
if(root.lastElementChild != null) {
preSort(root.lastElementChild);
}
}
function midSort(root) {
if(root.firstElementChild != null) {
midSort(root.firstElementChild);
}
sortArray.push(root);
if(root.lastElementChild != null) {
midSort(root.lastElementChild);
}
}
function latSort(root) {
if(root.firstElementChild != null) {
latSort(root.firstElementChild);
}
if(root.lastElementChild != null) {
latSort(root.lastElementChild);
}
sortArray.push(root);
}
var i = 0;
var flag = false;
var render = function() {
if (i == sortArray.length) {
sortArray[i-1].style.backgroundColor = "white";
i = 0;
flag = false;
return;
}
if(sortArray[i-1]) {
sortArray[i-1].style.backgroundColor = "white";
}
sortArray[i].style.backgroundColor = "blue";
setTimeout(render,500);
i++;
} |
const config = (getState, url, method, value=null) => {
const token = getState().auth.token
const configuration = {
url : url,
method : method,
headers : {
"Content-Type":"application/json"
},
data : value ? JSON.stringify(value) : null
}
if(token){
configuration.headers['Authorization'] = `Bearer ${token}`
}
return configuration
}
export default config |
var app = getApp();
Page({
data: {
agree: true,
payFail: false,
//支付失败
statusBarHeight: app.globalData.statusBarHeight,
barHeight: app.globalData.barHeight,
sendCodeText: "发送验证码",
showyanzheng: true,
time: 60,
mobile: "",
popup: {
bgOpacity: 0,
wrapAnimate: "",
popupAnimate: "",
flag: ""
}
},
onLoad: function onLoad() {},
// 发送验证码
sendCode: function sendCode(e) {
var that = this;
var mobile = that.data.mobile;
if (mobile.length == 0) {
wx.showToast({
title: "请输入手机号",
image: "none",
duration: 2e3
});
} else {
if (/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(mobile)) {
that.setData({
showyanzheng: !that.data.showyanzheng
});
var times = setInterval(function() {
that.setData({
time: that.data.time - 1
});
if (that.data.time == 0) {
that.setData({
sendCodeText: "重新发送验证码",
showyanzheng: !that.data.showyanzheng,
time: 60
});
clearInterval(times);
}
}, 1e3);
} else {
wx.showToast({
title: "请输入正确手机号",
image: "none",
duration: 2e3
});
}
}
},
// 输入手机号
getMobile: function getMobile(e) {
this.setData({
mobile: e.detail.value
});
},
showPopup: function showPopup() {
var that = this;
that.setData({
"popup.bgOpacity": 0,
"popup.wrapAnimate": "wrapAnimate",
"popup.popupAnimate": "popupAnimate",
"popup.flag": true
});
},
hidePopup: function hidePopup() {
var that = this;
that.setData({
"popup.bgOpacity": .4,
"popup.wrapAnimate": "wrapAnimateOut",
"popup.popupAnimate": "popupAnimateOut"
});
setTimeout(function() {
that.setData({
"popup.flag": false
});
}, 200);
},
// 退出
goBack: function goBack() {
this.showPopup();
},
// 退出选择
goBackChoose: function goBackChoose(e) {
var that = this;
var choosetype = e.currentTarget.dataset.choosetype;
switch (parseInt(choosetype)) {
//1 要意见反馈
case 1:
that.hidePopup();
wx.navigateBack({
delta: 1
});
break;
case 2:
that.hidePopup();
wx.navigateBack({
delta: 1
});
break;
case 3:
that.hidePopup();
break;
}
},
goPayDetail: function goPayDetail() {
this.setData({
payFail: true
});
},
// 继续支付
continuePay: function continuePay() {
this.setData({
payFail: false
});
},
// 关闭支付
closePay: function closePay() {
this.showPopup();
},
chooseAgree: function chooseAgree() {
this.setData({
agree: !this.data.agree
});
}
}); |
const mongodb = require("mongodb");
const db = await mongodb.connect('url', {
useNewUrlParser: true,
useUnifiedTopology: true
}).db('report'); //db initialize (MongoDB 연결)
module.exports = (url, fileName) => {
db.insertOne({
url: url,
time: Date.now(),
fileName: fileName
}); //DB에 데이터를 넣음
//TODO: report to government
};
|
var searchData=
[
['keep_20track_20when_20processing_20files',['Keep track when processing files',['../neo_state.html',1,'index']]],
['kyoto_20cabinet',['Kyoto Cabinet',['../store_kc.html',1,'lib_store']]]
];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.