text stringlengths 7 3.69M |
|---|
import React from 'react';
import axios from 'axios';
import AdminPageCreate from '../../components/PageAdmin/Create/Create';
import NavbarAdmin from '../../components/Navbar/NavbarMenu';
const CreatePage = ()=>{
return(
<div>
<NavbarAdmin/>
<AdminPageCreate/>
</div>
);
}
export default CreatePage; |
export default{
SET_Flags(state,payload){
state.flags = payload
},
SET_Flags_Details(state,payload){
state.details = payload
}
} |
var menu = require('./app/menu.js');
var likes = require('./app/likes.js');
menu.render();
likes.render(); |
import React from "react";
import styled from "styled-components";
import Switch from "./Switch";
import EditIcon from "./Svg/EditIcon";
import InfoIcon from "./Svg/InfoIcon";
const ControlsContainer = styled.section`
display: flex;
`;
const DeleteX = styled.span`
align-self: flex-start;
font-family: Arial;
margin-left: 6px;
margin-right: 8px;
line-height: 0.95;
font-size: 25px;
font-weight: 900;
cursor: pointer;
color: ${props =>
props.isTaskDone
? "var(--main-bg-color); opacity:0.7"
: "var(--accent-color); opacity:1"};
`;
const TaskControls = props => {
const { isTaskDone, removeTask, keyName, doneTask, makeTaskEditable } = props;
return (
<ControlsContainer>
<Switch
type="checkbox"
isTaskDone={isTaskDone}
doneTask={doneTask}
keyName={keyName}
/>
<button
disabled={isTaskDone && true}
onClick={makeTaskEditable}
style={{
height: "20px",
border: "none",
background: "none",
cursor: "pointer"
}}
>
<EditIcon isTaskDone={isTaskDone} />
</button>
<DeleteX
isTaskDone={isTaskDone}
onClick={e => {
if (window.confirm("Are u sure?")) {
e.currentTarget.parentElement.parentElement.style.transform =
"scale(0)";
setTimeout(() => {
removeTask(keyName);
}, 500);
}
}}
>
×
</DeleteX>
<span cursor="pointer" style={{ height: "20px", cursor: "pointer" }}>
<InfoIcon isTaskDone={isTaskDone} />
</span>
</ControlsContainer>
);
};
export default TaskControls;
|
(function() {
/* constants */
var constants = {
likeOperationId: 'Services.Like',
cancelLikeOperationId: 'Services.CancelLike',
miniMessageVerb: 'minimessage',
filter: {
all: "all",
discussions: "discussions",
events: "events"
},
noActivityTypeIcon: "icons/activity_empty.png"
};
/* end constants */
/* templates */
var templates = {};
templates.tabLine =
'<div class="tabLine">' +
'<div class="tabLineLinks">' +
'<a href="#" class="selected" data-filter="{{allFilter}}">{{allMessage}}</a>' +
'<a href="#" data-filter="{{discussionsFilter}}">{{discussionsMessage}}</a>' +
'<a href="#" data-filter="{{eventsFilter}}">{{eventsMessage}}</a>' +
'</div>' +
'<div class="tabLineButtons">' +
'<a href="#" title="{{postMessage}}" class="button jsPostMessage">{{postMessage}}</a>' +
'</div>' +
'</div>';
templates.activity =
'<div class="activityContainerItem jsMainActivity" data-activityid="{{id}}" data-likescount="{{likeStatus.likesCount}}" data-userlikestatus="{{likeStatus.userLikeStatus}}">' +
'<div class="container">' +
'<div class="activityTypeContainer">' +
'<span class="activityType"><img src="{{icon}}"></span>' +
'</div>' +
'<div class="activityContentContainer">' +
'<div class="message">' +
'<span class="avatar"><img src="{{actorAvatarURL}}" alt="{{displayActor}}" /></span>' +
'<div class="event">{{{activityMessage}}}</div>' +
'</div>' +
'<div class="actions jsActions">' +
'<span class="timestamp">{{publishedDate}}</span>' +
'</div>' +
'<div class="answers jsRepliesContainer">{{{repliesHtml}}}</div>' +
'</div>' +
'</div>' +
'</div>';
templates.miniMessage =
'<div class="activityContainerItem jsMainActivity" data-activityid="{{id}}" data-likescount="{{likeStatus.likesCount}}" ' +
'data-userlikestatus="{{likeStatus.userLikeStatus}}" data-allowdeletion="{{allowDeletion}}">' +
'<div class="container">'+
'<div class="activityTypeContainer">' +
'<span class="activityType"><img src="{{icon}}"></span>' +
'</div>' +
'<div class="activityContentContainer">' +
'<div class="messageHeader">' +
'<span class="avatar"><img src="{{actorAvatarURL}}" alt="{{displayActor}}" /></span>' +
'{{{displayActorLink}}}' +
'</div>' +
'<div class="message">{{{activityMessage}}}</div>' +
'<div class="actions jsActions">' +
'<span class="timestamp">{{{publishedDate}}}</span>' +
'</div>' +
'<div class="answers jsRepliesContainer">{{{repliesHtml}}}</div>' +
'</div>' +
'</div>' +
'</div>';
templates.reply =
'<div class="activityContainerItem {{replyClass}}" data-replyid="{{id}}" data-likescount="{{likeStatus.likesCount}}" ' +
'data-userlikestatus="{{likeStatus.userLikeStatus}}" data-allowdeletion="{{allowDeletion}}">' +
'<div class="container">' +
'<div class="message">' +
'<span class="avatar"><img src="{{actorAvatarURL}}" alt="{{displayActor}}" /></span>' +
'<div class="event">' +
'{{{displayActorLink}}}' +
'<div class="message">{{{message}}}</div>' +
'</div>' +
'</div>' +
'<div class="actions jsReplyActions">' +
'<span class="timestamp">{{{publishedDate}}}</span>' +
'</div>' +
'</div>' +
'</div>';
templates.newMiniMessage =
'<div class="displayN jsNewMiniMessage">' +
'<form name="newMiniMessageForm" class="newMiniMessageForm">' +
'<textarea placeholder="{{placeholderMessage}}" rows="3" name="newMiniMessageText" class="miniMessageText jsMiniMessageText"></textarea>' +
'<p class="newMiniMessageActions">' +
'<span class="miniMessageCounter jsMiniMessageCounter"></span>' +
'<input class="button writeMiniMessageButton disabled jsWriteMiniMessageButton" name="writeMiniMessageButton" type="button" value="{{writeLabel}}" disabled="disabled" />' +
'</p>' +
'</form>' +
'</div>';
templates.newActivityReply =
'<div class="displayN jsNewActivityReply messageBlock" data-activityid="{{activityId}}">' +
'<form>' +
'<textarea placeholder="{{placeholderMessage}}" rows="1" class="jsActivityReplyText"></textarea>' +
'<p class="newMiniMessageActions">' +
'<span class="miniMessageCounter jsActivityReplyCounter"></span>' +
'<input class="button disabled jsWriteActivityReplyButton" name="writeActivityReplyButton" type="button" value="{{writeLabel}}" />' +
'</p>' +
'</form>' +
'</div>';
templates.deleteActivityAction =
'<div class="actionItem jsDelete" data-activityid="{{activityId}}">' +
'<img src="{{deleteImageURL}}" />' +
'<a href="#">{{deleteMessage}}</a>' +
'</div>';
templates.deleteActivityReplyAction =
'<div class="actionItem jsDelete" data-replyid="{{replyId}}">' +
'<img src="{{deleteImageURL}}" />' +
'<a href="#">{{deleteMessage}}</a>' +
'</div>';
templates.replyAction =
'<div class="actionItem jsReply" data-activityid="{{activityId}}">' +
'<img src="{{replyImageURL}}" />' +
'<a href="#">{{replyMessage}}</a>' +
'</div>';
templates.likeAction =
'<div class="actionItem jsLike">' +
'<img class="likeIcon jsLikeIcon" src="{{likeImageURL}}" />' +
'<span class="likesCount">{{likesCount}}</span>' +
'</div>';
templates.moreActivitiesBar =
'<div class="moreActivitiesBar jsMoreActivitiesBar">{{moreActivitiesMessage}}</div>';
templates.noMoreActivitiesBar =
'<div class="moreActivitiesBar noMore">{{noMoreActivitiesMessage}}</div>';
templates.moreRepliesBar =
'<div class="moreActivitiesBar jsMoreRepliesBar">{{moreRepliesMessage}}</div>';
templates.newActivitiesBar =
'<div class="newActivitiesBar jsNewActivitiesBar">{{newActivitiesMessage}}</div>';
/* end templates */
var prefs = new gadgets.Prefs();
var activityStreamName = prefs.getString("activityStreamName");
var documentContextPath = gadgets.util.unescapeString(prefs.getString("nuxeoTargetContextPath"));
var wallOperationParams = {
language: prefs.getLang(),
timeZone: prefs.getString("timeZone"),
contextPath: documentContextPath,
activityStreamName: activityStreamName,
activityLinkBuilder: prefs.getString("activityLinkBuilder")
};
var miniMessageOperationParams = {
language: prefs.getLang(),
contextPath: documentContextPath
};
var currentActivities = [];
var waitingActivities = [];
var offset = 0;
var waitingOffset = 0;
var hasMoreActivities = true;
var filter = constants.filter.all;
function loadWallActivityStream() {
var NXRequestParams = {
operationId: 'Services.GetWallActivityStream',
operationParams: wallOperationParams,
operationContext: {},
operationCallback: function(response, params) {
currentActivities = response.data.activities;
offset = response.data.offset;
displayWallActivities();
}
};
doAutomationRequest(NXRequestParams);
}
function pollWallActivityStream() {
var NXRequestParams= { operationId : 'Services.GetWallActivityStream',
operationParams: wallOperationParams,
operationContext: {},
operationCallback: function(response, params) {
var newActivities = response.data.activities;
if (newActivities.length > 0 && currentActivities[0].id !== newActivities[0].id) {
// there is at least one new activity
waitingActivities = newActivities;
waitingOffset = response.data.offset;
addNewActivitiesBarHtml();
registerNewActivitiesBarHandler();
gadgets.window.adjustHeight();
}
}
};
doAutomationRequest(NXRequestParams);
}
function displayWallActivities() {
var htmlContent = '';
if (currentActivities.length == 0) {
htmlContent += '<div class="noStream">' + prefs.getMsg('label.no.activity') + '</div>';
} else {
for (var i = 0; i < currentActivities.length; i++) {
var currentActivity = currentActivities[i];
if (currentActivity.activityVerb == constants.miniMessageVerb && filter !== constants.filter.events) {
htmlContent += buildActivityHtml(templates.miniMessage, currentActivity);
} else if (currentActivity.activityVerb !== constants.miniMessageVerb && filter !== constants.filter.discussions) {
htmlContent += buildActivityHtml(templates.activity, currentActivity);
}
}
}
$('#container').html(htmlContent);
addLikeStatusHtml();
addReplyLinksHtml();
addDeleteLinksHtml();
registerLikeStatusHandler();
registerDeleteLinksHandler();
registerReplyLinksHandler();
registerNewActivityReplyHandler();
registerMoreRepliesHandler();
if (hasMoreActivities) {
addMoreActivitiesBarHtml();
registerMoreActivityBarHandler();
} else {
addNoMoreActivitiesTextHtml();
}
gadgets.window.adjustHeight();
}
/* HTML building functions */
function addNewMiniMessageHtml() {
var htmlContent = Mustache.render(templates.newMiniMessage,
{ placeholderMessage: prefs.getMsg('label.placeholder.new.message'),
writeLabel: prefs.getMsg('command.write') });
$(htmlContent).insertBefore('#container');
gadgets.window.adjustHeight();
}
function buildActivityHtml(template, activity) {
var repliesHtml = '';
if (activity.replies.length > 0) {
if (activity.replies.length > 3) {
var moreRepliesMessage = prefs.getMsg('label.view.all') + ' ' +
activity.replies.length + ' ' + prefs.getMsg('label.activity.replies');
repliesHtml += Mustache.render(templates.moreRepliesBar, {
moreRepliesMessage: moreRepliesMessage
});
}
for (var i = 0; i < activity.replies.length; i++) {
var reply = activity.replies[i];
reply.replyClass = i < activity.replies.length - 3 ? 'displayN' : '';
repliesHtml += Mustache.render(templates.reply, reply);
}
}
repliesHtml += Mustache.render(templates.newActivityReply, {
activityId: activity.id,
placeholderMessage: prefs.getMsg('label.placeholder.new.activity.reply'),
writeLabel: prefs.getMsg('command.reply') });
activity.repliesHtml = repliesHtml;
var icon = activity.icon;
if (icon != null && icon.length > 0) {
if (icon.indexOf(NXGadgetContext.clientSideBaseUrl) < 0) {
if (icon[0] == '/') {
icon = icon.substring(1);
}
icon = NXGadgetContext.clientSideBaseUrl + icon;
}
} else {
icon = NXGadgetContext.clientSideBaseUrl + constants.noActivityTypeIcon;
}
activity.icon = icon;
return Mustache.render(template, activity);
}
function addTabLineHtml() {
var htmlContent = Mustache.render(templates.tabLine,
{ allFilter: constants.filter.all,
allMessage: prefs.getMsg('label.activities.filter.all'),
discussionsFilter: constants.filter.discussions,
discussionsMessage: prefs.getMsg('label.activities.filter.messages'),
eventsFilter: constants.filter.events,
eventsMessage: prefs.getMsg('label.activities.filter.events'),
postMessage: prefs.getMsg('label.write.message')
});
$(htmlContent).insertBefore('#container');
}
function addDeleteLinksHtml() {
// activities
$('div[data-activityid][data-allowdeletion="true"]').each(function() {
$(this).removeAttr('data-allowdeletion');
var activityId = $(this).attr('data-activityid');
var deleteImageURL = NXGadgetContext.clientSideBaseUrl + 'icons/delete.png'
var actions = $(this).find('div.jsActions');
var htmlContent = Mustache.render(templates.deleteActivityAction,
{ activityId: activityId, deleteImageURL: deleteImageURL,
deleteMessage: prefs.getMsg('command.delete') });
actions.append(htmlContent);
});
// activity replies
$('div[data-replyid][data-allowdeletion="true"]').each(function() {
$(this).removeAttr('data-allowdeletion');
var replyId = $(this).attr('data-replyid');
var deleteImageURL = NXGadgetContext.clientSideBaseUrl + 'icons/delete.png'
var actions = $(this).find('div.jsReplyActions');
var htmlContent = Mustache.render(templates.deleteActivityReplyAction,
{ replyId: replyId, deleteImageURL: deleteImageURL,
deleteMessage: prefs.getMsg('command.delete') });
actions.append(htmlContent);
});
}
function addLikeStatusHtml() {
$('div[data-activityid][data-likescount]').each(function() {
var activityId = $(this).attr('data-activityid');
var likesCount = $(this).attr('data-likescount');
var userLikeStatus = $(this).attr('data-userlikestatus');
var actions = $(this).find('div.jsActions');
addActivityLikeStatusHtml(actions, activityId, likesCount, userLikeStatus);
});
$('div[data-replyid][data-likescount]').each(function() {
var replyId = $(this).attr('data-replyid');
var likesCount = $(this).attr('data-likescount');
var userLikeStatus = $(this).attr('data-userlikestatus');
var actions = $(this).find('div.jsReplyActions');
addActivityLikeStatusHtml(actions, replyId, likesCount, userLikeStatus);
});
}
function addActivityLikeStatusHtml(actions, activityId, likesCount, userLikeStatus) {
actions.find('.jsLike').remove();
var likeImageURL = userLikeStatus == 1
? NXGadgetContext.clientSideBaseUrl + 'icons/like_active.png'
: NXGadgetContext.clientSideBaseUrl + 'icons/like_unactive.png';
var htmlContent = Mustache.render(templates.likeAction,
{ likeImageURL: likeImageURL, likesCount: likesCount });
var deleteAction = $(actions).find('.jsDelete');
if (deleteAction.length > 0) {
$(htmlContent).insertAfter(deleteAction);
} else {
$(htmlContent).insertAfter(actions.find('.timestamp'));
}
}
function addReplyLinksHtml() {
$('div[data-activityid]').each(function() {
var activityId = $(this).attr('data-activityid');
var replyImageURL = NXGadgetContext.clientSideBaseUrl + 'icons/reply.png'
var actions = $(this).find('div.jsActions');
var htmlContent = Mustache.render(templates.replyAction,
{ activityId: activityId, replyImageURL: replyImageURL,
replyMessage: prefs.getMsg('command.reply') });
actions.append(htmlContent);
});
}
function addMoreActivitiesBarHtml() {
var htmlContent = Mustache.render(templates.moreActivitiesBar,
{ moreActivitiesMessage: prefs.getMsg('label.show.more.activities') });
$('#container').append(htmlContent);
}
function addNoMoreActivitiesTextHtml() {
var htmlContent = Mustache.render(templates.noMoreActivitiesBar,
{ noMoreActivitiesMessage: prefs.getMsg('label.no.more.activities') });
$('#container').append(htmlContent);
}
function addNewActivitiesBarHtml() {
if ($('.jsNewActivitiesBar').length > 0) {
return;
}
var htmlContent = Mustache.render(templates.newActivitiesBar,
{ newActivitiesMessage: prefs.getMsg('label.show.new.activities') });
$('#container').prepend(htmlContent);
}
/* end HTML building functions */
/* handler functions */
function registerTabLineHandler() {
$('a[data-filter]').click(function() {
if (!$(this).is('.selected')) {
$('[data-filter]').removeClass('selected');
$(this).addClass('selected');
filter = $(this).attr('data-filter');
displayWallActivities();
}
});
}
function registerNewMiniMessageHandler() {
$('.jsPostMessage').click(function() {
$('.jsNewMiniMessage').fadeIn(300, function() {
gadgets.window.adjustHeight();
});
$('.jsNewMiniMessage textarea.jsMiniMessageText').focus();
});
// hide the form when clicking outside
$('body').click(function(e) {
if ($(e.target).hasClass('jsPostMessage') || $(e.target).hasClass('jsNewMiniMessage')) {
return;
}
if ($(e.target).parents('.jsNewMiniMessage').length > 0) {
return;
}
if ($('.jsNewMiniMessage textarea.jsMiniMessageText').val().length == 0) {
$('.jsNewMiniMessage').hide();
}
});
$('.jsNewMiniMessage .jsWriteMiniMessageButton').click(function() {
if ($('.jsNewMiniMessage textarea.jsMiniMessageText').val().length > 0) {
createMiniMessage();
}
});
updateMiniMessageCounter();
$('.jsNewMiniMessage textarea.jsMiniMessageText').keyup(function() {
if ($(this).val().length == 0) {
$('.jsNewMiniMessage .jsWriteMiniMessageButton').addClass('disabled');
} else {
$('.jsNewMiniMessage .jsWriteMiniMessageButton').removeClass('disabled');
}
updateMiniMessageCounter();
});
}
function registerLikeStatusHandler() {
// activities
$('div.jsMainActivity[data-activityid]').each(function() {
var activityId = $(this).attr('data-activityid');
var likeIcon = $(this).find('.jsActions .jsLikeIcon');
registerLikeStatusHandlerFor(activityId, likeIcon);
});
// replies
$('div[data-replyid]').each(function() {
var replyId = $(this).attr('data-replyid');
var likeIcon = $(this).find('.jsReplyActions .jsLikeIcon');
registerLikeStatusHandlerFor(replyId, likeIcon);
});
}
function registerLikeStatusHandlerFor(activityId, likeIcon) {
likeIcon.click(function() {
var userLikeStatus = likeIcon.parents('div[data-userlikestatus]')
.attr('data-userlikestatus');
var operationId = userLikeStatus == 1
? constants.cancelLikeOperationId
: constants.likeOperationId;
var NXRequestParams= { operationId : operationId,
operationParams: {
activityId: activityId
},
operationContext: {},
operationCallback: function(response, params) {
var likeStatus = response.data;
var i, activity;
if ($('div.jsMainActivity[data-activityid="' + activityId + '"]').length > 0) {
for (i = 0; i < currentActivities.length; i++) {
activity = currentActivities[i];
if (activity.id == activityId) {
activity.likeStatus = likeStatus;
}
}
$('div.jsMainActivity[data-activityid="' + activityId + '"]').each(function() {
$(this).attr('data-likescount', likeStatus.likesCount);
$(this).attr('data-userlikestatus', likeStatus.userLikeStatus);
var actions = $(this).find('div.jsActions');
addActivityLikeStatusHtml(actions, activityId,
likeStatus.likesCount, likeStatus.userLikeStatus);
registerLikeStatusHandlerFor(activityId, actions.find('.jsLikeIcon'));
});
} else {
// reply
var parentActivityId = $('div[data-replyid="' + activityId + '"]').parents('div[data-activityid]').attr('data-activityid');
for (i = 0; i < currentActivities.length; i++) {
activity = currentActivities[i];
if (activity.id == parentActivityId) {
for (var j = 0; j < activity.replies.length; j++) {
var reply = activity.replies[j];
if (reply.id == activityId) {
reply.likeStatus = likeStatus;
}
}
}
}
$('div[data-replyid="' + activityId + '"]').each(function() {
$(this).attr('data-likescount', likeStatus.likesCount);
$(this).attr('data-userlikestatus', likeStatus.userLikeStatus);
var actions = $(this).find('div.jsReplyActions');
addActivityLikeStatusHtml(actions, activityId,
likeStatus.likesCount, likeStatus.userLikeStatus);
registerLikeStatusHandlerFor(activityId, actions.find('.jsLikeIcon'));
});
}
}
};
doAutomationRequest(NXRequestParams);
});
}
function registerDeleteLinksHandler() {
$('div.jsDelete[data-activityid]').click(function() {
if (!confirmDeleteMessage()) {
return false;
}
var activityId = $(this).attr("data-activityid");
removeMiniMessage(activityId);
});
$('div.jsDelete[data-replyid]').each(function() {
handleDeleteActivityReply($(this));
});
}
function handleDeleteActivityReply(deleteLink) {
deleteLink.click(function() {
if (!confirmDeleteReply()) {
return false;
}
var replyId = $(deleteLink).attr('data-replyid');
var activityId = $(deleteLink).parents('div[data-activityid]').attr('data-activityid');
removeActivityReply(activityId, replyId);
});
}
function registerReplyLinksHandler() {
$('.jsReply').click(function() {
var activityId = $(this).attr('data-activityid');
var newActivityReply = $('.jsNewActivityReply[data-activityid="' + activityId + '"]');
updateActivityReplyMessageCounter(newActivityReply);
newActivityReply.show();
newActivityReply.find('textarea.jsActivityReplyText').focus();
gadgets.window.adjustHeight();
});
}
function registerNewActivityReplyHandler() {
$('.jsActivityReplyText').keyup(function () {
var writeButton = $(this).siblings('.newMiniMessageActions').find('.jsWriteActivityReplyButton');
if ($(this).val().length == 0) {
writeButton.addClass('disabled');
} else {
writeButton.removeClass('disabled');
}
var newActivityReply = $(this).parents('.jsNewActivityReply');
updateActivityReplyMessageCounter(newActivityReply);
});
$('.jsNewActivityReply').each(function() {
var newActivityReply = $(this);
var activityId = $(this).attr('data-activityid');
var writeButton = $(this).find('.jsWriteActivityReplyButton');
writeButton.attr('data-activityid', activityId);
writeButton.click(function() {
if (newActivityReply.find('textarea.jsActivityReplyText').val().length > 0) {
createActivityReply(newActivityReply);
}
});
});
}
function registerMoreRepliesHandler() {
$('.jsMoreRepliesBar').click(function() {
var repliesContainer = $(this).parents('.jsRepliesContainer');
repliesContainer.find('div[data-replyid]').each(function() {
$(this).show();
});
repliesContainer.find('.jsMoreRepliesBar').each(function() {
$(this).remove();
});
gadgets.window.adjustHeight();
});
}
function registerMoreActivityBarHandler() {
$('.jsMoreActivitiesBar').click(function() {
showMoreActivities();
});
}
function registerNewActivitiesBarHandler() {
$('.jsNewActivitiesBar').click(function() {
showNewActivities();
});
}
/* end handler functions */
/* mini message */
function updateMiniMessageCounter() {
var delta = 140 - $('.jsNewMiniMessage textarea.jsMiniMessageText').val().length;
var miniMessageCounter = $('.jsNewMiniMessage .miniMessageCounter');
miniMessageCounter.text(delta);
miniMessageCounter.toggleClass('warning', delta < 5);
if (delta < 0) {
$('.jsWriteMiniMessageButton').attr('disabled', 'disabled');
} else {
$('.jsWriteMiniMessageButton').removeAttr('disabled');
}
}
function createMiniMessage() {
var miniMessageText = $('textarea.jsMiniMessageText').val();
var newOperationParams = jQuery.extend(true, {}, miniMessageOperationParams);
newOperationParams.message = miniMessageText;
var opCallParameters = {
operationId: 'Services.AddMiniMessage',
operationParams: newOperationParams,
entityType: 'blob',
operationContext: {},
operationCallback: function (response, opCallParameters) {
loadWallActivityStream();
$('.jsNewMiniMessage').hide();
$('.jsNewMiniMessage textarea.jsMiniMessageText').val('');
$('.jsNewMiniMessage .jsWriteMiniMessageButton').attr('disabled', 'disabled');
updateMiniMessageCounter();
}
};
doAutomationRequest(opCallParameters);
}
function confirmDeleteMessage() {
return confirm(prefs.getMsg('label.wall.message.confirmDelete'));
}
function removeMiniMessage(miniMessageId) {
var opCallParameters = {
operationId: 'Services.RemoveMiniMessage',
operationParams: {
miniMessageId: miniMessageId
},
entityType: 'blob',
operationContext: {},
operationCallback: function (response, opCallParameters) {
loadWallActivityStream();
}
};
doAutomationRequest(opCallParameters);
}
/* end mini message */
/* activity replies */
function updateActivityReplyMessageCounter(newActivityReply) {
var delta = 140 - newActivityReply.find('textarea.jsActivityReplyText').val().length;
var miniMessageCounter = newActivityReply.find('.jsActivityReplyCounter');
miniMessageCounter.text(delta);
miniMessageCounter.toggleClass('warning', delta < 5);
if (delta < 0) {
newActivityReply.find('.jsWriteActivityReplyButton').attr('disabled', 'disabled');
} else {
newActivityReply.find('.jsWriteActivityReplyButton').removeAttr('disabled');
}
}
function createActivityReply(newActivityReply) {
var activityReplyText = newActivityReply.find('textarea.jsActivityReplyText').val();
var activityId = newActivityReply.attr('data-activityid');
var opCallParameters = {
operationId: 'Services.AddActivityReply',
operationParams: {
message: activityReplyText,
language: prefs.getLang(),
activityId: activityId,
activityLinkBuilderName: prefs.getString("activityLinkBuilderName")
},
entityType: 'blob',
operationContext: {},
operationCallback: function (response, opCallParameters) {
newActivityReply.find('.jsActivityReplyText').val('');
updateActivityReplyMessageCounter(newActivityReply);
newActivityReply.hide();
var repliesContainer = $('div[data-activityId="' + activityId + '"]')
.find('.jsRepliesContainer');
var reply = response.data;
reply.likeStatus = {};
reply.likeStatus.likesCount = 0;
reply.likeStatus.userLikeStatus = 0;
// add the new reply to the reply list of the activity
for (var i = 0; i < currentActivities.length; i++) {
var activity = currentActivities[i];
if (activity.id == activityId) {
activity.replies.push(reply);
}
}
var replyHtml = Mustache.render(templates.reply, reply);
$(replyHtml).insertBefore(repliesContainer.find('.jsNewActivityReply'));
repliesContainer.find('div[data-replyid="' + reply.id + '"]').each(function() {
// like status
var replyId = $(this).attr('data-replyid');
var likesCount = $(this).attr('data-likescount');
var userLikeStatus = $(this).attr('data-userlikestatus');
var replyActions = $(this).find('div.jsReplyActions');
addActivityLikeStatusHtml(replyActions, replyId, likesCount, userLikeStatus);
registerLikeStatusHandlerFor(replyId, replyActions.find('.jsLikeIcon'));
// delete link
var allowDeletion = $(this).attr('data-allowdeletion');
if (allowDeletion === 'true') {
$(this).removeAttr('data-allowdeletion');
var deleteImageURL = NXGadgetContext.clientSideBaseUrl + 'icons/delete.png'
var htmlContent = Mustache.render(templates.deleteActivityReplyAction,
{ replyId: replyId, deleteImageURL: deleteImageURL,
deleteMessage: prefs.getMsg('command.delete') });
replyActions.append(htmlContent);
replyActions.find('div.jsDelete[data-replyid="' + replyId + '"]').each(function() {
handleDeleteActivityReply($(this));
});
}
});
gadgets.window.adjustHeight();
}
};
doAutomationRequest(opCallParameters);
}
function confirmDeleteReply() {
return confirm(prefs.getMsg('label.wall.reply.confirmDelete'));
}
function removeActivityReply(activityId, replyId) {
var opCallParameters = {
operationId: 'Services.RemoveActivityReply',
operationParams: {
activityId: activityId,
replyId: replyId
},
entityType: 'blob',
operationContext: {},
operationCallback: function (response, opCallParameters) {
if (response.rc > 200 && response.rc < 300) {
$('div[data-replyid="'+ replyId + '"]').remove();
for (var i = 0; i < currentActivities.length; i++) {
var activity = currentActivities[i];
if (activity.id == activityId) {
for (var j = 0; j < activity.replies.length; j++) {
var reply = activity.replies[j];
if (reply.id == replyId) {
activity.replies.splice(j, 1);
}
}
}
}
gadgets.window.adjustHeight();
}
}
};
doAutomationRequest(opCallParameters);
}
/* end activity replies */
function showMoreActivities() {
var newOperationParams = jQuery.extend(true, {}, wallOperationParams);
newOperationParams.offset = offset;
var NXRequestParams= { operationId : 'Services.GetWallActivityStream',
operationParams: newOperationParams,
operationContext: {},
operationCallback: function(response, params) {
var newActivities = response.data.activities;
if (newActivities.length > 0) {
currentActivities = currentActivities.concat(newActivities);
offset = response.data.offset;
} else {
hasMoreActivities = false;
}
displayWallActivities();
}
};
doAutomationRequest(NXRequestParams);
}
function showNewActivities() {
currentActivities = waitingActivities;
offset = waitingOffset;
displayWallActivities();
}
// gadget initialization
gadgets.util.registerOnLoadHandler(function() {
var contentStyleClass = prefs.getString("contentStyleClass");
if (contentStyleClass) {
_gel('content').className = contentStyleClass;
}
addTabLineHtml();
addNewMiniMessageHtml();
registerTabLineHandler();
registerNewMiniMessageHandler();
loadWallActivityStream();
window.setInterval(pollWallActivityStream, 30*1000);
});
}());
|
import tw from 'tailwind-styled-components'
/** */
export const StyledColumnSectionLiner = tw.div`
p-4
` |
var mongoose = require("mongoose"),
Recipe = require("./models/recipe"),
Comment = require("./models/comment");
var data =[
{
name: "Cloud's Rest",
image: "https://pixabay.com/get/e834b70c2cf5083ed1584d05fb1d4e97e07ee3d21cac104496f5c27ba2edb5b1_340.jpg",
description: "blah blah blah"
},
{
name: "Desert Mesa",
image: "https://pixabay.com/get/e136b60d2af51c22d2524518b7444795ea76e5d004b0144290f3c37ca7edbc_340.jpg",
description: "blah blah blah"
},
{
name: "Beach",
image: "https://www.photosforclass.com/download/pixabay-182951?webUrl=https%3A%2F%2Fpixabay.com%2Fget%2Fe83db3062df51c22d2524518b7444795ea76e5d004b0144290f4c47ea3eab5_960.jpg&user=Hans",
description: "blah blah blah"
}
];
function seedDB() {
//Remove all recipes
Recipe.remove({}, function(err){
if(err) console.log(err);
console.log("removed recipes!");
// add new recipes
// data.forEach(function(seed){
// Recipe.create(seed, function(err, recipe){
// if(err) console.log(err);
// else {
// console.log("add new recipe");
// Comment.create(
// {
// text: "This is a great place",
// author: "Can Dong"
// },function(err, comment){
// if(err) console.log(err);
// else {
// recipe.comments.push(comment);
// recipe.save();
// console.log("created new comment");
// }
// })
// }
// })
// });
})
}
module.exports = seedDB; |
// ==UserScript==
// @id wayfarer-overlays
// @name IITC plugin: Wayfarer Overlays
// @category Layer
// @version 1.0
// @namespace https://github.com/adamculpepper/wayfarer-layers
// @downloadURL https://github.com/adamculpepper/wayfarer-layers/raw/master/wayfarer-layers.js
// @homepageURL https://github.com/adamculpepper/wayfarer-layers
// @description Place markers on the map for your candidates in Wayfarer.
// @match https://intel.ingress.com/*
// @grant none
// ==/UserScript==
/* forked from https://gitlab.com/AlfonsoML/wayfarer */
/* eslint-env es6 */
/* eslint no-var: "error" */
/* globals L, map */
/* globals GM_info, $, dialog */
;function wrapper(plugin_info) { // eslint-disable-line no-extra-semi
'use strict';
// PLUGIN START ///////////////////////////////////////////////////////
let editmarker = null;
let isPlacingMarkers = false;
let markercollection = [];
let plottedmarkers = {};
let plottedtitles = {};
let plottedsubmitrange = {};
let plottedinteractrange = {};
// Define the layers created by the plugin, one for each marker status
const mapLayers = {
potential: {
color: 'grey',
title: '2Potentials',
optionTitle: 'Potential'
},
school: {
color: 'orange',
title: 'Schools',
optionTitle: 'Submitted'
},
park: {
color: 'green',
title: 'Parks',
optionTitle: 'Live'
},
church: {
color: 'red',
title: 'Churches',
optionTitle: 'Rejected'
},
potentialedit: {
color: 'cornflowerblue',
title: '2Potential edit',
optionTitle: 'Edit location. Potential'
},
sentedit: {
color: 'purple',
title: '2Sent edit',
optionTitle: 'Edit location. Sent'
}
};
const defaultSettings = {
showTitles: true,
showRadius: false,
showInteractionRadius: false,
scriptURL: '' //REMOVE
};
let settings = defaultSettings;
function saveSettings() {
localStorage['wayfarer_layer_settings'] = JSON.stringify(settings);
}
function loadSettings() {
const tmp = localStorage['wayfarer_layer_settings'];
if (!tmp) {
upgradeSettings();
return;
}
try {
settings = JSON.parse(tmp);
} catch (e) { // eslint-disable-line no-empty
}
}
// importing from totalrecon_settings will be removed after a little while
function upgradeSettings() {
const tmp = localStorage['totalrecon_settings'];
if (!tmp)
return;
try {
settings = JSON.parse(tmp);
} catch (e) { // eslint-disable-line no-empty
}
saveSettings();
localStorage.removeItem('totalrecon_settings');
}
function getStoredData() {
//const url = settings.scriptURL;
// ID of the Google Spreadsheet
//var spreadsheetID = '';
// Make sure it is public or set to "anyone with link can view" and "published to web"
var url = 'https://spreadsheets.google.com/feeds/list/' + settings.sheetKey + '/od6/public/values?alt=json';
if (!settings.sheetKey) {
markercollection = [];
drawMarkers();
return;
}
var arrayLayers = [];
$.getJSON(url, function(data) {
var entry = data.feed.entry;
//debugger;
$(entry).each(function() {
var id = this.gsx$id.$t;
var timestamp = this.gsx$timestamp.$t;
var title = this.gsx$title.$t;
var description = this.gsx$description.$t;
var lat = this.gsx$lat.$t;
var lng = this.gsx$lng.$t;
var status = this.gsx$status.$t;
var submitteddate = this.gsx$submitteddate.$t;
var responsedate = this.gsx$responsedate.$t;
var candidateimageurl = this.gsx$candidateimageurl.$t;
var intellink = this.gsx$intellink.$t;
arrayLayers.push({
"id": id,
"timestamp": timestamp,
"title": title,
"description": description,
"lat": lat,
"lng": lng,
"status": status,
"submitteddate": submitteddate,
"responsedate": responsedate,
"candidateimageurl": candidateimageurl,
"intellink": intellink
});
});
console.log('Wayfarer Layers - 1');
console.table(arrayLayers);
console.log('Wayfarer Layers - 2');
//markercollection = JSON.stringify(arrayLayers);
console.log(markercollection);
console.table(markercollection);
try {
//markercollection = JSON.parse(data);
markercollection = arrayLayers;
//debugger;
} catch (e) {
console.log('Wayfarer Layers. Exception parsing response: ', e); // eslint-disable-line no-console
alert('Wayfarer Layers. Exception parsing response.');
return;
}
//setTimeout(function() {
drawMarkers();
//}, 10000);
});
// $.ajax({
// url: url,
// type: 'GET',
// dataType: 'text',
// success: function (data, status, header) {
// try {
// markercollection = JSON.parse(data);
// } catch (e) {
// console.log('Wayfarer Layers. Exception parsing response: ', e); // eslint-disable-line no-console
// alert('Wayfarer Layers. Exception parsing response.');
// return;
// }
// drawMarkers();
// },
// error: function (x, y, z) {
// console.log('Wayfarer Layers. Error message: ', x, y, z); // eslint-disable-line no-console
// alert('Wayfarer Layers. Failed to retrieve data from the scriptURL.');
// }
// });
}
function drawMarker(candidate) {
//debugger;
if (candidate != undefined && candidate.lat != '' && candidate.lng != '') {
addMarkerToLayer(candidate);
addTitleToLayer(candidate);
addCircleToLayer(candidate);
}
}
function addCircleToLayer(candidate) {
if (settings.showRadius) {
const latlng = L.latLng(candidate.lat, candidate.lng);
// Specify the no submit circle options
const circleOptions = {color: 'black', opacity: 1, fillColor: 'grey', fillOpacity: 0.40, weight: 1, clickable: false, interactive: false};
const range = 20; // Hardcoded to 20m, the universal too close for new submit range of a portal
// Create the circle object with specified options
const circle = new L.Circle(latlng, range, circleOptions);
// Add the new circle
const existingMarker = plottedmarkers[candidate.id];
existingMarker.layer.addLayer(circle);
plottedsubmitrange[candidate.id] = circle;
}
if (settings.showInteractionRadius) {
const latlng = L.latLng(candidate.lat, candidate.lng);
// Specify the interaction circle options
const circleOptions = {color: 'grey', opacity: 1, fillOpacity: 0, weight: 1, clickable: false, interactive: false};
const range = 40;
// Create the circle object with specified options
const circle = new L.Circle(latlng, range, circleOptions);
// Add the new circle
const existingMarker = plottedmarkers[candidate.id];
existingMarker.layer.addLayer(circle);
plottedinteractrange[candidate.id] = circle;
}
}
function removeExistingCircle(guid) {
const existingCircle = plottedsubmitrange[guid];
if (existingCircle !== undefined) {
const existingMarker = plottedmarkers[guid];
existingMarker.layer.removeLayer(existingCircle);
delete plottedsubmitrange[guid];
}
const existingInteractCircle = plottedinteractrange[guid];
if (existingInteractCircle !== undefined) {
const existingMarker = plottedmarkers[guid];
existingMarker.layer.removeLayer(existingInteractCircle);
delete plottedinteractrange[guid];
}
}
function addTitleToLayer(candidate) {
if (settings.showTitles) {
const title = candidate.title;
if (title != '') {
const portalLatLng = L.latLng(candidate.lat, candidate.lng);
const titleMarker = L.marker(portalLatLng, {
icon: L.divIcon({
className: 'wayfarer-planner-name',
iconAnchor: [100,5],
iconSize: [200,10],
html: title
}),
data: candidate
});
const existingMarker = plottedmarkers[candidate.id];
existingMarker.layer.addLayer(titleMarker);
plottedtitles[candidate.id] = titleMarker;
}
}
}
function removeExistingTitle(guid) {
const existingTitle = plottedtitles[guid];
if (existingTitle !== undefined) {
const existingMarker = plottedmarkers[guid];
existingMarker.layer.removeLayer(existingTitle);
delete plottedtitles[guid];
}
}
function removeExistingMarker(guid) {
const existingMarker = plottedmarkers[guid];
if (existingMarker !== undefined) {
existingMarker.layer.removeLayer(existingMarker.marker);
removeExistingTitle(guid);
removeExistingCircle(guid);
}
}
function addMarkerToLayer(candidate) {
removeExistingMarker(candidate.id);
const portalLatLng = L.latLng(candidate.lat, candidate.lng);
const layerData = mapLayers[candidate.status];
const markerColor = layerData.color;
const markerLayer = layerData.layer;
const marker = createGenericMarker(portalLatLng, markerColor, {
title: candidate.title,
id: candidate.id,
data: candidate,
draggable: true
});
marker.on('dragend', function (e) {
const data = e.target.options.data;
const latlng = marker.getLatLng();
data.lat = latlng.lat;
data.lng = latlng.lng;
drawInputPopop(latlng, data);
});
marker.on('dragstart', function (e) {
const guid = e.target.options.data.id;
removeExistingTitle(guid);
removeExistingCircle(guid);
});
markerLayer.addLayer(marker);
plottedmarkers[candidate.id] = {'marker': marker, 'layer': markerLayer};
}
function clearAllLayers() {
Object.values(mapLayers).forEach(data => data.layer.clearLayers());
/* clear marker storage */
plottedmarkers = {};
plottedtitles = {};
plottedsubmitrange = {};
plottedinteractrange = {};
}
function drawMarkers() {
clearAllLayers();
markercollection.forEach(drawMarker);
}
function onMapClick(e) {
if (isPlacingMarkers) {
if (editmarker != null) {
map.removeLayer(editmarker);
}
const marker = createGenericMarker(e.latlng, 'pink', {
title: 'Place your mark!'
});
editmarker = marker;
marker.addTo(map);
drawInputPopop(e.latlng);
}
}
function drawInputPopop(latlng, markerData) {
const formpopup = L.popup();
let title = '';
let description = '';
let id = '';
let submitteddate = '';
let lat = '';
let lng = '';
let status = 'potential';
let imageUrl = '';
if (markerData !== undefined) {
id = markerData.id;
title = markerData.title;
description = markerData.description;
submitteddate = markerData.submitteddate;
status = markerData.status;
imageUrl = markerData.candidateimageurl;
lat = parseFloat(markerData.lat).toFixed(6);
lng = parseFloat(markerData.lng).toFixed(6);
} else {
lat = latlng.lat.toFixed(6);
lng = latlng.lng.toFixed(6);
}
formpopup.setLatLng(latlng);
const options = Object.keys(mapLayers)
.map(id => '<option value="' + id + '"' + (id == status ? ' selected="selected"' : '') + '>' + mapLayers[id].optionTitle + '</option>')
.join('');
let formContent = `<div class="wayfarer-planner-popup"><form id="submit-to-wayfarer">
<label>Status
<select name="status">${options}</select>
</label>
<label>Title
<input name="title" type="text" autocomplete="off" placeholder="Title (required)" required value="${title}">
</label>
<label>Description
<input name="description" type="text" autocomplete="off" placeholder="Description" value="${description}">
</label>
<div class='wayfarer-expander' title='Click to expand additional fields'>»</div>
<div class='wayfarer-extraData'>
<label>Submitted date
<input name="submitteddate" type="text" autocomplete="off" placeholder="dd-mm-jjjj" value="${submitteddate}">
</label>
<label>Image
<input name="candidateimageurl" type="text" autocomplete="off" placeholder="http://?.googleusercontent.com/***" value="${imageUrl}">
</label>
</div>
<input name="id" type="hidden" value="${id}">
<input name="lat" type="hidden" value="${lat}">
<input name="lng" type="hidden" value="${lng}">
<input name="nickname" type="hidden" value="${window.PLAYER.nickname}">
<button type="submit" id='wayfarer-submit'>Send</button>
</form>`;
if (id !== '') {
formContent += '<a style="padding:4px; display: inline-block;" id="deletePortalCandidate">Delete 🗑️</a>';
}
if (imageUrl !== '' && imageUrl !== undefined) {
formContent += ' <a href="' + imageUrl + '" style="padding:4px; float:right;" target="_blank">Image</a>';
}
const align = id !== '' ? 'float: right' : 'box-sizing: border-box; text-align: right; display: inline-block; width: 100%';
formContent += ` <a href="https://www.google.com/maps?layer=c&cbll=${lat},${lng}" style="padding:4px; ${align};" target="_blank">Street View</a>`;
formpopup.setContent(formContent + '</div>');
formpopup.openOn(map);
const deleteLink = formpopup._contentNode.querySelector('#deletePortalCandidate');
if (deleteLink != null) {
deleteLink.addEventListener('click', e => confirmDeleteCandidate(e, id));
}
const expander = formpopup._contentNode.querySelector('.wayfarer-expander');
expander.addEventListener('click', function () {
expander.parentNode.classList.toggle('wayfarer__expanded');
});
}
// function confirmDeleteCandidate(e, id) {
// e.preventDefault();
// if (!confirm('Do you want to remove this candidate?'))
// return;
// const formData = new FormData();
// formData.append('status', 'delete');
// formData.append('id', id);
// $.ajax({
// url: settings.scriptURL,
// type: 'POST',
// data: formData,
// processData: false,
// contentType: false,
// success: function (data, status, header) {
// removeExistingMarker(id);
// map.closePopup();
// },
// error: function (x, y, z) {
// console.log('Wayfarer Layers. Error message: ', x, y, z); // eslint-disable-line no-console
// alert('Wayfarer Layers. Failed to send data to the scriptURL');
// }
// });
// }
function markerClicked(event) {
// bind data to edit form
if (editmarker != null) {
map.removeLayer(editmarker);
editmarker = null;
}
drawInputPopop(event.layer.getLatLng(), event.layer.options.data);
}
function getGenericMarkerSvg(color) {
const markerTemplate = `<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" baseProfile="full" viewBox="0 0 25 41">
<path d="M19.4,3.1c-3.3-3.3-6.1-3.3-6.9-3.1c-0.6,0-3.7,0-6.9,3.1c-4,4-1.3,9.4-1.3,9.4s5.6,14.6,6.3,16.3c0.6,1.2,1.3,1.5,1.7,1.5c0,0,0,0,0.2,0h0.2c0.4,0,1.2-0.4,1.7-1.5c0.8-1.7,6.3-16.3,6.3-16.3S23.5,7.2,19.4,3.1z M13.1,12.4c-2.3,0.4-4.4-1.5-4-4c0.2-1.3,1.3-2.5,2.9-2.9c2.3-0.4,4.4,1.5,4,4C15.6,11,14.4,12.2,13.1,12.4z" fill="%COLOR%" stroke="#fff"/>
<path d="M12.5,34.1c1.9,0,3.5,1.5,3.5,3.5c0,1.9-1.5,3.5-3.5,3.5S9,39.5,9,37.5c0-1.2,0.6-2.2,1.5-2.9 C11.1,34.3,11.8,34.1,12.5,34.1z" fill="%COLOR%" stroke="#fff"/>
</svg>`;
return markerTemplate.replace(/%COLOR%/g, color);
}
function getGenericMarkerIcon(color, className) {
return L.divIcon({
iconSize: new L.Point(25, 41),
iconAnchor: new L.Point(12, 41),
html: getGenericMarkerSvg(color),
className: className || 'leaflet-iitc-divicon-generic-marker'
});
}
function createGenericMarker(ll, color, options) {
options = options || {};
const markerOpt = $.extend({
icon: getGenericMarkerIcon(color || '#a24ac3')
}, options);
return L.marker(ll, markerOpt);
}
function showDialog() {
if (window.isSmartphone())
window.show('map');
const html =
`<p><label for="txtScriptUrl">Sheet Key</label><br><input type="text" id="txtSheetKey" spellcheck="false" placeholder="https://script.google.com/macros/***/exec"></p>
<p><a class='wayfarer-refresh'>Update candidate data</a></p>
<p><input type="checkbox" id="chkShowTitles"><label for="chkShowTitles">Show titles</label></p>
<p><input type="checkbox" id="chkShowRadius"><label for="chkShowRadius">Show submit radius</label></p>
<p><input type="checkbox" id="chkShowInteractRadius"><label for="chkShowInteractRadius">Show interaction radius</label></p>
`;
const container = dialog({
width: 'auto',
html: html,
title: 'Wayfarer Layers',
buttons: {
OK: function () {
const newUrl = txtInput.value;
if (!txtInput.reportValidity())
return;
if (newUrl != '') {
if (newUrl.startsWith('http') || newUrl.startsWith('www.')) {
alert('This should be your Sheet Key, not a full URL".');
return;
}
// if (newUrl.includes('echo') || !newUrl.endsWith('exec')) {
// alert('You must use the short URL provided by "creating the webapp", not the long one after executing the script.');
// return;
// }
}
if (newUrl != settings.sheetKey) {
settings.sheetKey = newUrl;
saveSettings();
getStoredData();
}
container.dialog('close');
}
}
});
const div = container[0];
const txtInput = div.querySelector('#txtSheetKey');
txtInput.value = settings.sheetKey;
const linkRefresh = div.querySelector('.wayfarer-refresh');
linkRefresh.addEventListener('click', () => {
settings.sheetKey = txtInput.value;
saveSettings();
getStoredData();
});
const chkShowTitles = div.querySelector('#chkShowTitles');
chkShowTitles.checked = settings.showTitles;
chkShowTitles.addEventListener('change', e => {
settings.showTitles = chkShowTitles.checked;
saveSettings();
drawMarkers();
});
const chkShowRadius = div.querySelector('#chkShowRadius');
chkShowRadius.checked = settings.showRadius;
chkShowRadius.addEventListener('change', e => {
settings.showRadius = chkShowRadius.checked;
saveSettings();
drawMarkers();
});
const chkShowInteractRadius = div.querySelector('#chkShowInteractRadius');
chkShowInteractRadius.checked = settings.showInteractionRadius;
chkShowInteractRadius.addEventListener('change', e => {
settings.showInteractionRadius = chkShowInteractRadius.checked;
saveSettings();
drawMarkers();
});
// const chkPlaceMarkers = div.querySelector('#chkPlaceMarkers');
// chkPlaceMarkers.checked = isPlacingMarkers;
// chkPlaceMarkers.addEventListener('change', e => {
// isPlacingMarkers = chkPlaceMarkers.checked;
// if (!isPlacingMarkers && editmarker != null) {
// map.closePopup();
// map.removeLayer(editmarker);
// editmarker = null;
// }
// //settings.isPlacingMarkers = chkPlaceMarkers.checked;
// //saveSettings();
// });
if (!settings.sheetKey) {
//chkPlaceMarkers.disabled = true;
//chkPlaceMarkers.parentNode.classList.add('wayfarer-planner__disabled');
linkRefresh.classList.add('wayfarer-planner__disabled');
}
txtInput.addEventListener('input', e => {
//chkPlaceMarkers.disabled = !txtInput.value;
//chkPlaceMarkers.parentNode.classList.toggle('wayfarer-planner__disabled', !txtInput.value);
linkRefresh.classList.toggle('wayfarer-planner__disabled', !txtInput.value);
});
}
// Initialize the plugin
const setup = function () {
loadSettings();
$('<style>')
.prop('type', 'text/css')
.html(`
.wayfarer-planner-popup {
width:200px;
}
.wayfarer-planner-popup a {
color: #ffce00;
}
.wayfarer-planner-name {
font-size: 12px;
font-weight: bold;
color: gold;
opacity: 0.7;
text-align: center;
text-shadow: -1px -1px #000, 1px -1px #000, -1px 1px #000, 1px 1px #000, 0 0 2px #000;
pointer-events: none;
}
#txtSheetKey {
width: 100%;
}
.wayfarer-planner__disabled {
opacity: 0.8;
pointer-events: none;
}
#submit-to-wayfarer {
position: relative;
}
#submit-to-wayfarer input,
#submit-to-wayfarer select {
width: 100%;
}
#submit-to-wayfarer input {
color: #CCC;
}
#submit-to-wayfarer label {
margin-top: 5px;
display: block;
color: #fff;
}
#wayfarer-submit {
height: 30px;
margin-top: 10px;
width: 100%;
}
.wayfarer-expander {
cursor: pointer;
transform: rotate(90deg) translate(-1px, 1px);
transition: transform .2s ease-out 0s;
position: absolute;
right: 0;
}
.wayfarer-extraData {
max-height: 0;
overflow: hidden;
margin-top: 1em;
}
.wayfarer__expanded .wayfarer-expander {
transform: rotate(270deg) translate(1px, -3px);
}
.wayfarer__expanded .wayfarer-extraData {
max-height: none;
margin-top: 0em;
}
`)
.appendTo('head');
// $('body').on('submit','#submit-to-wayfarer', function (e) {
// e.preventDefault();
// map.closePopup();
// $.ajax({
// url: settings.scriptURL,
// type: 'POST',
// data: new FormData(e.currentTarget),
// processData: false,
// contentType: false,
// success: function (data, status, header) {
// drawMarker(data);
// if (editmarker != null) {
// map.removeLayer(editmarker);
// editmarker = null;
// }
// },
// error: function (x, y, z) {
// console.log('Wayfarer Layers. Error message: ', x, y, z); // eslint-disable-line no-console
// alert('Wayfarer Layers. Failed to send data to the scriptURL');
// }
// });
// });
map.on('click', onMapClick);
Object.values(mapLayers).forEach(data => {
const layer = new L.featureGroup();
data.layer = layer;
window.addLayerGroup('Layers - ' + data.title, layer, true);
layer.on('click', markerClicked);
});
// const toolbox = document.getElementById('toolbox');
// const toolboxLink = document.createElement('a');
// toolboxLink.textContent = 'Wayfarer';
// toolboxLink.title = 'Settings for Wayfarer Layers';
// toolboxLink.addEventListener('click', showDialog);
// toolbox.appendChild(toolboxLink);
if (settings.sheetKey) {
getStoredData();
} else {
showDialog();
}
};
// PLUGIN END //////////////////////////////////////////////////////////
setup.info = plugin_info; //add the script info data to the function as a property
// if IITC has already booted, immediately run the 'setup' function
if (window.iitcLoaded) {
setup();
} else {
if (!window.bootPlugins) {
window.bootPlugins = [];
}
window.bootPlugins.push(setup);
}
}
// wrapper end
(function () {
const plugin_info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) {
plugin_info.script = {
version: GM_info.script.version,
name: GM_info.script.name,
description: GM_info.script.description
};
}
// Greasemonkey. It will be quite hard to debug
if (typeof unsafeWindow != 'undefined' || typeof GM_info == 'undefined' || GM_info.scriptHandler != 'Tampermonkey') {
// inject code into site context
const script = document.createElement('script');
script.appendChild(document.createTextNode('(' + wrapper + ')(' + JSON.stringify(plugin_info) + ');'));
(document.body || document.head || document.documentElement).appendChild(script);
} else {
// Tampermonkey, run code directly
wrapper(plugin_info);
}
})(); |
/*
* @Author: 注册页面
* @Date: 2019-08-15 19:58:38
* @Last Modified by: 乔帅
* @Last Modified time: 2019-08-16 10:05:17
*/
import React, { Component } from 'react';
import axios from 'axios'
class Join extends Component {
state={
name:'',
user:'',
pwd:'',
newPwd:''
}
render() {
let {name,user,pwd,newPwd} =this.state
return (
<div>
<header>注册页面</header>
<form>
<div className="form-group">
<label >真实姓名</label>
<input type="email" name="name" value={name} onChange={this.change.bind(this)} className="form-control" id="exampleInputEmail1" placeholder="姓名" />
</div>
<div className="form-group">
<label >账号</label>
<input type="email" name="user" value={user} onChange={this.change.bind(this)} className="form-control" id="exampleInputEmail1" placeholder="账号" />
</div>
<div className="form-group">
<label>密码</label>
<input type="password" name="pwd" value={pwd} onChange={this.change.bind(this)} className="form-control" id="exampleInputPassword1" placeholder="密码" />
</div>
<div className="form-group">
<label>再次输入密码</label>
<input type="password" name="newPwd" value={newPwd} onChange={this.change.bind(this)} className="form-control" id="exampleInputPassword2" placeholder="确认密码" />
</div>
<input className="btn btn-default" onClick={this.btn.bind(this)} type="button" value="注册"/>
</form>
</div>
);
}
btn(){
let{name,user,pwd,newPwd} =this.state
console.log(user,pwd,name)
if(pwd ===newPwd){
axios.post('/register',{
userName:user,
password:pwd,
realName:name
}).then(res=>{
if(res.data.code == 1){
this.props.history.go(-1)
}
// console.log(res.data)
})
}
}
change(e){
let user = e.target.name
let val =e.target.value
this.setState({
[user]:val
})
}
}
export default Join;
|
'use strict';
function Employee(name) {
this.name = name;
}
function Schedule() {
this.monday = [];
this.tuesday = [];
this.wednesday = [];
this.thursday = [];
this.friday = [];
}
|
// detail.js
var Util = require('../../utils/util.js');
var Api = require('../../utils/api.js');
Page({
data: {
title: '我的',
showEdit: false,
user: {},
logged: false
},
goMyAddr: function (e) {
var url = '../myAddr/myAddr';
wx.navigateTo({
url: url
})
},
goBindPhone: function(e) {
var url = '../bind/bind';
wx.navigateTo({
url: url
})
},
goLogin: function (e) {
var url = '../login/login';
wx.navigateTo({
url: url
})
},
fetchUserInfo: function () {
var that = this;
getApp().doRequest({
url: getApp().config.host + "/get_user_info",
method: "GET",
header: {
"Content-Type": "application/x-www-form-urlencoded",
"token": getApp().globalData.userInfo.token
},
success: function (res) {
that.setData({
user: res.data.data.user,
addrInfo: res.data.data.addr_info
})
}
})
},
uploadAvatar: function () {
var that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
// 返回选定照片的本地文件路径列表,tempFilePath可以作为img标签的src属性显示图片
console.log(res);
var tempFilePaths = res.tempFilePaths
wx.uploadFile({
url: getApp().config.host + '/upload_avatar', //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
method: "POST",
header: {
"Content-Type": "application/x-www-form-urlencoded",
"token": getApp().globalData.userInfo.token
},
name: 'file',
success: function (res) {
console.log(res)
res.data = JSON.parse(res.data)
if (res.data.code != 0) {
wx.showToast({
title: res.data.msg,
icon: 'error',
duration: 1000
})
return
}
wx.showToast({
title: res.data.msg,
icon: 'error',
duration: 1000
})
that.fetchUserInfo();
getApp().globalData.needRefreshHome = true;
},
fail: function (e) {
console.log(e);
},
complete: function () {
console.log("complete");
}
})
}
}
)
},
onTabNickname: function (e) {
console.log(e);
var that = this;
this.setData(
{
showEdit: !this.data.showEdit
}
)
},
bindGenderChange: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setGender(e.detail.value);
},
setGender: function(gender) {
var that=this;
var data = {};
data["gender"] = gender
getApp().doRequest({
url: getApp().config.host + '/edit_user_info',
data: data,
method: 'POST',
header: {
"Content-Type": "application/x-www-form-urlencoded",
"token": getApp().globalData.userInfo.token
},
success: function (res) {
console.log(res, "ssssuccess");
if (res.data.code != 0) {
wx.showToast({
title: res.data.msg,
icon: 'error',
duration: 1000
})
return
}
wx.showToast({
title: res.data.msg,
icon: 'error',
duration: 1000
})
that.fetchUserInfo();
getApp().globalData.needRefreshHome = true;
}
})
},
confirmEdit: function (e) {
var that = this;
var nickname = e.detail.value.nickname;
var data = {};
data["nickname"] = nickname
getApp().doRequest({
url: getApp().config.host + '/edit_user_info',
data: data,
method: 'POST',
header: {
"Content-Type": "application/x-www-form-urlencoded",
"token": getApp().globalData.userInfo.token
},
success: function (res) {
console.log(res, "ssssuccess");
if (res.data.code != 0) {
wx.showToast({
title: res.data.msg,
icon: 'error',
duration: 1000
})
return
}
wx.showToast({
title: res.data.msg,
icon: 'error',
duration: 1000
})
that.onTabNickname();
that.fetchUserInfo();
getApp().globalData.needRefreshHome = true;
}
})
},
touchStartElement: function (e) {
console.log("start", e);
var id = e.currentTarget.id;
this.setData({
activeHoverIndex: id
})
},
touchEndElement: function (e) {
console.log("end", e);
var that = this;
setTimeout(function () {
that.setData({
//warnning undefined==""=="0"==0
activeHoverIndex: "none"
})
}, 500)
},
touchMoveElement: function (e) {
console.log("move", e);
this.setData({
activeHoverIndex: "none"
})
},
onLoad: function (options) {
this.fetchUserInfo();
},
onShow: function () {
if (this.data.chooseAddr) {
this.setData(
{
addrInfo: this.data.chooseAddr
}
)
}
},
onMyAccount: function () {
var url = '../myAccount/myAccount';
wx.navigateTo({
url: url
})
}
})
|
'use strict';
import * as chai from 'chai';
const chaiAsPromised = require('chai-as-promised');
const sinonChai = require('sinon-chai');
const expect = chai.expect;
import * as sinon from 'sinon';
import { List } from 'moonmail-models';
import { RecipientsCounterService } from './recipients_counter_service';
import * as sinonAsPromised from 'sinon-as-promised';
import * as recipientEvents from './fixtures/recipients_dynamo_stream.json';
const awsMock = require('aws-sdk-mock');
const AWS = require('aws-sdk');
chai.use(chaiAsPromised);
chai.use(sinonChai);
describe('RecipientsCounterService', () => {
let recipientsCounterService;
describe('#updateCounters()', () => {
before(() => {
recipientsCounterService = new RecipientsCounterService(recipientEvents);
sinon.stub(List, 'incrementAll').resolves('Ok');
});
it('updates List statistics accordingly', (done) => {
recipientsCounterService.updateCounters().then(() => {
expect(List.incrementAll).to.have.been.called;
done();
});
});
after(() => {
List.incrementAll.restore();
});
});
describe('#_getListIdUserIdMapping()', () => {
before(() => {
recipientsCounterService = new RecipientsCounterService(recipientEvents);
});
it('returns listId and userId mappings from the stream', () => {
expect(recipientsCounterService._getListIdUserIdMapping()).to.deep.equal({ 'my-list': 'user-id', 'my-list2': 'user-id' });
});
});
describe('#_getIncrements()', () => {
before(() => {
recipientsCounterService = new RecipientsCounterService(recipientEvents);
});
it('returns counters for the lists attributes according to events operations', () => {
expect(recipientsCounterService._getIncrements()).to.deep.equal({
'my-list':
{
total: 1,
bouncedCount: 0,
complainedCount: 0,
subscribedCount: 1,
awaitingConfirmationCount: 0,
unsubscribedCount: 0
},
'my-list2':
{
total: 0,
bouncedCount: 0,
complainedCount: 0,
subscribedCount: 0,
awaitingConfirmationCount: 0,
unsubscribedCount: 0
}
});
});
});
});
|
import React, { Component } from 'react';
import Modal from 'react-bootstrap/Modal';
import Nav from 'react-bootstrap/Nav';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Col from 'react-bootstrap/Col'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheckDouble, faExclamation, faEye, faNewspaper, faPenAlt, faPlusCircle, faSyncAlt } from '@fortawesome/free-solid-svg-icons';
import { toDecorType2 } from '../utils/mutils'
import * as MuConstants from '../exports/MuConstants'
class MuSaveStoryModal extends Component {
constructor(props) {
super(props);
this.state = {
jsonTab: false,
titleValidity: '',
pointsValidity: '',
descriptionValidity: ''
}
};
onStoryTab = () => {
this.setState({ jsonTab: false })
}
onJsonTab = () => {
this.setState({ jsonTab: true })
}
onClose = () => {
// Reset the state so it doesn't get sticky
this.setState({ jsonTab: false, titleValidity: '', pointsValidity: '', descriptionValidity: '' })
this.props.onClose();
}
isValidValue = (key, value) => {
var isValid = true;
if (key == MuConstants.STORY_FIELD_TITLE) {
isValid = (value != null && value != '');
this.setState({ titleValidity: isValid ? 'is-valid' : 'is-invalid' });
}
else if (key == MuConstants.STORY_FIELD_DESCRIPTION) {
isValid = (value != null && value != '');
this.setState({ descriptionValidity: isValid ? 'is-valid' : 'is-invalid' });
}
else if (key == MuConstants.STORY_FIELD_POINTS) {
value = Number.parseInt(value);
isValid = (Number.isInteger(value) && value > 0);
this.setState({ pointsValidity: isValid ? 'is-valid' : 'is-invalid' });
}
return isValid;
}
onFormChange = (field, event) => {
var value = event.target.value;
this.isValidValue(field, value);
if (field == MuConstants.STORY_FIELD_POINTS)
value = Number.parseInt(value);
this.props.onChange(field, value);
}
isValidForm = () => {
var isValid;
// Scan fields to be validate
isValid =
this.isValidValue(MuConstants.STORY_FIELD_TITLE, this.props.story.content.title) &&
this.isValidValue(MuConstants.STORY_FIELD_POINTS, this.props.story.content.points) &&
this.isValidValue(MuConstants.STORY_FIELD_DESCRIPTION, this.props.story.content.description);
return isValid;
}
onFormSubmit = () => {
if (this.isValidForm()) {
this.props.onConfirm();
// Reset the state so it doesn't get sticky
this.setState({ jsonTab: false, titleValidity: '', pointsValidity: '', descriptionValidity: '' })
}
}
render() {
const renderStorySaveForm = () => {
return (
<div className={`mu-story border border-${toDecorType2(this.props.header)} bg-white`}
style={{ padding: '20px' }}>
<Form noValidate>
<Form.Row>
<Col>
<Form.Label><strong>Title</strong></Form.Label>
<Form.Control type="text" placeholder="Enter story title"
className={this.state.titleValidity}
readOnly={this.props.action == MuConstants.STORY_ACTION_VIEW ? true : null}
plaintext={this.props.action == MuConstants.STORY_ACTION_VIEW ? true : null}
defaultValue={this.props.story.content.title}
onChange={this.onFormChange.bind(this, 'title')} />
<Form.Control.Feedback type="invalid">
Please enter story title.
</Form.Control.Feedback>
</Col>
<Col xs={3}>
<Form.Label><strong>Story Points</strong></Form.Label>
<Form.Control type="text" placeholder="Points"
className={this.state.pointsValidity}
readOnly={this.props.action == MuConstants.STORY_ACTION_VIEW ? true : null}
plaintext={this.props.action == MuConstants.STORY_ACTION_VIEW ? true : null}
defaultValue={this.props.story.content.points}
onChange={this.onFormChange.bind(this, 'points')} />
<Form.Control.Feedback type="invalid">
Invalid integer.
</Form.Control.Feedback>
</Col>
</Form.Row>
<br />
<Form.Row>
<Col>
<Form.Label><strong>Subtitle</strong></Form.Label>
<Form.Control type="text" placeholder="Enter story subtitle (optional)"
readOnly={this.props.action == MuConstants.STORY_ACTION_VIEW ? true : null}
plaintext={this.props.action == MuConstants.STORY_ACTION_VIEW ? true : null}
defaultValue={this.props.story.content.subtitle}
onChange={this.onFormChange.bind(this, 'subtitle')} />
</Col>
</Form.Row>
<br />
<Form.Row>
<Col>
<Form.Label><strong>Description</strong></Form.Label>
<Form.Control as="textarea" placeholder="Description of the story goes here..."
className={this.state.descriptionValidity}
readOnly={this.props.action == MuConstants.STORY_ACTION_VIEW ? true : null}
plaintext={this.props.action == MuConstants.STORY_ACTION_VIEW ? true : null}
defaultValue={this.props.story.content.description} rows={5}
onChange={this.onFormChange.bind(this, 'description')} />
<Form.Control.Feedback type="invalid">
Please enter story description.
</Form.Control.Feedback>
</Col>
</Form.Row>
</Form>
</div>
)
}
const renderStoryIcon = () => {
// Choose header icon based on the type
if (this.props.header == MuConstants.STORY_HEADER_TODO)
return <FontAwesomeIcon icon={faExclamation} />
else if (this.props.header == MuConstants.STORY_HEADER_INPROGRESS)
return <FontAwesomeIcon icon={faSyncAlt} />
else if (this.props.header == MuConstants.STORY_HEADER_COMPLETED)
return <FontAwesomeIcon icon={faCheckDouble} />
}
const renderStoryCard = () => {
return (
<div className={`mu-story border border-${toDecorType2(this.props.header)} bg-white`}
style={{ padding: '20px' }}>
<span className={`badge badge-${toDecorType2(this.props.header)} float-right`}>
{this.props.story.content.points}
</span>
<h5>{renderStoryIcon()}{this.props.story.content.title}</h5> <hr />
<blockquote className="blockquote"> {this.props.story.content.subtitle} </blockquote>
<p className="lead">{this.props.story.content.description}</p>
</div>
)
}
const renderHeaderIcon = () => {
// Choose header icon based on the type
if (this.props.action == MuConstants.STORY_ACTION_ADD)
return <FontAwesomeIcon icon={faPlusCircle} />
else if (this.props.action == MuConstants.STORY_ACTION_EDIT)
return <FontAwesomeIcon icon={faPenAlt} />
else if (this.props.action == MuConstants.STORY_ACTION_VIEW)
return <FontAwesomeIcon icon={faEye} />
}
const renderModalTitle = () => {
return (
<Modal.Title>
<span className={`badge badge-${toDecorType2(this.props.header)} float-right`}>
{renderHeaderIcon()} {this.props.header}
</span>
</Modal.Title>
)
}
const renderJsonStory = () => {
return (
<div className="border bg-light"
style={{ borderRadius: '5px', padding: '10px' }}>
<pre className="text-dark">
<code>
{JSON.stringify(this.props.story, null, 2)}
</code>
</pre>
</div>
)
}
return (
<Modal show={this.props.show} onHide={this.onClose} scrollable={true}>
<Modal.Header closeButton variant="danger">
{renderModalTitle()}
</Modal.Header>
<Modal.Body>
<Nav variant="tabs" defaultActiveKey="story">
<Nav.Item>
<Nav.Link eventKey="story" onClick={this.onStoryTab}>
<FontAwesomeIcon icon={faNewspaper} />
</Nav.Link>
</Nav.Item>
<Nav.Item>
<Nav.Link eventKey="json" onClick={this.onJsonTab}>
{ }
</Nav.Link>
</Nav.Item>
</Nav>
<br />
{
!this.state.jsonTab
? (this.props.action != MuConstants.STORY_ACTION_VIEW
? renderStorySaveForm()
: renderStoryCard())
: (renderJsonStory())
}
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.onClose}>
Discard
</Button>
{
this.props.action != MuConstants.STORY_ACTION_VIEW &&
<Button variant="primary" onClick={this.onFormSubmit}>
Save
</Button>
}
</Modal.Footer>
</Modal>
);
}
}
export default MuSaveStoryModal; |
import {Login, Register} from './auth';
import {AuthorBlog, AuthorAbstract, ArticleEdit, ArticlePage} from './blog/author-page';
const Blog = () => import('./blog/blog.vue');
const UsersAbstract = () => import('./blog/abstract/abstract.vue');
export default [
{
path: '/blog',
component: Blog,
children: [
{
path: '',
name: 'blog',
component: UsersAbstract,
meta: {
title: '博客'
}
},
{
path: 'author/:userId',
component: AuthorBlog,
children: [
{
path: '',
name: 'author',
component: AuthorAbstract,
meta: {
title: '主页'
}
},
{
path: 'article',
name: 'article',
component: ArticlePage
},
{
path: 'edit',
name: 'edit',
component: ArticleEdit,
meta: {
action: ['needLogin', 'checkUser']
}
}
]
}
]
},
{
path: '/login',
name: 'login',
component: Login,
meta: {
action: ['needUnLogin']
}
},
{
path: '/register',
name: 'register',
component: Register,
meta: {
action: ['needUnLogin']
}
},
{path: '**', redirect: '/blog'}
];
|
import Sequelize from 'sequelize';
import connectionDB from '../../server/database';
const Test = connectionDB.define('test', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true,
allowNull: false
},
categoryId: {
type: Sequelize.INTEGER,
},
name: Sequelize.STRING,
})
export default Test; |
import Annotate from './js/annotate'
export default Annotate
|
tl = new TimelineMax({ paused: true });
tl.to(".menu-left", 1, {
left: 0,
ease: Expo.easeInOut,
});
tl.to(
".menu-right",
1,
{
right: 0,
ease: Expo.easeInOut,
},
"-=1"
);
tl.staggerFrom(
".menu-links > div",
0.8,
{
y: 100,
opacity: 0,
ease: Expo.easeOut,
},
"0.1",
"-=0.4"
);
tl.staggerFrom(
".mail > div, .lavora > div, .socials > div, .footer-privacy-menu > *",
0.8,
{
y: 100,
opacity: 0,
ease: Expo.easeOut,
},
"0.1",
"-=1"
);
tl.from(
".menu-close",
1,
{
scale: 0,
opacity: 1,
ease: Expo.easeInOut,
},
"-=1"
);
tl.to(
".hr",
0.4,
{
scaleY: 1,
transformOrigin: "0% 50%",
ease: Power2.ease,
},
"-=2"
);
tl.reverse();
document.getElementById('menu-open').addEventListener("click", function(){
tl.reversed(!tl.reversed());
})
document.getElementById('menu-close').addEventListener("click", function(){
tl.reversed(!tl.reversed());
})
document.getElementById('getPrivacy').addEventListener("click", function(){
tl.reversed(!tl.reversed());
getPrivacy()
})
document.getElementById('getLegal').addEventListener("click", function(){
tl.reversed(!tl.reversed());
getLegal()
})
//this is the button
var acc = document.getElementsByClassName("acc-block");
var i;
for (i = 0; i < acc.length; i++) {
//when one of the buttons are clicked run this function
acc[i].onclick = function () {
//variables
var panel = this.nextElementSibling;
var coursePanel = document.getElementsByClassName("panel");
var courseAccordion = document.getElementsByClassName("acc-block");
var courseAccordionActive = document.getElementsByClassName("acc-block active");
/*if pannel is already open - minimize*/
if (panel.style.maxHeight) {
//minifies current pannel if already open
panel.style.maxHeight = null;
//removes the 'active' class as toggle didnt work on browsers minus chrome
this.classList.remove("active");
} else { //pannel isnt open...
//goes through the buttons and removes the 'active' css (+ and -)
for (var ii = 0; ii < courseAccordionActive.length; ii++) {
courseAccordionActive[ii].classList.remove("active");
}
//Goes through and removes 'activ' from the css, also minifies any 'panels' that might be open
for (var iii = 0; iii < coursePanel.length; iii++) {
this.classList.remove("active");
coursePanel[iii].style.maxHeight = null;
}
//opens the specified pannel
panel.style.maxHeight = panel.scrollHeight + "px";
//adds the 'active' addition to the css.
this.classList.add("active");
}
}//closing to the acc onclick function
}//closing to the for loop. |
function add(num1,num2=0){
//num2=num2||0;
// if(num2==undefined){
// num2=0;
// }
return num1+num2;
}
const total=add(12);
console.log(total); |
app.controller('DashboardCtrl', function ($q, $scope, $http, ApiService) {
var dashboard = this;
dashboard.currentProduct = 'Please select...';
// dashboard.productList = [];
dashboard.defaultDataValue = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
dashboard.month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
dashboard.labels = dashboard.month;
dashboard.series = ['Amount Expense = PHP', 'Amount Sales = PHP'];
dashboard.data = [];
dashboard.onClick = function (points, evt) {
console.log(points, evt);
};
dashboard.getAllProduct = function () {
dashboard.currentProduct = 'Please select...';
function salesFn() {
var deferred = $q.defer();
var sales = dashboard.defaultDataValue;
ApiService.getData('productsales/').success(function (response) {
if (response.length != 0) {
sales = [];
var data = dashboard.getMonthData(response);
for (var i = 0; i < data.length; i++) {
sales.push(data[i]);
};
}
deferred.resolve(sales);
})
return deferred.promise;
}
var promise = salesFn();
promise.then(function (sales) {
var expense = dashboard.defaultDataValue;
ApiService.getData('productexpense/').success(function (response) {
if (response.length != 0) {
expense = []
var data = dashboard.getMonthData(response);
for (var i = 0; i < data.length; i++) {
expense.push(data[i]);
};
}
dashboard.data = [
expense,
sales,
];
})
})
};
dashboard.getSelectedProduct = function (currentProduct) {
if (currentProduct._id !== undefined) {
function salesFn() {
var deferred = $q.defer();
var sales = dashboard.defaultDataValue;
ApiService.getDataById('productsales/' + currentProduct._id).success(function (response) {
if (response.length != 0) {
sales = [];
var data = dashboard.getMonthData(response);
for (var i = 0; i < data.length; i++) {
sales.push(data[i]);
};
}
deferred.resolve(sales);
})
return deferred.promise;
}
var promise = salesFn();
promise.then(function (sales) {
var expense = dashboard.defaultDataValue;
ApiService.getDataById('productexpense/' + currentProduct._id).success(function (response) {
if (response.length != 0) {
expense = [];
var data = dashboard.getMonthData(response);
for (var i = 0; i < data.length; i++) {
expense.push(data[i]);
};
}
dashboard.data = [
expense,
sales,
];
})
})
}
};
dashboard.getMonthData = function (response) {
var monthValue = { '1': 0, '2': 0, '3': 0, '4': 0, '5': 0, '6': 0, '7': 0, '8': 0, '9': 0, '10': 0, '11': 0, '12': 0 };
response.forEach(function (element) {
var year = dashboard.getYear(element.datePurchased);
if (parseInt(year) === parseInt(dashboard.yearSelected)) {
var month = dashboard.getMonth(element.datePurchased);
var amount = monthValue[month];
amount = amount + element.totalAmount;
monthValue[month] = amount;
}
}, this);
return dashboard.sortArrayByKey(monthValue);
}
dashboard.getMonth = function (date) {
var month = new Date(Date.parse(date)).getUTCMonth();
return month + 1;
// return date.split('-')[1];
}
dashboard.getYear = function (date) {
var year = new Date(Date.parse(date)).getUTCFullYear();
return year;
// return date.split('-')[0];
}
dashboard.sortArrayByKey = function (arr) {
var data = [];
var key = Object.keys(arr);
// var intKey = [];
// for (var i = 0; i < key.length; i++) {
// if (key[i] < key[i + 1]) {
// intKey.push(key[i]);
// } else {
// intKey.push(key[i]);
// }
// }
key.sort(dashboard.sortArrayByValue);
for (var i = 0; i < key.length; i++) {
data.push(arr[key[i]]);
}
return data;
}
dashboard.sortArrayByValue = function (a, b) {
return a - b;
}
dashboard.getProducts = function (callback) {
ApiService.getData('product').success(function (data) {
// dashboard.productList = data;
callback(data);
}
)
};
dashboard.yearSelected = dashboard.getYear(new Date().toISOString()).toString();
dashboard.getYears = function (callback) {
var years = [];
ApiService.getData('product').success(function (response) {
response.forEach(function (element) {
var year = dashboard.getYear(element.datePurchased);
year = year + '';
if (years.indexOf(year) < 0) {
years.push('' + year);
}
}, this);
years.sort(dashboard.sortArrayByValue);
callback(years);
}
)
}
if (angular.isUndefined(dashboard.currentProduct._id)) {
dashboard.getAllProduct();
}
});
|
import Map from './Map.vue'
jest.mock('mapbox-gl/dist/mapbox-gl', () => ({
Map: jest.fn(),
Marker: jest.fn().mockReturnValue({
setLngLat: jest.fn().mockReturnValue({
setPopup: jest.fn().mockReturnValue({
addTo: jest.fn().mockReturnValue({}),
}),
}),
}),
Popup: jest.fn().mockReturnValue({
setHTML: jest.fn().mockReturnValue({ on: jest.fn() }),
}),
}))
describe.skip('Map', () => {
it('should match snapshot', () => {
// When
const wrapper = shallowMount(Map)
// Then
expect(wrapper).toMatchSnapshot()
})
})
|
import { combineReducers } from 'redux';
import articles from './reducers/articles';
import authUser from './reducers/authUser';
import common from './reducers/common';
import { routerReducer } from 'react-router-redux';
// combineReducers function from redux used to combine our reducers into single reducer function
// With this combination of reducers into one reducer function, it will be used as an argument to
// create our store using redux’s createStore function.
export default combineReducers({
articles,
authUser,
common,
router: routerReducer
}); |
import * as React from "react";
import Select from "../../Select";
import { format, addDays, isDate } from "date-fns";
export default class createProjectForm extends React.Component {
state = {
topic: "",
brief: "",
format: "blog",
industry: "finance",
word_count: "00,000",
formats: [
{
"value": "blog",
"text": "Blog Posts"
},
{
"value": "page",
"text": "Website Pages"
},
],
industrials: [
{
"value": "finance",
"industry_name": "Finance / Insurance: Tax, Banking, Economy",
"text": "Finance / Insurance"
},
{
"value": "im",
"industry_name": "Internet Marketing: SEO, SEM, CRO, E-comm, Social, Blogging",
"text": "Internet Marketing"
},
]
};
render() {
const { date } = this.props;
const orderOnDate = isDate(date) ? format(date, "YYYY-MM-DD") : "";
const plannedDate = isDate(date) ? format(addDays(date, 5), "YYYY-MM-DD") : "";
const { formats, industrials, word_count } = this.state;
// return (
// <div className="popup-add popup" style={{ display: open ? "block" : "none" }}>
// <div className="popup-inner">
// <div className="popup-close" onClick={close}></div>
// <div className="popup-title">Add project</div>
// <div className="popup-body">
// <form onSubmit={this.onSubmit}>
// <div className="form-input">
// <label htmlFor="topic">Project topic*</label>
// <input required type="text" id="topic" name="topic" placeholder="Lorem ipsum dolor" onChange={this.handleChange} />
// </div>
// <div className="form-input">
// <label htmlFor="brief">Project brief</label>
// <textarea required onChange={this.handleChange} name="brief" id="brief" defaultValue="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."/>
// </div>
// <div className="form-input form-input__file">
// <input type="file" id="file" name="attach" placeholder="Lorem ipsum dolor" />
// <label htmlFor="file">Attach files</label>
// </div>
// <div className="form-input form-input-flex">
// <div className="form-input-3">
// <label htmlFor="format">Format</label>
// <select onChange={this.handleChange} name="format" id="format">
// <option value="blog">Blog Posts</option>
// <option value="page">Website Pages</option>
// </select>
// </div>
// <div className="form-input-2">
// <label htmlFor="word_count">Word count</label>
// <input required onChange={this.handleChange} type="text" name="word_count"/>
// </div>
// <div className="form-input-5">
// <label htmlFor="industry">Compaing</label>
// <select name="industry" id="industry">
// <option value="finance">Finance / Insurance</option>
// <option value="im">Internet Marketing</option>
// </select>
// </div>
// </div>
// <div className="form-input form-input-flex">
// <div className="form-input-33">
// <label htmlFor="Order on">Order on</label>
// <input type="date" name="Order on" id="Order on" defaultValue={date}/>
// </div>
// <div className="form-input-33">
// <label htmlFor="Planned_publish">Planned publish</label>
// <input type="date" name="Planned_publish" id="Planned_publish" />
// </div>
// <div className="form-input-33">
// <label htmlFor="Time">Time</label>
// <input type="date" name="Time" id="Time" />
// </div>
// </div>
// <div className="form-input-flex form-input-submit">
// <input type="submit" value="Save draft" />
// <button type="submit" name="Order">Order</button >
// </div>
// </form>
// </div>
// </div>
// </div>
// )
return (
<form onSubmit={this.onSubmit}>
<div className="form-input">
<label htmlFor="topic">Project topic*</label>
<input type="text" id="topic" name="topic" placeholder="Lorem ipsum dolor"
className="error" onChange={this.handleChange} />
</div>
<div className="form-input">
<label htmlFor="brief">Project brief</label>
<textarea onChange={this.handleChange} name="brief" id="brief" defaultValue="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat." />
</div>
<div className="form-input form-input__file">
<input type="file" id="file" name="attach" placeholder="Lorem ipsum dolor"/>
<label htmlFor="file">Attach files</label>
</div>
<div className="form-input form-input-flex">
<div className="form-input-3 dropdown-form-input">
<div className="label">Format</div>
<Select options={formats} />
</div>
<div className="form-input-2">
<label htmlFor="word_count">Word count</label>
<input value={word_count} name="word_count" onChange={this.onWordCountChange} />
</div>
<div className="form-input-5 dropdown-form-input">
<div className="label">Campaign</div>
<Select options={industrials}/>
</div>
</div>
<div className="form-input form-input-flex">
<div className="form-input-33">
<label htmlFor="Orderon">Order on</label>
<div className="input date">
<input type="text" className="js-date" name="Order_on" id="Order_on"
value={orderOnDate} />
</div>
</div>
<div className="form-input-33">
<label htmlFor="Planned_publish">Planned publish</label>
<div className="input date">
<input type="text" className="js-date" name="Planned_publish"
id="Planned_publish" value={plannedDate} />
</div>
</div>
<div className="form-input-33">
<label htmlFor="Time">Time</label>
<div className="input time">
<input type="text" className="js-time" name="Time" id="Time" defaultValue="12:00" />
</div>
</div>
</div>
<div className="form-input-help">
Too soon <img src="img/help.png" alt="help" />
</div>
<div className="form-input-flex form-input-submit">
<input type="submit" value="Save draft" className="button_filter" />
<button type="submit" name="Order">Order</button>
</div>
</form>
)
}
handleChange = (ev) => {
const target = ev.target;
this.setState({ [target.name]: target.value })
};
onWordCountChange = (ev) => {
const target = ev.target;
let value = target.value.replace(",", "");
if (+value || !value) {
if (value.length > 3) {
const startSlice = value.length - 3;
value = value.slice(0, startSlice) + "," + value.slice(-3)
}
this.setState({ word_count: value })
}
};
onSubmit = (ev) => {
ev.preventDefault();
// const { topic, brief, format, industry, word_count } = this.state;
const { close } = this.props;
// const data = {
// level: "standard",
// match: "no",
// turnaround: "regular",
// localization: "us",
// topic, brief, format, industry, word_count
// };
// createProject(data);
close();
}
} |
'use strict';
var Pg = require('pg');
var Hoek = require('hoek');
var Sql = require('./sql-templates.js');
const internals = {};
internals.bigintOid = 20;
internals.defaults = {
host: 'localhost',
port: 5432,
verbose: false,
dataType: 'jsonb'
};
Pg.types.setTypeParser(internals.bigintOid, function(n) {
return parseInt(n, 10);
});
exports = module.exports = internals.Connection = function PostgresCache(options) {
Hoek.assert(this.constructor === internals.Connection, 'Postgres cache client must be instantiated using new');
this.settings = Hoek.applyToDefaults(internals.defaults, options || {});
this.settings.verbose = !!this.settings.verbose;
this.settings.unlogged = !!this.settings.unlogged;
Hoek.assert(this.settings.dataType === 'json' || this.settings.dataType === 'jsonb', 'dataType must be either "json" or "jsonb"');
this._tableIsReady = false;
this._clientPoolIsReady = false;
internals.connectionConfig = {
host: this.settings.host,
port: this.settings.port,
database: this.settings.partition,
user: this.settings.user,
password: this.settings.password
};
};
internals.Connection.prototype.start = function (callback) {
var that = this;
// creates a pool of clients when called for the first time
// TODO: (?) create a dedicated pool, such that we can reuse the pg module in other parts
// of the app without interfering with each other
Pg.connect(internals.connectionConfig, function(err, pgClient, done) {
if (err) {
return callback(err);
}
if (that.settings.verbose){
internals.addListener.call(that, pgClient);
}
// verify if the pg version is compatible (>= 9.5)
pgClient.query('SHOW server_version;', function(err, result) {
if (err) {
return callback(err);
}
var version = result.rows[0]['server_version'];
pgClient.emit('notice', 'postgres version: ' + version)
var a = version.split('.');
if(Number(a[0]) < 9){
return callback(new Error('catbox-postgres requires postgres 9.5 or higher'))
}
if(Number(a[0]) === 9 && Number(a[1]) < 5){
return callback(new Error('catbox-postgres requires postgres 9.5 or higher'))
}
// make sure the pool has been created
var key = JSON.stringify(internals.connectionConfig);
that._clientPoolIsReady = !!Pg.pools.all[key];
done();
return callback(null);
});
});
};
internals.Connection.prototype.isReady = function () {
return this._clientPoolIsReady && this._tableIsReady;
};
internals.Connection.prototype.stop = function () {
// todo: what if we are sharing the pg module with other parts of the application?
// we should close only all the client from our pool
console.log("stop() - to be done");
//Pg.end();
};
// called once (in the policy constructor); this is where we create the table,
// if it doesn't exists
internals.Connection.prototype.validateSegmentName = function (name) {
if (!name) {
return new Error('Empty string');
}
if (name.indexOf('\u0000') !== -1) {
return new Error('Includes null character');
}
if (name.length > 63) {
return new Error('Postgres identifiers must be less than 64 characters (segment is the name of the table)');
}
if (!/[a-zA-Z_]/.test(name.charAt(0))) {
return new Error('Postgres identifiers must begin with a letter or an underscore (segment is the name of the table)');
}
// is there any other significant limitations of postgres identifiers that
// should be handled here?
// https://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS
// we should take into account theses cases as well:
// "The default value for segment when server.cache is called inside of a plugin will be '!pluginName'. When creating server methods, the segment value will be '#methodName'.
internals.createTable.call(this, name);
return null;
};
/*
Postgres doesn't have an "expire" statement like redis or other databases;
so we check if the value is stale in the "get" method, just after it is
retrieved from the database; if so we call an auxiliary postgres function
which will call the sql command delete on that row;
to avoid race conditions this function will
-create a row lock
-check if the value is actually stalled
-actually delete
select from ...
if Date.now() - stored > ttl
select * from begin transaction; select for update; delete from ... end transaction;
In addition to this, we must have a query that is executed periodically
to delete values that have become stalled meanwhile
TODO: how to avoid sql injection?
*/
internals.Connection.prototype.get = function (key, callback) {
var that = this;
Pg.connect(internals.connectionConfig, function(err, pgClient, done) {
if (err) {
return callback(err);
}
if (that.settings.verbose){
internals.addListener.call(that, pgClient);
}
// TODO: use json stringify from pg-promise for
var selectQuery = Sql.select(key.segment, key.id);
console.log(selectQuery);
pgClient.query(selectQuery, function(err, result) {
if (err || result.rows.length===0) {
done();
return callback(err || null, null);
}
// result.rows.length must be 1
var row = result.rows[0];
if(Date.now() - row.stored <= row.ttl){
done();
return callback(null, row);
}
// TODO: we should also have a timer with setInterval to peiodically delete
// stalled items
var deleteQuery = Sql.deleteCautiously(key.segment, key.id, row.stored);
console.log(deleteQuery);
pgClient.query(deleteQuery, function(err) {
done();
});
return callback(null, null);
});
});
};
internals.Connection.prototype.set = function (key, value, ttl, callback) {
var that = this;
Pg.connect(internals.connectionConfig, function(err, pgClient, done) {
if (err) {
return callback(err);
}
if (that.settings.verbose){
internals.addListener.call(that, pgClient);
}
// TODO: use json stringify from pg-promise for the value (to handle issues with quotations, etc)
var stored = Date.now();
var jsonValue = JSON.stringify(value).replace(/'/g, "''");
var upsertQuery = Sql.upsert(key.segment, key.id, jsonValue, stored, ttl);
console.log(upsertQuery);
pgClient.query(upsertQuery, function(err, result) {
if (err) {
return callback(err);
}
if(result.rows.length!==1){
return callback(new Error('value was not set'));
}
done();
// TODO: in the other catbox clients (redis, mongo, etc) -
// this callback should always be called
return callback();
});
});
};
// note: catbox's method "drop" is competely different from postgres' command "drop"
internals.Connection.prototype.drop = function (key, callback) {
var that = this;
Pg.connect(internals.connectionConfig, function(err, pgClient, done) {
if (err) {
return callback(err);
}
if (that.settings.verbose){
internals.addListener.call(that, pgClient);
}
var deleteQuery = Sql['delete'](key.segment, key.id);
console.log(deleteQuery);
pgClient.query(deleteQuery, function(err) {
if (err) {
return callback(err);
}
done();
return callback(null);
});
});
};
internals.pgErrorCodes = {
'42P07': ' (relation already exists, skipping)'
};
internals.addListener = function(pgClient){
if (pgClient.listenerCount('notice') === 0) {
pgClient.on('notice', function(obj) {
var output = '';
if(typeof obj === 'object' && obj.code){
var description = internals.pgErrorCodes[obj.code];
output = 'NOTICE: error code ' + obj.code + (description || '');
}
else if(typeof obj === 'string'){
output = obj;
}
else{
output = JSON.stringify(obj);
}
console.log(output);
});
}
};
internals.createTable = function(tableName){
var that = this;
// the next call to Pg.connect is almost surely syncronous because the pool
// should have 1 client available when the method is called
Pg.connect(internals.connectionConfig, function(err, pgClient, done) {
if (err) {
throw err;
}
if (that.settings.verbose){
internals.addListener.call(that, pgClient);
}
var createTableQuery = Sql.createTable(tableName, that.settings.dataType, that.settings.unlogged);
console.log(createTableQuery);
pgClient.query(createTableQuery, function(err, result) {
if (err) {
throw err;
}
done();
// calls to .get/.set/.drop can only be made after we have
// _tableIsReady === true
that._tableIsReady = true;
});
});
};
|
export default {
immutable: true,
html: `<div><h3>Called 0 times.</h3></div>`,
test({ assert, component, target, window }) {
component.$on('state', ({ changed }) => {
if (changed.foo) {
component.count = component.count + 1;
}
});
assert.htmlEqual(target.innerHTML, `<div><h3>Called 0 times.</h3></div>`);
component.foo = component.foo;
assert.htmlEqual(target.innerHTML, `<div><h3>Called 0 times.</h3></div>`);
}
};
|
export const normalizeDate = timestamp =>
handleNormalize(new Date(), new Date(timestamp))
const buildDateStructure = arrayOfDates =>
arrayOfDates.map(date => {
date.year = date.getFullYear()
date.month = date.getMonth()
date.day = date.getDate()
date.hours = date.getHours()
date.minutes = date.getMinutes()
return date
})
const compareDates = (current, post) => {
if(current.year - post.year != 0) return wasPostedIn(current.year - post.year, 'years')
if(current.month != post.month) return wasPostedIn(current.month - post.month, 'months')
if(current.month === post.month && current.day != post.day) return wasPostedIn(current.day - post.day, 'days')
if(current.day === post.day && current.hours != post.hours) return wasPostedIn(current.hours - post.hours, 'hours')
if(current.hours === post.hours) return wasPostedIn(current.minutes - post.minutes, 'minutes')
if(current.minutes === post.minutes) return wasPostedIn(0, 'minutes')
return wasPostedIn(-1, null)
}
const handleNormalize = (currentDate, postDate) => {
const [current, post] = buildDateStructure([currentDate, postDate])
return compareDates(current, post)
}
const wasPostedIn = (value, time) =>
value >= 0
? `${value} ${time} ago`
: 'no date available'
|
$(function () {
new ConvertionSliders({
min: 0,
max: 97,
init_value: 52,
slider: '#m-slider',
amount: '#m-amount',
cache_container: 'meters_feet',
api_endpoint: '/meters_to_feet',
api_field: 'meters'
}, {
min: 0,
max: 320,
init_value: 171,
slider: '#ft-slider',
amount: '#ft-amount',
cache_container: 'feet_meters',
api_endpoint: '/feet_to_meters',
api_field: 'feet'
}
).render();
});
|
import notePreview from './note-preview.js'
export default {
props: ['notes'],
template: `
<section class="note-list-container">
<h3 v-if="pinnedNotes.length">Pinned</h3>
<div class="note-list" >
<note-preview
v-for="note in pinnedNotes"
v-if="pinnedNotes.length"
:key="note.id"
:note="note"/>
</div>
<!--------- Seperate between Pinned and not Pinned notes -------------- -->
<h3 v-if="otherNotes.length && pinnedNotes.length">Notes</h3>
<div class="note-list" >
<note-preview
v-for="note in otherNotes"
v-if="otherNotes"
:key="note.id"
:note="note"/>
</div>
</section>
`,
computed: {
pinnedNotes() {
return this.notes.filter(note => note.isPinned)
},
otherNotes() {
return this.notes.filter(note => !note.isPinned)
}
},
components: {
notePreview
},
}
|
/**
* 本来 san 提供了 san.parseExpr 接口,但是没有开放 san.evalExpr 接口 :-(
*
* @file san-xui/x/forms/ExpressionEvaluator.js
* @author leeight
*/
import _ from 'lodash';
function expressionComparison(oper, expectedValue, realValue) {
switch (oper) {
case '$contains':
return _.includes(realValue, expectedValue);
case '$in':
return _.indexOf(expectedValue, realValue) !== -1;
case '$nin':
return _.indexOf(expectedValue, realValue) === -1;
case '$eq':
return expectedValue === realValue;
case '$ne':
return expectedValue !== realValue;
case '$gt':
return realValue > expectedValue;
case '$lt':
return realValue < expectedValue;
case '$gte':
return realValue >= expectedValue;
case '$lte':
return realValue <= expectedValue;
default:
return false;
}
}
/**
* 计算一个表达式的值
*
* @param {string|Object|Array.<Object>} expression The expression.
* @param {Object} scope The value scope.
* @return {boolean}
*/
export function evalExpr(expression, scope) {
if (!expression) {
return true;
}
if (_.isString(expression)) {
return !!scope.get(expression);
}
if (_.isArray(expression)) {
for (let i = 0, subExpr; subExpr = expression[i]; i++) {
if (evalExpr(subExpr, scope)) {
return true;
}
}
return false;
}
// {
// a: <value>
// b: {
// <oper1>: <value>,
// <oper2>: <value>,
// <oper3>: <value>
// }
// }
// <oper>: [$in, $nin, $eq, $ne, $gt, $lt, $gte, $lte]
// 如果计算的过程中,有任何一个值是 false,那么就停止计算,返回 false,否则返回 true
const keys = _.keys(expression);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const realValue = scope.get(key);
const value = expression[key];
if (_.isPlainObject(value)) {
const opers = _.keys(value);
for (let j = 0; j < opers.length; j++) {
const oper = opers[j];
const expectedValue = value[oper];
if (!expressionComparison(oper, expectedValue, realValue)) {
return false;
}
}
}
else {
// 如果没有 <oper>,实际上等于
// a: {
// $eq: <value>
// }
const expectedValue = value;
if (!expressionComparison('$eq', expectedValue, realValue)) {
return false;
}
}
}
return true;
}
|
var jwt = require('jwt-simple'); // libreria de encriptacion para generar token
var moment = require('moment'); // para tratar fechas de modo más amigable
var secret = 'clave_secreta_curso'; // clave que se usa en el algoritmo de encriptación
// generar token exclusivo y asociado a cada usuario
createToken = function(user){
// parámetros que vamos a utilizar para generar el token
// normalmente solo necesitaríamos el id de usuario referente al user
var payload = {
sub: user._id,
iat: moment().unix(), // fecha de creación del token, en timestamp en formato unix
exp: moment().add(7, 'days').unix(), // tiempo de expiración del token
};
return jwt.encode(payload, secret)
};
module.exports = {
createToken
}
|
'use strict';
const chai = require('chai');
chai.should();
const request = require('supertest');
const app = require('../../server/app');
describe('App on /ping', () => {
it('should be responded as 200 for get', (done) => {
request(app)
.get('/ping')
.expect(200, done);
});
it('should be responded as 404 for post', (done) => {
request(app)
.post('/ping')
.expect(404, done);
});
});
|
var tests = [];
for (var file in window.__karma__.files) {
if (/Tests\.js$/.test(file)) {
tests.push(file);
}
}
requirejs.config({
// Karma serves files from '/base'
baseUrl: '/base/scripts',
paths: {
'jquery': 'libs/jquery.min',
'underscore': 'libs/underscore',
'logic': 'crowdChat/logic',
'ui' : 'crowdChat/ui',
'httpRequest' : 'crowdChat/httpRequest'
},
shim: {
'underscore': {
exports: '_'
}
},
// ask Require.js to load these files (all our tests)
deps: tests,
// start test run, once Require.js is done
callback: window.__karma__.start
});
|
'use strict';
const config = require('../../config');
const controller = require('./baseController');
const Header = require('../models/Header');
controller.addHeader = (req, res) => {
let params = {};
const {name, category} = req.body;
params.name = name;
params.category = category;
Header.saveHeader(params, (err, header) => {
if (err) return res.json({
success: false,
err: err
});
res.json({
success: true,
header: header
});
});
};
controller.updateHeader = (req, res) => {
let params = req.body;
let id = req.body.id;
Header.updateHeader(id, params, (err, newHeader) => {
if (err) return res.json({
success: false,
err: err
}); else {
if (newHeader == null) return res.json({
success: false,
msg: 'header not found'
});
res.json({
success: true,
msg: 'header is update!!',
newHeader: newHeader
});
}
});
};
controller.deleteHeader = (req, res) => {
let id = req.body.id;
Header.deleteHeader(id, (err, header) => {
if (err) return res.json({
success: false,
err: err
}); else {
if (header == null) return res.json({
success: false,
msg: 'header not found'
});
res.json({
success: true,
msg: 'header is deleted !'
});
}
});
};
controller.getAllHeader = (req, res) => {
Header.findAllHeader((headers, err) => {
if (err) {
return res.json({
success: false,
err: err
})
} else {
res.json({
success: true,
headers: headers
})
}
})
};
module.exports = controller;
|
import axios from 'axios';
import * as actions from './types';
import {returnMessage} from './messageActions';
import {setContentLoading} from './contentActions';
export const getExpenses = (year_number,month_name,category_name,user_id) => (dispatch) => {
const action = 'expense';
dispatch(setContentLoading(action));
axios
.get(`/api/expense/${year_number}/${month_name}/${category_name}/${user_id}`)
.then(res => {
dispatch({
type: actions.GET_EXPENSES,
payload: res.data
})
})
.catch(err => {
dispatch(returnMessage(err.response.data, err.response.status));
});
}
export const addExpense = (newExpense) => (dispatch) => {
axios
.post('/api/expense',newExpense)
.then(res => {
dispatch({
type: actions.ADD_EXPENSE,
payload: res.data
})
})
.catch(err => {
dispatch(returnMessage(err.response.data, err.response.status, 'ADD_EXPENSE_FAIL'));
dispatch({
type: actions.ADD_EXPENSE_FAIL
})
});
}
export const deleteExpense = (id) => (dispatch) => {
axios
.delete(`/api/expense/${id}`)
.then(res => {
dispatch({
type: actions.DELETE_EXPENSE,
payload: id
})
})
.catch(err => {
dispatch(returnMessage(err.response.data, err.response.status));
})
} |
window.onload = function() {
var oMenu = document.getElementById("menu");
var aImg = oMenu.getElementsByTagName("img");
// var iScale = 2;
// var imgWidth = aImg[0].offsetWidth;
// var imgHeight = aImg[0].offsetHeight;
// for (var i = 0; i < aImg.length; i++) {
// aImg[i].style.width = imgWidth/iScale + "px";
// aImg[i].style.height = imgHeight/iScale + "px";
// aImg[i].onmouseover = function() {
// this.style.width = imgWidth + "px";
// this.style.height = imgHeight + "px";
// }
// aImg[i].onmouseout = function() {
// this.style.width = imgWidth/iScale + "px";
// this.style.height = imgHeight/iScale + "px";
// }
// };
var aWidth = [];
//保存原宽度,并设置当前宽度
for (var i = 0; i < aImg.length; i++) {
aWidth.push(aImg[i].offsetWidth);
aImg[i].width = parseInt(aImg[i].offsetWidth/2);
};
//鼠标移动事件
document.onmousemove = function(event){
var event = event || window.event;
for (var i = 0; i < aImg.length; i++) {
var a = event.clientX - aImg[i].offsetLeft - aImg[i].offsetWidth / 2;
var b = event.clientY - aImg[i].offsetTop - oMenu.offsetTop - aImg[i].offsetHeight / 2;
var iScale = 1 - Math.sqrt(a * a + b * b) / 300;
if(iScale < 0.5) iScale = 0.5;
aImg[i].width = aWidth[i] * iScale
};
}
} |
import { expect, sinon } from '../test-helper'
import GetArticlesMeta from '../../src/use_cases/get-articles-meta'
import ArticleRepository from '../../src/domain/repositories/article-repository'
import ChapterRepository from '../../src/domain/repositories/chapter-repository'
import PhotoRepository from '../../src/domain/repositories/photo-repository'
import chapterOfArticle from '../fixtures/chapterOfArticleSaved'
import photosOfArticle from '../fixtures/photoOfArticleSaved'
import articles from '../fixtures/articlesWithSharedLink'
describe('Unit | GetArticlesMeta | getAll()', () => {
beforeEach(() => {
sinon.stub(ArticleRepository, 'getAll').returns(articles())
sinon.stub(ChapterRepository, 'getChaptersOfArticle').returns(chapterOfArticle())
sinon.stub(PhotoRepository, 'getPhotosOfArticle').returns(photosOfArticle())
})
afterEach(() => {
ArticleRepository.getAll.restore()
ChapterRepository.getChaptersOfArticle.restore()
PhotoRepository.getPhotosOfArticle.restore()
})
it('should call ArticleRepository to getAll articles', async () => {
// when
await GetArticlesMeta.getAll()
// then
expect(ArticleRepository.getAll).to.have.been.calledWith()
expect(ChapterRepository.getChaptersOfArticle).to.have.been.callCount(3)
expect(PhotoRepository.getPhotosOfArticle).to.have.been.callCount(3)
})
// it.only('should return result', async (done) => {
// // when
// const articlesMeta = await GetArticlesMeta.getAll()
//
// console.log('here')
//
// // then
// return articlesMeta.map(promise => {
// return Promise.resolve(promise).then(x => {
// console.log(x)
//
// expect(x).to.eq('toto')
// })
// })
// // expect(articlesMeta).to.eqls([])
// })
})
|
//Created by VIMRIO helper
//Please rename XXX.
//For example. If current final stage is 013, this function's name is "initStage014" and save "stage014.js".
function initStage009(stage){
var item;
// Percent of one unit. if you want to change unit size, change this.
var u=7;
/////Animation Parameter/////
//
//dsp :display (true/false) startIndex.... display or hide
//x : position x (percent)
//y : position y (percent)
//w : width (percent)
//h : height (percent)
//bgc : background-color
//bdc : border-color
//img : background-image (filename)
//opc : opacity (0.0....1.0) default=1.0
//z : z-index (default=2)
//wd : character of word
//Answer String
//helper original string=hjjw"vim "w"is best"jjw"for you"jjb"it "b"do "b"can "b"I "jjw"this "w"is mine"jjb"up"b"cheer "jjw"favorite one"kk
stage.setAnsStr("hjjwwjjwjjbbbbjjwwjjbbjjwkk");
item=stage.createNewItem();
//class name
item.setName("vimrio");
//frame offset. default startindex=0
item.setFrameStartIndex(0);
stage.addItem(item);
//first frame
//1 start
item.addAnimation({"dsp":true,"x":1*u,"y":1*u,"w":u,"h":u,"bgc":"transparent","bdc":"blue","img":"vimrio01.png","z":5,"opc":1.0,"wd":""});
//following next frames
//2 h
item.addAnimation({"x":0*u});
//3 j
item.addAnimation({"y":2*u});
//4 j
item.addAnimation({"y":3*u});
//5 w
item.addAnimation({"x":4*u});
//6 w
item.addAnimation({"x":7*u});
//7 j
item.addAnimation({"y":4*u});
//8 j
item.addAnimation({"y":5*u});
//9 w
item.addAnimation({"x":11*u});
//10 j
item.addAnimation({"y":6*u});
//11 j
item.addAnimation({"y":7*u});
//12 b
item.addAnimation({"x":9*u});
//13 b
item.addAnimation({"x":6*u});
//14 b
item.addAnimation({"x":2*u});
//15 b
item.addAnimation({"x":0*u});
//16 j
item.addAnimation({"y":8*u});
//17 j
item.addAnimation({"y":9*u});
//18 w
item.addAnimation({"x":5*u});
//19 w
item.addAnimation({"x":8*u});
//20 j
item.addAnimation({"y":10*u});
//21 j
item.addAnimation({"y":11*u});
//22 b
item.addAnimation({"x":7*u});
//23 b
item.addAnimation({"x":1*u});
//24 j
item.addAnimation({"y":12*u});
//25 j
item.addAnimation({"y":13*u});
//26 w
item.addAnimation({"x":10*u});
//27 k
item.addAnimation({"y":12*u});
//28 k
item.addAnimation({"y":11*u});
//1 goal
item=stage.createNewItem();
item.setName("goal");
item.addAnimation({"dsp":true,"x":10*u,"y":11*u,"w":u,"h":u,"img":"goal01.png","bgc":"yellow","bdc":"yellow"});
stage.addItem(item);
//word "vim " [v] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":0*u,"y":3*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"v"});
stage.addItem(item);
//word "vim " [i] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":1*u,"y":3*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"i"});
stage.addItem(item);
//word "vim " [m] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":2*u,"y":3*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"m"});
stage.addItem(item);
//word "vim " [ ] 4
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":3*u,"y":3*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "is best" [i] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":4*u,"y":3*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"i"});
stage.addItem(item);
//word "is best" [s] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":5*u,"y":3*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"s"});
stage.addItem(item);
//word "is best" [ ] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":6*u,"y":3*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "is best" [b] 4
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":7*u,"y":3*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"b"});
stage.addItem(item);
//word "is best" [e] 5
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":8*u,"y":3*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"e"});
stage.addItem(item);
//word "is best" [s] 6
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":9*u,"y":3*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"s"});
stage.addItem(item);
//word "is best" [t] 7
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":10*u,"y":3*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"t"});
stage.addItem(item);
//word "for you" [f] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":7*u,"y":5*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"f"});
stage.addItem(item);
//word "for you" [o] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":8*u,"y":5*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"o"});
stage.addItem(item);
//word "for you" [r] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":9*u,"y":5*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"r"});
stage.addItem(item);
//word "for you" [ ] 4
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":10*u,"y":5*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "for you" [y] 5
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":11*u,"y":5*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"y"});
stage.addItem(item);
//word "for you" [o] 6
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":12*u,"y":5*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"o"});
stage.addItem(item);
//word "for you" [u] 7
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":13*u,"y":5*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"u"});
stage.addItem(item);
//word "it " [ ] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":11*u,"y":7*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "it " [t] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":10*u,"y":7*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"t"});
stage.addItem(item);
//word "it " [i] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":9*u,"y":7*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"i"});
stage.addItem(item);
//word "do " [ ] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":8*u,"y":7*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "do " [o] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":7*u,"y":7*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"o"});
stage.addItem(item);
//word "do " [d] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":6*u,"y":7*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"d"});
stage.addItem(item);
//word "can " [ ] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":5*u,"y":7*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "can " [n] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":4*u,"y":7*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"n"});
stage.addItem(item);
//word "can " [a] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":3*u,"y":7*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"a"});
stage.addItem(item);
//word "can " [c] 4
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":2*u,"y":7*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"c"});
stage.addItem(item);
//word "I " [ ] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":1*u,"y":7*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "I " [I] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":0*u,"y":7*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"I"});
stage.addItem(item);
//word "this " [t] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":0*u,"y":9*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"t"});
stage.addItem(item);
//word "this " [h] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":1*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"h"});
stage.addItem(item);
//word "this " [i] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":2*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"i"});
stage.addItem(item);
//word "this " [s] 4
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":3*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"s"});
stage.addItem(item);
//word "this " [ ] 5
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":4*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "is mine" [i] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":5*u,"y":9*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"i"});
stage.addItem(item);
//word "is mine" [s] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":6*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"s"});
stage.addItem(item);
//word "is mine" [ ] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":7*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "is mine" [m] 4
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":8*u,"y":9*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"m"});
stage.addItem(item);
//word "is mine" [i] 5
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":9*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"i"});
stage.addItem(item);
//word "is mine" [n] 6
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":10*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"n"});
stage.addItem(item);
//word "is mine" [e] 7
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":11*u,"y":9*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"e"});
stage.addItem(item);
//word "up" [p] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":8*u,"y":11*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"p"});
stage.addItem(item);
//word "up" [u] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":7*u,"y":11*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"u"});
stage.addItem(item);
//word "cheer " [ ] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":6*u,"y":11*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "cheer " [r] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":5*u,"y":11*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"r"});
stage.addItem(item);
//word "cheer " [e] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":4*u,"y":11*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"e"});
stage.addItem(item);
//word "cheer " [e] 4
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":3*u,"y":11*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"e"});
stage.addItem(item);
//word "cheer " [h] 5
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":2*u,"y":11*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"h"});
stage.addItem(item);
//word "cheer " [c] 6
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":1*u,"y":11*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"c"});
stage.addItem(item);
//word "favorite one" [f] 1
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":1*u,"y":13*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"f"});
stage.addItem(item);
//word "favorite one" [a] 2
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":2*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"a"});
stage.addItem(item);
//word "favorite one" [v] 3
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":3*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"v"});
stage.addItem(item);
//word "favorite one" [o] 4
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":4*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"o"});
stage.addItem(item);
//word "favorite one" [r] 5
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":5*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"r"});
stage.addItem(item);
//word "favorite one" [i] 6
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":6*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"i"});
stage.addItem(item);
//word "favorite one" [t] 7
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":7*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"t"});
stage.addItem(item);
//word "favorite one" [e] 8
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":8*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"e"});
stage.addItem(item);
//word "favorite one" [ ] 9
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":9*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":" "});
stage.addItem(item);
//word "favorite one" [o] 10
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":10*u,"y":13*u,"w":u,"h":u,"img":"word01.png","bgc":"transparent","bdc":"white","wd":"o"});
stage.addItem(item);
//word "favorite one" [n] 11
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":11*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"n"});
stage.addItem(item);
//word "favorite one" [e] 12
item=stage.createNewItem();
item.setName("word");
item.addAnimation({"dsp":true,"x":12*u,"y":13*u,"w":u,"h":u,"img":"word02.png","bgc":"transparent","bdc":"lightgray","wd":"e"});
stage.addItem(item);
//wall 1
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":0*u,"y":0*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 2
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":1*u,"y":0*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 3
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":0*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 4
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":1*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 5
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":1*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 6
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 7
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":3*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 8
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":4*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 9
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":5*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 10
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":6*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 11
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":7*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 12
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":8*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 13
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":9*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 14
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":10*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 15
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":11*u,"y":2*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 16
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":11*u,"y":3*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 17
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":0*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 18
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":1*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 19
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 20
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":3*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 21
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":4*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 22
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":5*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 23
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":6*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 24
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":8*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 25
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":9*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 26
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":10*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 27
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":11*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 28
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":12*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 29
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":13*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 30
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":14*u,"y":4*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 31
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":6*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 32
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":14*u,"y":5*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 33
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":0*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 34
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":1*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 35
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 36
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":3*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 37
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":4*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 38
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":5*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 39
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":6*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 40
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":7*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 41
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":8*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 42
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":9*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 43
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":10*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 44
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":12*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 45
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":13*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 46
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":14*u,"y":6*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 47
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":12*u,"y":7*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 48
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":1*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 49
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 50
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":3*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 51
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":4*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 52
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":5*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 53
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":6*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 54
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":7*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 55
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":8*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 56
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":9*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 57
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":10*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 58
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":11*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 59
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":12*u,"y":8*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 60
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":12*u,"y":9*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 61
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":0*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 62
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":1*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 63
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 64
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":3*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 65
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":4*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 66
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":5*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 67
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":6*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 68
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":7*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 69
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":9*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 70
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":10*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 71
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":11*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 72
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":12*u,"y":10*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 73
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":0*u,"y":11*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 74
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":9*u,"y":11*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 75
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":11*u,"y":11*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 76
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":0*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 77
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 78
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":3*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 79
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":4*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 80
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":5*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 81
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":6*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 82
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":7*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 83
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":8*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 84
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":9*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 85
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":11*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 86
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":12*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 87
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":13*u,"y":12*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 88
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":0*u,"y":13*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 89
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":13*u,"y":13*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 90
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":0*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 91
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":1*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 92
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":2*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 93
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":3*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 94
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":4*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 95
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":5*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 96
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":6*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 97
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":7*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 98
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":8*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 99
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":9*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 100
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":10*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 101
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":11*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 102
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":12*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
//wall 103
item=stage.createNewItem();
item.setName("wall");
item.addAnimation({"dsp":true,"x":13*u,"y":14*u,"w":u,"h":u,"img":"brick01.png","bgc":"BlanchedAlmond","bdc":"peru"});
stage.addItem(item);
}
|
/**
* Created by benjamin on 09/03/17.
*/
$(".full-item").hide();
$('.item-comp').on('mouseenter',function () {
console.log(this+' .full-item')
$(this).find('.full-item').fadeIn( 200, function() {
// Animation complete.
});
});
$('.item-comp').on('mouseleave',function () {
$(this).find('.full-item').fadeOut( 200, function() {
});
});
|
/* eslint-disable flowtype/require-valid-file-annotation */
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Stepper, { Step, StepLabel, StepContent } from 'material-ui/Stepper';
import Button from 'material-ui/Button';
import {gql} from 'react-apollo';
import Paper from 'material-ui/Paper';
import {client} from '../../../../utils'
import Typography from 'material-ui/Typography';
import Step1 from './Step1'
import Step2 from './Step2'
import Step3 from './Step3'
import Step4 from './Step4'
const styles = theme => ({
root: {
width: '90%',
},
button: {
marginRight: theme.spacing.unit,
},
actionsContainer: {
marginTop: theme.spacing.unit,
marginBottom: theme.spacing.unit,
},
resetContainer: {
marginTop: 0,
padding: theme.spacing.unit * 3, // TODO: See TODO note on Stepper
},
});
function getSteps() {
return ['Product Name', 'Product Image','Mandatory Information', 'Publish'];
}
function getStepContent(step,_this) {
switch (step) {
case 0:
return <Step1 setProduct={_this.setProduct} />;
case 1:
return <Step2 />;
case 2:
return <Step3 setPrice={_this.setPrice} setRange={_this.setRange} />;
case 3:
return <Step4 submit={_this.submit} />;
default:
return 'Unknown step';
}
}
class AddProduct extends React.Component {
state = {
activeStep: 0,
ProductID:null,
Price:null,
Range:null,
UserID:localStorage.getItem("login_id")
};
handleNext = () => {
this.setState({
activeStep: this.state.activeStep + 1,
});
};
handleBack = () => {
this.setState({
activeStep: this.state.activeStep - 1,
});
};
handleReset = () => {
this.setState({
activeStep: 0,
});
};
setProduct=(v)=>{
this.setState({ProductID:v})
this.handleNext()
}
setPrice=(v)=>{
this.setState({Price:v})
}
setRange=(v)=>{
this.setState({Range:v})
this.handleNext()
}
submit=async()=>{
let state=this.state
state=JSON.stringify(state)
try {
let result = await client.mutate({
mutation: gql`
mutation($state:String!) {
PlaceAd(state:$state)
}
`,
variables: {
state:state
}
})
result = result.data.PlaceAd
alert(result);
this.handleReset()
this.props.history.push("/app/view-products")
}
catch(e)
{
alert("Error",e.message);
}
finally{
}
}
render() {
const { classes } = this.props;
const steps = getSteps();
const { activeStep } = this.state;
return (
<div className={classes.root}>
<Stepper activeStep={activeStep} orientation="vertical">
{steps.map((label, index) => {
return (
<Step key={label}>
<StepLabel>{label}</StepLabel>
<StepContent>
<Typography>{getStepContent(index,this)}</Typography>
<br /><br />
{activeStep !== steps.length - 1?
<div className={classes.actionsContainer}>
<div>
<Button
disabled={activeStep === 0}
onClick={this.handleBack}
className={classes.button}
>
Back
</Button>
<Button
raised
color="primary"
onClick={this.handleNext}
className={classes.button}
>
{activeStep === steps.length - 1 ? 'Finish' : 'Next'}
</Button>
</div>
</div>
:null}
</StepContent>
</Step>
);
})}
</Stepper>
{activeStep === steps.length && (
<Paper square elevation={0} className={classes.resetContainer}>
<Typography>All steps completed - you"re finished</Typography>
<Button onClick={this.handleReset} className={classes.button}>
Reset
</Button>
</Paper>
)}
</div>
);
}
}
AddProduct.propTypes = {
classes: PropTypes.object,
};
export default withStyles(styles)(AddProduct); |
class bostonAllInclusive {
navigateToBostonAllInclusive() {
cy.visit('/boston/en-us/products/all-inclusive');
}
verifyBostonAllInclusivePage(pageTitle) {
cy.get('head > title').should('contain.text', pageTitle) //'All-Inclusive Pass'
cy.url().should('include', '/all-inclusive')
}
dayPass(pass) {
cy.get('div.cart-product-stack--dropdown__select>select.form-control')
.select(pass)
.should('contain.text', pass)
}
filterProductList() {
cy.get('section.block.block-go-pass-product.block-react-attraction-product-list.clearfix.block-wrapper').should('exist')
}
verifyCheckOutButtonDisabled() {
cy.get('div.lc-cart__prices.lc-cart__loader > a').should('have.class','lc-cart__purchase--disabled')
}
AdultCartItemIncrease() {
cy.get(':nth-child(3) > .lc-cart__item-amount-wrapper > .lc-cart__item-amount > [data-testid=cartItemIncrease]')
.trigger('click', { detail: 1 })
.trigger('click', { detail: 2 })
.trigger('click', { detail: 3 })
}
AdultCartItemDecrease() {
cy.get(':nth-child(3) > div.lc-cart__item-amount-wrapper div.lc-cart__item-amount-minus').click()
.trigger('click', { detail: 1 })
.trigger('click', { detail: 2 })
.trigger('click', { detail: 3 })
}
ChildCartItemIncrease() {
cy.get('.lc-cart__item:nth-child(4) .lc-cart__item-amount-plus').click()
.trigger('click', { detail: 1 })
.trigger('click', { detail: 2 })
.trigger('click', { detail: 3 })
}
ChildCartItemDecrease() {
cy.get(':nth-child(4) > div.lc-cart__item-amount-wrapper div.lc-cart__item-amount-minus').click()
.trigger('click', { detail: 1 })
.trigger('click', { detail: 2 })
.trigger('click', { detail: 3 })
}
adultAmountValue(value){
cy.get('.lc-cart__item:nth-child(3) .lc-cart__item-amount-value').should('contain.text', value)
}
childAmountValue(value){
cy.get('.lc-cart__item:nth-child(4) .lc-cart__item-amount-value').should('contain.text', value)
}
OrderTotalValue(total){
cy.get('.lc-cart__prices-total > .lc-cart__prices-number > .formatted-price').should('contain.text', total)
}
shoppingBasketOpen(){
cy.get('.react-component:nth-child(3) .cart-icon__icon').click()
}
shoppingBasketCounter(value){
cy.get('div.site-lower-nav div.cart-icon__icon div.cart-icon__icon-counter').should('contain.text', value)
}
verifyShoppingCardOrderTotal(value)
{
cy.get('.lc-cart__prices-box:nth-child(1) > .lc-cart__prices-total .formatted-price').should('contain.text', value)
}
shoppingCartCheckoutButton(){
cy.get("a[class='lc-cart__purchase lc-font__regular']").click()
}
subMenuLink1PageLoad(firstLink)
{
cy.get('.secondary-menu--item:nth-child(1) > a').contains(firstLink)
cy.get('.secondary-menu--item:nth-child(1) > a').click()
cy.url().should('include', '/all-inclusive/what-you-get')
cy.get('.content__title').should('have.text','What’s included with the Go Boston All-Inclusive pass')
}
subMenuLink2PageLoad(secondLink)
{
cy.get('.secondary-menu--item:nth-child(2) > a').contains(secondLink)
cy.get('.secondary-menu--item:nth-child(2) > a').click()
cy.url().should('include', '/all-inclusive/how-it-works')
cy.get('.content__title').should('have.text','How does the Go Boston All–Inclusive pass work?')
}
subMenuLink3PageLoad(thirdLink)
{
cy.get('.secondary-menu--item:nth-child(3) > a').contains(thirdLink)
cy.get('.secondary-menu--item:nth-child(3) > a').click()
cy.url().should('include', '/all-inclusive/attractions')
cy.get('.content__title').should('have.text','All-in admission to 40+ Boston attractions')
}
subMenuLink4PageLoad(fourthLink)
{
cy.get('.secondary-menu--item:nth-child(4) > a').contains(fourthLink)
cy.get('.secondary-menu--item:nth-child(4) > a').click()
cy.url().should('include', '/all-inclusive-guidebook')
cy.get('.content__title').should('have.text','Download your free Boston guidebook')
}
subMenuBuyBtnPageLoad(buttonName)
{
cy.get('.react-component:nth-child(3) .lc-font__regular').contains(buttonName)
cy.get('.react-component:nth-child(3) .lc-font__regular').click()
cy.url().should('include', '/products/all-inclusive/pricing')
cy.get('.products-stack-header--title').should('have.text','Choose your All-Inclusive pass')
}
reactComponentCartProductSelector(){
cy.get('section.block.block-go-commerce.block-react-product-selector.clearfix.block-wrapper > div > div > div > div').screenshot()
}
sellingPointSection()
{
cy.get('.view-content-wrapper.view-content-wrapper--even').screenshot()
}
}
export default bostonAllInclusive |
export default {
API_ENDPOINT:'https://sleepy-hollows-33967.herokuapp.com',
API_KEY:'3160816e-b877-4a6c-86f7-af4a1fafee7d',
}
|
'use strict';
angular
.module('common.services', ['ngResource', 'ui.bootstrap', 'ui.bootstrap.modal', 'ui.bootstrap.tpls', 'angular-loading-bar','angular.snackbar'])
; |
import {
ACTION_REQUEST,
RECEIVE_ARTICULOS, FAILURE_ARTICULOS,
CREATE_ARTICULO_SUCCESS, CREATE_ARTICULO_FAILURE,
DELETE_ARTICULO_SUCCESS, DELETE_ARTICULO_FAILURE,
UPDATE_ARTICULO_SUCCESS, UPDATE_ARTICULO_FAILURE
} from './index';
import { getArticulos, addArticulo, deleteArticulo, updateArticulo } from '../requests/ArticuloService';
/*
()=>(dispatch)=>{}
significa que la funcion getArticulosAction no recibe
parametros y retorna una funcion que recibe como parametro
dispatch y hace lo que esta dentro de llaves
*/
export const getArticulosAction = () => (dispatch) => {
dispatch({ type: ACTION_REQUEST });
//timeout simulador para añadir retardo
setTimeout(() => {
return getArticulos().then(res => {
dispatch({ type: RECEIVE_ARTICULOS, payload: res.data });
}).catch(error => {
dispatch({ type: FAILURE_ARTICULOS, error });
});
}, 500);
};
export const createArticuloAction = (articulo) => (dispatch) => {
dispatch({ type: ACTION_REQUEST });
return addArticulo(articulo).then(res => {
dispatch({ type: CREATE_ARTICULO_SUCCESS, payload: res.data.articulo });
}).catch(error => {
dispatch({ type: CREATE_ARTICULO_FAILURE, error })
});
};
export const deleteArticuloAction = (id) => (dispatch) => {
dispatch({ type: ACTION_REQUEST });
return deleteArticulo(id).then(res => {
dispatch({ type: DELETE_ARTICULO_SUCCESS, payload: res.data.articulo._id });
}).catch(error => {
dispatch({ type: DELETE_ARTICULO_FAILURE, error })
});
};
export const updateArticuloAction = (id, articulo) => (dispatch) => {
dispatch({ type: ACTION_REQUEST });
return updateArticulo(id, articulo).then(res => {
dispatch({ type: UPDATE_ARTICULO_SUCCESS, payload: res.data.articulo });
}).catch(error => {
dispatch({ type: UPDATE_ARTICULO_FAILURE, error })
});
}; |
/* @flow */
import React, { Component } from "react";
import Player from "../components/Player";
import { connect } from "react-redux";
import { error } from "../utils/error";
import { changePlayerStatus, onSetSong } from "../actions/player";
import Expo, { Audio } from "expo";
class PlayerContainer extends Component {
constructor(props) {
super(props);
this.playbackInstance = null;
}
async componentDidMount() {
await Audio.setIsEnabledAsync(true);
Audio.setAudioModeAsync({
allowsRecordingIOS: false,
interruptionModeIOS: Audio.INTERRUPTION_MODE_IOS_DO_NOT_MIX,
playsInSilentLockedModeIOS: true,
shouldDuckAndroid: true,
interruptionModeAndroid: Audio.INTERRUPTION_MODE_ANDROID_DO_NOT_MIX
});
}
shouldComponentUpdate(nextProps) {
if (
this.props.expand !== nextProps.expand ||
this.props.playlist !== nextProps.playlist
) {
return false;
}
return true;
}
componentWillUpdate(props) {
const { preview_url } = props;
if (this.playbackInstance) {
this._unLoadInstance(preview_url);
} else if (preview_url) {
this._LoadInstance(preview_url);
}
}
_LoadInstance = async preview_url => {
if (preview_url) {
this.playbackInstance = new Audio.Sound({
source: preview_url
});
this.props.changePlayerStatus({
showPlayer: true,
isLoading: true,
position: null,
duration: null
});
this.playbackInstance.setCallback(this._callbackSong);
this.playbackInstance.setCallbackPollingMillis(1000);
try {
await this.playbackInstance.loadAsync();
const { durationMillis } = await this.playbackInstance.playAsync();
this.props.changePlayerStatus({
isLoading: false,
isPlaying: true,
duration: durationMillis
});
} catch (error) {
error("Error al reproducir la canción");
}
} else {
error("canción sin URL");
}
};
_unLoadInstance = preview_url => {
this.playbackInstance.unloadAsync();
this.playbackInstance.setCallback(null);
if (preview_url) this._LoadInstance(preview_url);
};
_callbackSong = status => {
if (status.isPlaying) {
this.props.changePlayerStatus({
position: status.positionMillis
});
}
if (status.didJustFinish && !this.props.index) {
this._unLoadInstance();
this.props.changePlayerStatus({
showPlayer: false
});
}
if (status.didJustFinish && this.props.index) {
this._onForward();
}
};
_onPlayPause = async () => {
if (this.playbackInstance != null) {
const { isPlaying } = await this.playbackInstance.getStatusAsync();
if (isPlaying) {
this.playbackInstance.pauseAsync();
this.props.changePlayerStatus({
isPlaying: false
});
} else {
this.playbackInstance.playAsync();
this.props.changePlayerStatus({
isPlaying: true
});
}
}
};
_onForward = () => {
const { index, playlist } = this.props;
newIndex = index >= playlist.length ? 0 : index;
this.props.onSetSong(playlist[newIndex]);
};
_onBackward = () => {
const { index, playlist } = this.props;
newIndex = index == 1 ? playlist.length - 1 : index - 2;
this.props.onSetSong(playlist[newIndex]);
};
_onExpand = () => {
this.props.changePlayerStatus({
expand: !this.props.expand
});
};
render() {
return (
<Player
onPlayPause={this._onPlayPause}
onNext={this._onForward}
onBack={this._onBackward}
onExpand={this._onExpand}
/>
);
}
}
const mapStateToProps = ({
player: { song, playlist, status: { expand } }
}) => ({
preview_url: song.preview_url,
index: song.track_number,
playlist,
expand
});
export default connect(mapStateToProps, {
changePlayerStatus,
onSetSong
})(PlayerContainer);
|
// Include gulp & plugins
const gulp = require("gulp"),
argv = require("yargs").argv,
childProc = require("child_process"),
csso = require("gulp-csso"),
del = require("del"),
fs = require("fs"),
gulpIf = require("gulp-if"),
htmlmin = require("gulp-htmlmin"),
removeLogging = require("gulp-remove-logging"),
removeCode = require("gulp-remove-code"),
terser = require("gulp-terser"),
zip = require("gulp-zip");
// Options specified at the command line.
const taskName = argv._[0] || argv.$0,
optDebug = false || !!argv.debug,
optMinify = false || !!argv.minify,
optZip = taskName.startsWith("zip") || !!argv.zip;
let src, dist, packed;
/* ===== Utility tasks. =====
These tasks are not exported, and require targetChrome() or targetFirefox()
to be called first to set the src, dist and packed directories. */
const targetChrome = function(done) {
src = "./src/Chrome/";
dist = "./dist/Chrome/";
packed = "./dist/packed/Chrome/";
done();
};
targetChrome.description =
"Targets the Chrome src and dist directories for subsequent tasks.";
const targetFirefox = function(done) {
src = "./src/Firefox/";
dist = "./dist/Firefox/";
packed = "./dist/packed/Firefox/";
done();
};
targetFirefox.description =
"Targets the Firefox src and dist directories for subsequent tasks.";
const makeDistWritable = function(done) {
childProc.exec(`attrib -r ${dist}*.* /s`, done);
};
makeDistWritable.description =
"Makes the files in the targeted dist directory writeable.";
const makeDistReadOnly = function(done) {
childProc.exec(`attrib +r ${dist}*.* /s`, done);
};
makeDistReadOnly.description =
"Makes the files in the targeted dist directory read-only.";
const copyScripts = function() {
return gulp
.src(`${src}*.js`)
.pipe(
gulpIf(
!optDebug,
removeLogging({
replaceWith: "0;",
methods: [
"assert",
"clear",
"count",
"countReset",
"debug",
"dir",
"dirxml",
"group",
"groupCollapsed",
"groupEnd",
"info",
"log",
"profile",
"profileEnd",
"table",
"time",
"timeEnd",
"timeLog",
"timeStamp",
"trace",
],
})
)
)
.pipe(gulpIf(!optDebug, removeCode({ allowDebug: false })))
.pipe(gulpIf(optMinify, terser()))
.pipe(gulp.dest(dist));
};
copyScripts.description = "Deploys the Javascript files (src/*.js).";
copyScripts.flags = {
"--debug": "Keep debug related logic in the JavaScript (default: false)",
"--minify": "Minify the Javascript source code (default: false)",
};
const copyCss = function() {
return gulp
.src(`${src}*.css`)
.pipe(gulpIf(optMinify, csso()))
.pipe(gulp.dest(dist));
};
copyCss.description = "Deploys the CSS files (src/*.css).";
copyCss.flags = {
"--minify": "Minify the CSS source code (default: false)",
};
const copyHtml = function() {
return gulp
.src(`${src}*.html`)
.pipe(gulpIf(!optDebug, removeCode({ allowDebug: false })))
.pipe(
gulpIf(
optMinify,
htmlmin({
collapseWhitespace: true,
removeComments: true,
})
)
)
.pipe(gulp.dest(dist));
};
copyHtml.description = "Deploys the HTML files (src/*.html).";
copyHtml.flags = {
"--debug": "Keep debug related logic in the HTML (default: false)",
"--minify": "Minify the HTML source code (default: false)",
};
const copyFiles = function() {
return gulp
.src([`${src}manifest.json`, `${src}images/*`], { base: src })
.pipe(gulp.dest(dist));
};
copyFiles.description = "Copies src/images/* and src/manifest.json to dist.";
const zipTarget = function(done) {
if (!optZip) {
console.log("Skipping zipTarget task.");
done();
return;
}
const manifest = JSON.parse(fs.readFileSync(`${dist}manifest.json`)),
zipFilename =
manifest.name.toLowerCase().replace(/\s/g, "-") +
"-v" +
manifest.version.replace(/\./g, "_") +
(dist.endsWith("fox/") ? "@john30013.com.zip" : ".zip");
return gulp
.src(`${dist}**/*`)
.pipe(zip(zipFilename))
.pipe(gulp.dest(packed));
};
zipTarget.description =
"Zips the targeted dist directory into its packed directory. If called from another script, runs only if --zip command line option is specified.";
const cleanTarget = function() {
return del([dist]);
};
cleanTarget.description = "Cleans the target dist directory tree.";
/* ===== Exported tasks. ===== */
const logArgs = function(done) {
console.log({ taskName, optDebug, optMinify, optZip, argv });
done();
};
logArgs.description =
"Logs the task name and arguments to the console (mainly for debugging).";
logArgs.flags = {
"--debug": "Keep debug related logic in the extension (default: false)",
"--minify": "Minify the extension's source code (default: false)",
"--zip":
"Zip the dist files for deployment to the targeted browser's web store (default: false)",
};
const buildChrome = function(done) {
return gulp.series(
targetChrome,
makeDistWritable,
cleanTarget,
gulp.parallel(copyScripts, copyCss, copyHtml, copyFiles),
zipTarget,
makeDistReadOnly
)(done);
};
buildChrome.description = "Cleans and builds the Chrome extension.";
buildChrome.flags = {
"--debug": "Keep debug related logic in the extension (default: false)",
"--minify": "Minify the extension's source code (default: false)",
"--zip":
"Zip the dist files for deployment to the Chrome web store (default: false)",
};
const buildFirefox = function(done) {
return gulp.series(
targetFirefox,
makeDistWritable,
cleanTarget,
gulp.parallel(copyScripts, copyCss, copyHtml, copyFiles),
zipTarget,
makeDistReadOnly
)(done);
};
buildFirefox.description = "Cleans and builds the Firefox extension.";
buildFirefox.flags = {
"--debug": "Keep debug related logic in the extension (default: false)",
"--minify": "Minify the extension's source code (default: false)",
"--zip":
"Zip the dist files for deployment to the Firefox Add-ons store (default: false)",
};
const cleanAll = function() {
return del(["./dist/"]);
};
cleanAll.description = "Cleans the entire dist directory tree.";
const cleanChrome = function(done) {
return gulp.series(
targetChrome,
makeDistWritable,
cleanTarget,
makeDistReadOnly
)(done);
};
cleanChrome.description =
"Targets Chrome and cleans the Chrome dist directory tree.";
const cleanFirefox = function(done) {
return gulp.series(
targetFirefox,
makeDistWritable,
cleanTarget,
makeDistReadOnly
)(done);
};
cleanFirefox.description =
"Targets Firefox and cleans the Firefox dist directory tree.";
const zipChrome = function(done) {
return gulp.series(
targetChrome,
makeDistWritable,
zipTarget,
makeDistReadOnly
)(done);
};
zipChrome.description =
"Zips the Chrome dist directory to its packed directory.";
const zipFirefox = function(done) {
return gulp.series(
targetFirefox,
makeDistWritable,
zipTarget,
makeDistReadOnly
)(done);
};
zipFirefox.description =
"Zips the Firefox dist directory to its packed directory.";
const defaultTasks = function(done) {
return gulp.series(buildChrome, buildFirefox)(done);
};
defaultTasks.description =
"Cleans and builds the Chrome and Firefox versions of the extension.";
defaultTasks.flags = {
"--debug": "Keep debug related logic in the extension (default: false)",
"--minify": "Minify the extension's source code (default: false)",
"--zip":
"Zip the dist files for deployment to the web store (default: false)",
};
module.exports = {
buildChrome,
buildFirefox,
cleanAll,
cleanChrome,
cleanFirefox,
zipChrome,
zipFirefox,
logArgs,
};
module.exports.default = defaultTasks;
|
const fetch = require("node-fetch");
const cheerio = require("cheerio");
const axios = require("axios");
const Discord = require("discord.js");
const client = new Discord.Client();
var prefix = "!";
async function discord() {
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("message", (msg) => {
if (!msg.content.startsWith(prefix) || msg.author.bot) return;
const args = msg.content.slice(prefix.length).split(" ");
const command = args.shift().toLowerCase();
if (command === "stockx") {
msg.channel.send("Searching...");
let sneakerSearch = args.slice(0).join(" ").split(",");
let shoe = sneakerSearch[0];
let size = sneakerSearch[1];
return stockx(shoe, size, msg);
}
return main(msg);
});
client.login("DISCORD WEBHOOK HERE...");
}
async function stockx(shoe, size, msg) {
let url = `https://stockx.com/api/browse?productCategory=sneakers&_search=${shoe}&dataType=product`;
try {
const dataFetch = await fetch(
url,
(headers = {
method: "GET",
headers: {
authority: "stockx.com",
"x-requested-with": "XMLHttpRequest",
"x-anonymous-id": "6a9cb494-72d6-4c66-991e-8965ad3618f4",
authorization: "",
"user-agent":
"Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Mobile Safari/537.36",
appversion: "0.1",
"sec-fetch-site": "same-origin",
"accept-language": "en-US,en;q=0.9",
},
})
);
let data = await dataFetch.json();
urlKey = data.Products[0].urlKey;
imgUrl = data.Products[0].media.thumbUrl;
return productsku(urlKey, size, imgUrl, msg);
} catch (err) {
console.log(err);
}
}
async function productsku(urlKey, size, imgUrl, msg, sizeUrl) {
try {
let sizeUrl = `https://stockx.com/${urlKey}?size=${size}`;
const skuFetch = await axios.get(sizeUrl, headers);
const $ = cheerio.load(skuFetch.data);
let sku = $(".product-view").find("script").html();
let objSku = JSON.parse(sku.toString()).sku;
return checkPrice(objSku, imgUrl, msg, sizeUrl);
} catch (err) {
console.log(err);
}
}
async function checkPrice(objSku, imgUrl, msg, sizeUrl) {
try {
let itemUrl = `https://stockx.com/api/products/${objSku}/market?currency=USD&country=US`;
const getPrices = await axios.get(itemUrl, headers);
let size = getPrices.data.Market.lastSaleSize;
let lowestAsk = getPrices.data.Market.lowestAsk;
let highestBid = getPrices.data.Market.highestBid;
return main(imgUrl, msg, size, lowestAsk, highestBid, sizeUrl);
} catch (err) {
console.log(err);
}
}
async function main(imgUrl, msg, size, lowestAsk, highestBid, sizeUrl) {
stockxEmbed = {
color: 0x0099ff,
title: "StockX-Check",
image: {
url: imgUrl,
},
fields: [
{
name: "LowestAsk",
value: lowestAsk,
inline: true,
},
{
name: "HighestBid",
value: highestBid,
inline: true,
},
{
name: "Size",
value: size,
inline: true,
},
{
name: "ProductLink",
value: sizeUrl,
inline: true,
},
],
timestamp: new Date(),
};
msg.channel.send({ embed: stockxEmbed });
}
discord();
|
export const SOME_URL = '/some/url';
|
import { useState } from "react";
import Chart from "./Chart/Chart";
import Header from "./Header/Header";
import Nav from "./Nav/Nav";
import Sorts from "./sort.json";
// function for generatin random array
const randomArr = (len, min = 100, max = 1000) => {
let result = [];
for(let i = 0; i < len; i++) {
result[i] = Math.floor(Math.random() * (max - min)) + min - 1;
};
return result
};
const App = () => {
// states
const [nav, setNav] = useState(false);
const [type, setType] = useState("bubble-sort");
const [list, setList] = useState(randomArr(50));
// event handlers
const navHandler = () => {
let newState = !nav;
setNav(newState);
};
const selectMethod = (e) => {
setType(e.target.value);
};
const createNewArr = () => {
setList(randomArr(50));
};
let desc = (
<div className="nav__desc">
<p>{Sorts[type]["bigO"]}</p>
<p>{Sorts[type]["desc"]}</p>
</div>
);
return (
<section className="main">
<Header navHandler={navHandler}/>
<Nav
open={nav}
type={type}
selectMethod={selectMethod}
genNew={createNewArr}
description={desc}
/>
<Chart list={list} type={type}/>
</section>
);
}
export default App;
|
const express = require('express')
const router = express.Router()
// Importing Controller
const AuthController = require('../../src/Auth/AuthController')
const isAuthMiddleware = require('../../middleware/isAuthMiddleware')
/**
* @desc : to Login from User Request
* @route /api/v{Num}/auth/login
*/
router.post('/login', AuthController.LOGIN_USER)
/**
* Get User Profile
* @desc : Using Middlware JWT to Authenticate
* @route /api/v{Num}/auth/me
*/
router.get('/me', isAuthMiddleware, AuthController.GET_PROFILE_DATA)
/**
* @desc : Create User
* @route /api/v{Num}/auth/
*/
router.post('/', AuthController.CREATE_USER)
module.exports = router
|
var randomNumber1 = diceRoll();
var randomNumber2 = diceRoll();
var firstDiceImage = "images/" + "dice" + randomNumber1 + ".png";
var secondDiceImage = "images/" + "dice" + randomNumber2 + ".png";
document.getElementsByTagName("img")[0].setAttribute("src", firstDiceImage);
document.getElementsByTagName("img")[1].setAttribute("src", secondDiceImage);
if (randomNumber1 > randomNumber2) {
document.querySelector("h1").innerText = "🚩 Player 1 Wins!";
} else if (randomNumber1 < randomNumber2) {
document.querySelector("h1").innerText = "Player 2 Wins! 🚩";
} else {
document.querySelector("h1").innerText = "Draw!";
}
function diceRoll() {
return Math.floor(Math.random() * 6) + 1;
} |
/**Test cases for Story 001 of Adhat.*/
/**
* Context : UPLOAD -> SALE -> BUY
* -----------------------------------------
* Story 001 :: PROPERTY OWNERSHIP
* -----------------------------------------
* 1. Alice : I have a valuable content which I will upload to the platform. Now I want to put it on sale.
* 2. Bob : I buyer I want to buy that content. So I came to adhat market place to buy it. I saw Alice is selling
* a content which I am interested in. I want the owner ship of the content to be delivered to me.
*
* -------------------------------------------
* Note : Same story can be applied to car owner ship, flat ownership etc.
* --------------------------------------------
* Alice : content Owner
* Bob : Buyer 1
*/
'use strict';
// import expectThrow from './expectThrow';
const MediaStore = artifacts.require('../contracts/MediaStore.sol');
contract('MediaStore', function (accounts) {
let ms;
let bob;
let alice;
let adhatOwner;
before(async function () {
// Instantiate the MediaStore Contract
ms = await MediaStore.new();
console.log('****************THE PROPERTY OWNERSHIP****************************')
console.log('Welcome to Adhat Story Part 001!')
console.log('The story depicts following feature of application : UPLOAD -> SALE -> BUY')
console.log('Actors of this story are :: ...........')
console.log('Alice - a content owner.')
console.log('Bob - a content buyer.')
console.log('****************THE PROPERTY OWNERSHIP****************************')
bob = accounts[0];
alice = accounts[1];
});
describe("User Module", function() {
describe("lets first onboard Alice and Bob", function(){
it("should onbord Alice", async function(){
await ms.registerUser("Alice", {from : alice});
let exists = await ms.getUser(alice);
assert.isTrue(exists);
})
it("should onbord Bob", async function(){
await ms.registerUser("Bob", {from : bob});
let exists = await ms.getUser(bob);
assert.isTrue(exists);
})
})
})
describe("Content Module", function(){
describe("Add content", function(){
it("Alice should be able to add a new content - 1", async function(){
await ms.addContent("a_mediaHash1", 0, 10, {from :alice});
let [count, commaSepIds] = await ms.getUserUploadedContents({from: alice})
assert.equal(count, 1);
})
it("Alice should be able to add another content - 2", async function(){
await ms.addContent("a_mediaHash2", 0, 10, {from :alice});
let [count, commaSepIds] = await ms.getUserUploadedContents({from: alice})
assert.equal(count, 2);
})
it("Alice should be able to add another content - 3", async function(){
await ms.addContent("a_mediaHash3", 0, 10, {from :alice});
let [count, commaSepIds] = await ms.getUserUploadedContents({from: alice})
assert.equal(count, 3);
})
it("Alice should NOT be able to add an existing content document", async function(){
try {
await ms.addContent("a_mediaHash2", 0, 10, {from :alice});
}
catch (error) {
assert(true);
}
})
it("Alice should be able to retrive all of her uploaded doc ids", async function(){
let [count, commaSepIds] = await ms.getUserUploadedContents({from: alice});
let contentHashes = commaSepIds.split(',');
assert.equal(count, 3);
// console.log('List of documents which Alice has uploaded so far...')
// contentHashes.forEach(element => {
// console.log(element);
// });
})
})
describe("Sell content", function(){
it("Alice should be able to put content on sale", async function(){
await ms.putContentForSale('a_mediaHash1', 1, {from :alice});
let [creator, cntType, isSold, resaleCnt, price, forSale] = await ms.getContentDetByHash('a_mediaHash1')
assert.equal(forSale, true);
assert.equal(price, 1);
})
it("Alice should be able to put another content on sale", async function(){
await ms.putContentForSale('a_mediaHash2', 1, {from :alice});
let [creator, cntType, isSold, resaleCnt, price, forSale, currentOwner] = await ms.getContentDetByHash('a_mediaHash2')
assert.equal(forSale, true);
assert.equal(price, 1);
assert.equal(currentOwner, alice);
})
it("Bob (or some other person) should NOT be able to put the content on sale as he doesnt own", async function(){
try{
await ms.putContentForSale('a_mediaHash2', 1, {from :bob});
}catch(err){
assert(true);
}
})
it("should be able to retrive all contents on sale", async function(){
let [commaSepContentIds, count] = await ms.getContentsOnSale(0);
//commaSepContentIds : \
assert.equal(count, 3);
})
})
describe("Buy Content", function(){
it("Bob should be able to buy the content on sale", async function(){
await ms.buyContent('a_mediaHash2', {from : bob, value : 1})
let [creator, cntType, isSold, resaleCnt, price, forSale, currentOwner] = await ms.getContentDetByHash('a_mediaHash2')
assert.equal(forSale, false);
assert.equal(forSale, false);
assert.equal(currentOwner, bob);
})
it("Bob should be able to retrive list of bought contents", async function(){
let [contentCount, commaSepContentIds] = await ms.getUserBoughtContents({from : bob});
assert.equal(contentCount, 1);
})
it("Alice should NOT be able to buy her own contents", async function(){
try{
await ms.putContentForSale('a_mediaHash2', 1, {from :alice});
}catch(err){
assert(true);
}
})
it("Alice should recieve crypto from Bob", async function(){
})
it("Bob should NOT be able to buy the content which is not in sale", async function(){
try{
await ms.putContentForSale('a_mediaHash2', 1, {from :bob});
}catch(err){
assert(true);
}
})
it("Bob can also put the content on sale", async function(){
await ms.putContentForSale('a_mediaHash2', 1, {from :bob});
let [creator, cntType, isSold, resaleCnt, price, forSale] = await ms.getContentDetByHash('a_mediaHash2')
assert.equal(forSale, true);
assert.equal(price, 1);
})
})
})
})
|
const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
app.use(cookieParser())
const mongoose = require('mongoose')
//Affichage de l'icône avec express
var favicon = require('serve-favicon')
var path = require('path')
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')))
//Each file inside this folder will be accessible from the root URL
app.use( express.static( "public" ) );
//Permet de pouvoir appeler nos variables d'environnement
require('dotenv').config()
//Pour pouvoir test les requêtes avec REST Client sous format JSON
app.use(express.json());
//Access values from form inside of our request
//variable inside of our POST method
app.use(express.urlencoded({ extended : false }))
//les routeurs
const authRouter = require('./routes/auth')
app.use('/', authRouter)
const eventRouter = require('./routes/eventsRoute')
app.use('/evenements', eventRouter)
const reservationRouter = require('./routes/timeSlotsRoute')
app.use('/reserver',reservationRouter)
// connecte la base de donnée
mongoose.connect('mongodb+srv://'+ process.env.MONGODB_ATLAS_USER + ':'+ process.env.MONGODB_ATLAS_PW + '@'+ process.env.MONGODB_ATLAS_NAME + '.ybw8y.mongodb.net/projetpiscine?retryWrites=true&w=majority',{
useNewUrlParser: true , useUnifiedTopology: true, useCreateIndex: true, useFindAndModify: false })
// mongoose.connect('mongodb://127.0.0.1/projetpiscineg4',{
// useNewUrlParser: true , useUnifiedTopology: true })
// view engine is going to convert our ejs code to html
app.set('view engine', 'ejs')
//affiche la page d'affichage dde notre serveur
const evenementController = require('./controller/eventController')
app.route('/')
.get( function(req, res){
res.render('login', { title : "login"})
} )
app.route('/planningTest')
.get(function(req, res){
res.render('planningTest')
})
app.get('*', function(req, res) {
res.render('error')
})
app.listen(4000)
|
/*
var edad = prompt("Ingrese su edad");
function calcularEdad(edad)
{
if(edad >= 18)
{
console.log("Usted es mayor de edad");
if(edad <= 33)
{
console.log("Usted es millenial",edad);
} else if(edad >= 70)
{
console.log("usted es un anciano",edad);
}else{
console.log("Usted ya no es millenial",edad);
}
}
else
{
console.log("Usted es menor de edad",edad);
}
}
calcularEdad(edad);
calcularEdad(23);
calcularEdad(89);
calcularEdad(15);
calcularEdad(67);
*/
/**Operadores de comparacion */
var a = 5;
var b = (5);
if (a==b){
console.log("a y b son igual");
}
if (a===b){
console.log("a y b son iguales en tipo y en vslor");
}
else{
console.log("no son iguales en tipo y valor");
}
//** operador ternario */
var x = 5;
var y = 10;
if (a==b){
console.log("",x);
}
else{
console.log("",y);
}
var resultado = a==b? 10:20;
console.log(resultado);
var year = prompt("Introduzca un año");
var resultado1 = year != 2018? true : false ;
console.log(resultado1);
//** Switch */
var day = prompt ("intruduzca un dia de la semana");
function setDay(day){
switch (day) {
case "sabado":
console.log("Voy a ir al cine");
break;
case "domingo":
console.log("Voy a hacer deporte");
break;
case "lunes":
console.log("Voy a trabajar");
break;
default:
console.log("No es un dia valido");
}
}
setDay(day);
setDay(domingo);
|
import React from "react";
const ImprovedCard = props => {
return (
<div className="movies-list-item">
<h2>{props.title}</h2>
<p>Director: {props.director}</p>
{/* true && x will evaluate to x */}
{ props.hasOscars && <p>Got the Oscar Award! </p> }
{ !props.hasOscars && <p>Great movie but no Oscars! </p> }
{/* can also do it like this:
{
props.hasOscars ?
<p>Got that Oscar! </p>
:
<p>No Oscars here... </p>
}
*/}
<button onClick={props.clickToDelete}>Delete</button>
</div>
);
};
export default ImprovedCard; |
// @ts-check
// * @type { import('eslint').Linter.Config }
// https://typescript-eslint.io/docs/linting/
// https://www.npmjs.com/package/eslint-config-airbnb-typescript
// https://github.com/iamturns/eslint-config-airbnb-typescript/blob/master/lib/shared.js
module.exports = {
root: true,
overrides: [
{
// Config files for Node.js tools like ESLint, Babel, webpack, postcss, stylelint, Jest, etc.
files: ['./*.js'],
env: {
// 'eslint-config-airbnb-base' includes 'node: true' as env.
// See https://github.com/airbnb/javascript/issues/1476 and
// https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb-base/rules/node.js
// for more details.
// node: true,
},
extends: [
// https://www.npmjs.com/package/eslint-config-airbnb-base
// https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb-base/index.js
'airbnb-base',
],
plugins: [
// Inherited from 'eslint-config-airbnb-base' automatically
// 'import',
],
rules: {
'no-multi-spaces': ['error', {
ignoreEOLComments: true,
}],
},
},
{
// Files that run in the browser
files: ['src/**/*.+(ts|tsx)'],
env: {
browser: true,
node: false, // overrides 'node: true' from 'eslint-config-airbnb'
},
parserOptions: {
project: './tsconfig.json',
// ecmaFeatures: {
// jsx: true,
// },
// ecmaVersion: 'latest',
// sourceType: 'module',
},
plugins: [
// 'react', // eslint-plugin-react
// '@typescript-eslint', // @typescript-eslint/eslint-plugin
],
extends: [
// The 'extends' property value can omit the 'eslint-config-' prefix of the package name.
// https://github.com/airbnb/javascript/blob/master/packages/eslint-config-airbnb/index.js
'airbnb', // eslint-config-airbnb
'airbnb/hooks', // eslint-config-airbnb/hooks
// https://github.com/iamturns/eslint-config-airbnb-typescript/blob/master/lib/shared.js
'airbnb-typescript', // eslint-config-airbnb-typescript
// https://github.com/typescript-eslint/typescript-eslint/tree/main/packages/eslint-plugin
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
],
rules: {
// React will be automatically imported by specifying { runtime: 'automatic' } in
// babel.config.js.
'react/react-in-jsx-scope': 'off',
},
},
{
// *.(ts|tsx) files for unit testing with Jest
files: [
'**/__tests__/**/*.[jt]s?(x)',
'**/?(*.)+(spec|test).[tj]s?(x)',
],
plugins: [
// There is no need to specify the 'jest' plugin since the 'plugin:jest/recommended' config
// already includes it.
// See https://github.com/jest-community/eslint-plugin-jest/blob/main/src/index.ts for
// more details.
],
extends: [
'plugin:jest/recommended',
],
env: {
// No need to specify 'jest: true' since the 'eslint-plugin-jest' plugin specifies
// 'jest/globals: true'
node: true,
},
},
],
};
|
import { combineReducers } from 'redux';
import coinsReducer from './coinsReducer';
import selectedCoinReducer from './selectedCoinReducer';
import chartReducer from './chartReducer';
import chartDurationReducer from './chartDurationReducer';
import pageReducer from './pageReducer';
export default combineReducers({
coins: coinsReducer,
page: pageReducer,
selectedCoin: selectedCoinReducer,
chartData: chartReducer,
chartDuration: chartDurationReducer
}); |
// Copyright (c) 2021 Antti Kivi
// Licensed under the MIT License
import localizedLinkQuery from './localizedLinkQuery';
export default {
...localizedLinkQuery,
allContentfulMenu: {
edges: [
{
node: {
node_locale: 'fi',
links: [
{
contentful_id: '6JksITICuGCEYUIVHlWl5U',
title: 'Etusivu',
internal: {
type: 'ContentfulIndexPage',
},
},
{
contentful_id: '29kQlzt1s2bR8OirrtTbCo',
title: 'Ansioluettelo',
internal: {
type: 'ContentfulCurriculumVitaePage',
},
},
],
},
},
{
node: {
node_locale: 'en-GB',
links: [
{
contentful_id: '6JksITICuGCEYUIVHlWl5U',
title: 'Front Page',
internal: {
type: 'ContentfulIndexPage',
},
},
{
contentful_id: '29kQlzt1s2bR8OirrtTbCo',
title: 'Curriculum Vitae',
internal: {
type: 'ContentfulCurriculumVitaePage',
},
},
],
},
},
],
},
};
|
function update() {
get('heater');
get('extruder');
get('fiber')
}
function get(device) {
const req = new Request('/api/' + device, {method:'GET'});
fetch(req)
.then(response => {
if (response.status === 200) {
return response.json()
}
}).then(response => {
value = response['value']
if (device == 'heater') {
heaterinput.value = value;
} else if (device == 'extruder') {
extruderinput.value = value;
} else if (device == 'fiber') {
fiberinput.value = value;
}
}).catch(error => {
console.error(error);
})
}
// function getheater() {
// return
// }
function set(device) {
value = document.getElementById(device + '-input').value;
var formData = new FormData();
formData.append('value', value);
const req = new Request('/api/' + device, {method: 'POST', body: formData});
fetch(req)
.catch(error => console.error(error))
}
function inc(device, inc=true) {
// increase value of given device
input = document.getElementById(device + '-input')
input.value = parseFloat(input.value) + (inc ? 1 : -1);
set(device);
}
function stopAll() {
heaterinput.value = 0;
set('heater');
extruderinput.value = 0;
set('extruder');
fiberinput.value = 0;
set('fiber');
}
function authorize(username, auth) {
var formData = new FormData();
formData.append('username', username);
formData.append('authorize', auth)
const req = new Request('/users', { method: 'POST', body: formData });
fetch(req)
.catch(error => console.error(error))
}
document.addEventListener("DOMContentLoaded", () => {
heaterinput = document.getElementById('heater-input');
extruderinput = document.getElementById('extruder-input');
fiberinput = document.getElementById('fiber-input');
update();
}) |
Ext.onReady(function(){
/*
* LabelField示例
*/
var form = new Ext.form.FormPanel({
title : '员工管理',
renderTo:'example',
width : 300, height : 300,
labelWidth:60,
frame:true,
labelAlign:'right',
waitMsgTarget: true,
defaultType:'labelfield',
defaults:{anchor:'-20'},
bodyStyle : 'padding:5px;',
items:[
{fieldLabel:'姓名',name:'name',allowBlank:false},
{
fieldLabel:'性别',name:'sex',
renderer:function(v){
switch(v){
case 0 :
return '女' ;
case 1 :
return '男' ;
default :
return '未知';
}
}
},
{name:'age',fieldLabel:'年龄'},
{
fieldLabel:'部门',
name:'dept',
renderer:function(v){
return Ext.getObjVal(v,'name')
}
},
{
fieldLabel:'当前时间',
name:'nowDate',
renderer:Ext.util.Format.dateRenderer('Y-m-d H:m:s')
},
{fieldLabel:'备注',name : 'remark'}
],
buttons:[
{
itemId : 'reload_btn' ,
text : '重新加载数据' ,
disabled : true,
handler:function(){
var btn = form.getFooterToolbar().get('reload_btn');
btn.disable();
form.getForm().load({
waitMsg:'loadding...',url : 'data/labelField-data.json',
success:function(){
btn.enable();
}
});
}
}
],
listeners:{
render : {
delay : 300 ,
fn : function(){
var btn = form.getFooterToolbar().get('reload_btn');
form.getForm().load({
waitMsg:'loadding...',
url : 'data/labelField-data.json',
success:function(){
btn.enable();
}
})
}
}
}
});
},this);
|
import Ember from 'ember';
export default Ember.Route.extend({
setupController: function(controller, model) {
controller.set('model', model);
controller.set('semesters', this.store.all('semester'));
controller.set('isSaving', false);
},
deactivate: function() {
this.get('controller.weights').filterProperty('isDirty').forEach(function(weight) {
weight.rollback();
});
}
});
|
import React from 'react';
import PropTypes from 'prop-types';
import { getButtonsType } from './ButtonsType';
import {Button} from 'reactstrap';
import {Link} from 'react-router-dom'
const ButtonsRequest = props => {
let buttonOption = getButtonsType(props.userType,props.state,props.id)
const buttons =buttonOption.map((bt,i)=>(
<Link key ={i} to={{ pathname: bt.path}}>
<Button className={`btn btn-sm mr-1 btn-${bt.type}`} id="retirarr">{bt.action}</Button>
</Link>
))
return (
<div className="d-flex justify-content-center justify-content-lg-start flex-wrap">
{buttons}
</div>
);
};
ButtonsRequest.propTypes = {
};
export default ButtonsRequest; |
import instance from './instance';
const configRequest = () => ({
withCredentials: true,
});
export default class Klickart {
constructor(config = {}) {
this.path = config.path;
this.axios = instance();
}
get(resource = '', config = {}) {
return this.axios.get(`${this.path}/${resource}`, { ...configRequest(), ...config });
}
put(resource = '', data, config = {}) {
return this.axios.put(`${this.path}/${resource}`, data, { ...configRequest(), ...config });
}
post(resource = '', data, config = {}) {
return this.axios.post(`${this.path}/${resource}`, data, { ...configRequest(), ...config });
}
delete(resource = '', config = {}) {
return this.axios.delete(`${this.path}/${resource}`, { ...configRequest(), ...config });
}
}
|
define(['frame'], function(ngApp) {
'use strict';
ngApp.provider.controller('ctrlDoc', ['$scope', 'http2', '$uibModal', function($scope, http2, $uibModal) {
var _oPage, _oCriteria;
$scope.criteria = _oCriteria = {
start: '',
end: ''
};
$scope.page = _oPage = {
at: 1,
size: 30,
j: function() {
return '&page=' + this.at + '&size=' + this.size;
}
};
//分页
$scope.list = function() {
var url;
url = '/rest/pl/fe/user/readList?site='+ $scope.siteId +'&uid=' + $scope.userId;
url += '&startAt=' + _oCriteria.start + '&endAt=' + _oCriteria.end;
url += _oPage.j();
http2.get(url).then(function(rsp) {
$scope.matters = rsp.data.logs;
_oPage.total = rsp.data.total || 0;
});
};
$scope.cancle = function() {
_oCriteria.start = _oCriteria.end = '';
$scope.list();
};
$scope.detail = function(matter, type) {
$uibModal.open({
templateUrl: '/views/default/pl/fe/_module/statDetail.html?_=1',
controller: ['$scope', '$uibModalInstance', 'http2', function($scope, $mi, http2) {
var criteria = {
byOp: type,
byUserId: matter.userid,
start: _oCriteria.start,
end: _oCriteria.end
}
$scope.page = {
at: 1,
size: 15,
j: function() {
return '&page=' + this.at + '&size=' + this.size;
}
};
$scope.doSearch = function() {
var url;
url = '/rest/pl/fe/user/userDetailLogs?matterId=' + matter.matter_id + '&matterType=' + matter.matter_type + $scope.page.j();
http2.post(url, criteria).then(function(rsp) {
$scope.logs = rsp.data.logs;
$scope.page.total = rsp.data.total;
});
};
$scope.cancle = function() {
$mi.dismiss();
};
$scope.doSearch();
}],
backdrop: 'static'
})
};
$scope.$on('xxt.tms-datepicker.change', function(event, data) {
_oCriteria[data.state] = data.value;
if(_oCriteria.start || _oCriteria.end) {
$scope.list();
}
});
$scope.list();
}])
}); |
$(document).ready(function () {
// $.url.add({'agenda':'agenda/inicio'});
// $.url.add({'agenda':'agenda/inicio'});
// if (menuDefault == undefined){
// if ($('#menu_dashboard')[0] != undefined){
// menuDefault = $('#menu_dashboard')[0];
// }else if ($('#menu_agenda')[0] != undefined){
// menuDefault = $('#menu_agenda')[0];
// }else if ($('#menu_log')[0] != undefined){
// menuDefault = $('#menu_log')[0];
// }
// }
abrirMenu($("#menu").val());
});
function abrirMenu(obj){
$("#menu_dashboard").removeClass("active");
$("#menu_agenda").removeClass("active");
$("#menu_log").removeClass("active");
$("#menu_atualizacao").removeClass("active");
$("#"+obj).addClass("active");
//redirecionar($.url.get('agenda'));
}
//function getController(key){
// var map ={};
//
// map["aba_contrato"] = "contrato";
// map["aba_email"] = "email";
// map["aba_vinculo"] = "vinculo";
// map["aba_arquivo"] = "vinculo";
//
// return map[key];
//}; |
/*
* Jeu du pendu en JavaScript
* Pierre Romestant, Elyan Poujol, Morgane Tuffery, Aleksandr Vassilyev
*/
"use strict";
class Inscription {
constructor(pseudo, motDePasse) {
this.pseudo = pseudo;
this.motDePasse = motDePasse;
this.fichierUtilisateurs = "donnees/utilisateurs.json";
}
/*
* Inscrit l'utilisateur si le format de son pseudo et son mot de passe
* est correct
* callback:
* fonction de callback ayant pour parametre:
* err: 0 si aucune erreur n'est survenue
* 1 si le pseudo ou le mot de passe ne respectent pas le format
* 2 si erreur de lecture/ecriture du fichier des comptes
* 3 si le pseudo est deja utilise
*/
inscrire(callback) {
var _this = this;
// on verifie la validite du pseudo et du mot de passe
// pseudo: >= 3 caracteres
// mot de passe: >= 7 carateres
if (this.pseudo.length < 3 || this.motDePasse.length < 7) {
// on met le parametre err a true
callback(1);
} else {
jsonfile.readFile(this.fichierUtilisateurs, function(err, obj) {
if (err) {
// on met le parametre err a true
callback(2);
} else {
var dejaExistant = false;
// on verifie que le pseudo ne soit pas deja utilise
for (var i = 0; i < obj.utilisateurs.length; i++) {
if (obj.utilisateurs[i].pseudo == _this.pseudo) {
dejaExistant = true;
}
}
if (dejaExistant) {
// on met le parametre err a true
callback(3);
} else {
// si le pseudo n'est pas utilise
obj.utilisateurs.push({"pseudo": _this.pseudo,
"pass": _this.motDePasse,
"idjoueur": ++obj.dernierId,
"score": 0,
"niveau": 0});
jsonfile.writeFile(_this.fichierUtilisateurs, obj, function(err) {
if (err) {
// on met le parametre err a true
callback(2);
} else {
// on a un nouvel inscrit !
callback(0);
}
});
}
}
});
}
}
}
var jsonfile = require("jsonfile");
jsonfile.spaces = 4;
module.exports = Inscription; |
export const REQUEST_STATION = 'REQUEST_STATION';
export const RECEIVE_STATION = 'RECEIVE_STATION';
export const REQUEST_STATIONS = 'REQUEST_STATIONS';
export const RECEIVE_STATIONS = 'RECEIVE_STATIONS';
export const CLEAR_STATIONS = 'CLEAR_STATIONS';
export const REQUEST_STATION_STATS = 'REQUEST_STATION_STATS';
export const RECEIVE_STATION_STATS = 'RECEIVE_STATION_STATS';
export const REQUEST_STATION_STATUS = 'REQUEST_STATION_STATUS';
export const RECEIVE_STATION_STATUS = 'RECEIVE_STATION_STATUS';
|
const express = require("express");
const multer = require("multer");
const multerConfig = require("./config/multer");
const PetController = require("./controllers/PetController");
const FileController = require("./controllers/FileController");
const routes = express.Router();
routes.get("/files", FileController.index);
routes.get("/files/:id", FileController.show);
routes.post(
"/files/:id",
multer(multerConfig).single("file"),
FileController.store
);
routes.get("/pets", PetController.index);
routes.post("/pets", PetController.store);
routes.get("/pets/:id", PetController.show);
module.exports = routes;
// routes.get("/files/:id", (req, res) => {
// var file = req.params.id;
// var fileLocation = path.join("./tmp", file);
// res.download(fileLocation, file);
// });
|
var {
user,
friend,
userandfriendsmssage
} = require("./../../mongodb/schema");
var {promiseTryCatch} = require("./../../../utils/promiseTryCatch");
var UserCheck = async function (options) {
let [success, err] = await promiseTryCatch(
user.findOne(...options)
)
if (success !== null) {
return true;
} else {
return false;
}
}
var updateUserMessage = async function (id, message) {
let [success, err] = await promiseTryCatch(
userandfriendsmssage.findOne({
'_id': id,
}, {
$push: {
'message': message
}
})
)
return [success, err]
}
module.exports = {
updateUserMessage,
UserCheck
} |
import { html, css, LitElement } from 'lit';
import '../reqbaz-comments-thread.js';
import dayjs from 'dayjs/esm/index.js';
import relativeTime from 'dayjs/esm/plugin/relativeTime/index.js';
import localizedFormat from 'dayjs/esm/plugin/localizedFormat/index.js';
import { starIcon } from './reqbaz-icons.js';
/**
* Here is a description of my web component.
*
* @element reqbaz-requirement-card
*
*/
export class ReqbazRequirementCard extends LitElement {
static get styles() {
return css`
:host {
display: block;
box-sizing: border-box
width: 100%;
max-width: 800px;
padding: 10px 16px;
color: var(--test-component-two-text-color, #000);
border-radius: 8px;
box-shadow: 0 1px 2px lightgrey;
font-family: system-ui;
background-color: white;
}
#container {
}
.line {
margin: 10px 0;
background: #c6c6c6 no-repeat scroll center;
width: 100%;
height: 1px;
}
.icon {
width: 24px;
height: 24px;
fill: #757575;
}
#header {
display: flex;
flex-direction: row;
}
#name {
flex: 1;
font-size: 20px;
}
#lastUpdated {
font-size: 14px;
color: #5d5d5d;
}
#description {
margin-top: 8px;
}
.subtitle {
font-weight: bold;
}
#actionButtons {
width: 100%;
display: flex;
flex-direction: row;
}
.button {
display: flex;
height: 36px;
flex: 1;
margin: 5px;
border-radius: 6px;
background-color: #f3f3f3;
cursor: pointer;
align-items: center;
justify-content: center;
font-weight: bold;
color: #5d5d5d;
}
#actionButtons :first-child {
margin-left: 0px;
}
.button:hover {
background: #e4e4e4;
}
`;
}
static get properties() {
return {
/**
* Base URL of the Requirements Bazaar instance to work with.
*/
baseUrl: { type: String },
requirementId: { type: Number },
name: { type: String },
description: { type: String },
creationDate: { type: String },
lastUpdated: { type: String },
creator: { type: String },
comments: { type: Array },
numberOfComments: { type: Number },
numberOfFollowers: { type: Number },
numberOfAttachments: { type: Number },
};
}
constructor() {
super();
this.baseUrl = 'https://requirements-bazaar.org/bazaar/';
this.requirementId = 2337;
this.name = '';
this.description = '';
this.creator = '';
this.comments = [];
this.numberOfComments = 0;
this.numberOfFollowers = 0;
this.numberOfAttachments = 0;
this._commentsVisible = false;
dayjs.extend(relativeTime);
dayjs.extend(localizedFormat);
}
render() {
// use https://day.js.org/docs/en/installation/browser for date
return html`
<div id="container">
<div id="header">
<div id="name">${this.name}</div>
<div class="icon">${starIcon}</div>
</div>
<div id="lastUpdated" title=${dayjs(this.creationDate).format('LLL')}>${dayjs(this.creationDate).fromNow()} by ${this.creator}</div>
<div id="description">${this.description}</div>
<div class="line"></div>
<div id="actionButtons">
<div id="upvoteButton" class="button">Vote</div>
<div id="commentsButton" class="button" @click="${this._handleCommentsButtonClick}">${this.numberOfComments} Comments</div>
<div id="followersButton" class="button">${this.numberOfFollowers} Follow</div>
<!--<div id="attachmentsButton" class="button">${this.numberOfAttachments} Attachments</div>-->
<div id="shareButton" class="button">Share</div>
</div>
${this._commentsVisible?
html`
<div id="comments">
<div class="subtitle">Comments</div>
<reqbaz-comments-thread requirementId=${this.requirementId}></reqbaz-comments-thread>
</div>
`: html``}
</div>
`;
}
connectedCallback() {
super.connectedCallback();
// the fetch is anyway called when the property changes
// this.fetchRequirement();
}
updated(changedProperties) {
changedProperties.forEach((oldValue, propName) => {
if (propName === 'requirementId') {
this.fetchRequirement();
}
});
}
async fetchRequirement() {
const url = `${this.baseUrl}requirements/${this.requirementId}`;
const response = await fetch(url);
const jsonResponse = await response.json();
// update properties
this._populateProperties(jsonResponse);
}
_populateProperties(requirementJson) {
this.name = requirementJson.name;
this.description = requirementJson.description;
this.creator = requirementJson.creator.userName;
this.creationDate = requirementJson.creationDate;
this.numberOfComments = requirementJson.numberOfComments;
this.numberOfFollowers = requirementJson.numberOfFollowers;
this.numberOfAttachments = requirementJson.numberOfAttachments;
}
_handleCommentsButtonClick() {
this._commentsVisible = !this._commentsVisible;
this.requestUpdate();
}
}
|
const fs = require('fs')
const path = require('path')
const md5File = require('md5-file')
const findParentDir = require('find-parent-dir')
/**
* 收集资源信息
*
* @param {String} file
*/
const collectAssetInfo = file => {
// 文件信息
let stat = null
try { stat = fs.statSync(file) } catch(e) {}
// 文件版本
const version = stat && stat.isFile() ? collectAssetVersion(file) : ''
return {stat, version, file}
}
/**
* 计算文件版本
*
* @param {*} file
*/
const collectAssetVersion = file => {
let version = ''
if (file.match(/node_modules\//)) {
// 查询到package.json获取版本信息
try {
const dir = findParentDir.sync(path.dirname(file), 'package.json')
if (dir) {
version = require(path.join(dir, 'package.json')).version
}
} catch (e) {}
}
// 文件md5作为版本信息
if (!version) {
version = md5File.sync(file)
}
return version
}
module.exports = {
collectAssetInfo,
collectAssetVersion
} |
var AWS = require('aws-sdk');
AWS.config.update({region: 'eu-central-1'});
const listTopics = async () => {
var listTopicsPromise = new AWS.SNS({apiVersion: '2010-03-31'}).listTopics({}).promise();
let list = await listTopicsPromise;
return list.Topics;
};
const isTopic = async (topic) => {
let topicArn = 'arn:aws:sns:eu-central-1:666702137936:' + topic;
let isTopic = false;
const topics = await listTopics();
if(!topics) return false;
topics.forEach( topic => {
if(topic.TopicArn === topicArn) {
isTopic = true;
}
});
return isTopic;
}
exports.isTopic = isTopic; |
import nodemailer from "nodemailer";
const from = '"Onebit" <info@http://companygovern.com.com>';
function setup() {
return nodemailer.createTransport({
host: process.env.EMAIL_HOST,
port: process.env.EMAIL_PORT,
auth: {
user: process.env.EMAIL_USER,
pass: process.env.EMAIL_PASS
}
});
}
export function sendConfirmationEmail(user) {
const tranport = setup();
const email = {
from,
to: user.email,
subject: "[IMPORTANT] Confirm your Email Address",
text: `
Thanks for getting started with Onebit!
Click the link below to activate the Onebit!
Profile associated with the following email address;
${user.email}
Please verify with below link.
${user.generateConfirmationUrl()}
`
};
tranport.sendMail(email);
}
export function sendResetPasswordEmail(user) {
const tranport = setup();
const email = {
from,
to: user.email,
subject: "[IMPORTANT] Reset Password",
text: `
Click the link below to reset your password to Codex dashboard.
Profile associated with the following email address;
${user.email}
${user.generateResetPasswordLink()}
`
};
tranport.sendMail(email);
}
export function sendAccountConfirmedEmail(user) {
const tranport = setup();
const email = {
from,
to: user.email,
subject: "OBT Tokensale Platform: You Are Welcome!",
text: `
Congratulations !
You've successfully registered for our token sale.
Let us guide you to make the whole buying process easier.
`
};
tranport.sendMail(email);
}
|
import React, { Component } from 'react'
import fireApp from '../firebase'
import firebase from 'firebase'
import {
BrowserRouter as Router,
Route,
Redirect
} from 'react-router-dom'
import PlayerSignIn from './PlayerSignIn';
import Game from './Game'
class App extends Component {
constructor (props) {
super(props)
this.state = {
descriptionText: '',
players: {},
userActive: false,
userName: '',
activeUid: '',
showVotes: false
}
}
componentDidMount () {
firebase.auth().onAuthStateChanged(user => {
if (user && this.state.userName) {
fireApp.database().ref(`users/${user.uid}`).set({
points: '',
name: this.state.userName
})
.then(() => fireApp.database().ref('users/').once('value'))
.then(snapshot => snapshot.val())
.then(data => {
this.setState({
players: data,
userActive: true,
activeUid: user.uid
})
})
.catch((err) => console.error("This is error: ", Error(err)))
} else if (user) {
fireApp.database().ref('users/').once('value')
.then(snapshot => snapshot.val())
.then(data => {
this.setState({
players: data,
userActive: true,
activeUid: user.uid
})
})
.catch((err) => console.error("This is error: ", Error(err)))
}
})
fireApp.database().ref('users/').on('value', this.updatePlayers)
fireApp.database().ref('showVotes/').on('value', (snapshot) => {
this.setState({
showVotes: snapshot.val()
})
})
}
componentWillUnmount () {
fireApp.database().ref('users/').off(this.updatePlayers)
}
updatePlayers = (snapshot) => {
this.setState({
players: snapshot.val()
})
}
authUser = () => {
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.SESSION)
.then(() => firebase.auth().signInAnonymously())
.catch(err => console.error(Error(err)))
}
signOut = () => {
const {activeUid} = this.state
firebase.auth().currentUser.delete()
.then((snapshot) => {
this.setState({
userActive: false,
userName: '',
activeUid: '',
})
})
.then(() => {
return fireApp.database().ref('users/' + activeUid).remove()
})
.catch(err => console.error(Error(err)))
}
updateDescription = (evt) => {
this.setState({descriptionText: evt.target.value})
}
showVotes = () => {
this.setState({showVotes: !this.state.showVotes}, () => {
fireApp.database().ref('showVotes/').set(this.state.showVotes)
})
}
clearVotes = () => {
const updates = {}
Object.keys(this.state.players).forEach((uid) => {
updates[`users/${uid}/points`] = ''
})
updates['showVotes/'] = false
fireApp.database().ref().update(updates)
}
updatePoints = (points) => {
fireApp.database().ref(`users/${this.state.activeUid}/points`).set(points)
}
updateUserName = (evt) => {
this.setState({userName: evt.target.value})
}
render () {
const { descriptionText, userActive, userName, activeUid, players, showVotes } = this.state
return (
<Router>
<div>
<Route exact path='/' render={(props) => {
return (userActive ? <Redirect to={'/game'} /> :
<PlayerSignIn
{...props}
userName={userName}
updateUserName={this.updateUserName}
authUser={this.authUser}
/>)
}}/>
<Route exact path='/game' render={(props) => {
return (userActive ?
<Game
{...props}
descriptionText={descriptionText}
activeUid={activeUid}
players={players}
showVotes={showVotes}
updatePoints={this.updatePoints}
updateDescription={this.updateDescription}
showVotesFunc={this.showVotes}
clearVotes={this.clearVotes}
signOut={this.signOut}
/>
:
<Redirect to={'/'} />
)}}
/>
</div>
</Router>
)
}
}
export default App
|
// Kitchen
// for DanIdle version 4
// provides a place where foods can be processed and prepared to be eaten. Since we're starting with very limited technology, this assumes the
// only real tools you have (to start with) is a knife
import { game } from "./game.js";
import { item, food } from "../index.js";
import {
blockOutputsItems,
blockHasWorkerPriority,
blockHandlesFood,
blockDeletesClean,
blockShowsOutputItems
} from "./activeBlock.js";
import { blockRequiresTool } from "./blockAddon_RequiresTool.js";
import { blockHasOutputsPerInput } from "./blockAddon_HasOutputsPerInput.js";
import $ from "jquery";
export const kitchen = mapSquare => {
let state = {
name: "kitchen",
tile: mapSquare,
id: game.getNextBlockId(),
counter: 0,
alloutOutput: true,
outputItems: [
{
name: "Whole Wheat",
craftTime: 5,
output: [
{ name: "Wheat Seeds", qty: 1 },
{ name: "Wheat Stalks", qty: 1 }
]
}
],
toolChoices: [
{
groupName: "Cutter",
isRequired: true,
choices: ["None", "Flint Knife"]
}
],
// getItem() is already defined in blockOutputsItems
// possibleOutputs() is already defined in blockHasOutputsPerInput
// inputsAccepted() is already defined in blockHasOutputsPerInput
// willOutput() is already defined in blockOutputsItems
// willAccept() is already defined in blockHasOutputsPerInput
// receiveItem() is already defined in blockHasOutputsPerInput
update() {
// Yes, this is copied directly from the ButcherShop block. But they behave exactly the same
if (!state.readyToCraft()) {
if (game.workPoints <= 0) return; // We have no workers to work this block anyway
state.searchForItems();
return;
}
if (game.workPoints <= 0) return;
const eff = state.checkTool(true);
if (eff === null) return;
game.workPoints--;
state.processCraft(1);
},
drawPanel() {
let curjob = "n/a";
let craftPercent = "n/a";
if (state.inItems.length > 0) {
curjob = state.inItems[0].name;
craftPercent = Math.floor(
(state.counter * 100) /
state.outputItems.find(
ele => ele.name === state.inItems[0].name
).craftTime
);
}
$("#sidepanel").html(`
<b><center>Kitchen</center></b><br />
<br />
<p>As more food options become available, preparing foods before cooking becomes necessary.</p>
<p>
Actions available:
<ul>
<li>Cut whole wheat into stems and seeds
<li>Other options to come later
</ul>
</p>
`);
state.showPriority();
$("#sidepanel").append(`
<br />
Items to process:<span id="sidepanelinput">${state.inItems.length}</span><br />
Current work: <span id="sidepanelworking">${curjob}</span><br />
Current progress: <span id="sidepanelprogress">${craftPercent}</span>%<br />
`);
state.showDeleteLink();
$("#sidepanel").append(`
<br />
Output items on hand:
<div id="sidepanelonhand">${state.displayItemsOnHand()}</div>
`);
state.showTools();
},
updatePanel() {
$("#sidepanelinput").html(state.inItems.length);
if (state.inItems.length > 0) {
$("#sidepanelworking").html(state.inItems[0].name);
$("#sidepanelprogress").html(
Math.floor(
(state.counter * 100) /
state.outputItems.find(
ele => ele.name === state.inItems[0].name
).craftTime
)
);
} else {
$("#sidepanelworking").html("n/a");
$("#sidepanelprogress").html("n/a");
}
$("#sidepanelonhand").html(state.displayItemsOnHand());
state.updateToolPanel();
},
deleteBlock() {
// Nothing extra to do here
state.finishDelete();
}
};
game.blockList.push(state);
mapSquare.structure = state;
$("#" + state.tile.id + "imageholder").html(
'<img src="img/kitchen.png" />'
);
return Object.assign(
state,
blockOutputsItems(state),
blockShowsOutputItems(state),
blockRequiresTool(state),
blockHasWorkerPriority(state),
blockDeletesClean(state),
blockHasOutputsPerInput(state)
);
};
|
class {
onCreate() {
this.state = { count:0 };
}
increment() {
this.state.count++;
}
}
style {
.count {
color:#09c;
font-size:3em;
}
.example-button {
font-size:1em;
padding:0.5em;
}
}
<div.count>
${state.count}
</div>
<button.example-button on-click('increment')>
Click me!
</button> |
var _viewer = this;
//打开自服务列表
if(typeof(_viewer.opts.paramData) !="undefined"){
var sid = _viewer.opts.paramData.showTab;
if(sid != ""){
var topObj = jQuery("li.rhCard-tabs-topLi[sid='" + sid + "']",_viewer.tabs);
topObj.find("a").click();
}
} |
import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import Book from "./Book";
import { getAll, search, update } from "./BooksAPI";
function Search() {
const [books, setBooks] = useState([]);
const [homeBooks, setHomeBooks] = useState([]);
// mount logic
useEffect(() => {
getAll().then((books) => setHomeBooks(books));
}, []);
function updateBook(book, shelf) {
update(book, shelf)
.then((res) => {
const slice = books.slice();
// update the updated book shelf in our local list on success
slice.find(({ id }) => id === book.id).shelf = shelf;
setBooks(slice);
})
.catch(() => {
alert("Something went wrong while updating the book");
});
}
function handleSearch(evt) {
const query = evt.currentTarget.value;
if (!query) return setBooks([]);
search(query)
.then((searchBooks) => {
if (searchBooks.error) return setBooks([]);
// add shelf attr to searchBooks
homeBooks.forEach(({ id, shelf }) => {
const target = searchBooks.find((book) => book.id === id);
if (target) target.shelf = shelf;
});
setBooks(searchBooks);
})
.catch(() => {
alert("Something went wrong while fetching your books");
});
}
return (
<div className="search-books">
<div className="search-books-bar">
<Link to="/" className="close-search">
Close
</Link>
<div className="search-books-input-wrapper">
<input
type="text"
name="query"
placeholder="Search by title or author"
onChange={handleSearch}
/>
</div>
</div>
<div className="search-books-results">
<ol className="books-grid">
{books.map((book) => {
return (
<li key={book.id}>
<Book book={book} onUpdateBook={updateBook} />
</li>
);
})}
</ol>
</div>
</div>
);
}
export default Search;
|
;
(function(undefined) {
var files = [];
var FS = MKNoteWebclipper.FS = {
removeFiles: function() {
},
onFileError: function(err) {
},
create: function(size, fileName, blob, callback, errorFn) {
callback(null);
}
}
})(); |
const jwt = require('jsonwebtoken');
const User = require('../models/User');
const error = {
success: false,
message: 'Failed to authenticate token.'
};
const verifyToken = (token, ctx) =>
new Promise(async (resolve, reject) => {
if (token) {
jwt.verify(token, 'secret', function(err, decoded) {
if (err) {
reject(error);
} else {
resolve(decoded);
}
});
} else {
reject(error);
}
});
module.exports = async (ctx, next) => {
var token =
ctx.request.body.token ||
ctx.request.headers['authorization'].replace('Bearer ', '');
try {
const decoded = await verifyToken(token, ctx);
ctx.request.user = await User.findOne({ email: decoded.email });
await next();
} catch (error) {
ctx.body = error;
ctx.status = 403;
}
};
|
function inheritPrototype(childObject, parentObject) {
var copyOfParent = Object.create(parentObject.prototype);
copyOfParent.constructor = childObject;
childObject.prototype = copyOfParent;
}
function User(theName, theEmail) {
this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;
}
User.prototype = {
constructor: User,
saveScores: function(theScoreToAdd) {
this.quizScores.push(theScoreToAdd);
},
showNameAndScores: function() {
var scores = this.quizScores.length > 0 ? this.quizScores.join(","): "No score yet!";
return this.name + "Scores: " + scores;
},
changeEmail: function(newEmail) {
this.email = newEmail;
return "New Email saved: " + this.email;
}
}
firstUser = new User('Bright', 'menezy10@gmail.com');
console.log(firstUser.changeEmail('menezy25@gmail.com'));
firstUser.saveScores(15);
firstUser.saveScores(25);
console.log(firstUser.showNameAndScores());
secondUser = new User('Magdalene', 'magdalene@gmail.com');
secondUser.saveScores(30);
secondUser.saveScores(12);
console.log(secondUser.showNameAndScores());
function Question(theQuestion, theChoices, theCorrectAnswer) {
this.question = theQuestion;
this.choices = theChoices;
this.correctAnswer = theCorrectAnswer;
this.userAnswer = "";
var newDate = new Date();
QUIZ_CREATED_DATE = newDate.toLocaleDateString();
this.getQuizDate = function(){
return QUIZ_CREATED_DATE;
};
console.log("Quiz created on: " + this.getQuizDate());
}
Question.prototype.getCorrectAnswer = function(){
return this.correctAnswer;
}
Question.prototype.getUserAnswer = function() {
return this.userAnswer;
}
Question.prototype.displayQuestion = function() {
var questionToDisplay = "<div class='question'>" + this.question + "</div> <ul>";
choiceCounter = 0;
this.choices.forEach(function(eachChoice){
questionToDisplay += '<li><input type="radio" name="choice" value="'+ choiceCounter +'">' + eachChoice + '</li>';
choiceCounter++;
})
questionToDisplay += '</ul>';
document.getElementById('quiz').innerHTML = questionToDisplay;
};
function multipleChoiceQuestion(theQuestion, theChoices, theCorrectAnswer){
Question.call(this, theQuestion, theChoices, theCorrectAnswer);
};
inheritPrototype(multipleChoiceQuestion, Question);
function dragAndDropQuestion(theQuestion, theChoices, theCorrectAnswer){
Question.call(this, theQuestion, theChoices,theCorrectAnswer);
}
inheritPrototype(dragAndDropQuestion, Question);
dragAndDropQuestion.prototype.displayQuestion = function(){
console.log(this.question);
};
var allQuestions = [
new multipleChoiceQuestion('Who is the Prime Minister of England?', ['Obama','Blair','Brown','Cameron'], 3),
new multipleChoiceQuestion('What is the capital of Nigeria?', ['Lagos','Calabar','Abuja','Port-Harcourt'], 2),
new dragAndDropQuestion('Drag the correct city to the world map', ['Washington DC','London','Paris','Lagos'],3)
];
allQuestions.forEach(function (eachQuestion) {
eachQuestion.displayQuestion();
}); |
/*
* Sous objet Test.Messages
* ------------------------
* Pour le traitement des messages
*/
function tostring(exp){
switch(exp){
case null: return "NULL"
case false: return "FALSE"
case true: return "TRUE"
case undefined: return "UNDEFINED"
case "DEFINED": return exp
default:
switch(typeof exp){
case 'string': return '“'+exp+'”';
default: return exp.toString();
}
}
}
window.Test.Messages = {
// Méthode qui permet d'écrire à l'écran les spécificités d'un test, par exemple ce qu'on
// attend d'une méthode testée
// @param message Le message à afficher
// @param options Unused.
specs:function(message, options){
if(Test.SILENCE) return
Test.write_in_rapport('div', message, 'specs')
},
// Écriture d'un "message bleu" dans le rapport
blue:function(message){
w("\n"+message, BLUE)
},
// Construit le message de résultat du test en fonction de :
// * La réussite ou l'échec
// * L'ajout de données (p.e. `after_if_failure`)
// * La définition de messages customisés
build_message_test:function(ok, options){
var mesres;
options.test = (this.positif?'should':'should_not') + '.' + options.test
// Existe-t-il des messages personnalisés pour la méthode de test courante ?
if(this.table = this.get_table_customized_messages(options)){
mesres = this.message_propre_au_test(ok, options);
(undefined == mesres) && (mesres = this.message_defaut_of_test(ok, options));
}
mesres = mesres || this.get_regular_message(ok, options)
mesres = this.correct_templates_in(mesres, options)
// Retourner le message préparé
return mesres;
},
// Méthode qui regarde si une table de messages personnalisés existe pour la
// méthode de test courante.
// Si oui, elle renvoie cette table, sinon elle renvoie FALSE
get_table_customized_messages:function(options){
try{return eval("UMessages."+options.test)}
catch(erreur){return false}
},
// Regarde si des messages customisés propre au test précis existe et les
// renvoie. Retourne UNDEFINED dans le cas contraire
message_propre_au_test:function(ok, options){
if(undefined != this.table[options.args[0]]){
return this.table[options.args[0]][ok?'success':'failure'];
}
},
// Regarde si des messages customisés par défaut existent pour la fonction de
// test.
message_defaut_of_test:function(ok, options){
if(undefined != this.table.default) return this.table.default[ok?'success':'failure'];
},
// Nouvelle tournure avec les nouvelles propriétés
//
// @note Pour ne pas afficher la valeur 'expected', mettre `no_expected_result` à true :
// no_expected_result:true
//
// @note Si `dont_inspect_expected' est true, la propriété expected_result est
// inscrite telle quelle
//
get_regular_message:function(ok, options){
// Nouvelle tournure
var ksens = options.positif ? 'positif' : 'negatif' ;
var kresu = ok ? 'success' : 'failure' ;
return (options.before || "") +
options.sujet + ' ' +
(options._before_result ? options._before_result[ksens][kresu] : "") +
options.result[ksens][kresu] + " " +
this.build_texte_expected(options) +
this.build_texte_after(ok, options);
},
// Construire ce qui doit être écrit "_after"
build_texte_after:function(ok, options){
var ajout_after = "" ;
var ksens = options.positif ? 'positif' : 'negatif' ;
(options._after_result) && (ajout_after += options._after_result);
(!ok && options.after_if_failure && options.after_if_failure[ksens]) && (ajout_after += " ("+options.after_if_failure[ksens]+")");
return ajout_after
},
// Construire le texte de la valeur attendue (expected)
build_texte_expected:function(options){
if( options.no_expected_result ) return ""
if( options.dont_inspect_expected ) return options.expected_result
return inspect(options.expected_result)
},
// Correction des templates dans le messages +mes+
// Retourne le texte apprêté
correct_templates_in:function(mes, options){
var iarg, reali, val_arg;
if (mes.indexOf('#{') < 0) return mes;
for(iarg = 0, len=options.args.length; iarg<len; ++iarg){
reali = 1 + parseInt(iarg,10);
if(mes.indexOf("#{"+reali+"}") < 0) continue;
val_arg = options.args[iarg];
if(iarg > 0) val_arg = tostring(val_arg);
mes = mes.replace(
new RegExp('\\#\\{'+reali+'\\}', 'g'),
val_arg
);
}
if(mes.indexOf("#{value}") > -1 ){
mes = mes.replace(
new RegExp('\\#\\{value\\}', 'g'),
tostring(options.eval_result)
);
}
if(mes.indexOf("#{subject}") > -1){
mes = mes.replace(
new RegExp('\\#\\{subject\\}', 'g'),
options.sujet
);
}
return mes;
},
correct_code_in:function(messa)
{
// console.log(messa.match(/\`([^\`\n]+)\`/g))
return messa.replace(/\`([^\`\n]+)\`/g, function(tout, code, index){
return '<code>' + code.replace(/\</g,'<').replace(/\>/g, '>') + '</code>'
})
}
}
window.specs = Test.Messages.specs
window.blue = Test.Messages.blue |
import { useToggle } from '..';
describe('useToggle', () => {
it('is truthy', () => {
expect(useToggle).toBeTruthy();
});
}); |
define([
'extensions/views/view'
], function (View) {
return View.extend({
initialize: function () {
this.listenTo(this.collection, 'reset add remove', this.render);
},
render: function() {
var url = this.collection.url();
var urlJson = url+'&format=json';
this.$el.html( $('<a href="' + urlJson + '">JSON</a>') );
return this;
}
});
});
|
//-------------------------------------------------------------------------------------------------
// FILLING IN PREFLIGHT INFORMATION IN THE HTML
//-------------------------------------------------------------------------------------------------
// Given the page index for a page (0-based), sets the correct URL to inElement.
// Example: updatePreviewImage( "#preview_image", 0 )
//
// inElement: a jQuery compatible element identifier
// inPage: the (0-based) page number for the page you're interested in
//
function updatePreviewImage( inElement, inPage ) {
$(inElement).attr("src", cals_doc_info.docs[0].pages[0].page_img);
}
// Looks for elements with specific names and replaces their value with the information provided by
// pdfToolbox in the cals_params file or in the XML report file. This function fills elements with
// the following classes:
// - params_document_name
// - params_number_of_pages
// - params_summary_trim_size
// - params_profile_name
// - params_preflighted_when_by
// - params_summary_result
// - params_file_size
// - params_pdf_version
// - params_standards
// - params_document_title
// - params_creator
// - params_producer
// - params_preflight_information
//
// This function uses classes instead of ids because the same value might have to be replaced for
// multiple elements in the DOM
//
function completeFromParams() {
// Document name
$(".params_document_name").html( cals_doc_info.docs[0].file_name );
// Number of pages
$(".params_number_of_pages").html( getNumPages() );
// Trim size summary
$(".params_summary_trim_size").html( getTrimSizeSummary() );
// Preflight profile name
$(".params_profile_name").html( cals_res_info.profile_name );
// Preflighted when and by
$(".params_preflighted_when_by").html( cals_env_info.date.slice(0, 10) + " <span class='lighter translatable'>at</span> " + cals_env_info.date.slice(11, 16) );
// Summary result
$(".params_summary_result").html( (getNumberOfErrors() == 0) ? "Success!" : "Errors!" ).addClass("translatable");
// File size
$(".params_file_size").html( humanFileSize( cals_doc_info.docs[0].file_size, true ) );
// PDF version
$(".params_pdf_version").html( cals_doc_info.docs[0].pdf_version );
// Standards
var theStandardsText = ($.isArray( cals_doc_info.docs[0].standards ) && (cals_doc_info.docs[0].standards.length > 0)) ? cals_doc_info.docs[0].standards.join( ", " ) : "none";
$(".params_standards").html( theStandardsText );
// Document title
$(".params_document_title").html( cals_doc_info.docs[0].docinfo.Title );
// Creator
$(".params_creator").html( cals_doc_info.docs[0].docinfo.Creator );
// Producer
$(".params_producer").html( cals_doc_info.docs[0].docinfo.Producer );
// Preflight information
$(".params_preflight_information").html( cals_env_info.tool_name + " " + cals_env_info.tool_variant + " " + cals_env_info.tool_version + " <span class='lighter translatable'>on</span> " + cals_env_info.os_version_text + " <span class='lighter translatable'>by</span> " + cals_env_info.user_name );
}
// Hides either the success or the error image in the report
//
function updateResultImages( inElementSuccess, inElementError ) {
if (getNumberOfErrors()==0) {
$(inElementError).hide();
} else {
$(inElementSuccess).hide();
}
}
// Rearranges the summary section based on the information about the preview image
//
function arrangeSummarySection( inElementPreview, inElementPreviewImage, inElementNonPreview, inElementText, inElementIcons ) {
// Determine whether our preview image is landscape or portrait
var previewWidth = $( inElementPreviewImage ).width();
var previewHeight = $( inElementPreviewImage ).height();
var previewLandscape = previewWidth > previewHeight;
// Add different layout depending on which case we have
if (previewLandscape) {
// Landscape
$( inElementPreviewImage ).css( {
"max-width": "120mm",
"max-height": "80mm"
} );
$( inElementNonPreview ).css( {
"clear": "both",
} );
$( inElementText ).css( {
"float": "left",
"padding-top": "10mm"
} );
$( inElementIcons ).css( {
"float": "left",
"padding-left": "10mm",
"padding-top": "10mm"
} );
} else {
// Portrait
$( inElementPreview ).css( {
"float": "left"
} );
$( inElementPreviewImage ).css( {
"max-width": "85mm",
"max-height": "110mm"
} );
$( inElementNonPreview ).css( {
"position": "relative",
"padding-left": "10mm",
"float": "left",
"max-width": "105mm"
} );
$( inElementNonPreview ).height($( inElementPreviewImage ).height());
$( inElementIcons ).css( {
"position": "absolute",
"bottom": 0
} );
}
}
// Inserts all hits and fixups in the result section of the report
//
function insertHitsAndFixups( inContainer ) {
// Get the information we need to insert
var theHits = getHits();
var theFixups = getFixups();
// If there is content, create it
if ((theHits.length > 0) || (theFixups.length > 0)) {
// Insert all errors, then warnings, then informational items
for (var theErrorIndex = 0; theErrorIndex < theHits.length; theErrorIndex++) {
var theError = theHits[theErrorIndex];
if (theError.severity == "error") {
insertHit( inContainer, "img/hit_error.pdf", theError.rule_name, theError.matches, theError.on_pages, "error" );
}
}
for (var theWarningIndex = 0; theWarningIndex < theHits.length; theWarningIndex++) {
var theWarning = theHits[theWarningIndex];
if (theWarning.severity == "warning") {
insertHit( inContainer, "img/hit_warning.pdf", theWarning.rule_name, theWarning.matches, theWarning.on_pages, "warning" );
}
}
for (var theInfoIndex = 0; theInfoIndex < theHits.length; theInfoIndex++) {
var theInfo = theHits[theInfoIndex];
if (theInfo.severity == "info") {
insertHit( inContainer, "img/hit_info.pdf", theInfo.rule_name, theInfo.matches, theInfo.on_pages, "info" );
}
}
// Insert all fixups
for (var theFixupIndex = 0; theFixupIndex < theFixups.length; theFixupIndex++) {
var theFixup = theFixups[theFixupIndex];
insertFixup( inContainer, "img/hit_fixup.pdf", theFixup.fixup_name, theFixup.succeeded, theFixup.failed );
}
} else {
// Nothing to do, hide this section
$( inContainer ).hide();
}
}
// Inserts a single hit item in the result section of the report
//
function insertHit( inContainer, inImageURL, inName, inNumberOfTimes, inPageList, inType ) {
// Insert a container for the hit
var theHitContainer = $( '<div/>', {
class: 'section_hits_hit ' + inType
}).appendTo( $(inContainer) );
// Insert an image and a paragraph
var theHitImage = $( '<img/>', {
src: inImageURL
}).appendTo( theHitContainer );
// Insert an image and a paragraph
var theHitText = $( '<p/>').appendTo( theHitContainer );
// Format the occurrence string as we want
var theOccurrence = addTimes( inNumberOfTimes );
if ((inPageList != undefined) && (inPageList.length > 0)) {
theOccurrence += " " + formatPageList( inPageList );
}
// Calculate the text we want for this item and insert it
theHitText.html( inName + "<span class='lighter smaller'>" + " (" + theOccurrence + ")" + "</span>");
}
// Formats a page list for human consumption
//
function formatPageList( inPageList ) {
// Add one to all pages or they'll be wrong (0-based)
for (var theIndex = 0; theIndex < inPageList.length; theIndex++) {
inPageList[theIndex]++;
}
// Our page list must at least have one page or we wouldn't get here... let's format easy cases
// in a special way...
if (inPageList.length == 1) {
return "<span class='translatable'>on</span> <span class='translatable'>page</span> " + inPageList[0];
} else if (inPageList.length < 6) {
return "<span class='translatable'>on</span> <span class='translatable'>pages</span> " + inPageList.join( ", " );
} else {
var theShortList = inPageList.slice( 0, 5);
var theRemaining = inPageList.length - 5;
return "<span class='translatable'>on</span> <span class='translatable'>pages</span> " +
theShortList.join( ", " ) + " <span class='translatable'>and</span> " + theRemaining + " <span class='translatable'>more</span>";
}
}
// Inserts a single fixup item in the result section of the report
//
function insertFixup( inContainer, inImageURL, inName, inSucceeded, inFailed ) {
// Insert a container for the fixup
var theFixupContainer = $( '<div/>', {
class: 'section_hits_fixup'
}).appendTo( $(inContainer) );
// Insert an image and a paragraph
var theFixupImage = $( '<img/>', {
src: inImageURL
}).appendTo( theFixupContainer );
// Insert an image and a paragraph
var theFixupText = $( '<p/>').appendTo( theFixupContainer );
// Calculate the text we want for this item and insert it
var theOccurrence = "";
var theSucceededString = addTimes( inSucceeded );
var theFailedString = "<span class='translatable'>failed</span> " + addTimes( inFailed );
if (inSucceeded == 0) {
theOccurrence = theFailedString;
} else {
theOccurrence = (inFailed == 0) ? theSucceededString : theSucceededString + ", " + theFailedString;
}
var theDescription = inName + "<span class='lighter smaller'>" + " (" + theOccurrence + ")</span>";
theFixupText.html( theDescription );
}
// Adds "time" or "times" to a string depending on the number
//
function addTimes( inNumber ) {
if (inNumber == 1) {
return inNumber + " <span class='translatable'>time</span>";
} else {
return inNumber + " <span class='translatable'>times</span>";
}
}
// Inserts information about colors
//
function insertColorInformation( inContainer ) {
// Get the color information for the whole document
var theColorInformation = xmlGetInkCoverageStatistics( 0 );
// Loop over the colors and divide it in process colors and spot colors
var theProcessColors = [];
var theSpotColors = [];
for (var theIndex = 0; theIndex < theColorInformation.length; theIndex++) {
// Only handle those that are used
var theColor = theColorInformation[theIndex];
if (theColor.percentage > 0) {
switch( theColor.name ) {
case "Cyan":
case "Magenta":
case "Yellow":
case "Black": {
theProcessColors.push( theColor );
break;
}
default: {
theSpotColors.push( theColor );
break;
}
}
}
}
// Add process information
for (var theProcessColorIndex = 0; theProcessColorIndex < theProcessColors.length; theProcessColorIndex++) {
var theColor = theProcessColors[theProcessColorIndex];
var theColorDefinition = xmlGetInkDefinitionAsText( theColor );
insertColorLine( inContainer, theColorDefinition, theColor.name, theColor.percentage, theColor.squareCm );
}
// Add spot color information
for (var theSpotColorIndex = 0; theSpotColorIndex < theSpotColors.length; theSpotColorIndex++) {
var theColor = theSpotColors[theSpotColorIndex];
var theColorDefinition = xmlGetInkDefinitionAsText( xmlGetInformationForSeparationWithName( theColor.name ) );
insertColorLine( inContainer, theColorDefinition, theColor.name, theColor.percentage, theColor.squareCm );
}
}
// Inserts one line with color information
//
function insertColorLine( inContainer, inColorDefinition, inName, inPercentage, inSurface ) {
// Insert a container for the color
var theColorContainer = $( '<div/>', {
class: 'section_color_key_value',
}).appendTo( $(inContainer) );
// Insert the color patch and the text
var theColorPatch = $( '<div/>', {
class: 'colorpatch',
}).css('background-color', inColorDefinition).appendTo( theColorContainer );
var theValueText = $( '<p/>', {
class: 'section_color_value'
}).appendTo( theColorContainer );
// Set the correct text for them
theValueText.html( inName + "<span class='lighter smaller'>" + " (" + inPercentage.toFixed(2) + "%, " + inSurface.toFixed(2) + "sqcm" + ")</span>" );
}
// Updates the ink coverage image in the report
//
function updateInkCoverageImage() {
// We support only one page so we'll always take page 1
var imageInkCoverage = $( ".ink_coverage_preview img" );
imageInkCoverage.attr("src", cals_doc_info.docs[0].pages[0].page_viz_images[0]);
}
// Inserts images to show all separations for the first page
//
function insertSeparationImages() {
// The container we want to insert them into
var separationContainer = $( ".separation_preview" );
// Loop over all images and insert them
for (var index = 1; index < cals_doc_info.docs[0].pages[0].page_viz_images.length; index++) {
// Separation image
var imagePath = cals_doc_info.docs[0].pages[0].page_viz_images[index];
var sepName = imagePath.split("_").pop().split(".").shift();
// Create an image, attach it and set its source to what we want
var imageContainer = $( '<div>', {
class: "separation_preview_single"
} ).appendTo( separationContainer );
var title = $( '<p>' ).appendTo( imageContainer );
title.text( sepName );
var image = $( '<img/>', {
src: imagePath
} ).appendTo( imageContainer );
}
}
//-------------------------------------------------------------------------------------------------
// PREFERENCES SUPPORT
//-------------------------------------------------------------------------------------------------
// Called when all resources for the page are ready and loaded
//
$( window ).on( "load", function() {
// Visibility control
$( ".section_hits_fixup" ).toggle( sShowFixups );
$( ".section_hits_hit.info" ).toggle( sShowInfos );
$( ".section_hits_hit.warning" ).toggle( sShowWarnings );
$( ".section_hits_hit.error" ).toggle( sShowErrors );
$( "#section_more_information" ).toggle( sShowMoreInformation );
$( "#section_colors" ).toggle( sShowColorInformation );
$( "#page_ink_coverage" ).toggle( sShowInkCoverage );
$( "#page_separations" ).toggle( sShowSeparations );
$( ".hide_elements" ).toggle( sShowElements );
});
|
import t from 'tcomb';
export function nonEmptyList(type, name) {
return t.refinement(
t.list(type, name),
array => array.length > 0,
name || `NonEmptyList<${ t.getTypeName(type) }>`
)
}
|
import $ from '../../core/renderer';
import { APPOINTMENT_SETTINGS_KEY } from './constants';
var utils = {
dataAccessors: {
getAppointmentSettings: element => {
return $(element).data(APPOINTMENT_SETTINGS_KEY);
},
getAppointmentInfo: element => {
var settings = utils.dataAccessors.getAppointmentSettings(element);
return settings === null || settings === void 0 ? void 0 : settings.info;
}
}
};
export default utils; |
import React from 'react'
import { reduxForm } from 'redux-form'
import { Button, Form, InputGroupAddon } from 'reactstrap'
import ReduxFormField from 'Components/ReduxFormField'
const validateDerivationPath = (path) => {
if (!(typeof path === 'string'
&& /^[a-z](\/[0-9]+'?)+$/.test(path.trim()))) {
return 'Invalid derivation path'
}
}
export default reduxForm({
form: 'derivationPathForm'
})(({ handleSubmit }) => (
<Form onSubmit={handleSubmit}>
<ReduxFormField
name='derivationPath'
label='Derivation path'
placeholder='Derivation path'
type='text'
bsSize='md'
autoCorrect={false}
autoCapitalize={false}
spellCheck={false}
validate={validateDerivationPath}
addonAppend={({ invalid }) => (
<Button color='primary' size='md' outline type='submit' disabled={invalid}>
<i className='fa fa-level-down fa-rotate-90' />
</Button>
)}
/>
</Form>
))
|
const reducer = (state, action)=>{
if(action.type === 'CLEAR_CART' ){
return{
...state,
cart:[],
}
}
if(action.type === 'REMOVE' ){
const newCart = state.cart.filter((item)=> item.id !== action.payload)
return{
...state,
cart:newCart,
}
}
if(action.type === 'INCREASE' ){
const newCart = state.cart.map((item)=> {
if(item.id === action.payload){
return{...item, amount:item.amount+1}
}
return item;
})
return{
...state,
cart:newCart,
}
}
if(action.type === "DECREASE"){
const newCart = state.cart.map((item)=>{
if(item.id === action.payload){
return{...item , amount : item.amount-1}
}
return item
}) .filter((cartItem)=>cartItem.amount !== 0);
return ({
...state,
cart:newCart
})
}
if(action.type === "TOGGLE_BUTTON"){
const newCart = state.cart.map((item)=>{
if(item.id === action.payload.id){
if(action.payload.btn === "inc"){
return{...item , amount : item.amount+1}
}
if(action.payload.btn === "dec"){
return{...item , amount : item.amount-1}
}
}
return item
}).filter((cartItem)=>cartItem.amount !== 0);
return{
...state,
cart : newCart}
}
if(action.type === "GET_TOTALS"){
let {total , amount} = state.cart.reduce(
(cartTotal , cartItem)=>{
const {price , amount} = cartItem;
const itemTotal = price * amount;
cartTotal.total += itemTotal;
cartTotal.amount += amount;
return cartTotal
},
{
total:0,
amount:0
}
)
total = parseFloat(total.toFixed(2));
return({...state, total, amount})
}
if(action.type === "LOADING"){
return{...state , loading:true}
}
if(action.type === "DISPLAY_ITEM"){
return{...state, cart : action.payload , loading:false}
}
throw new Error("no matching action type")
}
export default reducer; |
import parser from './parser';
const date = new Date();
const tommorow = `${date.getFullYear()}/${date.getMonth()}/${date.getDay()}`;
const getDate = tommorow;
module.export = {
getDate,
parser,
};
|
import React, { useState } from 'react'
import Header from '../Common/Header'
import { TaskContext } from './TaskContext'
import Tasklist from './Tasklist/Tasklist'
const Homepage = () => {
//overall taskboard of form
const [taskboard, setTaskboard] = useState(JSON.parse(localStorage.getItem("taskboard")) || [])
//task list name
const [tasklistname, setTasklistname] = useState('');
//function to add new list on board
const addtasklist = () => {
if (tasklistname.length < 1) {
alert('please type something..')
}
else {
let temp = [...taskboard, { name: tasklistname, tasks: [], id: Math.floor(Math.random() * 100000) }]
setTaskboard(temp)
localStorage.setItem("taskboard", JSON.stringify(temp));
setTasklistname('')
}
}
//delete tasklist from board
const deleteTasklist = (name) => {
let temp = taskboard
temp = temp.filter((list) => list.name !== name)
setTaskboard(temp)
localStorage.setItem("taskboard", JSON.stringify(temp));
}
return (
<TaskContext.Provider value={{ taskboard, setTaskboard }}>
<Header />
{ taskboard.length === 0 ?
<h3 style={{ color: '#10558c' }} className='p-5 text-center my-5'>No tasks list created yet <br />Create new one</h3>
:
<div className="mx-lg-5 m-3">
<div className="row row-cols-1 row-cols-md-4 g-4">
{taskboard.map((taskObject) => {
return <Tasklist
key={taskObject.id}
n={taskObject.id}
tasklist={taskObject}
setTaskboard={setTaskboard}
deleteTasklist={deleteTasklist}
/>
})}
</div>
</div>}
<div style={{}}>
<button className="btn p-0" style={{ backgroundColor: '#10558c', borderRadius: 30, position: 'fixed', width: 60, height: 60, right: 40, bottom: 40 }} data-bs-toggle="modal" data-bs-target="#exampleModal">
<i className="fa fa-plus fa-align-center text-white pt-1" style={{ fontSize: 30 }}></i>
</button>
</div>
<div className="modal fade" id="exampleModal" tabIndex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div className="modal-dialog modal-dialog-centered">
<div className="modal-content">
{/* <div className="modal-body"> */}
<div className="row no-gutters p-1 m-2" style={{ color: '#10558c' }}>
<input typr='text' className='col-10 border border-0 border-outline-primary' placeholder='New List' value={tasklistname} onChange={(e) => { setTasklistname(e.target.value) }}></input>
<i className="fa fa-plus-circle col-1" data-bs-dismiss="modal" aria-label="Close" style={{ fontSize: 45 }} onClick={() => { addtasklist() }}></i>
</div>
{/* </div> */}
</div>
</div>
</div>
</TaskContext.Provider>
)
}
export default Homepage |
/**
* hotkeys-extend.js 前端WEB快捷键组件模块
* @Date 2020-09-01 17:30:00
* @author jiangchengyong
*
***/
;(function(global, factory) {
typeof module !== 'undefined' && typeof exports === 'object' ? module.exports = factory() :
typeof define === 'function' && (define.cmd || define.amd) ? define(factory) :
(global.hotkey = factory());
}(this, function() {
/**
* 焦点转移
*/
let _focusShift = {
//焦点转移默认配置项
defaults: {
scanProp: '[focus-shift]',
enableHotkeys: ['ENTER', 'RIGHT', 'LEFT', 'ESC'],
focusElFilter: ':not(:hidden,[readonly],[disabled])'
},
options: {},
init: function(options) {
let opts = this.options = $.extend({}, this.defaults, options);
//扫描监听enter right快捷键
opts.enableHotkeys.forEach(function(item, index, arr) {
arr[index] = arr[index].toUpperCase();
})
//扫描监听enter right快捷键
opts.enableHotkeys.includes('ENTER') && hotkeys('ENTER', (e, handler) => {
console.log('you press ' + handler.key);
let el = e.target;
let tagName = el.tagName;
let type = el.type;
if (type != 'button' && type != 'submit' && type != 'reset' && tagName != 'BUTTON') {
e.preventDefault();
if ($(el).hasClass('select2-selection--single') || $(el).hasClass('select2-search__field')) {
let $select2Container = $(el).parents('.select2-container');
el = $select2Container.siblings('select');
if ($(el).length > 0) {
let $otherselect2Container = $select2Container.siblings('.select2-container');
if ($(el).attr('multiple') && $otherselect2Container.length == 1
&& $otherselect2Container.find('.select2-results__option.select2-results__option--highlighted').length > 0) {
$(el).select2('close');
return;
}
$(el).select2('close');
this.nextCtl(el, 1).focus();
}
return;
}
this.nextCtl(el, 1).focus();
}
});
//扫描监听enter right快捷键
opts.enableHotkeys.includes('RIGHT') && hotkeys('RIGHT', (e, handler) => {
console.log('you press ' + handler.key);
e.preventDefault();
let el = e.target;
if ($(el).hasClass('select2-selection--single') || $(el).hasClass('select2-search__field')) {
let $select2Container = $(el).parents('.select2-container');
el = $select2Container.siblings('select');
if ($(el).length > 0) {
$(el).select2('close');
this.nextCtl(el, 1).focus();
}
return;
}
this.nextCtl(el, 1).focus();
});
//扫描监听left快捷键
opts.enableHotkeys.includes('LEFT') && hotkeys('LEFT', (e, handler) => {
console.log('you press ' + handler.key);
e.preventDefault();
let el = e.target;
if ($(el).hasClass('select2-selection--single') || $(el).hasClass('select2-search__field')) {
let $select2Container = $(el).parents('.select2-container');
el = $select2Container.siblings('select');
if ($(el).length > 0) {
$(el).select2('close');
this.nextCtl(el, 2).focus();
}
return;
}
this.nextCtl(el, 2).focus();
});
//扫描监听ESC快捷键
opts.enableHotkeys.includes('ESC') && hotkeys('ESC', (e, handler) => {
console.log('you press ' + handler.key);
e.preventDefault();
let el = e.target;
el.blur();
});
},
/**
* @param {Object} $ctl
* @param {Object} type
* 获取焦点转移元素
*/
nextCtl: function($ctl, type) {
let opts = this.options;
let root = $($ctl).hasClass('modal') ? $($ctl) : $('body');
let $el = root.find(opts.scanProp).filter(opts.focusElFilter);
let nextEl;
if (!$ctl) {
return $el.get(0);
}
$el.each(function(index) {
if (index == $el.index($ctl)) {
let nextIndex;
if (type == 1) {
nextIndex = index < $el.length - 1 ? index + 1 : 0;
} else {
nextIndex = index == 0 ? $el.length - 1 : index - 1;
}
nextEl = $el.get(nextIndex);
return false;
}
});
return nextEl ? nextEl : $el.get(0);
}
}
/**
* fn [function] 需要防抖的函数
* wait [number] 毫秒,防抖期限值
* immediate 是否立即执行
*/
const _debounce = (fn, wait, immediate = false) => {
let timer;
return function () {
if (timer) clearTimeout(timer);
if (immediate) {
let trigger = !timer;
timer = setTimeout(() => {
timer = null;
}, wait);
if (trigger) {
return fn.apply(this, arguments);
}
return false;
}
timer = setTimeout(() => {
return fn.apply(this, arguments);
}, wait);
return false;
}
};
/**
* 扩展jquery 对象方法(快捷键注册)
* @param options {hotkey,scope,triggerEvent}
*/
$.fn.hotkey = function(options) {
this.each(function () {
let hotkeyOpts = $(this).data('hotkey');
hotkeyOpts = typeof hotkeyOpts !== 'object' ? (hotkeyOpts ? eval('(' + hotkeyOpts + ')') : undefined) :
hotkeyOpts;
let opts = $.extend({}, $.fn.hotkey.defaults, options, hotkeyOpts || {});
hotkeys(opts.key, opts.scope, _debounce((e, handler) => {
console.log('you press ' + handler.key);
if ($(this).is(":hidden"))
return;
let el = e.target;
let tagName = el.tagName;
let type = el.type;
if (type != 'button' && type != 'submit' && type != 'reset' && tagName != 'BUTTON') {
e.preventDefault();
}
$(this).trigger(opts.triggerEvent);
}, 500, true));
})
}
$.fn.hotkey.defaults = {
scope: 'root', //作用域
triggerEvent: 'click' //触发事件
}
let hotkey = {
defaults: {
//是否支持快捷键焦点转移
focusShift: true,
//焦点转移配置项
focusShiftOptions: _focusShift.defaults
},
start() {
let opts = $.extend({}, this.defaults, this.config);
hotkeys.filter = function(e) {
let el = e.target;
let tagName = el.tagName;
let type = el.type;
return !(el.isContentEditable || (type == 'text' || type == 'number' || type == 'password' || type == 'email' ||
type == 'url' || type == 'date' || type == 'search') || (tagName === 'TEXTAREA' || tagName === 'SELECT')) //可编辑标签快捷键失效多行文本框、下拉
||
el.readOnly || el.disabled || e.ctrlKey || e.altKey || e.shiftKey //只读、禁用、(ctrl、alt、shift组合快捷键) 生效
||
(e.keyCode >= 112 && e.keyCode <= 135) //F1-F24 生效
||
e.key == 'Enter' || e.key == 'ArrowLeft' || e.key == 'ArrowRight' || e.key == 'Escape' //回车、方向左、方向右 生效
;
}
//扫描监听相关自定义快捷键
$('[data-hotkey]').hotkey();
hotkeys.setScope('root'); //初始化 作用域范围默认root
//弹框打开事件
$(document).on('shown.bs.modal', '.modal', function(e) {
//扫描监听相关自定义快捷键
$(e.target).find('[data-hotkey]').hotkey({
scope: 'modal'
});
hotkeys.setScope('modal');
});
//弹框关闭事件
$(document).on('hidden.bs.modal', '.modal', function(e) {
hotkeys.deleteScope('modal');
hotkeys.setScope('root');
});
opts.focusShift && _focusShift.init(opts.focusShiftOptions);
}
}
return hotkey;
}));
|
import {combineReducers} from 'redux';
import accountInfoReducer from './accountInfo';
import editAccountInfoReducer from './editAccountInfo';
import editAvatarReducer from './editAvatar';
import confirmAccountReducer from './confirmAccount';
import resetPasswordReducer from '../auth/resetPassword';
import changePasswordReducer from './changePassword';
import changeEmailReducer from './changeEmail';
import deleteAccountReducer from './deleteAccount';
export default combineReducers({
accountInfoReducer,
editAccountInfoReducer,
editAvatarReducer,
confirmAccountReducer,
resetPasswordReducer,
changePasswordReducer,
changeEmailReducer,
deleteAccountReducer
});
|
// author: Dawid Jurkiewicz s396341
//Zadanie domowe
//symuluje mała aplikacje bizensowa, serwisuje samoloty
/*
wykonuje prace, olej itd.
apka ktora dodaje samoloty do bazy danych ew. usuwac
dodawac prace do samolotow, po jakim czasie wykonac te prace
*/
window.addEventListener('DOMContentLoaded', function() {
var mapArray,
aircrafts = [],
aircraftCode = document.getElementById('aircraftCode'),
aircraftWork = document.getElementById('inputWork'),
workTime = document.getElementById('inputTime'),
reduceTime = document.getElementById('reduceTime'),
maxTimeForRepair = document.getElementById('maxTimeForRepair'),
addAircraftButton = document.getElementById('addAircraft'),
addWorkButton = document.getElementById('addWork'),
removeButton = document.getElementById('delete_plane'),
reduceWorkButton = document.getElementById('reduceWorkButton'),
getForRepairButton = document.getElementById('getForRepair'),
servicesList = document.getElementById('servicesList'),
planeList = document.getElementById('plane_list'),
repairAircraftsList = document.getElementById('aircraftsForRepair');
addAircraft = function (newAircraftCode) {
if (typeof newAircraftCode === 'string') {
aircrafts.push({
code: newAircraftCode,
services: []
});
var entry = document.createElement('option');
entry.appendChild(document.createTextNode(newAircraftCode));
planeList.appendChild(entry);
return aircrafts[aircrafts.length - 1];
}
else {
console.log('newAircraftCode is not a string. Pass string value into the function. Returned undefined.');
}
// function should return new aircraft object
};
removeAircraft = function (aircraftObj) {
if (typeof aircraftObj === 'object') {
var index = aircrafts.indexOf(aircraftObj);
if (index != -1) {
aircrafts.splice(index, 1);
planeList.removeChild(planeList.options[planeList.selectedIndex]);
servicesList.innerHTML = ''; //delete all 'li' elements
updateWorks(event);
}
}
else {
console.log('Unproper arguments. Pass proper arguments.');
}
};
addWorkToAircraft = function (aircraftObj, name, timeToExxecute) {
if (typeof aircraftObj === 'object' &&
typeof name === 'string' &&
typeof timeToExxecute === 'number') {
//var index = aircrafts.indexOf(aircraftObj);
//aircrafts[index].services.push({
aircraftObj.services.push({
name: name,
timeToExecute: timeToExxecute
});
}
else {
console.log('Unproper arguments. Pass proprer arguments.');
}
};
reduceTimeToExecute = function (aircraft, time) {
if (typeof aircraft === 'object' && typeof time === 'number') {
//var index = aircrafts.indexOf(aircraft)
// !!!
aircraft.services.forEach(function (item) {
item.timeToExecute = item.timeToExecute - time;
if (item.timeToExecute < 0) {
item.timeToExecute = 0;
}
});
updateWorks(event);
}
else {
console.log('Unproper arguments. Pass proprer arguments.');
}
};
getAircraftsForRepairs = function (maxTimeToExecute) {
// !!!
var aircraftsForRepair = [];
if (typeof maxTimeToExecute === 'number') {
aircrafts.forEach(function (aircraftItem) {
aircraftItem.services.some(function (serviceItem) {
if (serviceItem.timeToExecute < maxTimeToExecute) {
//repair
aircraftsForRepair.push(aircraftItem);
return true;
}
});
});
}
return aircraftsForRepair;
};
getAircraftObj = function (aircraftCode) {
if (typeof aircraftCode === 'string') {
var aircraftObj = null;
aircrafts.forEach(function (aircraftItem) {
if (aircraftItem.code === aircraftCode) {
aircraftObj = aircraftItem;
}
});
return aircraftObj;
}
else {
console.log('Wrong parameter');
}
}
getSelectedAircraftObj = function () {
if (aircrafts.length > 0) {
aircraftCode = document.getElementById('plane_list')
[planeList.selectedIndex].textContent;
}
return getAircraftObj(aircraftCode);
}
function prepareAddAircraftCode(event) {
servicesList.innerHTML = ''; //clears planeList in case you change plane
updateWorks(event);
aircraftCode = document.getElementById('aircraftCode');
addAircraft(aircraftCode.value);
}
function prepareAddWork(event) {
var aircraftObj = getSelectedAircraftObj();
if (aircraftObj != null) {
aircraftWork = document.getElementById('inputWork').value;
workTime = document.getElementById('inputTime').value;
addWorkToAircraft(aircraftObj, aircraftWork, parseInt(workTime));
updateWorks(event);
}
}
function prepareRemovePlane(event) {
var aircraftObj = getSelectedAircraftObj();
removeAircraft(aircraftObj);
}
function prepareReduceTime(event) {
var aircraftObj = getSelectedAircraftObj();
reduceTime = document.getElementById('reduceTime').value;
reduceTimeToExecute(aircraftObj, parseInt(reduceTime));
}
function updateWorks(event) {
servicesList.innerHTML = ''; //clears planeList in case you change plane
var aircraftObj = getSelectedAircraftObj();
if (aircraftObj != null) {
aircraftObj.services.forEach(function (work) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode('Work: ' + work.name));
var newline = document.createElement('br');
entry.appendChild(newline);
entry.appendChild(document.createTextNode(
'Time: ' + work.timeToExecute));
servicesList.appendChild(entry);
});
}
console.log('selected');
}
function prepareGetAircraftsForRepair(event) {
var maxTimeForRepair = document.getElementById('maxTimeForRepair').value;
var aircraftsForRepair = getAircraftsForRepairs(parseInt(maxTimeForRepair));
repairAircraftsList.innerHTML = '';
aircraftsForRepair.forEach(function(aircraft) {
var entry = document.createElement('li');
entry.appendChild(document.createTextNode(aircraft.code));
var newline = document.createElement('br');
entry.appendChild(newline);
repairAircraftsList.appendChild(entry);
});
}
if (planeList) {
planeList.addEventListener('change', updateWorks);
}
if (addAircraftButton) {
addAircraftButton.addEventListener('click', prepareAddAircraftCode);
}
if (addWorkButton) {
addWorkButton.addEventListener('click', prepareAddWork);
}
if (removeButton) {
removeButton.addEventListener('click', prepareRemovePlane);
}
if (reduceWorkButton) {
reduceWorkButton.addEventListener('click', prepareReduceTime);
}
if (getForRepairButton) {
getForRepairButton.addEventListener('click', prepareGetAircraftsForRepair)
}
//zrobic reduce time to execute i get aircrafts for repair
});
/*
Przykład użycia:
var newAircraft1 = addAircraft('SP-XY1');
var newAircraft2 = addAircraft('SP-XY2');
addWorkToAircraft(newAircraft1, 'serviceXY1a', 110);
addWorkToAircraft(newAircraft1, 'serviceXY1b', 130);
reduceTimeToExecute(newAircraft1, 20);
var sxy2a = addWorkToAircraft(newAircraft2, 'serviceXY2a', 130);
var sxy2b = addWorkToAircraft(newAircraft2, 'serviceXY2b', 160);
reduceTimeToExecute(newAircraft2, 20);
getAircraftsForRepairs(100); // [ newAircraft1 ]
removeAircraft(newAircraft1);
getAircraftsForRepairs(100); // []
reduceTimeToExecute(newAircraft2, 20);
getAircraftsForRepairs(100); // [ newAircraft2 ]
*/
|
$(document).ready(function() {
$('.fechar').click(function() {
$(this).parent().fadeOut(300);
})
}) |
import React from 'react'
const PEButton = ({ quote, averageEarningsPerShare }) => {
const value = quote / averageEarningsPerShare
const present = value.toPrecision(value >= 10 ? 3 : 2)
return (
<div className='PE'>
<button className='btn btn-outline-info'>
{
!quote ?
'PE ~'
: isNaN(value) ?
'PE ***'
: value <= 14 ?
<b>PE {present}</b>
: `PE ${present}`
}
</button>
</div>
)
}
export default PEButton
|
import * as React from 'react'
import {Text,View,TouchableOpacity,StyleSheet,TextInput,Image} from 'react-native'
import {BarCodeScanner} from 'expo-barcode-scanner'
import * as Permissions from 'expo-permissions'
import { askAsync } from 'expo-permissions';
import firebase from 'firebase';
import db from '../config.js'
export default class Transactions extends React.Component{
constructor(){
super();
this.state={
hasCameraPermissions:null,
scanned:false,
// scannedData:"",
buttonState:"normal",
scannedBookID:"",
scannedStudentID:"",
transactionMessage:""
}
}
getCameraPermission=async(ID)=>{
const{status}=await Permissions.askAsync(Permissions.CAMERA)
this.setState({
hasCameraPermissions:status==="granted",
buttonState:ID,
scanned:false
})
}
handleBarcodeScanned=async({type,data})=>{
const {buttonState}=this.state
if(buttonState==="BookId"){
this.setState({
scanned:true,
scannedBookID:data,
buttonState:"normal"
})
}
else if(buttonState==="StudentId"){
this.setState({
scanned:true,
scannedStudentID:data,
buttonState:"normal"
})
}
}
handleTransaction=async()=>{
var transactionMessage=null
db.collection('books').doc(this.state.scannedBookID).get()
}
render(){
const hasCameraPermission=this.state.hasCameraPermissions;
const scanned=this.state.scanned;
const buttonState=this.state.buttonState;
if(buttonState!=="normal" && hasCameraPermission){
return(
<BarCodeScanner
onBarCodeScanned={scanned?undefined:this.handleBarcodeScanned}/>
);
}
else if(buttonState==="normal"){
return(
<View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
<View>
<Image source={require("../assets/booklogo.jpg")}
style={{width:200,height:200}}/>
<Text style={styles.Title}>
Library App!
</Text>
</View>
<View style={{flexDirection:'row',margin:20,}}>
<TextInput style={styles.inputBox}
placeholder='Book ID'
value={this.state.scannedBookID}
/>
<TouchableOpacity style={styles.scanButton} onPress={()=>{
this.getCameraPermission('BookId')
}}>
<Text style={styles.buttonText}>
SCAN
</Text>
</TouchableOpacity>
</View>
{/* //<Text style={{fontSize:15,textDecorationLine:"underline"}}>
//{hasCameraPermission===true?this.state.scannedData:"requestCameraPermissions"}
//</Text> */}
<View style={{flexDirection:'row',margin:20,}} onPress={()=>{
this.getCameraPermission('StudentId')
}}>
<TextInput style={styles.inputBox}
placeholder=' Student ID'
value={this.state.scannedStudentID}
/>
<TouchableOpacity style={styles.scanButton}>
<Text style={styles.buttonText}>
SCAN
</Text>
</TouchableOpacity>
</View>
<TouchableOpacity style={{backgroundColor="blue",width:100,height:50}} onPress={async()=>{
var transactionMessage= await this.handleTransaction()
}}>
<Text style={{textAlign:'center',fontSize:20,color:'green',padding:10}}>
Submit
</Text>
</TouchableOpacity>
{/* <TouchableOpacity style={styles.QRButton} onPress={this.getCameraPermission}>
<Text style={{fontSize:20}}>
Scan The QR Code
</Text>
</TouchableOpacity> */}
</View>
)
}
}
}
const styles=StyleSheet.create({
QRButton:{
backgroundColor:"orange",
padding:10,
borderRadius:20,
margin:10,
},
inputBox:{
width:200,
height:40,
borderWidth:1.5,
fontSize:20,
borderRightWidth:0
},
scanButton:{
backgroundColor:'green',
width:55,
borderWidth:1.5,
borderLeftWidth:0,
},
buttonText:{
fontSize:15,
textAlign:'center',
marginTop:10
},
Title:{
textAlign:'center',
fontSize:40,
}
})
|
const path = require('path');
var paths = {
input: path.resolve(__dirname, './src'),
output: path.resolve(__dirname, './dist/static')
};
module.exports.paths = paths; |
import { useState} from "react";
const Counter = () => {
const [count, setCount] = useState(0);
return (
<article className="counter-article">
<h1>Counter</h1>
<div className="counter-div">
<button onClick={()=>setCount(count+1)}>+</button>
<h1>{count}</h1>
<button onClick={()=>setCount(count-1)}>-</button>
</div>
<br/>
<button className="reset" onClick={()=>setCount(0)}>RESET</button>
</article>
);
}
export default Counter; |
import React from 'react'
function HomeView () {
return (
<div className="home-view">home-view</div>
)
}
export default HomeView
|
import h from '../h';
import m from 'mithril';
import projectsShow from '../root/projects-show';
const projectPreview = {
view: function({attrs}) {
return attrs.project() ? m('div', [
m('.u-text-center',
m('.w-container',
m('.w-row', [
m('.w-col.w-col-8.w-col-push-2', [
m('.fontweight-semibold.fontsize-large.u-margintop-40',
'É hora dos feedbacks!'
),
m('p.fontsize-base',
'Compartilhe o link abaixo com seus amigos e aproveite o momento para fazer ajustes finos que ajudem na sua campanha.'
),
m('.w-row.u-marginbottom-30', [
m('.w-col.w-col-3'),
m('.w-col.w-col-6',
m(`input.w-input.text-field[type='text'][value='https://www.catarse.me/${attrs.project().permalink}']`)
),
m('.w-col.w-col-3')
])
]),
m('.w-col.w-col-2')
])
)
),
m(projectsShow, attrs)
]) : h.loader();
}
};
export default projectPreview;
|
function master () {
let game = createGame();
let userInput = prompt('[home] or [away]?');
determineUserControlledTeam(game, userInput);
let numberOfInnings = prompt('how many innings would you like to play?');
while (game.inning <= numberOfInnings) {
playBallForHalfAnInning(game);
}
game.printScorecard();
}
function playBallForHalfAnInning (game) {
// while (game.numberOfOuts < 3) {
while (game.numberOfOuts < 3) {
let pTeam = game.checkPitchingTeam ();
let batterType = getBatterType ();
let hittingTeam = game.checkScoringTeam ();
let pitchType = getPitchType ();
let pitchSpeed = getPitchSpeed ();
game.displayPitch (pitchType, pitchSpeed, pTeam);
let contact = getHitOutcome ();
let outOrSafe = determineOutOrSafe ();
if (contact === true && outOrSafe === true) {
game.resetStrikeCount ();
getBasehit (hittingTeam);
}
else if (contact === true && outOrSafe === false) {
game.resetStrikeCount ();
game.incrementOut ();
}
else if (contact === false) {
game.incrementStrike ();
}
game.printScorecard ();
}
if (game.numberOfOuts === 3) {
game.switchSides();
}
}
// }
// }
// }
function rollDie (numberOfSides) {
let dieRoll = Math.floor(Math.random() * numberOfSides) + 1;
return dieRoll;
}
function getBasehit (team) {
let numberOfSides = 20;
let dieRoll = rollDie (numberOfSides);
if (dieRoll >= 1 && dieRoll <= 5) {
team.activateFirstbase();
}
else if (dieRoll >= 6 && dieRoll <= 10) {
team.activateSecondbase();
}
else if (dieRoll >= 11 && dieRoll <= 15) {
team.activateThirdbase();
}
else if (dieRoll >= 16 && dieRoll <= 20) {
team.incrementScore();
}
}
function determineOutOrSafe () {
let numberOfSides = 12;
let dieRoll = rollDie (numberOfSides);
if (dieRoll >= 1 && dieRoll <= 3) {
return false;
}
else if (dieRoll >= 4 && dieRoll <= 6) {
return true;
}
else if (dieRoll >= 7 && dieRoll <= 9) {
return false;
}
else if (dieRoll >= 10 && dieRoll <= 12) {
return true;
}
else {
return true;
}
}
function getHitOutcome () {
let numberOfSides = 10;
let dieRoll = rollDie (numberOfSides);
if (dieRoll % 2 === 0) {
return true;
}
else {
return false;
}
}
function getBatterType () {
let numberOfSides = 6;
let dieRoll = rollDie (numberOfSides);
switch (dieRoll) {
case 1:
return 'Slugger';
case 2:
return 'Single Hitter';
case 3:
return 'Pitcher';
case 4:
return 'Rookie';
case 5:
return 'Pinch Hitter';
case 6:
return 'AA Call Up';
default:
return 'Ernie Banks';
}
}
function getPitchType () {
let numberOfSides = 4;
let dieRoll = rollDie (numberOfSides);
switch (dieRoll) {
case 1:
return 'Fastball';
case 2:
return 'Curveball';
case 3:
return 'Slider';
case 4:
return 'Changeup';
default:
return 'Knuckleball';
}
}
function getPitchSpeed () {
let numberOfSides = 8;
let dieRoll = rollDie (numberOfSides);
switch (dieRoll) {
case 1:
return 60;
case 2:
return 65;
case 3:
return 70;
case 4:
return 75;
case 5:
return 80;
case 6:
return 85;
case 7:
return 90;
case 8:
return 95;
default:
return 100;
}
}
function determineUserControlledTeam (game, input) {
if (input === 'home') {
game.homeTeam.determineUserControl();
}
else if (input === 'away') {
game.awayTeam.determineUserControl();
}
else if (input === 'banana') {
console.log('Get outta here Nevin!');
}
else {
return;
}
}
function createGame () {
return {
inning: 1,
numberOfOuts: 0,
isTopInning: true,
strikeCount: 0,
homeTeam: {
name: 'Home Team',
firstBase: false,
secondBase: false,
thirdBase: false,
score: 0,
isPitching: true,
isUserControlled: false,
incrementScore: function() {
this.score++;
console.log('The home team scored a run!');
},
activateFirstbase: function() {
this.firstBase = !this.firstBase;
console.log('The home team hit a single!');
},
activateSecondbase: function() {
this.secondBase = !this.secondBase;
console.log('The home team hit a double!');
},
activateThirdbase: function() {
this.thirdBase = !this.thirdBase;
console.log('The home team hit a triple!');
},
switchSide: function() {
this.isPitching = !this.isPitching;
this.firstBase = false;
this.secondBase = false;
this.thirdBase = false;
},
determineUserControl: function() {
this.isUserControlled = !this.isUserControlled;
}
},
awayTeam: {
name: 'Away Team',
firstBase: false,
secondBase: false,
thirdBase: false,
score: 0,
isPitching: false,
isUserControlled: false,
incrementScore: function() {
this.score++;
console.log('The away team scored a run!');
},
activateFirstbase: function() {
this.firstBase = !this.firstBase;
console.log('The away team hit a single!');
},
activateSecondbase: function() {
this.secondBase = !this.secondBase;
console.log('The away team hit a double!');
},
activateThirdbase: function() {
this.thirdBase = !this.thirdBase;
console.log('The away team hit a triple!');
},
switchSide: function() {
this.isPitching = !this.isPitching;
this.firstBase = false;
this.secondBase = false;
this.thirdBase = false;
},
determineUserControl: function() {
this.isUserControlled = !this.isUserControlled;
}
},
switchSides: function() {
this.homeTeam.switchSide();
this.awayTeam.switchSide();
this.resetStrikeCount();
this.resetNumberOfOuts();
this.checkScoringTeam();
this.checkPitchingTeam();
this.incrementInning();
console.log('Inning: ' + this.inning);
},
incrementInning: function() {
this.inning++;
},
incrementOut: function() {
this.numberOfOuts++;
console.log('urrrrrroooouuuuttttt!!');
},
incrementStrike: function() {
this.strikeCount++;
},
resetStrikeCount: function() {
this.strikeCount = 0;
},
resetNumberOfOuts: function() {
this.numberOfOuts = 0;
},
checkScoringTeam: function() {
if(this.homeTeam.isPitching === false) {
return this.homeTeam;
}
else if(this.awayTeam.isPitching === false) {
return this.awayTeam;
}
},
checkPitchingTeam: function() {
if(this.homeTeam.isPitching === true) {
return this.homeTeam;
}
else if(this.awayTeam.isPitching === true) {
return this.awayTeam;
}
},
displayPitch: function(type, speed, team) {
console.log('The ' + team.name + ' threw a ' + speed + ' mph ' + type + '.');
},
printScorecard: function() {
console.log('----------------------------------');
console.log('| SCORECARD |');
console.log('| Home Team : ' + this.homeTeam.score + ' | Away Team : ' + this.awayTeam.score + ' |');
console.log('| Inning: ' + this.inning + ' | Outs: ' + this.numberOfOuts + ' |');
console.log('----------------------------------');
}
}
}
master(); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.