text
stringlengths 7
3.69M
|
|---|
import React from "react";
import {Box, IconButton, useColorMode, useColorModeValue,} from "@chakra-ui/react";
import {GiMoon, GiSun} from "react-icons/gi";
const ColorSwitch = (props) => {
const {toggleColorMode} = useColorMode();
const text = useColorModeValue("dark", "light");
const SwitchIcon = useColorModeValue(GiSun, GiMoon);
return (
<IconButton
{...props}
aria-label={`Switch to ${text} mode`}
variant="outline"
rounded="100%"
color="currentcolor"
onClick={toggleColorMode}
icon={
<Box fontSize={25}>
<SwitchIcon/>
</Box>
}
size="md"
fontSize="lg"
/>
);
};
export default ColorSwitch;
|
import { createStore, applyMiddleware, compose } from 'redux';
import reducer from './reducers/index';
import { persistReducer } from 'redux-persist';
import storage from 'redux-persist/lib/storage';
import createSagaMiddleware from 'redux-saga';
import watchAllRequest from '../redux/actions/actionCreator';
const sagaMiddleware = createSagaMiddleware();
const persistConfig = {
key: 'root',
storage
};
const initialState = {
password: '',
url: 'http://localhost:3001',
phone_no: '',
showLogin: false
};
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const persistedReducer = persistReducer(persistConfig, reducer, initialState);
const store = createStore(persistedReducer, initialState, composeEnhancers(applyMiddleware(sagaMiddleware)));
sagaMiddleware.run(watchAllRequest);
window.store = store;
export default store;
|
import "babel-polyfill";
import {Player} from './mixins/Player';
// expose player Class publicaly
window.ViewsayPlayer = Player;
|
/**
* 2016, Rastislav Bertusek
*/
'use strict';
angular.module('$translate.mock', []).provider('$translate', function(){
const $translateProvider = jasmine.createSpyObj('$translateProvider',
['useLocalStorage', 'preferredLanguage', 'useLoaderCache', 'useSanitizeValueStrategy', 'useLoader']);
return {
useLoaderCache: $translateProvider.useLoaderCache,
useSanitizeValueStrategy: $translateProvider.useSanitizeValueStrategy,
useLoader: $translateProvider.useLoader,
useLocalStorage: $translateProvider.useLocalStorage,
preferredLanguage: $translateProvider.preferredLanguage,
$get: ['$q', function($q){
function $translateMock(key){
function transformArrayToObject(values) {
let res = {};
forEach(values, function (value) {
res[value] = value;
});
return res;
}
return $q.when(angular.isArray(key) ? transformArrayToObject(key) : key);
}
const noop = angular.noop;
$translateMock.useLoader = jasmine.createSpy('$translate.useLoader');
$translateMock.use = jasmine.createSpy('$translate.use');
$translateMock.preferredLanguage = noop;
$translateMock.storage = noop;
$translateMock.storageKey = noop;
$translateMock.instant = function (translationId) {
return translationId;
};
$translateMock.directivePriority = noop;
$translateMock.isPostCompilingEnabled = noop;
$translateMock.statefulFilter = noop;
return $translateMock;
}]
}
});
|
const webpack = require('webpack')
//const fs = require('fs')
if (process.env.NODE_ENV !== 'production') {
require('dotenv/config')
}
module.exports = {
webpack: config => {
config.plugins.push(
new webpack.DefinePlugin({
'process.env.CMS_URL': JSON.stringify(process.env.CMS_URL),
'process.env.LUME_URL': JSON.stringify(process.env.LUME_URL),
'process.env.API_URL': JSON.stringify(process.env.API_URL),
'process.env.S3_URL': JSON.stringify(process.env.S3_URL),
'process.env.AUTH_STRATEGY': JSON.stringify(process.env.AUTH_STRATEGY),
'process.env.FILE_STORAGE': JSON.stringify(process.env.FILE_STORAGE),
'process.env.LOCAL_TILE_URL': JSON.stringify(
process.env.LOCAL_TILE_URL
),
'process.env.MAPBOX_API_TOKEN': JSON.stringify(
process.env.MAPBOX_API_TOKEN
)
})
)
return config
}
// exportPathMap: function(defaultPathMap) {
// const data = JSON.parse(
// fs.readFileSync(`${__dirname}/../data-api/export/data.json`, 'utf8')
// )
// return {
// '/mia': {
// page: '/lume',
// query: {
// subdomain: 'mia',
// data
// }
// },
// '/mia/duluth-living-room': {
// page: '/lume/story',
// query: {
// subdomain: 'mia',
// storySlug: 'duluth-living-room',
// organization: data.organization,
// story: data.stories.find(
// story => story.storySlug === 'duluth-living-room'
// )
// }
// }
// }
// }
}
|
/**
* sayHello
* @param {String} name Represents a person's name.
* @throws Will throw a TypeError if the argument is not an String.
* @returns {String} The string that includes the person's name.
*/
module.exports.sayHello = function (name) {
if (typeof name !== 'string') {
throw new TypeError('ERR_INVALID_ARG_TYPE')
}
return `Hello ${name} !`
}
|
// chat app users
export default [
{
id: 2,
first_name: 'Elisabeth',
last_name: 'Ortega',
photo_url: require('Assets/avatars/user-1.jpg'),
last_chat_date: 'yesterday',
isActive: true,
status: "online",
last_chat: 'Ut vel consectetur ligula, non tincidunt elit. Nulla pellentesque finibus consequat.',
new_message_count: 5,
isSelectedChat: true,
previousChats: [
{
message: 'Sed mollis, mi in malesuada semper, ipsum nulla luctus sem',
sent: '12:47 PM',
isAdmin: false
},
{
message: 'Vivamus aliquet ligula augue, et suscipit mauris sollicitudin ',
sent: '12:49 PM',
isAdmin: true
},
{
message: 'Phasellus in felis posuere, fringilla ligula eget, tristique diam',
sent: '12:51 PM',
isAdmin: true
},
{
message: 'Ut vel consectetur ligula, non tincidunt elit. Nulla pellentesque finibus consequat.',
sent: '12:55 PM',
isAdmin: false
}
]
},
{
id: 3,
first_name: 'Madeleine',
last_name: 'Dean',
photo_url: require('Assets/avatars/user-2.jpg'),
last_chat_date: 'today',
isActive: true,
status: "online",
last_chat: 'Sed elementum vel ex ullamcorper egestas. Phasellus laoreet nec sem et tempus. Integer pellentesque sapien augue',
new_message_count: 10,
isSelectedChat: false,
previousChats: [
{
message: 'Maecenas lacus nunc, condimentum sed arcu eget,',
sent: '12:47 PM',
isAdmin: false
},
{
message: 'Duis ullamcorper laoreet nulla, sed mollis urna semper nec. Cras ac bibendum neque.',
sent: '12:49 PM',
isAdmin: true
},
{
message: 'Pellentesque interdum aliquam nunc quis viverra. Morbi placerat massa eget neque feugiat, sit amet porta nibh vehicula.',
sent: '12:51 PM',
isAdmin: true
},
{
message: 'Sed elementum vel ex ullamcorper egestas. Phasellus laoreet nec sem et tempus. Integer pellentesque sapien augue',
sent: '12:55 PM',
isAdmin: false
}
]
},
{
id: 4,
first_name: 'Lindsey',
last_name: 'Cruz',
photo_url: require('Assets/avatars/user-3.jpg'),
last_chat_date: 'yesterday',
isActive: false,
status: "Last seen yesterday",
last_chat: 'Maecenas commodo eros ac libero ultricies, eu iaculis diam commodo',
new_message_count: 0,
isSelectedChat: false,
previousChats: [
{
message: 'Quisque arcu massa, iaculis et sollicitudin id, sollicitudin non leo. Ut placerat mi rutrum enim hendrerit vestibulum. ',
sent: '12:47 PM',
isAdmin: false
},
{
message: 'Suspendisse nec orci odio. Donec rutrum ipsum sit amet lorem dignissim, non maximus nibh porta.',
sent: '12:49 PM',
isAdmin: true
},
{
message: 'Mauris quis metus urna. Proin vel magna in sem scelerisque congue eget non libero.',
sent: '12:51 PM',
isAdmin: true
},
{
message: 'Phasellus turpis erat, consectetur vel fermentum malesuada, volutpat in elit. Quisque egestas lorem lectus, quis porta dui vestibulum in.',
sent: '12:55 PM',
isAdmin: false
}
]
},
{
id: 5,
first_name: 'Erik',
last_name: 'Schneider',
photo_url: require('Assets/avatars/user-4.jpg'),
last_chat_date: '3 days ago',
isActive: false,
status: "Last seen 1 day ago",
last_chat: 'Proin hendrerit, nulla vel tincidunt rutrum, libero ante ornare justo, non luctus massa ligula ut orci. ',
new_message_count: 0,
isSelectedChat: false,
previousChats: [
{
message: 'Pellentesque mollis neque vel enim pellentesque, vel scelerisque erat ullamcorper.',
sent: '12:47 PM',
isAdmin: false
},
{
message: 'Cras vel tellus neque. Maecenas dapibus velit vitae ',
sent: '12:47 PM',
isAdmin: false
},
{
message: 'Proin hendrerit, nulla vel tincidunt rutrum, libero ante ornare justo, non luctus massa ligula ut orci. ',
sent: '12:50 PM',
isAdmin: true
}
]
},
{
id: 6,
first_name: 'Philip',
last_name: 'Phillips',
photo_url: require('Assets/avatars/user-5.jpg'),
last_chat_date: '1 week ago',
isActive: false,
"status": "Last seen 2 days ago",
last_chat: 'Phasellus ultrices porttitor orci, eget venenatis lorem ultrices quis. Proin eget magna tellus. Ut a magna feugiat, facilisis',
new_message_count: 0,
isSelectedChat: false,
previousChats: [
{
message: 'Vivamus vitae nibh ullamcorper, vulputate mauris et, porta turpis. Donec non mauris nec felis aliquam tristique eget eu mauris',
sent: '12:47 PM',
isAdmin: false
},
{
message: ' Nunc eget nulla nisl. Donec accumsan ex vel risus ornare, ac tincidunt risus auctor. Curabitur hendrerit felis tortor, ac ',
sent: '12:49 PM',
isAdmin: true
},
{
message: 'Sed risus est, scelerisque pharetra leo vitae, efficitur laoreet elit. Ut in nunc rutrum ligula auctor venenatis quis',
sent: '12:51 PM',
isAdmin: true
},
{
message: 'Phasellus ultrices porttitor orci, eget venenatis lorem ultrices quis. Proin eget magna tellus. Ut a magna feugiat, facilisis',
sent: '12:55 PM',
isAdmin: false
}
]
},
{
id: 7,
first_name: 'Sabrina',
last_name: 'White',
photo_url: require('Assets/avatars/user-6.jpg'),
last_chat_date: '2 weeks ago',
isActive: true,
status: "online",
last_chat: 'Curabitur fermentum felis ac eros convallis ornare. ',
new_message_count: 0,
isSelectedChat: false,
previousChats: [
{
message: 'Vivamus vitae nibh ullamcorper, vulputate mauris et, porta turpis. Donec non mauris nec felis aliquam tristique eget eu mauris',
sent: '12:47 PM',
isAdmin: false
},
{
message: ' Nunc eget nulla nisl. Donec accumsan ex vel risus ornare, ac tincidunt risus auctor. Curabitur hendrerit felis tortor, ac ',
sent: '12:49 PM',
isAdmin: true
},
{
message: 'Sed risus est, scelerisque pharetra leo vitae, efficitur laoreet elit. Ut in nunc rutrum ligula auctor venenatis quis',
sent: '12:51 PM',
isAdmin: true
},
{
message: 'Phasellus ultrices porttitor orci, eget venenatis lorem ultrices quis. Proin eget magna tellus. Ut a magna feugiat, facilisis',
sent: '12:55 PM',
isAdmin: false
}
]
},
{
id: 8,
first_name: 'Nicolas',
last_name: 'Wolf',
photo_url: require('Assets/avatars/user-7.jpg'),
last_chat_date: '2 weeks ago',
isActive: false,
status: "Last seen yesterday",
last_chat: ' Donec convallis sem in ex luctus, tempor commodo massa porta.',
new_message_count: 0,
isSelectedChat: false,
previousChats: [
{
message: 'Vivamus vitae nibh ullamcorper, vulputate mauris et, porta turpis. Donec non mauris nec felis aliquam tristique eget eu mauris',
sent: '12:47 PM',
isAdmin: false
},
{
message: ' Nunc eget nulla nisl. Donec accumsan ex vel risus ornare, ac tincidunt risus auctor. Curabitur hendrerit felis tortor, ac ',
sent: '12:49 PM',
isAdmin: true
},
{
message: 'Sed risus est, scelerisque pharetra leo vitae, efficitur laoreet elit. Ut in nunc rutrum ligula auctor venenatis quis',
sent: '12:51 PM',
isAdmin: true
},
{
message: 'Phasellus ultrices porttitor orci, eget venenatis lorem ultrices quis. Proin eget magna tellus. Ut a magna feugiat, facilisis',
sent: '12:55 PM',
isAdmin: false
}
]
}
]
|
import React from 'react';
import { Nav, Navbar, Container } from 'react-bootstrap';
import { Link, NavLink } from 'react-router-dom';
import styled from 'styled-components';
const Styles = styled.div`
.navbar {
height: 3.5rem;
box-shadow : none;
}
`;
const Navigation = () => {
return (
<Styles>
<Navbar variant="light" expand="md">
<Container>
<Link to="/">
<Navbar.Brand>
<img
src={`images/logo-1.png`}
width="90"
className="d-inline-block align-top"
alt="logo"
/>
</Navbar.Brand>
</Link>
<Nav className="ml-auto">
<NavLink className="nav-link" to="/">
Home
</NavLink>
<NavLink className="nav-link" to="/collection">
Collection
</NavLink>
<NavLink className="nav-link" to="/contact">
Contact
</NavLink>
</Nav>
</Container>
</Navbar>
</Styles>
);
};
export default Navigation;
|
var mn = mn || {};
mn.services = mn.services || {};
mn.services.MnApp = (function (Rx) {
"use strict";
MnApp.annotations = [
new ng.core.Injectable()
];
return MnApp;
function MnApp() {
this.stream = {};
this.stream.loading = new Rx.BehaviorSubject(false);
this.stream.httpResponse = new Rx.Subject();
this.stream.pageNotFound = new Rx.Subject();
this.stream.appError = new Rx.Subject();
this.stream.http401 =
this.stream.httpResponse.pipe(
Rx.operators.filter(function (rv) {
//rejection.config.url !== "/controller/changePassword"
//$injector.get('mnLostConnectionService').getState().isActivated
return (rv instanceof ng.common.http.HttpErrorResponse) &&
(rv.status === 401) && !rv.headers.get("ignore-401");
})
);
}
})(window.rxjs);
|
import React from "react";
import Song from "./Song";
const SongList = ({ songs }) => {
const songNodes = songs.map((song) => {
return (
<li key={song.id.attributes["im:id"]}>
{song["im:artist"].label} - {song["im:name"].label}
</li>
);
});
return <ul>{songNodes}</ul>;
};
export default SongList;
|
import React from 'react'
import SearchResultList from '../components/SearchResultList'
import SurveyTable from '../components/SurveyTable'
/**
*
* 종료된 설문조사 모음 페이지
* by : 우혜경
*
**/
function ClosedSurvey() {
const data=[
{
key: '1',
title:'ddd',
point:20,
num_of_response: 'New York No. 1 Lake Park',
period: 'New York No. 1 Lake Park',
},
{
key: '2',
title:'aaa',
point:10,
num_of_response: 'New York No. 1 Lake Park',
period: 'New York No. 1 Lake Park',
},
{
key: '3',
title:'ddgggd',
point:30,
num_of_response: 'ggg',
period: 'gggg',
},
{
key: '4',
title:'ddqqqqd',
point:20,
num_of_response: 'sgsgsd',
period: 'sdgsdgs',
}
]
return (
<div style={{width:'1920px', fontFamily:'Noto Sans CJK KR'}}>
<div style={{ float:'left', marginLeft:'320px',marginBottom:'20px',fontWeight: '700', fontSize:'18px' }}>
종료된 설문조사
</div>
<SurveyTable data={data}></SurveyTable>
</div>
)
}
export default ClosedSurvey
|
({
shouldDeps: [
{
block: 'yummy'
}
]
});
|
// HLS sti fra this.options
define("dr-media-flash-video-player", ["dr-media-video-player"], function (VideoPlayer) {
"use strict";
var FlashPlayer = new Class({
Extends: VideoPlayer,
options: {
'appData': {
'errorMessages': {
'obsolete_flash_player': 'Du skal have <a href="http://get.adobe.com/flashplayer/">Adobe Flash Player 10 eller nyere</a> installeret for at se denne video.'
},
bufferSettings: {
dynamicStreamBufferTime: 3,
staticStreamBufferTime: 3
}
}
},
getQuerystring: function (key, default_) {
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
},
build: function () {
if (Browser.Plugins.Flash.version < 10) {
// if this is a live stream we need to load the live data first, to be able to give the user an HLS stream
if (this.options.videoData.videoType === "live") {
this.ensureLiveStreams(this.showFlashErrorMessage.bind(this));
} else {
this.showFlashErrorMessage();
}
return;
}
if (this.options.videoData.videoType === 'ondemand') {
this.ensureResource(this.postBuild.bind(this));
} else if (this.options.videoData.videoType === 'live') {
this.ensureLiveStreams(this.postBuild.bind(this));
}
this.parent();
},
showFlashErrorMessage: function() {
this.displayError('obsolete_flash_player');
var links = this.links();
var HLSpath = "";
var errorContainer = this.options.element.getElement('.wrapper');
if (this.options.videoData.videoType === "live") {
if (!this.getChannel())
return;
this.getChannel().servers.each(function(link) {
if(link.linkType.toLowerCase() == "hls" && link.qualities.length > 0 && link.qualities[0].streams.length > 0) {
HLSpath = link.server + '/' + link.qualities[0].streams[0];
}
});
} else {
links.each(function(link) {
if(link.linkType.toLowerCase() == "hls") {
HLSpath = link.uri;
}
});
}
if (!HLSpath)
return;
var HlsPathMessage = new Element('a', {
html : 'Direkte sti til stream',
href : HLSpath
}).inject(errorContainer);
},
postBuild: function () {
this.containerHtmlCache = this.options.element.get('html');
var splittedHref = window.location.href.split('#!/');
if (splittedHref.length > 1 && splittedHref[1].length > 1) {
this.options.videoData.startTimeCode = splittedHref[1];
this.options.appData.autoPlay = true;
}
this.clearContent();
var flashWrapper = new Element('div', {'class':'image-wrap ratio-16-9 flash-wrap'}).inject(this.options.element);
// IE8 JS cannot communicate with swiff obj if using cached swf. So with IE8 we always want to avoid used the cached version.
var queryString = Browser.ie8 ? '?cachekill=' + Date.now() : '?cachekill=20131003';
var swfUrl = '';
if (this.getQuerystring('testplayer', '') == 'true') {
swfUrl = '/assets/swf/program-player-test.swf' + queryString;
} else {
swfUrl = '/assets/swf/program-player.swf' + queryString;
}
this.swiff = new Swiff(swfUrl, {
container: flashWrapper,
height: '100%',
width: '100%',
version: "11.0.0",
params: {
bgcolor: '#000000',
AllowScriptAccess: 'sameDomain',
AllowFullScreen: true,
wMode: 'direct'
},
vars: {
appData: JSON.encode(this.options.appData),
videoData: JSON.encode(this.options.videoData),
programcardResult: JSON.encode(this.programcardResult)
},
callBacks: {
as_play: this.onPlay.bind(this),
as_pause: this.onPause.bind(this),
as_buffering: this.onBuffering.bind(this),
as_buffering_complete: this.onBufferingComplete.bind(this),
as_seekBefore: this.onBeforeSeek.bind(this),
as_seekComplete: this.onAfterSeek.bind(this),
as_complete: this.onComplete.bind(this),
as_display_error: this.displayError.bind(this),
as_changeChannel: this.changeChannel.bind(this),
as_durationChange: this.onDurationChange.bind(this),
as_setFullscreen: (function (value) {
this.options.appData.isFullscreen = value;
}).bind(this),
as_changeODContent: this.changeContent.bind(this),
as_popUp: this.handlePopupRequest.bind(this),
as_queryGeofilter: this.queryGeofilter.bind(this)
}
}).toElement();
try {
this.swiff.setAttribute('tabindex', '-1');
} catch (err) {
if (window.console && console.log) {
console.log('error setting tabindex for swff.object');
}
}
// DR Login modal events:
document.body.addEvents({
'modal_open': this.onHtmlModalOpen.bind(this),
'modal_close': this.onHtmlModalClose.bind(this)
});
// AddThis modal events:
if (window.addthis) {
window.addthis.addEventListener('addthis.menu.open', this.onHtmlModalOpen.bind(this));
window.addthis.addEventListener('addthis.menu.close', this.onHtmlModalClose.bind(this));
}
this.options.appData.controlsHeight = 32;
this.updateElementHeight();
this.buildAccessabilityControls();
},
onHtmlModalOpen: function () {
clearTimeout(this.showPlayerTimer);
if (this.swiff !== null) {
try { //IE8 throws exception
this.pause();
} catch (e) {}
this.detach();
}
},
/**
* wrapper for Swiff.remote
*/
swiffRemote: function () {
try {
var arg = Array.prototype.slice.call(arguments);
arg.unshift(this.swiff);
return Swiff.remote.apply(Swiff, arg);
} catch (e) {
// if (window.console && console.log) console.log(e.message);
return 0;
}
},
onHtmlModalClose: function () {
this.showPlayerTimer = this.reattach.delay(100, this);
},
play: function () {
return this.swiffRemote('js_play');
},
pause: function () {
return this.swiffRemote('js_pause');
},
position: function () {
try {
return this.swiffRemote('js_position');
} catch (e) { return 0; }
},
/*duration: function () {
try {
return this.swiffRemote('js_duration');
} catch (e) {
return this.parent.duration();
}
},*/
/** @private */
_seek: function (value) {
try {
if (typeof(value) === 'string') {
this.swiffRemote('js_seekToTimeCode', value);
} else {
this.swiffRemote('js_seek', value);
}
return true;
} catch (e) { }
return false;
},
updateOptions: function (options) {
this.parent(options);
this.ensureResource(function () {
if (this.swiff) {
return this.swiffRemote('js_setOptions', {
'videoData': this.options.videoData,
'appData': this.options.appData,
'programcardResult': this.programcardResult
});
}
this.build();
}.bind(this));
},
reattach: function () {
if (this.swiff === null) {
this.build();
}
var container = this.options.element;
if (container.hasClass('detached')) {
container.removeClass('detached');
}
container.removeEvent('click', this.bindedClick);
this.fireEvent('reattached');
},
handlePopupRequest: function () {
try { //IE8 throws exception
this.pause();
} catch (e) {}
if (this.options.appData.isPopup === true) {
window.close();
} else {
var url;
if (this.options.videoData.videoType === "live") {
url = this.options.appData.urls.popupUrl;
} else {
url = this.options.appData.urls.popupUrl + '#!/' + this.currentTimeCode();
}
this.popup = window.open(url, 'popupPlayer', 'height=478,width=830,resizable=yes,scrollbars=no');
}
},
detach: function (isPopup) {
var container, contentContainer;
container = this.options.element;
this.clearContent();
if (isPopup) {
this.bindedClick = this.detachedContainerClick.bind(this);
container.addEvent('click', this.bindedClick);
container.addClass('detached');
contentContainer = new Element('div', { 'class': 'wrapper' });
contentContainer.adopt(new Element('h1', {
text: 'Luk popup!'
}));
container.grab(new Element('div', { 'class': 'floater' }));
container.grab(contentContainer);
}
this.swiff = null;
this.fireEvent('detached');
},
detachedContainerClick: function (event) {
if (this.popup !== null) {
this.popup.close();
} else {
this.reattach();
}
},
buildErrorDetails: function(errorDetails, info, errorCode) {
if (!errorDetails)
errorDetails = [];
errorDetails['userAgent'] = navigator.userAgent;
errorDetails['info'] = info;
errorDetails['errorCode'] = errorCode;
errorDetails['url'] = document.URL;
var sortable = [];
for (var p in errorDetails)
sortable.push([p, errorDetails[p]]);
sortable.sort().reverse();
//for (var p in errorDetails) {
for (var i = 0; i < sortable.length; i++) {
var key = sortable[i][0];
var value = sortable[i][1];
var text = '';
if (typeof(value) === 'object') {
text = 'Capabilities:';
for (var o in value) {
text += '\r\n\t' + o + ': ' + value[o];
}
} else {
text = key + ': ' + value;
}
this.logOutput = text + '\r\n' + this.logOutput;
}
var downloadLinkElement = new Element('a', { html:'Hent fejlbeskrivelse' } );
downloadLinkElement.setProperty('download', this.getLogFileName());
downloadLinkElement.set('href', this.makeTextFile(this.logOutput));
return downloadLinkElement;
},
makeTextFile: function(text) {
this.logTextFile = "data:text/plain," + encodeURIComponent(text);
return this.logTextFile;
},
getLogFileName: function() {
var filename = 'dr-player-';
var date = new Date();
var month = date.getMonth() + 1;
if (month.toString().length == 1) month = '0' + month;
var day = date.getDate();
if (day.toString().length == 1) day = '0' + day;
// Add today's date
filename += date.getFullYear().toString() + month.toString() + day.toString();
// Add time of day
filename += '-' + date.getHours() + '_' + date.getMinutes();
// Add file extension
filename += '.txt';
return filename;
},
handleGeoResponse: function(isInDenmark) {
if (isInDenmark == 'true') {
this.swiffRemote('js_geofilterResponse', true);
} else {
this.displayError('access_denied');
}
}
});
return FlashPlayer;
});
|
var routes = {};
routes.home = function(req, res) {
res.render("home", {"heading": "Welcome to Jessica's burgers!",
"message": "Things to do:",
"links": ["/ingredients",
"/order",
"/kitchen"
]});
}
module.exports = routes;
|
const { Client } = require("discord.js");
const JoinCodeCommand = require("./commands/joincode_command");
const RegisterCodeCommand = require("./commands/registercode_command");
const bot = new Client();
const commands = [new JoinCodeCommand(), new RegisterCodeCommand()];
bot.on("ready", () => {
console.log("Bot activated");
});
bot.on("message", (message) => {
if (message.author.bot) return;
var tmp = message.content.split(" ");
const enteredCmd = tmp.shift().toLowerCase();
const args = tmp;
if (enteredCmd.startsWith(".")) {
for (var i in commands) {
const command = commands[i];
const prefixlessEnteredCmdSplit = enteredCmd.split("");
const prefixlessEnteredCmd = prefixlessEnteredCmdSplit.slice(1, prefixlessEnteredCmdSplit.length).join("");
if (command.names.includes(prefixlessEnteredCmd)) {
command.run(message, args);
}
}
}
});
console.log("Loading..");
bot.login(process.env.token);
|
var auctionNotification = require('./auction-close');
var timedEvents = {};
module.exports = {
addAuction: function(auction) {
// find time to true end
var currentTime = new Date().getTime();
var timeTill = auction.trueEnd - currentTime;
// for auctions in the future, build queue to notify winners
if (timeTill > 0) {
// account for setTimeout not being able to handle more than 24 days
setDaysTimeout(auctionNotification, timeTill, auction);
console.log("Auction " + auction._id + " added to event: auction close.");
}
},
updateAuction: function(auction) {
console.log("Updating Auction Close Event");
// --- delete the current timer
var timer = timedEvents[auction._id];
clearTimeout(timer);
clearInterval(timer);
// --- add a new one
var currentTime = new Date().getTime();
var timeTill = auction.trueEnd - currentTime;
// for auctions in the future, build queue to notify winners
if (timeTill > 0) {
// account for setTimeout not being able to handle more than 24 days
setDaysTimeout(auctionNotification, timeTill, auction);
}
},
deleteAuction: function(auction) {
console.log('Deleting Auction Close Event: ' + auction._id);
var timer = timedEvents[auction._id];
clearTimeout(timer);
clearInterval(timer);
delete timedEvents[auction._id];
}
};
function clearTimer(auctionId) {
delete timedEvents[auctionId];
}
function setDaysTimeout(callback, timeTill, auction) {
// 86400 seconds in a day
var msInDay = 86400*1000;
var daysTill = Math.floor(timeTill / msInDay);
var dayCount = 0;
var timer;
// if within this day
if (daysTill === 0) {
timer = setTimeout(callback, timeTill, auction);
setTimeout(clearTimer, timeTill + 100, auction._id);
}
else {
// set interval that counts the days
timer = setInterval(function() {
dayCount++; // a day has passed
timeTill = timeTill - msInDay;
if(dayCount === daysTill) {
clearInterval(timer);
setTimeout(callback, timeTill, auction);
setTimeout(clearTimer, timeTill + 100, auction._id);
}
},msInDay);
}
// save auction timer
timedEvents[auction._id] = timer;
}
|
import React, { Component } from 'react';
import Aux from '../../hoc/Aux/Aux';
import Cards from '../../components/Cards/Cards';
import classes from './FriendFinder.scss';
import typography from '../../sass/base/_typography.scss';
class FriendFinder extends Component {
state = {
fish: [
{
name: "salmon",
keyword: "salmon",
description: "There are five species of Pacific salmon. Some are abundant in Oregon; others make a much more limited appearance."
},
{
name: "trout",
keyword: "trout",
description: "Trout is Oregon's number one game fish. From one end of the state to the other, anglers will find native populations of rainbow, cutthroat and other species of trout. In addition to the native populations, ODFW stocks over 5 million trout each year to provide even more opportunity. As a result, there's good trout fishing somewhere in Oregon 365 days a year."
},
{
name: "steelhead",
keyword: "steelhead",
description: "The steelhead, a sea-run rainbow or redband trout, is the largest race of rainbow in Oregon. They are famous worldwide for line-peeling runs and putting up spectacular, acrobatic fights."
},
{
name: "bass",
keyword: "bass",
description: "Oregon offers great bass fishing throughout the state. Whether you're after smallmouth, largemouth or hybrids, there's a place nearby to catch a bass"
},
{
name: "sturgeon",
keyword: "sturgeon",
description: "Sturgeon appeared in the fossil record 200-million years ago and have survived to today little changed. Both green and the larger white sturgeon are found in Oregon waters. Some of these fish can live to be 100-years-old, but they spawn only once every 2- to 8-years."
},
{
name: "catfish",
keyword: "catfish",
description: "Channel catfish are a prized species in many parts of the state. At the same time, illegally introduced bullhead catfish can distupt other fisheries such as trout."
}
],
locations: [
{
name: "Columbia Gorge",
description: "There are five species of Pacific salmon. Some are abundant in Oregon; others make a much more limited appearance.",
keyword: "columbia"
},
{
name: "Hood River",
description: "Trout is Oregon's number one game fish. From one end of the state to the other, anglers will find native populations of rainbow, cutthroat and other species of trout. In addition to the native populations, ODFW stocks over 5 million trout each year to provide even more opportunity. As a result, there's good trout fishing somewhere in Oregon 365 days a year.",
keyword: "hood"
},
{
name: "Rogue River",
description: "The steelhead, a sea-run rainbow or redband trout, is the largest race of rainbow in Oregon. They are famous worldwide for line-peeling runs and putting up spectacular, acrobatic fights.",
keyword: "rogue"
},
{
name: "Umpqua River",
description: "Oregon offers great bass fishing throughout the state. Whether you're after smallmouth, largemouth or hybrids, there's a place nearby to catch a bass",
keyword: "umpqua"
},
{
name: "Indian Heaven",
description: "Sturgeon appeared in the fossil record 200-million years ago and have survived to today little changed. Both green and the larger white sturgeon are found in Oregon waters. Some of these fish can live to be 100-years-old, but they spawn only once every 2- to 8-years.",
keyword: "indian"
},
{
name: "Molalla River",
description: "Channel catfish are a prized species in many parts of the state. At the same time, illegally introduced bullhead catfish can distupt other fisheries such as trout.",
keyword: "molalla"
}
],
currentTrip: {
fish: {
salmon: false,
trout: false,
steelhead: false,
bass: false,
sturgeon: false,
catfish: false,
},
location: {
columbia: false,
hood: false,
rogue: false,
umpqua: false,
indian: false,
molalla: false
}
},
currentStage: "location"
}
toggleOptionHandler = ( type, option ) => {
const updatedTrip = {
...this.state.currentTrip
};
const oldBoolean = this.state.currentTrip[type][option];
const updatedBoolean = !oldBoolean;
updatedTrip[type][option] = updatedBoolean;
this.setState( { currentTrip: updatedTrip } );
}
render() {
let cards = (
<Cards
toggleOption={this.toggleOptionHandler}
info={this.state.fish}
type="fish"
tripInfo={this.state.currentTrip} />
);
if (this.state.currentStage == "location") {
cards = (
<Cards
toggleOption={this.toggleOptionHandler}
info={this.state.locations}
type="location"
tripInfo={this.state.currentTrip} />
);
}
return (
<div className={classes.FriendFinder}>
<h2 className={typography.HeadingSecondary}>Choose your {this.state.currentStage}</h2>
{cards}
</div>
);
}
}
export default FriendFinder;
|
import './index.css'
const Message = props => {
const {isLogin} = props
return (
<h1 className="app-heading">{isLogin ? 'Welcome User' : 'Please Login'}</h1>
)
}
export default Message
|
const {VlElement} = require('vl-ui-core').Test;
const {By} = require('vl-ui-core').Test.Setup;
const {VlProgressBar} = require('vl-ui-progress-bar').Test;
const VlWizardPane = require('./vl-wizard-pane');
class VlWizard extends VlElement {
async next() {
const pane = await this.getActivePane();
return pane.next();
}
async previous() {
const pane = await this.getActivePane();
return pane.previous();
}
async getTitleSlotElements() {
const slot = await this.shadowRoot.findElement(By.css('header slot[name="title"]'));
return this.getAssignedElements(slot);
}
async getHeaderSlotElements() {
const slot = await this.shadowRoot.findElement(By.css('header slot[name="header"]'));
return this.getAssignedElements(slot);
}
async getProgressBar() {
const element = await this.shadowRoot.findElement(By.css('vl-progress-bar'));
return new VlProgressBar(this.driver, element);
}
async getPanes() {
const elements = await this.findElements(By.css('vl-wizard-pane'));
return Promise.all(elements.map((element) => new VlWizardPane(this.driver, element)));
}
async getPane(number) {
const panes = await this.getPanes();
return panes[--number];
}
async getActivePane() {
const panes = await this.getPanes();
const isActive = await Promise.all(panes.map((pane) => pane.isActive()));
return panes.find((pane, index) => isActive[index]);
}
}
module.exports = VlWizard;
|
class View {
renderQuestion(target, question) {
const getInput = () => {
const getOptions = () => {
let markup = ``;
question.choices.map(el => {
markup += `<option value="${el}">${el}</option>`
});
return markup;
}
switch (question.answerType) {
case 1:
return `<input type="test">`;
break;
case 0:
return `<select>${getOptions()}</select>`;
break;
default:
console.log('Unnown answerType')
}
}
const markup = `
<div class="question">
<div class="question-label">${question.label}</div>
${getInput()}
</div>
`;
target.innerHTML += markup;
}
render(target, questions) {
questions.forEach(el => {
this.renderQuestion(target, el);
})
}
}
export default View;
|
import axios from "axios";
var paginationWrapper = document.querySelector(".pagination");
var postListWrapper = document.querySelector(".list-unstyled");
var perPageCount = 10;
var getContent = (start, end, stopPaginationRender = false) => {
axios
.get(`http://localhost:3000/posts?_start=${start}&_end=${end}`)
.then((response) => {
var totalCount = response.headers["x-total-count"];
var countPaginationNumber = Math.floor(totalCount / perPageCount);
renderPostList(response.data);
if (!stopPaginationRender) {
renderPagination(countPaginationNumber);
}
});
};
getContent(0, 10, false);
var renderPostList = (postList) => {
postListWrapper.innerHTML = "";
postList.forEach((postItem) => {
var postlistItem = document.createElement("li");
postlistItem.classList.add("media");
postlistItem.classList.add("mt-2");
var postbody = document.createElement("div");
var header = document.createElement("h5");
header.classList.add("mt-0");
header.classList.add("mb-1");
header.innerHTML = postItem.title + postItem.id;
var bodyContent = document.createElement("div");
bodyContent.innerHTML = postItem.body;
postbody.appendChild(header);
postbody.appendChild(bodyContent);
postlistItem.appendChild(postbody);
postListWrapper.appendChild(postlistItem);
});
};
var renderPagination = (countPaginationNumber) => {
paginationWrapper.innerHTML = "";
for (let i = 0; i < countPaginationNumber; i++) {
var anchor = document.createElement("a");
anchor.classList.add("page-link");
anchor.setAttribute("href", "#");
var count = i + 1;
anchor.innerHTML = count;
var pageItem = document.createElement("li");
pageItem.classList.add("page-item");
if (i === 0) {
pageItem.classList.add("active");
}
pageItem.addEventListener("click", (event) => {
var end = count * perPageCount;
var start = end - perPageCount;
console.log(start, end);
getContent(start, end, true);
// Remove All active class
Array.from(paginationWrapper.querySelectorAll("li")).forEach(
(listItem) => {
listItem.classList.remove("active");
}
);
pageItem.classList.add("active");
});
pageItem.appendChild(anchor);
paginationWrapper.appendChild(pageItem);
}
};
|
import React, { Component } from 'react';
import { Table } from 'antd';
import '../index1.css';
import '../AudioBooks/AudioBooks.css';
import './tables.css';
import Checkbox from '@material-ui/core/Checkbox';
import FormControlLabel from '@material-ui/core/FormControlLabel';
const visible = false;
// const checked = false;
export default class table1 extends Component {
handleChange = (event) => {
this.setState({checked: true})
};
onCheckChange(e) {
console.log(`checked = ${e.target.checked}`);
}
showModal = () => {
this.setState({
visible: true,
});
};
handleOk = e => {
console.log(e);
this.setState({
visible: false,
});
};
handleCancel = e => {
console.log(e);
this.setState({
visible: false,
});
};
constructor(){
super();
this.state = visible;
this.onChange = this.onChange.bind(this);
this.handleChange = this.handleChange(this);
// this.onSubmit = this.onSubmit.bind(this);
}
// onChange(e){
// this.setState({[e.target.name]: e.target.value});
// }
// onSubmit(e){
// e.preventDefault();
// };
// }
onChange(filters, sorter, extra) {
console.log('params', filters, sorter, extra);
}
render() {
const columns = [
{
title: <p className = "RequestedTableTitle">Cover Image</p>,
dataIndex: "coverImage",
key: 'coverImage',
// filters: [
// {
// text: 'Joe',
// value: 'Joe',
// },
// {
// text: 'Jim',
// value: 'Jim',
// },
// {
// text: 'Submenu',
// value: 'Submenu',
// children: [
// {
// text: 'Green',
// value: 'Green',
// },
// {
// text: 'Black',
// value: 'Black',
// },
// ],
// },
// ],
// specify the condition of filtering result
// here is that finding the name started with `value`
onFilter: (value, record) => record.name.indexOf(value) === 0,
// sorter: (a, b) => a.name.length - b.name.length,
// sortDirections: ['descend'],
},
{
title: <p className = "RequestedTableTitle" style = {{textAlign: "center"}}>Action</p>,
dataIndex: "actions",
key: "actions",
render: actions => (
<>
<div>
<button type = "button" className="btn btn-success" data-toggle="modal" data-target="#myModal" key={actions} onClick = {this.showModal} style = {{maxHeight: "40px", width: "122px", color: "white", backgroundColor: "#00CD3B", border: "none", fontSize: "11px", fontFamily: "Futura-Medium-01", fontWeight: "500", marginTop: "-5px"}}>
CONFIRM REVIEW GIVEN
</button>
<br/>
<br/>
<button type = "button" className="btn btn-success" data-toggle="modal" data-target="#myModal1" key={actions} style = {{maxHeight: "40px", width: "122px", color: "white", backgroundColor: "#FF003D", border: "none", fontSize: "11px", fontFamily: "Futura-Medium-01", fontWeight: "500", marginTop: "-15px"}}>
FILE DISPUTE
</button>
</div>
</>
),
// filters: [
// {
// text: 'London',
// value: 'London',
// },
// {
// text: 'New York',
// value: 'New York',
// },
// ],
filterMultiple: false,
onFilter: (value, record) => record.address.indexOf(value) === 0,
// sorter: (a, b) => a.address.length - b.address.length,
sortDirections: ['descend', 'ascend'],
},
{
title: <p className = "RequestedTableTitle">Audiobook Name</p>,
dataIndex: "audioBookName",
key: "audioBookName",
defaultSortOrder: 'descend',
sorter: (a, b) => a.age - b.age,
},
{
title: <p className = "RequestedTableTitle">Region</p>,
dataIndex: "region",
key: "region",
// filters: [
// {
// text: 'London',
// value: 'London',
// },
// {
// text: 'New York',
// value: 'New York',
// },
// ],
// filterMultiple: false,
onFilter: (value, record) => record.address.indexOf(value) === 0,
sorter: (a, b) => a.address.length - b.address.length,
sortDirections: ['descend', 'ascend'],
},
{
title: <p className = "RequestedTableTitle">Author</p>,
dataIndex: "author",
key: "author",
// filters: [
// {
// text: 'London',
// value: 'London',
// },
// {
// text: 'New York',
// value: 'New York',
// },
// ],
// filterMultiple: false,
// onFilter: (value, record) => record.address.indexOf(value) === 0,
// sorter: (a, b) => a.address.length - b.address.length,
// sortDirections: ['descend', 'ascend'],
},
{
title: <p className = "RequestedTableTitle">Days Remaining</p>,
dataIndex: "daysRemaining",
key: "daysRemaining",
// filters: [
// {
// text: 'London',
// value: 'London',
// },
// {
// text: 'New York',
// value: 'New York',
// },
// ],
filterMultiple: false,
onFilter: (value, record) => record.address.indexOf(value) === 0,
sorter: (a, b) => a.address.length - b.address.length,
sortDirections: ['descend', 'ascend'],
},
{
title: <p className = "RequestedTableTitle">Promo Code</p>,
dataIndex: "promoCode",
key: "promoCode",
// filters: [
// {
// text: 'London',
// value: 'London',
// },
// {
// text: 'New York',
// value: 'New York',
// },
// ],
filterMultiple: false,
onFilter: (value, record) => record.address.indexOf(value) === 0,
sorter: (a, b) => a.address.length - b.address.length,
sortDirections: ['descend', 'ascend'],
},
{
title: <p className = "RequestedTableTitle">Status</p>,
dataIndex: "status",
key: "status",
// filters: [
// {
// text: 'London',
// value: 'London',
// },
// {
// text: 'New York',
// value: 'New York',
// },
// ],
filterMultiple: false,
onFilter: (value, record) => record.address.indexOf(value) === 0,
// sorter: (a, b) => a.address.length - b.address.length,
sortDirections: ['descend', 'ascend'],
},
{
title: <p className = "RequestedTableTitle">Date</p>,
dataIndex: "date",
key: "date",
// filters: [
// {
// text: 'London',
// value: 'London',
// },
// {
// text: 'New York',
// value: 'New York',
// },
// ],
filterMultiple: false,
onFilter: (value, record) => record.address.indexOf(value) === 0,
sorter: (a, b) => a.address.length - b.address.length,
sortDirections: ['descend', 'ascend'],
},
];
const data = [
{
key: "coverImage",
coverImage: <img src = {require("../../../Assets/Images/b1.png")} style = {{maxHeight: "80px", maxWidth: "80px"}} alt = "table"/> ,
audioBookName: <p className = "AudioBookName">Harry Potter</p>,
region: <p className = "RequestedTableData">US</p>,
author: <p className = "RequestedTableData"><u>Jackson Barber</u></p>,
daysRemaining: <p className = "DAYSREMAINING">29</p>,
promoCode: <p className = "RequestedTableData">327KQXCGGDNG7</p>,
status: <p className = "RequestedTableData">Requires Review</p>,
date: <p className = "RequestedTableData">08-04-2020</p>
},
];
return (
<div>
<div className="container" style = {{textAlign: 'center'}}>
<div className="modal fade" id="myModal1">
<div className="modal-dialog MODAL" style = {{maxWidth: "400px", maxHeight: "477px"}}>
<div className="modal-content">
<h4 className="modal-title MODALTITLE">FILE DISPUTE</h4>
<button type="button" className="close" data-dismiss="modal" style = {{textAlign: "right", marginTop: "-50px", marginRight: "5px"}}>×</button>
<br/>
<br/>
<div className="modal-body MODALCHECKBOXES">
<FormControlLabel
style = {{float: "left", marginLeft: "4rem"}}
control={
<Checkbox
checked={this.state.checked}
onChange={this.handleChange}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
}
label="Already Redeemed"
/>
<br/>
<FormControlLabel
style = {{float: "left", marginLeft: "4rem"}}
control={
<Checkbox
checked={this.state.checked}
onChange={this.handleChange}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
}
label="Invalid Promo Code"
/>
<FormControlLabel
style = {{float: "left", marginLeft: "4rem"}}
control={
<Checkbox
checked={this.state.checked}
onChange={this.handleChange}
inputProps={{ 'aria-label': 'primary checkbox' }}
/>
}
label="Inactive Promo Code"
/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<form noValidate onSubmit = {this.onSubmit} className="col-md-8 m-auto" style = {{backgroundColor: "White"}}>
<input type="button" className = "btn btn mr-1 CancelBtn" value = "Cancel"/>
<input type="submit" className="btn btn Submit"/>
</form>
</div>
</div>
</div>
</div>
</div>
<div className="container" style = {{textAlign: 'center'}}>
<div className="modal fade" id="myModal">
<div className="modal-dialog MODAL" style = {{maxWidth: "400px", maxHeight: "477px"}}>
<div className="modal-content">
<h4 className="modal-title MODALTITLE">CONFIRM REVIEW</h4>
<button type="button" className="close" data-dismiss="modal" style = {{textAlign: "right", marginTop: "-50px", marginRight: "5px"}}>×</button>
<br/>
<br/>
<div className="modal-body">
<img src = {(require('../../../Assets/Images/checkmark.png'))} alt = "checkbox" style = {{textAlign: "center", maxHeight: "100px", maxWidth: "100px"}}></img>
<br/>
<br/>
<p style = {{fontFamily: "Roboto-Regular", fontSize: "20px", lineHeight: "30px", textAlign: "center", color: "#686868"}}>I confirm I have left an honest, unbiased review on this audiobook.</p>
<form noValidate onSubmit = {this.onSubmit} className="col-md-8 m-auto" style = {{backgroundColor: "White"}}>
<input type="button" className="btn btn mr-1" style = {{backgroundColor: "White", borderRadius: "5px", width: "100px", height: "44px", border: "0.7solid", borderColor: "#B8B298", fontFamily: "Avenir", fontStyle: "normal", fontWeight: "500", fontSize: "15px", lineHeight: "20px", textAlign: "center", color: "#B8B298"}} value = "Cancel"/>
<input type="submit" className="btn btn" style = {{backgroundColor: "#00A2FF", borderRadius: "4px", width: "100px", height: "44px", fontFamily: "Roboto", fontStyle: "normal", fontWeight: "normal", fontSize: "13px", lineHeight: "22px", textAlign: "center", color: "#FFFFFF", display: "inline-block"}} value = "I CONFIRM"/>
</form>
</div>
</div>
</div>
</div>
</div>
<Table columns={columns} dataSource={data} onChange={this.onChange} pagination = {false}/>
</div>
)
}
}
;
|
import React, { Component } from 'react';
import {BrowserRouter as Router, Link, Route, Switch} from 'react-router-dom';
import ListEOfficerComponent from '../components/ListEOfficerComponent';
import CreateEOfficerComponent from '../components/CreateEOfficerComponent';
import ViewEOfficerComponent from '../components/ViewEOfficerComponent';
import HeaderComponent from '../components/HeaderComponent';
import FooterComponent from '../components/FooterComponent';
import Navbar from '../components/Navbar';
class ElectionOfficer extends Component {
render() {
return (
<div className='officers'>
<Navbar/>
<Router>
{/* <HeaderComponent /> */}
<div className="container">
<Switch>
<Route path = "/" exact component = {ListEOfficerComponent}></Route>
<Route path = "/officers" component = {ListEOfficerComponent}></Route>
<Route path = "/add-officer/:officerId" component = {CreateEOfficerComponent}></Route>
<Route path = "/view-officer/:officerId" component = {ViewEOfficerComponent}></Route>
</Switch>
</div>
<FooterComponent />
</Router>
</div>
);
}
}
export default ElectionOfficer;
|
export default {
computed: {
getPermissionsTranslation() {
return (permission) => {
if (this.$te('role.permissions.' + permission)) {
return this.$t('role.permissions.' + permission)
} else {
return permission
}
}
}
}
}
|
/* Maps and Sets Exercise */
// Quick Question #1
//What does the following code return?
new Set([1,1,2,2,3,4]);
//Answer: it removes duplicates and returns Set { 1, 2, 3, 4 }
// Quick Question #2
// What does the following code return?
[...new Set("referee")].join("");
//Answer: this removes duplicates and returns ref.
// Quick Questions #3
// What does the Map m look like after running the following code?
let m = new Map();
m.set([1,2,3], true);
m.set([1,2,3], false);
// Answer: m looks like { [ 1, 2, 3 ] => true, [ 1, 2, 3 ] => false }
// hasDuplicate
//Write a function called hasDuplicate which accepts an array and returns true or false if that array contains a duplicate
function hasDuplicate(array){
let newSet = new Set(array);
//console.log(newSet);
if (array.length === newSet.size){
return false;
}
return true;
}
console.log(hasDuplicate([1,3,2,1])); // true
console.log(hasDuplicate([1,5,-1,4])) // false
// vowelCount
/* Write a function called vowelCount which accepts a string and returns a map where the keys are numbers and the
values are the count of the vowels in the string.
vowelCount('awesome') // Map { 'a' => 1, 'e' => 2, 'o' => 1 }
vowelCount('Colt') // Map { 'o' => 1 }
*/
/*
Steps: create a string of vowels,
convert charcters of argument into lowercase, and check if an argument contains characters of vowel string.
If it does, then count that vowel character.
create map, and put that vowel into that map.
*/
function vowelCount(str){
let str1 = 'aeiou';
let newMap = new Map();
for(let char of str){
let charToLowerCase = char.toLowerCase();
if(str1.includes(charToLowerCase)){
if(newMap.has(charToLowerCase)){
newMap.set(charToLowerCase, newMap.get(charToLowerCase) + 1);
} else {
newMap.set(charToLowerCase, 1);
}
}
}
return newMap;
}
console.log(vowelCount('aaaaeibbcciiiccceeee'));
console.log(vowelCount('awesome'));
console.log(vowelCount('Colt'));
|
import { createStackNavigator, createSwitchNavigator } from 'react-navigation';
import LoadingScreen from './Loading';
import HomeScreen from './Home';
import SignUpScreen from './SignUp';
import SignUpVerificationScreen from './SignUpVerification';
import LogonScreen from './Logon';
import LogonVerificationScreen from './LogonVerification';
const AuthStack = createStackNavigator({
Logon: LogonScreen,
LogonVerification: LogonVerificationScreen,
SignUp: SignUpScreen,
SignUpVerification: SignUpVerificationScreen,
}, {
headerMode: 'none',
initialRouteName: 'Logon'
});
const AppStack = createStackNavigator({
Home: HomeScreen,
});
export default createSwitchNavigator(
{
Loading: LoadingScreen,
App: AppStack,
Auth: AuthStack,
},
{
initialRouteName: 'Loading',
}
);
|
import React from "react";
import ProductGroup from "../../layouts/ProductGroup";
import ProductList from "../../components/ProductList";
import styles from "./ProductsPage.module.css";
const ProductsPage = ({ pageTitle, category, products }) => {
return (
<ProductGroup pageTitle={pageTitle}>
{products.length ? (
<ProductList
className={styles.list}
category={category}
products={products}
/>
) : null}
</ProductGroup>
);
};
export default ProductsPage;
|
var client = require('./Mailgun.js');
var utils = require('./util/user.js');
var base64 = require('./util/base64.js');
Parse.Cloud.define("sendSignupEmail", function(request, response) {
utils.getUser(request.params.userid, function(user) {
var fs = require('fs');
var ejsFileContents = fs.readFileSync('./cloud/views/signupEmail.ejs');
var EJS = require('ejs');
var message = EJS.render(ejsFileContents, { name: request.params.firstname, email: request.params.email, usercount: request.params.userid});
client.sendEmail({
to: user.get("email"),
from: "Poppo <support@poppo.com>",
subject: "Welcome to Poppo!",
html: message
}).then(function(httpResponse) {
response.success("Email sent");
}, function(httpResponse) {
console.error(httpResponse);
response.error("Email send failed");
});
});
});
|
/// <reference path="../../../core/plugins/lz-string.d.ts" />
/// <reference path="../../../core/PagesPositionsCache/PPCache.ts" />
var LocalBookmarks;
(function (LocalBookmarks) {
var LocalBookmarksClass = /** @class */ (function () {
function LocalBookmarksClass(ArtID) {
this.ArtID = ArtID;
this.LocalBookmarks = [];
this.local = window.localStorage;
this.storageVal = 'bookmarks';
this.LZState = true; // for testing only, default = true
this.GetBookmarks();
this.CurPos = [0];
this.DateTime = 0;
var FoundBookmark;
if (FoundBookmark = this.GetBookmarkByArt(this.ArtID)) {
if (FoundBookmark.CurPos) {
this.CurPos = FoundBookmark.CurPos;
}
if (FoundBookmark.DateTime) {
this.DateTime = FoundBookmark.DateTime;
}
}
}
LocalBookmarksClass.prototype.GetBookmarkByArt = function (ArtID) {
for (var j = 0; j < this.LocalBookmarks.length; j++) {
if (this.LocalBookmarks[j].ArtID == ArtID) {
return this.LocalBookmarks[j];
}
}
return null;
};
LocalBookmarksClass.prototype.GetBookmarks = function () {
if (!FB3PPCache.CheckStorageAvail()) {
return;
}
var bookmarksXML = this.local.getItem(this.storageVal);
if (bookmarksXML) {
var cacheData = this.DecodeData(bookmarksXML);
this.LocalBookmarks = JSON.parse(cacheData);
}
};
LocalBookmarksClass.prototype.StoreBookmarks = function (XMLString) {
if (!FB3PPCache.CheckStorageAvail()) {
return;
}
if (this.LocalBookmarks.length >= 10) {
this.LocalBookmarks.shift();
}
var localBookmarksTmp = {
ArtID: this.ArtID,
Cache: XMLString,
CurPos: this.CurPos,
DateTime: this.DateTime
};
for (var j = 0; j < this.LocalBookmarks.length; j++) {
if (this.LocalBookmarks[j].ArtID == this.ArtID) {
this.LocalBookmarks.splice(j, 1);
}
}
this.LocalBookmarks.push(localBookmarksTmp);
var BookmarksString = JSON.stringify(this.LocalBookmarks);
var cacheData = this.EncodeData(BookmarksString);
this.local.setItem(this.storageVal, cacheData);
};
LocalBookmarksClass.prototype.GetCurrentArtBookmarks = function () {
if (!FB3PPCache.CheckStorageAvail()) {
return;
}
var FoundBookmark;
if (FoundBookmark = this.GetBookmarkByArt(this.ArtID)) {
return FoundBookmark.Cache;
}
else {
return null;
}
};
LocalBookmarksClass.prototype.SetCurrentPosition = function (LitresCurPos) {
this.CurPos = LitresCurPos;
};
LocalBookmarksClass.prototype.GetCurrentPosition = function () {
return this.CurPos;
};
LocalBookmarksClass.prototype.SetCurrentDateTime = function (value) {
this.DateTime = value;
};
LocalBookmarksClass.prototype.GetCurrentDateTime = function () {
return this.DateTime;
};
LocalBookmarksClass.prototype.EncodeData = function (Data) {
if (this.LZState) {
return LZString.compressToUTF16(Data);
}
else {
return Data;
}
};
LocalBookmarksClass.prototype.DecodeData = function (Data) {
if (this.LZState) {
return LZString.decompressFromUTF16(Data);
}
else {
return Data;
}
};
return LocalBookmarksClass;
}());
LocalBookmarks.LocalBookmarksClass = LocalBookmarksClass;
})(LocalBookmarks || (LocalBookmarks = {}));
|
export function isFnKey(name) {
return name.match(/^[fF]([2-9]|(1([0-2]?)))$/)
}
export function isSpaceKey(name) {
return name === ' ' || name.match(/^[sS]pace$/);
}
export function isCtrlKey(name) {
return name.match(/(^([cC]ontrol)|ctrl)$/);
}
export function isAltKey(name) {
return name.match(/^[aA]lt$/);
}
export function isShiftKey(name) {
return name.match(/^[sS]hift$/);
}
export function isMetaKey(name) {
return name.toLowerCase().match(/^(command|windows|meta)$/);
}
/***
*
* @param {string} text
* @return {string}
*/
export function normalizeKeyBindingIdent(text) {
var keys = text.trim().toLowerCase().split(/[-+\s_.]+/)
.filter(function (w) {
return w.length > 0;
});
var values = {
meta: 1,
ctrl: 2,
alt: 3,
shift: 4
};
keys.sort(function (a, b) {
var va, vb;
va = values[a] || 100;
vb = values[b] || 100;
return va - vb;
});
return keys.join('-');
}
/***
*
* @param {KeyboardEvent} event
* @return {string}
*/
export function keyboardEventToKeyBindingIdent(event) {
var keys = [];
if (event.metaKey) {
keys.push('meta');
}
if (event.ctrlKey)
keys.push('ctrl');
if (event.altKey)
keys.push('alt');
if (event.shiftKey)
keys.push('shift');
if (isSpaceKey(event.key)) {
keys.push('space');
}
else if (isFnKey(event.key)) {
keys.push(event.key.toLowerCase())
}
else if (!isMetaKey(event.key) && !isAltKey(event.key) && !isCtrlKey(event.key) && !isShiftKey(event.key))
keys.push(event.key.toLowerCase());
return keys.join('-');
}
|
import axios from 'axios'
import qs from 'qs'
axios.defaults.headers.post['Content-Type']
= 'application/x-www-form-urlencoded';
// axios.defaults.baseURL
// = 'http://120.78.90.119:8099';
axios.defaults.baseURL ="http://120.78.164.247:9999";
axios.defaults.withCredentials = true;
export default function(flag){
let instance=axios.create();
instance.interceptors.request.use((config)=>{
if(config.method==='post'){
if(flag&&flag=="array"){
config.data=qs.stringify(config.data,{allowDots:true})
}else{
config.data=qs.stringify(config.data,{arrayFormat:'repeat'})
}
}
return config;
}, (error) => {
return Promise.reject(error);
});
return instance
}
|
import chai from 'chai'
import chatHttp from 'chai-http'
import 'chai/register-should'
import app from '../index'
chai.use(chatHttp)
const { expect } = chai
const product = {
menu: 'allDay',
name: 'Bolo',
price: '5.00',
type: 'doces',
}
const order = {
client: 'Jessika',
status: 'em produção',
table: 1,
waiter: 'João',
}
const table = {
option: "bovino",
quant: 1,
productId: 2,
orderId: 2,
typeId: 2,
}
describe('Testing the tables endpoints:', () => {
it('It should create a tables', (done) => {
chai.request(app)
.post('/api/products')
.set('Accept', 'application/json')
.send(product)
.end((err, res) => {
expect(res.status).to.equal(201)
expect(res.body.data).to.include({
id: 2,
menu: product.menu,
name: product.name,
price: product.price,
type: product.type,
})
chai.request(app)
.post('/api/orders')
.set('Accept', 'application/json')
.send(order)
.end((err, res) => {
expect(res.status).to.equal(201)
expect(res.body.data).to.include({
id: 2,
client: order.client,
status: order.status,
table: order.table,
waiter: order.waiter,
})
chai.request(app)
.post('/api/tables')
.set('Accept', 'application/json')
.send(table)
.end((err, res) => {
expect(res.status).to.equal(201)
expect(res.body.data).to.include({
id: 1,
option: table.option,
quant: table.quant,
productId: table.productId,
orderId: table.orderId,
typeId: table.typeId,
})
done()
})
})
})
})
it('It should not create a table with incomplete parameters', (done) => {
const tables = {
quant: 3,
orderId: 2,
}
chai.request(app)
.post('/api/tables')
.set('Accept', 'application/json')
.send(tables)
.end((err, res) => {
expect(res.status).to.equal(400)
done()
})
})
it('It should get all tables', (done) => {
chai.request(app)
.get('/api/tables')
.set('Accept', 'application/json')
.end((err, res) => {
expect(res.status).to.equal(200)
res.body.data[0].should.have.property('id')
res.body.data[0].should.have.property('option')
res.body.data[0].should.have.property('quant')
res.body.data[0].should.have.property('productId')
res.body.data[0].should.have.property('orderId')
res.body.data[0].should.have.property('typeId')
done()
})
})
it('It should get a particular table', (done) => {
const tableId = 1
chai.request(app)
.get(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.end((err, res) => {
console.log("erro get all tables", res.body);
expect(res.status).to.equal(200)
res.body.data.should.have.property('id')
res.body.data.should.have.property('option')
res.body.data.should.have.property('quant')
res.body.data.should.have.property('productId')
res.body.data.should.have.property('orderId')
res.body.data.should.have.property('typeId')
done()
})
})
it('It should not get a particular table with invalid id', (done) => {
const tableId = 8888
chai.request(app)
.get(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.end((err, res) => {
expect(res.status).to.equal(404)
res.body.should.have.property('message')
.eql(`Cannot find Table with the id ${tableId}`)
done()
})
})
it('It should not get a particular table with non-numeric id', (done) => {
const tableId = 'aaa'
chai.request(app)
.get(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.end((err, res) => {
expect(res.status).to.equal(400)
res.body.should.have.property('message')
.eql('Please input a valid numeric value')
done()
})
})
it('It should update a table', (done) => {
const tableId = 1
const updatedTable = {
id: tableId,
option: "vegetariano",
quant: 2,
productId: 2,
orderId: 2,
typeId: 2,
}
chai.request(app)
.put(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.send(updatedTable)
.end((err, res) => {
expect(res.status).to.equal(200)
expect(res.body.data.id).equal(updatedTable.id)
expect(res.body.data.option).equal(updatedTable.option)
expect(res.body.data.quant).equal(updatedTable.quant)
expect(res.body.data.productId).equal(updatedTable.productId)
expect(res.body.data.orderId).equal(updatedTable.orderId)
expect(res.body.data.typeId).equal(updatedTable.typeId)
done()
})
})
it('It should not update a table with invalid id', (done) => {
const tableId = '9999'
const updatedTable = {
id: tableId,
option: "vegetariano",
quant: 2,
productId: 2,
orderId: 2,
typeId: 2,
}
chai.request(app)
.put(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.send(updatedTable)
.end((err, res) => {
expect(res.status).to.equal(404)
res.body.should.have.property('message')
.eql(`Cannot find Table with the id: ${tableId}`)
done()
})
})
it('It should not update a table with non-numeric id value', (done) => {
const tableId = 'ggg'
const updatedTable = {
id: tableId,
option: "vegetariano",
quant: 2,
productId: 2,
orderId: 2,
typeId: 2,
}
chai.request(app)
.put(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.send(updatedTable)
.end((err, res) => {
expect(res.status).to.equal(400)
res.body.should.have.property('message')
.eql('Please input a valid numeric value')
done()
})
})
it('It should delete a table', (done) => {
const tableId = 1
chai.request(app)
.delete(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.end((err, res) => {
expect(res.status).to.equal(200)
expect(res.body.data).to.include({})
done()
})
})
it('It should not delete a table with invalid id', (done) => {
const tableId = 777
chai.request(app)
.delete(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.end((err, res) => {
expect(res.status).to.equal(404)
res.body.should.have.property('message')
.eql(`Table with the id ${tableId} cannot be found`)
done()
})
})
it('It should not delete a table with non-numeric id', (done) => {
const tableId = 'bbb'
chai.request(app)
.delete(`/api/tables/${tableId}`)
.set('Accept', 'application/json')
.end((err, res) => {
expect(res.status).to.equal(400)
res.body.should.have.property('message').eql('Please provide a numeric value')
done()
})
})
})
|
class HashTable {
constructor(size = 53) {
this.keyMap = new Array(size);
}
_hash(key) {
let result = 0;
let WEIRD_PRIME = 31;
// loops through at most 100 characters
for (let i = 0; i < Math.min(key.length, 100); i++) {
// map "a" to 1, "b" to 2, etc. by using charCodeAt() - 96
let value = key.charCodeAt(i) - 96;
result = (result * WEIRD_PRIME + value) % this.keyMap.length;
}
return result;
}
set(key, value) {
let index = this._hash(key);
if (!this.keyMap[index]) this.keyMap[index] = [];
this.keyMap[index].push([key, value]);
// TO DO: account for duplicate key -- should just update value
// if (this.keyMap[index].length) {
// for (let item of this.keyMap[index]) {
// if (item[0] === key) {
// item[1] = value;
// }
// }
// // this.keyMap[index].push([key, value]);
// // console.log(this.keyMap[index]);
// }
// this.keyMap[index].push([key, value]);
// console.log(this.keyMap[index]);
return true;
}
get(key) {
let index = this._hash(key);
if (this.keyMap[index]) {
for (let keyInMap of this.keyMap[index]) {
if (keyInMap[0] === key) {
return keyInMap[1];
}
}
}
}
// returns all unique keys in keyMap
keys() {
let keys = [];
for (let item of this.keyMap) {
if (!item) continue;
for (let innerItem of item) {
if (!keys.includes(innerItem[0])) {
keys.push(innerItem[0]);
}
}
}
return keys;
}
// returns all unique values in keyMap
values() {
let values = [];
for (let item of this.keyMap) {
if (!item) continue;
for (let innerItem of item) {
if (!values.includes(innerItem[1])) {
values.push(innerItem[1]);
}
}
}
return values;
}
}
let hash = new HashTable();
hash.set("hello", 1);
hash.set("pink", 2);
hash.set("salmon", 3);
hash.set("dog", 4);
hash.set("gray", 5);
hash.set("purple", 6);
hash.set("blue", 7);
hash.set("yellow", 7);
hash.set("yellow", 8);
console.log(hash);
// console.log(hash.get("I love")); // undefined
// console.log(hash.get("dog")); // 4
// console.log(hash.keys());
// console.log(hash.values());
// hash function
// NOT A GOOD FUNCTION
// function hash(key, arrLength) {
// let result = 0;
// for (let i = 0; i < key.length; i++) {
// // map "a" to 1, "b" to 2, etc. by using charCodeAt() - 96
// let value = key.charCodeAt(i) - 96;
// result = (result + value) % arrLength;
// }
// return result;
// }
// BETTER - using a prime arrLength value
// function hash(key, arrLength) {
// let result = 0;
// let WEIRD_PRIME = 31;
// // loops through at most 100 characters
// for (let i = 0; i < Math.min(key.length, 100); i++) {
// // map "a" to 1, "b" to 2, etc. by using charCodeAt() - 96
// let value = key.charCodeAt(i) - 96;
// result = (result * WEIRD_PRIME + value) % arrLength;
// }
// return result;
// }
// console.log(hash("gray", 13)); // BAD: 1 GOOD: 3
// console.log(hash("orange", 13)); // BAD: 0 GOOD: 10
// console.log(hash("black", 13)); // BAD: 9 GOOD: 6
// console.log(hash("pink", 13)); // BAD: 0 GOOD: 5
// console.log(hash("blue", 13)); // BAD: 0 GOOD: 10
// console.log(hash("white", 13)); // BAD: 5 GOOD: 1
|
"use strict";
let debug = require('debug')('APP:socket');
// GLOBALS
let confuser = [];
let io = (socket) =>{
debug('Sending conection true');
socket.emit('news', { hello: 'world' });
socket.on('my other event', (data) => {
console.log(data);
});
}
module.exports = io;
|
export const procedureXslt = '\
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">\
<xsl:output method="html"/>\
\
<xsl:template match="/dmodule/content">\
<div class="content">\
<xsl:apply-templates select="procedure" />\
</div>\
</xsl:template>\
\
<xsl:template match="procedure">\
<div class="procedure">\
<xsl:apply-templates select="mainProcedure" />\
</div>\
</xsl:template>\
\
<xsl:template match="mainProcedure">\
<div class="mainProcedure">\
<xsl:apply-templates select="proceduralStep" />\
</div>\
</xsl:template>\
\
<xsl:template match="proceduralStep">\
<div class="proceduralStep">\
<xsl:apply-templates select="para" />\
</div>\
</xsl:template>\
\
<xsl:template match="para">\
<p class="para">\
<xsl:value-of select="text()" />\
</p>\
</xsl:template>\
</xsl:stylesheet>'
|
import Enzyme, { shallow, render, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
Enzyme.configure({ adapter: new Adapter() });
global.shallow = shallow;
global.render = render;
global.mount = mount;
global.spyMount = (component, ...methodNames) => {
const mount = require('enzyme').mount;
const wrapper = mount(component);
const result = [wrapper];
methodNames.forEach(methodName => {
result.push(jest.spyOn(wrapper.instance(), methodName));
});
wrapper.instance().forceUpdate();
return result;
};
|
import React, { createContext, useEffect, useState } from "react";
import axios from "axios";
export const NewsContext = createContext();
export const NewsContextProvider = (props) => {
const [data, setData] = useState();
const apiKey = "81f8edbb675e40dc8735ccee0e159315";
useEffect(() => {
axios
.get(
`https://newsapi.org/v2/top-headlines?country=us&apiKey=81f8edbb675e40dc8735ccee0e159315`
)
.then((response) => setData(response.data))
.catch((error) => console.log(error));
}, []);
/* Para realizar una solicitud GET llamamos al método get de Axios,
pasando como parámetro la URL que deseamos solicitar.
Luego de esto llamamos a los métodos then y catch ,
que se encargan de capturar la respuesta del servidor así como los errores,
en caso de que llegue a ocurrir alguno.
*/
return (
<NewsContext.Provider value={{ data }}>
{props.children}
</NewsContext.Provider>
);
};
|
// Importing npm modules
const [mongoose, path, dotenv] = [
require("mongoose"),
require("path"),
require("dotenv").config(),
];
// Importing app module from index.js
const app = require(path.join(__dirname, "index"));
// Environment Variables
const { PORT, MONGODB_URI, MONGO_LOCAL, MONGODB_PASS } = process.env;
// Mongoose Connection
mongoose
.connect(MONGO_LOCAL, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log("DB Connected Successfully!!!");
// Listening Port
app.listen(PORT, () =>
console.log(
`Server Connected At Port ${PORT} in ${process.env.NODE_ENV} environment`
)
);
})
.catch((err) => console.log(err));
|
// Connecting to ROS
// -----------------
var ros = new ROSLIB.Ros({
url : 'ws://localhost:9090'
});
ros.on('connection', function() {
console.log('Connected to websocket server.');
});
ros.on('error', function(error) {
console.log('Error connecting to websocket server: ', error);
});
ros.on('close', function() {
console.log('Connection to websocket server closed.');
});
// The ActionClient
// ----------------
var teachModeClient = new ROSLIB.ActionClient({
ros : ros,
serverName : '/teach_mode_server',
actionName : 'strategy/TeachCommandListAction'
});
// Subscribing to a Topic
// ----------------------
var joint_Sub = new ROSLIB.Topic({
ros:ros,
name: '/joint_states',
messageType : 'sensor_msgs/JointState'
});
var eef_Sub = new ROSLIB.Topic({
ros:ros,
name: '/eef_states',
messageType : 'geometry_msgs/Twist'
});
function saveBtn(){
console.log("save Btn click");
}
$(document).ready(function(){
$("#infoPanel").draggable();
$("#ioPanel").draggable();
//Detect mouse still down
$('#direction_front').mousedown(function(e){
mouseStillDown = true;
doSomething();
});
var temp=1;
function doSomething(){
if (!mouseStillDown) {return;}
else if (mouseStillDown) {
console.log(temp++);
setInterval(doSomething, 1000);
}
}
$('#direction_front').mouseup(function(e){
mouseStillDown = false;
clearInterval(doSomething);
temp=1;
});
//Panel_Edit
$('#control_edit_joint').on('click',function(e){
$('#dialog_table_joint').show();
$('#dialog_table_eef').hide();
$('#dialog_table_plus').hide();
});
$('#control_edit_eef').on('click',function(e){
$('#dialog_table_eef').show();
$('#dialog_table_joint').hide();
$('#dialog_table_plus').hide();
});
//ROS_Bridge
$('#control_send_joint').on('click',function(e){
var float64 = new Float64Array(6);
float64[0] = $('#input_j1').val()*(Math.PI/180);
float64[1] = $('#input_j2').val()*(Math.PI/180);
float64[2] = $('#input_j3').val()*(Math.PI/180);
float64[3] = $('#input_j4').val()*(Math.PI/180);
float64[4] = $('#input_j5').val()*(Math.PI/180);
float64[5] = $('#input_j6').val()*(Math.PI/180);
var send_joint = new ROSLIB.Message({
cmd : 'JointPosition',
joint_position : [float64[0],float64[1],float64[2],
float64[3],float64[4],float64[5]]
});
mlist.push(send_joint);
// Create a goal.
var goal = new ROSLIB.Goal({
actionClient : teachModeClient,
goalMessage : {
cmd_list : mlist
}
});
// Print out their output into the terminal.
goal.on('feedback', function(feedback) {
console.log('Feedback: ' + feedback.status);
});
goal.on('result', function(result) {
console.log('Final Result: ' + result.notify);
});
// Send the goal to the action server.
$("#infoContent").html('Goal was send cmdlist'
+'<BR>Cmd : ' + send_joint.cmd
+"<BR>Joint Position : [ "+ send_joint.joint_position+" ]"
);
goal.send();
mlist = [];
});
$('#control_send_eef').on('click',function(e){
var float64 = new Float64Array(6);
float64[0] = $('#input_lx').val();
float64[1] = $('#input_ly').val();
float64[2] = $('#input_lz').val();
float64[3] = $('#input_ax').val();
float64[4] = $('#input_ay').val();
float64[5] = $('#input_az').val();
var twist = new ROSLIB.Message({
linear : {
x : float64[0],
y : float64[1],
z : float64[2]
},
angular : {
x : float64[3],
y : float64[4],
z : float64[5]
}
});
var send_eef = new ROSLIB.Message({
cmd : 'EEFPosition',
pose : twist
});
mlist.push(send_eef);
var goal = new ROSLIB.Goal({
actionClient : teachModeClient,
goalMessage : {
cmd_list : mlist
}
});
goal.on('feedback', function(feedback) {
console.log('Feedback: ' + feedback.status);
});
goal.on('result', function(result) {
console.log('Final Result: ' + result.notify);
});
$("#infoContent").html('Goal was send cmdlist'
+'<BR>Cmd : ' + send_eef.cmd +"<BR>Pose : "
+"<BR>linear:<BR>"+ send_eef.pose.linear.x +"<BR>"+ send_eef.pose.linear.y +"<BR>"+ send_eef.pose.linear.z
+"<BR>angular<BR>"+ send_eef.pose.angular.x +"<BR>"+ send_eef.pose.angular.y +"<BR>"+ send_eef.pose.angular.z
);
goal.send();
mlist = [];
});
$('#control_io').on('click',function(e){
if(io_default===false){
io_default=true;
$("#output_io").html('On');
var send_io = new ROSLIB.Message({
cmd : 'Vaccum',
vaccum : true
});
mlist.push(send_io);
}else{
io_default=false;
$("#output_io").html('Off');
var send_io = new ROSLIB.Message({
cmd : 'Vaccum',
vaccum : false
});
mlist.push(send_io);
}
var goal = new ROSLIB.Goal({
actionClient : teachModeClient,
goalMessage : {
cmd_list : mlist
}
});
goal.on('feedback', function(feedback) {
console.log('Feedback: ' + feedback.status);
});
goal.on('result', function(result) {
console.log('Final Result: ' + result.notify);
});
$("#infoContent").html('Goal was send cmdlist'
+'<BR>Cmd : ' + send_io.cmd
+'<BR>Vaccum : '+ send_io.vaccum
);
goal.send();
mlist = [];
});
$('#control_send_home').on('click',function(e){
var float64 = new Float64Array(6);
float64[0] = 0;
float64[1] = -1.5708;
float64[2] = 0;
float64[3] = -1.5708;
float64[4] = 0;
float64[5] = 0;
var send_joint = new ROSLIB.Message({
cmd : 'JointPosition',
joint_position : [float64[0],float64[1],float64[2],
float64[3],float64[4],float64[5]]
});
mlist.push(send_joint);
// Create a goal.
var goal = new ROSLIB.Goal({
actionClient : teachModeClient,
goalMessage : {
cmd_list : mlist
}
});
// Print out their output into the terminal.
goal.on('feedback', function(feedback) {
console.log('Feedback: ' + feedback.status);
});
goal.on('result', function(result) {
console.log('Final Result: ' + result.notify);
});
// Send the goal to the action server.
$("#infoContent").html('Goal was send cmdlist'
+'<BR>Cmd : ' + send_joint.cmd
+"<BR>Joint Position : [ "+ send_joint.joint_position+" ]"
);
goal.send();
mlist = [];
});
//Panel control(use Left,Right,Plus,Minus button)
//Dialog_send
$('#control_send_eef_d').on('click',function(e){
//console.log(('#table_test').children("tr:nth-child(1)").children("td:nth-child(1)").html('X'));
var float64 = new Float64Array(6);
float64[0] = $('#input_lx_d').val();
float64[1] = $('#input_ly_d').val();
float64[2] = $('#input_lz_d').val();
float64[3] = $('#input_ax_d').val();
float64[4] = $('#input_ay_d').val();
float64[5] = $('#input_az_d').val();
var twist = new ROSLIB.Message({
linear : {
x : float64[0],
y : float64[1],
z : float64[2]
},
angular : {
x : float64[3],
y : float64[4],
z : float64[5]
}
});
var send_eef = new ROSLIB.Message({
cmd : 'EEFPosition',
pose : twist
});
mlist.push(send_eef);
var goal = new ROSLIB.Goal({
actionClient : teachModeClient,
goalMessage : {
cmd_list : mlist
}
});
goal.on('feedback', function(feedback) {
console.log('Feedback: ' + feedback.status);
});
goal.on('result', function(result) {
console.log('Final Result: ' + result.notify);
});
$("#infoContent").html('Goal was send cmdlist'
+'<BR>Cmd : ' + send_eef.cmd
+'<BR>Vaccum : '+ send_eef.vaccum
+"<BR>Pose : "
+"<BR>linear:<BR>"+ send_eef.pose.linear.x
+"<BR>"+ send_eef.pose.linear.y
+"<BR>"+ send_eef.pose.linear.z
+"<BR>angular<BR>"+ send_eef.pose.angular.x
+"<BR>"+ send_eef.pose.angular.y
+"<BR>"+ send_eef.pose.angular.z
);
goal.send();
mlist = [];
});
$('#control_send_joint_d').on('click',function(e){
var float64 = new Float64Array(6);
float64[0] = $('#input_j1_d').val()*(Math.PI/180);
float64[1] = $('#input_j2_d').val()*(Math.PI/180);
float64[2] = $('#input_j3_d').val()*(Math.PI/180);
float64[3] = $('#input_j4_d').val()*(Math.PI/180);
float64[4] = $('#input_j5_d').val()*(Math.PI/180);
float64[5] = $('#input_j6_d').val()*(Math.PI/180);
var send_joint = new ROSLIB.Message({
cmd : 'JointPosition',
joint_position : [float64[0],float64[1],float64[2],
float64[3],float64[4],float64[5]]
});
mlist.push(send_joint);
// Create a goal.
var goal = new ROSLIB.Goal({
actionClient : teachModeClient,
goalMessage : {
cmd_list : mlist
}
});
// Print out their output into the terminal.
goal.on('feedback', function(feedback) {
console.log('Feedback: ' + feedback.status);
});
goal.on('result', function(result) {
console.log('Final Result: ' + result.notify);
});
// Send the goal to the action server.
$("#infoContent").html('Goal was send cmdlist'
+'<BR>Cmd : ' + send_joint.cmd
+"<BR>Joint Position : [ "+ send_joint.joint_position+" ]"
);
goal.send();
mlist = [];
});
//Topic_Subscribe
joint_Sub.subscribe(function(message){
//Show Progress-bar
// document.getElementById('progress-bar_j1').style.width = ((((message.position[0]/Math.PI)*180)+360)/720)*100+'%';
$("#progress-bar_j1").css({'width':((((message.position[0]/Math.PI)*180)+360)/720)*100+'%'});
$("#progress-bar_j2").css({'width':((((message.position[1]/Math.PI)*180)+360)/720)*100+'%'});
$("#progress-bar_j3").css({'width':((((message.position[2]/Math.PI)*180)+360)/720)*100+'%'});
$("#progress-bar_j4").css({'width':((((message.position[3]/Math.PI)*180)+360)/720)*100+'%'});
$("#progress-bar_j5").css({'width':((((message.position[4]/Math.PI)*180)+360)/720)*100+'%'});
$("#progress-bar_j6").css({'width':((((message.position[5]/Math.PI)*180)+360)/720)*100+'%'});
$("#output_j1p").html(((message.position[0]/Math.PI)*180).toFixed(2));
$("#output_j2p").html(((message.position[1]/Math.PI)*180).toFixed(2));
$("#output_j3p").html(((message.position[2]/Math.PI)*180).toFixed(2));
$("#output_j4p").html(((message.position[3]/Math.PI)*180).toFixed(2));
$("#output_j5p").html(((message.position[4]/Math.PI)*180).toFixed(2));
$("#output_j6p").html(((message.position[5]/Math.PI)*180).toFixed(2));
});
eef_Sub.subscribe(function(message){
eef_Sub_lx = message.linear.x;
eef_Sub_ly = message.linear.y;
eef_Sub_lz = message.linear.z;
eef_Sub_ax = message.angular.x;
eef_Sub_ay = message.angular.y;
eef_Sub_az = message.angular.z;
$("#output_lx").html(message.linear.x);
$("#output_ly").html(message.linear.y);
$("#output_lz").html(message.linear.z);
$("#output_ax").html(message.angular.x);
$("#output_ay").html(message.angular.y);
$("#output_az").html(message.angular.z);
});
});
|
//declare the main variables and array
let roundMoves = 0;
let gameMoves = 0;
let gameEndCount = 0;
let clicksCounts = 0;
let symbols = ['images/boat.png', 'images/boat.png', 'images/building.png', 'images/building.png', 'images/daruma.png', 'images/daruma.png', 'images/doll.png', 'images/doll.png', 'images/star.png', 'images/star.png', 'images/teddy-bear.png', 'images/teddy-bear.png', 'images/toys.png', 'images/toys.png', 'images/tricycle.png', 'images/tricycle.png']
let openCell = [];
let timeExcuation;
function clickedCell(evt) {
//Start the game time tracker
if (gameMoves === 0 && roundMoves === 0) {
timeCalculator();
}
//Track the clicks so I can use it on the stars rating system
clicksCounts++;
switch (clicksCounts) {
case 17:
$('.star-rating span:nth-child(3)').removeClass('checked');
break;
case 25:
$('.star-rating span:nth-child(2)').removeClass('checked');
break;
}
if (roundMoves === 0) {
roundMoves++;
$(evt.target).addClass('clicked');
$(evt.target).toggleClass('flipped');
openCell[0] = $(evt.target).children('img').attr('src');
} else if (roundMoves === 1) {
//Prevent more than 2 click on the same round
roundMoves = 2;
$(evt.target).addClass('clicked');
$(evt.target).toggleClass('flipped');
openCell[1] = $(evt.target).children('img').attr('src');
gameMoves++;
//Update game moves
$('.game-moves').text(gameMoves);
window.setTimeout(roundCheck, 1000);
}
}
function roundCheck() {
if (openCell[0] === openCell[1]) {
$('.clicked').addClass('identical pulse');
gameEndCount++;
if (gameEndCount === 8) {
gameResult();
}
}
$('.main-playground-container .playground-cell').removeClass('flipped clicked');
//Reset the round
roundMoves = 0;
//Empty the aray
openCell = [];
}
function shuffle(array) {
let currentIndex = array.length,
temporaryValue, randomIndex;
while (currentIndex !== 0) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
function distributionSymbols(array) {
shuffle(symbols);
for (let i = 0; i <= array.length; i++) {
$('.playground-cell:nth-child(' + (i + 1) + ') img').attr('src', array[i]);
}
}
function timeCalculator() {
let sec = 0;
function pad(val) {
return val > 9 ? val : '0' + val;
}
timeExcuation = setInterval(function () {
//To stop the game time tracker
if (gameEndCount === 8) {
return;
}
document.getElementById('seconds').innerHTML = pad(++sec % 60);
document.getElementById('minutes').innerHTML = pad(parseInt(sec / 60, 10));
}, 1000);
}
function gameResult() {
$('#resultModal').css('display', 'block');
$('.resault-moves').text('Your Moves: ' + gameMoves);
$('.resault-time').text('Your time: ' + document.getElementById('minutes').innerHTML + " : " + document.getElementById('seconds').innerHTML);
}
// When the user clicks on (x), close the modal
document.querySelector('.close').addEventListener('click', function () {
$('#resultModal').css('display', 'none');
});
// When the user clicks anywhere outside of the modal, close it
$(window).click(function (evt) {
if (evt.target == $('#resultModal')[0]) {
$('#resultModal').css('display', 'none');
}
});
$(".restart-game").each(function () {
let restartGame = this;
restartGame.addEventListener("click", function (evt) {
gameMoves = 0;
roundMoves = 0;
clicksCounts = 0;
$('.game-moves').text(gameMoves);
gameEndCount = 0;
openCell = [];
$('.main-playground-container .playground-cell').removeClass('flipped clicked identical pulse');
$('.star-rating span').addClass('checked');
clearInterval(timeExcuation);
$('#seconds').text('00');
$('#minutes').text('00');
window.setTimeout(distributionSymbols, 1000, symbols);
$('#resultModal').css('display', 'none');
});
});
//The main Event Listener for the playground
document.querySelector('.main-playground-container').addEventListener('click', function (evt) {
//Check if the user click on a card and disable click when there is two cards open.
if ($(evt.target).attr('class') === 'playground-cell' && roundMoves !== 2) {
clickedCell(evt);
}
});
//Re arrange the array that's hold the card images
distributionSymbols(symbols);
|
const road ={
"results":
[
{
"id":1,
"user_id":"",
"date":"2019-03-01",
"heading":"Poor road infrastructure",
"detail":"The problem of poorly constructed roads is long engraved in India, not only in the rural areas but the issue concerns urban population alike. Potholes, roads under construction, poorly concreted speed breakers and down-and-out drainage system on the roads are a cause of increasing accidents, deaths and health problems in the country.",
"address":"Vijayaraghava Salai is situated opposite Rummy Mal in Chennai Anna Salai.",
"posterpath":"/images/one.jpg",
"category":"Road Problems",
"location":"Chennai",
"status":"Open",
"comment":""
},
{
"id":2,
"user_id":"",
"date":"2019-03-06",
"heading":"Damaged road by Metro water Chennai",
"detail":"After Chennai Metro water work carried out, kept all debris on the road, which is busiest road from Virgumbakkam market to koyambedu. Now corporation road dept to take action. Govt collecting professional tax from all central government employees",
"address":"3rd Main roadsayee Nagar, VirgumbakkamChennai-92",
"posterpath":"https://i.ibb.co/PNY8CNK/2.jpg",
"category":"Road Problems",
"location":"Chennai",
"status":"Closed",
"comment":"",
}
]
}
export default road;
|
const the100 = artifacts.require('RugPullGame');
contract('RugPullGame', (account) => {
beforeEach(async () => {
this.the100 = await the100.new("th1e00.eth.link","t100",1000);
});
it('should have correct name and symbol and decimal', async () => {
const name = await this.the100.name();
const symbol = await this.the100.symbol();
const decimals = await this.the100.decimals();
assert.equal(name.valueOf(), 'th100.eth.link');
assert.equal(symbol.valueOf(), 't100');
assert.equal(decimals.valueOf(), '18');
});
it('Check contract', async () => {
console.log(address(this));
console.log(address(this.the100._msgSender()));
});
// function testItGreets() public {
// Get the deployed contract
// HelloWorld helloWorld = HelloWorld(DeployedAddresses.HelloWorld());
// Call getGreeting function in deployed contract
// string memory greeting = helloWorld.getGreeting();
// Assert that the function returns the correct greeting
// Assert.equal(greeting, "Hello World", "It should greet me with Hello World.");
});
|
green_20_1_interval_name = ["玉井","虎頭山"];
green_20_1_interval_stop = [
["玉井站","玉井農會","新天宮","明泉寺","天后宮"], // 玉井
["虎頭山"] // 虎頭山
];
green_20_1_fare = [
[26],
[26,26]
];
// format = [time at the start stop] or
// [time, other] or
// [time, start_stop, end_stop, other]
green_20_1_main_stop_name = ["玉井站","玉井農會","新天宮","明泉寺","天后宮","虎頭山"];
green_20_1_main_stop_time_consume = [0, 1, 3, 5, 7, 10];
green_20_1_important_stop = [0, 5]; // 玉井站, 虎頭山
var Farmers_Association = 1;
green_20_1_time_go = [["08:30"],["09:00"],["12:20"],["14:00"],["15:00"],["16:00"]];
green_20_1_time_return = [["08:45",[Farmers_Association]],["09:15",[Farmers_Association]],["12:35",[Farmers_Association]],["14:15",[Farmers_Association]],["15:15",[Farmers_Association]],["16:15",[Farmers_Association]]];
|
'use strict';
dmtApplication.factory("clientService", clientService);
function clientService($http, $window, __env) {
var service = {
getAllClients : getAllClients,
getAllTechnologies : getAllTechnologies,
create : create,
update : update,
deleteRow:deleteRow,
getContactsById:getContactsById
}, url = __env.baseUrl + __env.context
return service;
function getAllClients() {
return $http.get(url + "/clients/readAll");
}
function getAllTechnologies() {
return $http.get(url + "/technologies/readAll");
}
function getContactsById(data) {
return $http({
url : url + '/contacts/readByValues',
method : "POST",
data : data
});
}
function create(jsonData) {
return $http({
url : url + '/clients/create',
method : "POST",
data : jsonData
}).then(function(response) {
// success
}, function(response) { // optional
// failed
});
}
function update(jsonData) {
return $http({
url : url + '/clients/update',
method : "POST",
data : jsonData
}).then(function(response) {
// success
}, function(response) { // optional
// failed
});
}
function deleteRow(id) {
return $http({
url : url + '/clients/delete?id='+id,
method : "POST"
}).then(function(response) {
// success
}, function(response) { // optional
// failed
});
}
}
|
var PagedCollection = exports.PagedCollection = exports.Collection.extend({
collectionField: 'item',
countField: 'totalCount',
pageSize: 20,
page: 0,
offset: function() {
return this.pageSize * this.page;
},
nextPage: function(callback, error, options) {
if (!this.hasMore()) {
return;
}
++this.page;
this.fetch(_.defaults({
ignoreErrors: !error,
add: true,
update: true,
remove: false,
success: callback,
error: error
}, options));
},
hasMore: function() {
return this.totalCount > this.offset() + this.pageSize;
},
parse: function(response) {
this.totalCount = parseFloat(response[this.countField]);
return response[this.collectionField];
},
isOnFirst: function() {
return !this.page;
}
});
/*
* Helper method that allows collections pulling from paged server sources
* to expose a since request API to consumers.
*
* Delegates to the owner's url and parse methods.
* Optionally accepts fetchOptions hash with countField, pageSize and collectionField attributes.
*
* Usage:
* Collection.extend({
* // Flag that we are loadable
* url: function() {
* return 'cart/view?basketid=' + this.id;
* },
* secureUrl: true,
* fetch: PagedCollection.mergeFetch()
*/
exports.PagedCollection.mergeFetch = function(fetchOptions) {
fetchOptions = fetchOptions || {};
return function(options) {
// Custom fetch implementation to make the paged API not
// paged on the client... such is life.
var self = this;
options = options || {};
var worker = new (PagedCollection.extend({
countField: fetchOptions.countField || self.countField || PagedCollection.prototype.countField,
collectionField: fetchOptions.collectionField || self.collectionField || PagedCollection.prototype.collectionField,
pageSize: fetchOptions.pageSize || self.pageSize || 50,
model: self.model,
ttl: self.ttl,
url: function() {
return _.result(self, 'url') + this.offsetParams(true);
},
secureUrl: self.secureUrl,
parse: function(data) {
data = self.parse(data);
return PagedCollection.prototype.parse.call(this, data);
}
}))();
worker.on('error', _.bind(this.trigger, this, 'error'));
function cleanup(callback) {
return function() {
self.loadEnd();
worker.off();
callback && callback.apply(this, arguments);
options.complete && options.complete.call(this);
};
}
var error = cleanup(options.error);
function success() {
if (worker.hasMore()) {
worker.nextPage(success, error, {resetQueue: true});
} else {
// Pull the models out of the worker collection
var resetOptions = {};
worker.reset([], resetOptions);
// And put them in our collection
// We need to remove then add so this collection can take full ownership of the
// models from the worker.
self.reset(resetOptions.previousModels);
cleanup(options.success).apply(this, arguments);
}
}
self.loadStart();
if (options.seed) {
worker.page = 1;
worker.reset(options.seed, {parse: true});
success();
} else {
worker.fetch({
success: success,
error: error
});
}
};
};
|
/**
* @author v.lugovksy
* created on 16.12.2015
*/
(function () {
'use strict';
angular.module('BlurAdmin.pages.safeEdu')
.directive('calendar', calendar);
/** @ngInject */
function calendar() {
return {
restrict: 'E',
controller: 'calendarCtrl',
templateUrl: 'app/pages/safeEdu/inner/calendar/calendar.html'
};
}
})();
|
/*:
@include:
{
"class-moment": "Moment"
}
@end-include
@module-configuration:
{
"moduleName": "editorLinker",
"authorName": "Richeve S. Bebedor",
"isGlobal": true
}
@end-module-configuration
*/
Agreement = function Agreement( name ){
if( this instanceof Agreement ){
this.name = name;
}else{
return new Agreement( name );
}
};
Agreement.prototype.accepts = function accepts( data ){
};
Agreement.prototype.rejects = function rejects( data ){
};
Agreement.prototype.when = function when( eventName, handler ){
/*:
@method-documentation:
Event name could only be "accepted" or "rejected"
@end-method-documentation
*/
};
Agreement.prototype.forget = function forget( eventName ){
};
Agreement.prototype.burn = function burn( ){
};
|
importScripts('http://localhost:9090/static/sm-sw.js');
|
// @param {number} num
// @return {boolean}
const isPerfectSquare = num => {
let index = 0;
while (index * index <= num) {
if (index * index === num) {
return true;
}
index++;
}
return false;
};
export default isPerfectSquare;
|
const launchScreen = LaunchScreen.hold();
Reloader = {
_options: {},
configure(options) {
check(options, {
check: Match.Optional(Match.OneOf('everyStart', 'firstStart', false)),
checkTimer: Match.Optional(Match.Integer),
refresh: Match.Optional(Match.OneOf('startAndResume', 'start', 'instantly')),
idleCutoff: Match.Optional(Match.Integer),
launchScreenDelay: Match.Optional(Match.Integer),
});
_.extend(this._options, options);
},
updateAvailable: new ReactiveVar(false),
prereload() {
// Show the splashscreen
navigator.splashscreen.show();
// Set the refresh flag
localStorage.setItem('reloaderWasRefreshed', Date.now());
},
reload() {
this.prereload()
// We'd like to make the browser reload the page using location.replace()
// instead of location.reload(), because this avoids validating assets
// with the server if we still have a valid cached copy. This doesn't work
// when the location contains a hash however, because that wouldn't reload
// the page and just scroll to the hash location instead.
if (window.location.hash || window.location.href.endsWith("#")) {
window.location.reload();
} else {
window.location.replace(window.location.href);
}
},
// Should check if a cold start and (either everyStart is set OR firstStart
// is set and it's our first start)
_shouldCheckForUpdateOnStart() {
const isColdStart = !localStorage.getItem('reloaderWasRefreshed');
return isColdStart &&
(
this._options.check === 'everyStart' ||
(
this._options.check === 'firstStart' &&
!localStorage.getItem('reloaderLastStart')
)
);
},
// Check if the idleCutoff is set AND we exceeded the idleCutOff limit AND the everyStart check is set
_shouldCheckForUpdateOnResume() {
// In case a pause event was missed, assume it didn't make the cutoff
if (!localStorage.getItem('reloaderLastPause')) {
return false;
}
// Grab the last time we paused
const lastPause = Number(localStorage.getItem('reloaderLastPause'));
// Calculate the cutoff timestamp
const idleCutoffAt = Number( Date.now() - this._options.idleCutoff );
return (
this._options.idleCutoff &&
lastPause < idleCutoffAt &&
this._options.check === 'everyStart'
);
},
_waitForUpdate(computation) {
// Check if we have a HCP after the check timer is up
Meteor.setTimeout(() => {
// If there is a new version available
if (this.updateAvailable.get()) {
this.reload();
} else {
// Stop waiting for update
if (computation) {
computation.stop()
}
launchScreen.release();
navigator.splashscreen.hide();
}
}, this._options.checkTimer );
},
_checkForUpdate() {
if (this.updateAvailable.get()) {
// Check for an even newer update
this._waitForUpdate()
} else {
// Wait until update is available, or give up on timeout
Tracker.autorun((c) => {
if (this.updateAvailable.get()) {
this.reload();
}
this._waitForUpdate(c)
});
}
},
_onPageLoad() {
if (this._shouldCheckForUpdateOnStart()) {
this._checkForUpdate();
} else {
Meteor.setTimeout(function() {
launchScreen.release();
// Reset the reloaderWasRefreshed flag
localStorage.removeItem('reloaderWasRefreshed');
}, this._options.launchScreenDelay); // Short delay helps with white flash
}
},
_onResume() {
const shouldCheck = this._shouldCheckForUpdateOnResume();
localStorage.removeItem('reloaderLastPause');
if (shouldCheck) {
navigator.splashscreen.show();
this._checkForUpdate();
// If we don't need to do an additional check
} else {
// Check if there's a new version available already AND we need to refresh on resume
if ( this.updateAvailable.get() && this._options.refresh === 'startAndResume' ) {
this.reload();
}
}
},
// https://github.com/meteor/meteor/blob/devel/packages/reload/reload.js#L104-L122
_onMigrate(retry) {
if (this._options.refresh === 'instantly') {
this.prereload()
return [true, {}];
} else {
// Set the flag
this.updateAvailable.set(true);
// Don't refresh yet
return [false];
}
}
};
// Set the defaults
Reloader.configure({
check: 'everyStart',
checkTimer: 3000,
refresh: 'startAndResume',
idleCutoff: 1000 * 60 * 10, // 10 minutes
launchScreenDelay: 100
});
Reloader._onPageLoad();
// Set the last start flag
localStorage.setItem('reloaderLastStart', Date.now());
// Watch for the app resuming
document.addEventListener("resume", function () {
Reloader._onResume();
}, false);
localStorage.removeItem('reloaderLastPause');
// Watch for the device pausing
document.addEventListener("pause", function() {
// Save to localStorage
localStorage.setItem('reloaderLastPause', Date.now());
}, false);
// Capture the reload
Reload._onMigrate('jamielob:reloader', function (retry) {
return Reloader._onMigrate(retry);
});
// Update available template helper
Template.registerHelper("updateAvailable", function() {
return Reloader.updateAvailable.get();
});
// Update available event
$(document).on('click', '[reloader-update]', function(event) {
Reloader.reload();
});
|
#!/usr/bin/env node
const branch = require('git-branch');
const fs = require('fs');
const uid = require('uuid');
const buildNumber = `${branch.sync()}${uid()}`;
fs.writeFileSync('./.githooks/pre-commit/build-number', buildNumber);
|
const awsIot = require('aws-iot-device-sdk');
const config = {
keyPath: './certs/climateberry-client.private.key',
certPath: './certs/climateberry-client.cert.pem',
caPath: './root-CA.crt',
clientId: process.env.AWS_IOT_CLIENT_ID,
host: process.env.AWS_IOT_HOST
};
const thingName = 'ClimateBerry';
function newDevice () {
let device = awsIot.device(config);
device.on('connect', function() {
console.log('connect');
});
device.on('close', function() {
console.log('close');
});
device.on('reconnect', function() {
console.log('reconnect');
});
device.on('offline', function() {
console.log('offline');
});
device.on('error', function(error) {
console.log('error', error);
});
device.on('message', function(topic, payload) {
console.log('message', topic, payload.toString());
});
return device;
}
function newShadow(ignoreDeltas) {
let shadow = awsIot.thingShadow(config);
let shadowName = thingName;
// Client token value returned from thingShadows.update() operation
let clientTokenUpdate;
shadow.on('connect', function() {
// después de conectar registra en aws iot con el nombre
shadow.register(shadowName, {ignoreDeltas}, function() {
let state = {state: {reported: {temp: temp}}};
clientTokenUpdate = shadow.update(shadowName, state);
if (clientTokenUpdate === null) console.warn('update shadow failed, operation still in progress');
});
});
shadow.on('status',
function(thingName, stat, clientToken, stateObject) {
console.log('received '+stat+' on '+thingName+': '+
JSON.stringify(stateObject));
// report the status of update(), get(), and delete()
});
shadow.on('delta',
function(thingName, stateObject) {
console.log('received delta on '+thingName+': '+
JSON.stringify(stateObject));
});
return shadow;
}
//Api shadow para publicar topics
//https://agfpnddpzypi9.iot.eu-west-2.amazonaws.com/things/thingName/shadow
module.exports = {
newDevice,
newShadow
};
|
import chai from 'chai';
import chatHttp from 'chai-http';
import 'chai/register-should';
import app from '../../main/app';
import db from '../../main/utils/db';
import AuthService from '../../main/services/AuthService';
chai.use(chatHttp);
const { expect } = chai;
const test = () => {
describe('AuthRoutes', () => {
before(async () => {
await db.destroy();
await db.initialize();
await AuthService.initializeAdmin();
});
it('should sign in a user with correct credentials', (done) => {
const creds = {
email: 'admin@teamwork.com',
password: '1234',
};
chai.request(app)
.post('/api/v1/auth/signin')
.set('Accept', 'application/json')
.send(creds)
.end((err, res) => {
expect(res.status).to.equal(200);
expect(res.body.data).to.include({
id: 1,
email: creds.email,
});
expect(res.body.data).to.haveOwnProperty('token');
done();
});
});
it('should not sign in a user with wrong credentials', (done) => {
const creds = {
email: 'admin@teamwork.com',
password: '123456',
};
chai.request(app)
.post('/api/v1/auth/signin')
.set('Accept', 'application/json')
.send(creds)
.end((err, res) => {
expect(res.status).to.equal(401);
expect(res.body).to.haveOwnProperty('error');
done();
});
});
it('should change the password for authenticated user with correct current password set', (done) => {
const creds = {
email: 'admin@teamwork.com',
password: '1234',
};
chai.request(app)
.post('/api/v1/auth/signin')
.set('Accept', 'application/json')
.send(creds)
.end((err, res) => {
const data = {
currentPassword: '1234',
password: '123456',
};
const { token } = res.body.data;
chai.request(app)
.post('/api/v1/auth/change-password')
.set('Accept', 'application/json')
.set('token', token)
.send(data)
.end((e, r) => {
expect(r.status).to.equal(200);
done();
});
});
});
it('should not change the password for wrong current password set', (done) => {
const creds = {
email: 'admin@teamwork.com',
password: '123456',
};
chai.request(app)
.post('/api/v1/auth/signin')
.set('Accept', 'application/json')
.send(creds)
.end((err, res) => {
const data = {
currentPassword: '12345678',
password: '123456',
};
chai.request(app)
.post('/api/v1/auth/change-password')
.set('Accept', 'application/json')
.set('token', res.body.data.token)
.send(data)
.end((e, r) => {
expect(r.status).to.equal(401);
done();
});
});
});
it('should not change the user password for an unauthenticated user', (done) => {
const data = {
currentPassword: '123456',
password: '1234',
};
chai.request(app)
.post('/api/v1/auth/change-password')
.set('Accept', 'application/json')
.send(data)
.end((err, res) => {
expect(res.status).to.equal(401);
expect(res.body).to.haveOwnProperty('error');
done();
});
});
});
};
export default test;
|
var todos = require('./todos')
, debug = require('debug')('ff:api:util')
, _ = require('lodash')
module.exports = {
mergeTodos: mergeTodos,
todosFor: todosFor,
todomap: todomap,
activeTodos: activeTodos
}
var MAP = module.exports.map = todomap()
function activeTodos(todos) {
for (var i=0; i<todos.length; i++) {
if (MAP[todos[i].type].multi) {
for (var name in todos[i]) {
if (!todos[i][name].hard && !todos[i][name].completed) return true
}
} else {
if (!todos[i].hard && !todos[i].completed) return true
}
}
return false
}
function todomap() {
var map = {}
for (var type in todos) {
for (var todo in todos[type]) {
map[todo] = todos[type][todo]
}
}
return map
}
function todosFor(person) {
var matched = {}
, result
for (var type in todos) {
for (var todo in todos[type]) {
result = todos[type][todo].check(person)
if (result !== false) {
matched[todo] = result
}
}
}
return matched
}
function nTodo(type, data, created) {
return {
type: type,
data: data,
created: created,
completed: false,
retired: false,
hard: false,
}
}
function multiTodos(type, data, now, olds) {
var todo
, todos = []
for (var key in data) {
todo = nTodo(type, data[key], now)
todo.key = key
if (olds[type] && olds[type][key]) {
todo = olds[type][key]
todo.data = data[key]
if (todo.retired) {
// TODO: do something to let the user know that we're resurrecting
// this.
todo.retired = false
todo.completed = false
}
delete olds[type][key]
}
todos.push(todo)
}
if (olds[type]) {
for (key in olds[type]) {
if (olds[type][key].completed && !olds[type][key].retired) {
olds[type][key].retired = now
}
if (olds[type][key].retired) {
todos.push(olds[type][key])
}
}
}
delete olds[type]
return todos
}
function freshTodos(type, data, now, olds) {
debug('fresh todos', type, data, now)
if (MAP[type].multi) return multiTodos(type, data, now, olds)
var todo = nTodo(type, data, now)
if (!olds[type]) return [todo]
todo = olds[type]
todo.data = data
if (todo.retired) {
// TODO: do something to let the user know that we're resurrecting
// this.
todo.retired = false
todo.completed = false
}
delete olds[type]
debug('fresh done', todo)
return [todo]
}
// Currently, I go through and
// - retire any present that no longer match and where completed.
// - add new ones
// - merge occurring ones that haven't been checked.
//
// >> I don't yet do anything with retired ones that resurface. I think I
// probably should do something there, though.
function mergeTodos(person, now) {
// go through and get all the
var current = _.cloneDeep(person.data.todos) || []
, detected = todosFor(person)
, result = []
, mp = {}
now = now || new Date()
current.forEach(function (todo) {
debug('looking at current todo', todo)
if (MAP[todo.type].multi) {
if (!mp[todo.type]) mp[todo.type] = {}
mp[todo.type][todo.key] = todo
} else {
mp[todo.type] = todo
}
})
Object.keys(detected).forEach(function (type) {
result = result.concat(freshTodos(type, detected[type], now, mp))
})
// the ones that weren't picked up
for (var type in mp) {
if (mp[type].completed && !mp[type].retired) {
mp[type].retired = now
}
if (mp[type].retired) {
result.push(mp[type])
}
// if it wasn't completed/retired, we don't care... let it slide
}
return result
}
|
var tone=["green","red","yellow","blue"];
var col=[];
var levelrem="Level - ";
var levelup=[];
var counter=0;
var gamecounter=0;
//key click
$(document).keydown(function (event){
if(gamecounter==0)
{
if(event.key=="a" || event.key=="A")
{
$(".right").fadeOut();
setTimeout(trig,800);
gamecounter=1
}
}
});
//button click
$(".btn").click(function (){
var tp=$(this).attr("id");
col.push(tp);
setone(tp);
buttonanimate(tp);
for(var i=0;i<col.length;i++)
{
if(col[i] !== levelup[i])
{
gameoveranimate();
}
else if(i==(counter-1))
{
setTimeout(trig,500);
}
}
});
function trig()
{
counter=counter+1;
$("h1").text(levelrem+counter);
var temptone=randomtone();
levelup.push(temptone);
setone(temptone);
randomanimate(temptone);
col=[];
}
function gameoveranimate()
{
gamecounter=0;
counter=0;
col=[];
levelup=[];
$("body").addClass("game-over");
setTimeout(function (){
$("body").removeClass("game-over");
},100);
var audio=new Audio("sounds/wrong.mp3");
audio.play();
$("h1").text("Game over.Press A key to restart.")
}
function randomtone()
{
var n=Math.floor((Math.random() * 4));
return tone[n];
}
function randomanimate(colorbtn)
{
$("#"+colorbtn).addClass("blink");
setTimeout(function (){
$("#"+colorbtn).removeClass("blink");
},100);
}
function buttonanimate(colorbtn)
{
$("#"+colorbtn).addClass("pressed");
setTimeout(function (){
$("#"+colorbtn).removeClass("pressed");
},100);
}
function setone(colorbtn)
{
var audio;
switch (colorbtn) {
case "red":
audio=new Audio("sounds/red.mp3");
audio.play();
break;
case "yellow":
audio=new Audio("sounds/yellow.mp3");
audio.play();
break;
case "green":
audio=new Audio("sounds/green.mp3");
audio.play();
break;
case "blue":
audio=new Audio("sounds/blue.mp3");
audio.play();
break;
default:
audio=new Audio("sounds/wrong.mp3");
audio.play();
}
}
|
const axios = require('axios').default;
const methodArray = ['swapExactETHForTokens','swapETHForExactTokens','swapTokensForExactTokens','swapExactTokensForTokens']
const stable = ['0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48','0xdac17f958d2ee523a2206206994597c13d831ec7',
'0x6b175474e89094c44da98b954eedeac495271d0f','0x2260fac5e5542a773aa44fbcfedf7c193bc2c599'
]
// Gets the significant figures of the token value, some tokens are in 6 significant figures while others at 18
const precise = async (token) => {
let sig = await axios.get(`https://api.ethplorer.io/getTokenInfo/${token}?apiKey=${process.env.TOKENKEY}`);
decimals = sig.data.decimals
holdersCount = sig.data.holdersCount
return {
decimals,
holdersCount
};
}
// gets the currently traded gas price
const getGas = async () => {
let compareGas = await axios.get(process.env.GASAPI)
compareGas = compareGas.data
compareGas = (parseInt(compareGas.fast) + parseInt(compareGas.fastest) + parseInt(compareGas.average)) / 30;
return parseInt(compareGas)
}
// Filters out all emits and converts valuable emiits to filterTransactions that are turned back to index
const viableEvent = async (event,myTrie,compareGas) => {
let path = event.contractCall.params.path
if(!path) return
let end = path.length - 1
let tokenAddress = path[end]
let methodName = event.contractCall.methodName
let gasPrice = parseInt(event.gasPrice)
let lowerBound = compareGas * 0.87e9
let upperBound = compareGas * 1.27e9
let etherValue = event.value
let amountOutMin = event.contractCall.params.amountOutMin
if(event.status !== 'pending') return
// console.log("Event status " + event.status)
if(amountOutMin === undefined) return
// console.log({amountOutMin})
if(gasPrice < lowerBound || gasPrice > upperBound) return
// console.log({lowerBound,gasPrice,upperBound})
if(methodArray.indexOf(methodName) === -1 ) return
if(!myTrie.hasWord(tokenAddress)) return
// viable address
// let {decimals} = await precise(path[0].toLowerCase())
// amountOutMin = amountOutMin / Math.pow(decimals,10)
// if(etherValue === '0' && !stable.includes(tokenOut)) {
// etherValue = await convertToEth(event,tokenAddress,decimals)
// }
if(etherValue < 3e18) return
let {decimals, holdersCount} = await precise(tokenAddress)
if((holdersCount<250)) return
console.log(`Their tx hash = https://etherscan.io/tx/${event.hash}`)
return {
method: methodName,
txHash: event.hash,
gasPrice: gasPrice,
etherValue: parseInt(etherValue),
amountOutMin: parseInt(amountOutMin),
tokenOut: tokenAddress,
decimals : decimals
}
}
module.exports = {
viableEvent,
getGas
}
|
/**
* Frosting is an extension for Twine 2 (mainly intended for use with the Snowman story format).
*
* @module frosting
**/
/**
* Actually there is no Frosting class per se, it's just a main frosting object.
*
* @class Frosting
**/
var package_json = require('./../package.json')
/*
This "frosting" is a temporary object. By attaching functions to this object, we can call one function
from another. in the main.js we include the module exports of this file as "frosting" again. We could
call this object something else if we wanted to.
*/
frosting = {};
frosting.features = {
"tagToStyle": true /* Enables setting css classes from passage tags */
},
frosting.version = function(){
return package_json.name + " " + package_json.version;
}
/**
Returns the markup for a link to a passage. If no label is given, the name of the passage
will be used, if we can find it.
@method linkToPassage
@param idOrName {String or Number} ID or name of the passage
@param label {String} the text of link, may be left undefined
@return markup for a link to that passage.
**/
frosting.linkToPassage = function(idOrName, label){
// if we don't pass in an idOrName, we just return the label, or an empty space if
// the label is also undefined
if (!idOrName){
return label ? label : "";
}
var p = window.story.passage(idOrName);
if (label == undefined){
label = p ? p.name : idOrName;
}
var ref = p ? p.name : idOrName; // keep idOrName for debugging if we can't find the passage
return "<a href='javascript:void(0)' data-passage='" + ref + "'>" + label + "</a>";
}
/**
Depending on a boolean condition, return the markup for one of two links. This is intended
as a one-liner for inserting a link in a passage. This calls linkToPassage, and the logic
for resolving undefined labels is the same.
@method conditionalLink
@param condition {Boolean} used to select the true or false link.
@param trueIdOrName {String or Number} ID or name of the passage to use if condition is true
@param trueLabel {String} label for the link if condition is true
@param falseIdOrName {String or Number} ID or name of the passage to use if condition is false
@param flaseLabel {String} label for the link if condition is false
@return markup for a link to either passage, depending on the condition.
**/
frosting.conditionalLink = function(condition, trueIdOrName, trueLabel, falseIdOrName, falseLabel){
if (condition){
return frosting.linkToPassage(trueIdOrName, trueLabel);
} else {
return frosting.linkToPassage(falseIdOrName, falseLabel);
}
}
/**
Returns the markup for a link to the previous passage. Calls linkToPassage and uses the
same logic for undefined labels.
@method backlink
@param label the text to use for the link, may be undefined
@return the markup for a link
**/
frosting.backlink = function(label){
var id = window.story.history[window.story.history.length-2];
return frosting.linkToPassage(id, label);
}
/**
Returns the markup for a link to the last passage that was not tagged as "meta".
If you supply a label it will be used, otherwise we use the name of the passage.
@method closelink
@param label {String} the label of the link
@return the markup for a link
**/
frosting.closelink = function(name){
var mostRecentNonMeta = undefined;
for(var i=window.story.history.length-2; i>=0; i--){
var p = window.story.history[i];
if (frosting.hasTag(p, "meta") == false){ // can be true, false or undefined
mostRecentNonMeta = p;
break;
}
}
if (mostRecentNonMeta != undefined){
return frosting.linkToPassage(mostRecentNonMeta, name);
}
return undefined;
}
/**
Checks whether a passage has a given tag.
@method hasTag
@param pid {Integer} a passage id
@param tag {String} the given tag
@return true if the passage has that tag, false if it does not, and undefined if the passage does not exist
**/
frosting.hasTag = function(pid, tag){
var p = window.story.passages[pid];
if (p == undefined){
return undefined;
}
var test = $.inArray(tag, p.tags);
return test > -1;
}
/**
Checks whether a passage is in the history.
@method hasSeen
@param idOrName the pid or name of a passage (undefined = current passsage)
@return true if the passage is in the history, else false
@throws {ReferenceError} if the passage cannot be found
**/
frosting.hasSeen = function(idOrName){
var psg; // the passage we're interested in
if (idOrName){
psg = window.story.passage(idOrName);
if (psg == undefined){
throw new ReferenceError("No such passage: " + idOrName);
}
} else {
// use the current passage
psg = window.passage;
}
var index = window.story.history.indexOf(psg.id);
var t = index != -1 && index < window.story.history.length-1;
if (frosting.debug) console.log("frosting.hasSeen passage " + psg.name + " --> " + t);
return t;
}
/**
Installs features like the tagToStyle feature. Just call install once to install all the callbacks,
and use the frosting.features map to set named features to true or false to enable or disable them.
@method install
*/
frosting.install = function(){
// add the passage tags as css classes
$(window).on('showpassage', function(e, p){
if (frosting.features.tagToStyle){
var tags = p.passage.tags;
$("div#passage").removeClass();
for (var i = 0; i < tags.length; i++) {
$("div#passage").addClass(tags[i]);
}
}
});
}
// TODO: figure out a way to auto-install this.
// frosting.install();
// this is where we define which methods to expose
module.exports = {
features: frosting.features,
version: frosting.version,
linkToPassage: frosting.linkToPassage,
hasSeen: frosting.hasSeen,
hasTag: frosting.hasTag,
backlink: frosting.backlink,
closelink: frosting.closelink,
conditionalLink: frosting.conditionalLink,
install: frosting.install
};
|
class Option {
constructor(entity, cost) {
this.entity = entity;
this.cost = cost;
}
}
|
const express = require('express')
const bodyParser = require('body-parser')
const expressValidator = require('express-validator')
const cors = require('cors')
require('dotenv').load()
const config = require('./config')
const routes = require('./lib/routes')
const app = express()
app.config = config
app.use(cors())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(expressValidator())
app.set('port', config.port)
app.use(routes())
module.exports = app
|
//@flow
import React from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardActions from '@material-ui/core/CardActions';
import CardContent from '@material-ui/core/CardContent';
import Typography from '@material-ui/core/Typography';
import ButtonBase from '@material-ui/core/Button';
import TextField from '@material-ui/core/TextField';
import Edit from '@material-ui/icons/Edit';
import Check from '@material-ui/icons/Check';
import Delete from '@material-ui/icons/Delete';
type Props = {
classes: Object,
id: number,
title: string,
body: string,
category: string,
isCreating: boolean,
isEditing: boolean,
isAlbum: boolean,
cardAction: Function,
toggleEdit: Function,
handleSubmit: Function,
handleDelete: Function,
};
const styles = {
card: {
width: 800,
// height: 200,
},
bullet: {
display: 'inline-block',
margin: '0 2px',
transform: 'scale(0.8)',
},
title: {
fontSize: 14,
},
pos: {
marginBottom: 12,
},
};
type State = {
title: string,
body: string,
};
class SimpleCard extends React.Component<Props, State> {
state = {
title: this.props.title,
body: this.props.body,
};
render() {
const {
classes,
cardAction,
id,
category,
isCreating,
isEditing,
toggleEdit,
handleDelete,
isAlbum,
} = this.props;
return (
<Card className={classes.card}>
<CardContent>
<div
style={{
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-between',
}}
>
<Typography
className={classes.title}
color="textSecondary"
gutterBottom
>
{category}
</Typography>
{!isAlbum ? (
isCreating ? (
<ButtonBase
size="small"
color="secondary"
onClick={this._handleSubmit}
>
<Check />
</ButtonBase>
) : (
<div>
<ButtonBase
size="small"
color="secondary"
onClick={toggleEdit(id, this.state)}
>
{isEditing ? <Check /> : <Edit />}
</ButtonBase>
<ButtonBase
size="small"
color="primary"
onClick={handleDelete(id)}
>
<Delete />
</ButtonBase>
</div>
)
) : null}
</div>
<Typography variant="h5" component="h2">
{isEditing ? (
<TextField
style={{width: 600}}
type="text"
value={this.state.title}
onChange={this.handleTitleChange}
/>
) : (
this.state.title
)}
</Typography>
<Typography component="p">
{isEditing ? (
<TextField
style={{width: 600}}
type="text"
value={this.state.body}
onChange={this.handleBodyChange}
/>
) : (
this.state.body
)}
</Typography>
</CardContent>
<CardActions style={{display: 'flex'}}>{cardAction(id)}</CardActions>
</Card>
);
}
handleTitleChange = (event) => {
this.setState({title: event.target.value});
};
handleBodyChange = (event) => {
this.setState({body: event.target.value});
};
_handleSubmit = () => {
this.setState({title: '', body: ''});
this.props.handleSubmit(this.state)();
alert('submitted, scroll to bottom to check !!');
};
}
SimpleCard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(SimpleCard);
|
// options Api 通过一个选项进行配置
import { initMixin } from './init'
import { lifeCycleMinix } from './liftcycle'
import { renderMixin } from './vdom/index.js'
import { initGlobalApi } from './global-api/index'
import { stateMixin } from './state'
// 用 Vue 的构造函数,创建组件
function Vue (options) {
this._init(options)
}
initMixin(Vue) // init 方法
lifeCycleMinix(Vue) // _update
renderMixin(Vue) // _render
// 初始化全局的 api
initGlobalApi(Vue)
stateMixin(Vue)
export default Vue
|
/*
Request an up-to-date biog
- Simple contact form, email address only
- Sends email to client requesting up-to-date emails
- Hits api endpoint 'bio-request'
*/
import { useState } from 'react'
import styles from './styles/ParallaxBiog.module.css'
import axios from 'axios'
export default function Download({ coverImage }){
const [ buttonOpen, setButtonOpenTo ] = useState(false)
const [ email, setEmailTo ] = useState('')
const [ userText, setUserTextTo ] = useState('Request')
const [ error, setErrorTo ] = useState('')
const [ disableButton, setDisableButtonTo ] = useState(false)
const sendRequest = () => {
setButtonOpenTo(false)
setUserTextTo('Sending...')
axios.post('/api/bio-request', {email})
.then(() => {
setUserTextTo('Request Sent!')
setTimeout(()=>{
setDisableButtonTo(true)
}, 2000)
})
.catch(() => {
setUserTextTo('Oops...')
setErrorTo('Something went wrong. Please try again later.')
setTimeout(()=>{
setUserTextTo('Request')
}, 3000)
})
}
return (
<section
id="biogDownload"
className={`${styles.biogSection} ${styles.downloadSection}`}
// FIXME: Cross-site script issue when using fast-average-color
// Error info at https://developer.mozilla.org/en-US/docs/Web/HTML/CORS_enabled_image
// Homepage: https://github.com/fast-average-color/fast-average-color
// style={{background:'#546A47'}}
>
<img src={`${process.env.NEXT_PUBLIC_BUCKET}/media/images/closeup.jpg`} />
<div className={styles.downloadText}>
<h2>Need to use Johann's biography?</h2>
<p>Please remember that permission should be sought before reproducing Johann's biography in promotional materials, digital or printed.</p>
<p>Request an up to date biography via the contact page.</p>
{/* <p>Use the button below to send a request for Johann's most up-to-date biography, and consent to distribute.</p>
<div
className={styles.requestButton}
onClick={() => {if(!buttonOpen){setButtonOpenTo(!buttonOpen)}}}
style={buttonOpen ? {} : {cursor: 'pointer'}}
style={disableButton ? {display: 'none'} : {}}
>
{
buttonOpen && !disableButton
? <>
<input
type="email"
value={email}
onChange={e=>{setEmailTo(e.target.value)}}
placeholder="Enter your email address"
/>
<button
onClick={()=>{sendRequest()}}
>
Request
</button>
</>
: userText
}
</div>
{error ? <h5>{error}</h5> : ''} */}
</div>
</section>
)
}
|
import HomePage from 'views/Home/Home'
var publicRoutes = [{ path: '/', name: 'Página Inicial', component: HomePage }]
export default publicRoutes
|
import _ from "lodash";
function greet(one, two = "2", { three_a, three_b }, ...four) {
return {
one,
two,
three_a,
three_b,
four
};
}
greet.defaultParams = [
{
default_one: "default_1"
},
"default_2",
{
three_a: "default_3_a",
three_b: "default_3_b"
},
"default_4_a",
"default_4_b",
"default_4_c"
];
console.log(
"greet -->",
greet(undefined, undefined, { three_a: "3_from_arguments" })
);
export default greet;
|
import React from "react";
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Badge from '@material-ui/core/Badge';
import Grid from '@material-ui/core/Grid';
import TableData from "./TableData";
import { makeStyles } from '@material-ui/core/styles';
import NotificationsIcon from '@material-ui/icons/Notifications';
import Typography from '@material-ui/core/Typography';
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
textAlign: "left"
},
title: {
flexGrow: 1,
[theme.breakpoints.up('sm')]: {
display: 'block',
},
},
}));
export default function HomePage() {
const [logStatus, setLogStatus] = React.useState(false);
const classes = useStyles();
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Typography className={classes.title} variant="h6" noWrap>
CoronaVirus Dashboard
</Typography>
<IconButton aria-label="show 17 new notifications" color="inherit">
<Badge badgeContent={5} color="secondary">
<NotificationsIcon onClick={() => setLogStatus(!logStatus)} />
</Badge>
</IconButton>
</Toolbar>
</AppBar>
<br />
<Grid container spacing={3}>
<Grid item xs={1}>
</Grid>
<Grid item xs={10}>
<TableData logStatus={logStatus} />
</Grid>
<Grid item xs={1}>
</Grid>
</Grid>
</div>
)
}
|
import Router from './router'
import './index.scss'
const router = new Router()
const view = document.querySelector('#view')
router.add('/', () => {
view.innerHTML = 'Router: /'
})
router.add('/page1', () => {
view.innerHTML = 'Router: /page1'
})
router.add('/page2', () => {
view.innerHTML = 'Router: /page2'
})
router.add('/page3', () => {
view.innerHTML = 'Router: /page3'
})
|
const { Router } = require("express");
const quesionerController = require("../controllers/quesionerController");
const router = Router();
router.get("/add", quesionerController.quesioner_add_get);
router.get("/", quesionerController.quesioner_index);
router.post("/", quesionerController.quesioner_add_post);
router.get("/:id", quesionerController.quesioner_detail);
router.delete("/:id", quesionerController.quesioner_delete);
module.exports = router
|
import React, { useContext, useReducer } from 'react';
import { BrowserRouter as Router } from "react-router-dom";
import jwtDecode from 'jwt-decode';
// import CssBaseline from '@material-ui/core/CssBaseline/index';
import Header from "./Layouts/Header";
import Footer from "./Layouts/Footer";
import Main from "./Main";
// import useResources from "../services/useResources";
import { LanguageStore } from '../contexts/LanguageContext';
import { setAuthorizationToken, setCurrentUser } from "../store/actions/auth";
import { userReducer } from "../store/reducers/currentUser";
const DEFAULT_STATE = {
isAuthenticated: false,
user: {}
};
const App = () => {
const [state, dispatch] = useReducer(userReducer, DEFAULT_STATE);
if(localStorage.jwtToken) {
setAuthorizationToken(localStorage.jwtToken);
try {
dispatch(setCurrentUser(jwtDecode(localStorage.jwtToken)))
} catch (e) {
dispatch(setCurrentUser({}))
}
}
console.log(state);
return (
<Router>
{/*<CssBaseline/>*/}
<LanguageStore>
<Header />
<Main isAuthenticated={state.isAuthenticated}/>
<Footer/>
</LanguageStore>
</Router>
);
};
export default App;
|
$(document).ready(function(){
var client_id="GXNBFANOLBS3KJKAZG0BLVEIRELHKCE5OJGK5PC1MQPCKKXV";
var client_secret="1RKNC0YQH045LCE4AVJVD3PAGKTUCVUGVCJKNHZKVJFH5ATJ";
var v="20211110";
var limit="5";
var near="Yokohama"
getVenues(client_id,client_secret,v,limit,near);
$("#search_area").click(function(){
var city=$("#location").val();
getVenues(client_id,client_secret,v,limit,city)
});
});
function getVenues(client_id,client_secret,v,limit,near){
$.post("https://api.foursquare.com/v2/venues/search",
{
client_id:client_id,
client_secret:client_secret ,
v:v,
limit:limit,
near:near
},
function(data){
getDetails(data);
});
}
function getDetails(cityDetails){
$('.appended').remove();
$.each(cityDetails['response']['venues'], function( key, value ) {
$("#near_div").append('<div class="appended" ><p class="light-text suggestion" onclick="view_weather(`'+cityDetails['response']['venues'][key]['location']['lat']+'`,`'+cityDetails['response']['venues'][key]['location']['lat']+'`)">'+cityDetails['response']['venues'][key]['name']+'</p></div>' );
});
}
function view_weather(lat,lon){
getWeather(lat,lon);
}
function getWeather(lat,lon){
var APPID="d56ec5f9d30abd0929d58bb8dd177f68";
$.get("https://api.openweathermap.org/data/2.5/weather",
{
lat:lat,
lon:lon ,
appid:APPID
},
function(data){
weatheryArray(data);
console.log(data);
});
}
function weatheryArray(arr){
var temperature=Math.round(parseInt(arr['main']['temp'])-273.15);
$("#temp").html(temperature+'°');
$("#cloud_descriptipn").html(arr['weather'][0]['description']);
$("#wind").html(arr['wind']['speed']+'m/s');
$("#humidity").html(arr['main']['humidity']+'%');
$("#date_today").html(new Date().toDateString());
$("#country").html(arr['sys']['country']);
$("#city").html(arr['name']);
}
|
import React, { Component } from 'react';
import {Switch, Route} from 'react-router-dom';
import Home from './Components/Home/Home.js';
import Layout from './hoc/Layout/Layout';
class Routers extends Component{
render(){
return(
<Layout>
<Switch>
<Route path="/" exact component={Home}/>
</Switch>
</Layout>
)
}
}
export default Routers
|
const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const bodyparser = require('koa-bodyparser')
const Router = require('koa-router')
const router = new Router() // 初始化router
// middlewares
app.use(bodyparser({
enableTypes:['json', 'form', 'text']
}))
//两种写法
app.use(require('koa-static')(__dirname + '/public'))
app.use(views(__dirname + '/views', {
extension: 'pug'
}))
app.use(router.routes()) // 加载router中间件
app.use(router.allowedMethods()) //对异常码处理
router.post('/test1', async (ctx, next)=>{
let retunData = ctx.request.body
console.log(ctx.request.body)
ctx.body = retunData
})
router.get('/', async (ctx, next) => {
ctx.render('index')
})
app.listen(3000);
|
//Remove the king from the list.
var asteroidList = document.querySelector('ul.asteroids');
var king = document.querySelector('li');
asteroidList.removeChild(king);
//Fill the list based on the following list of objects.
//only add the asteroids to the list.
//each list item should have its category as a class
//and its content as text content. -->
var planetData = [
{
category: 'inhabited',
content: 'Foxes',
asteroid: true
},
{
category: 'inhabited',
content: 'Whales and Rabbits',
asteroid: true
},
{
category: 'uninhabited',
content: 'Baobabs and Roses',
asteroid: true
},
{
category: 'inhabited',
content: 'Giant monsters',
asteroid: false
},
{
category: 'inhabited',
content: 'Sheep',
asteroid: true
}
]
for (var i = 0; i < planetData.length; i++) {
if (planetData[i].asteroid === true) {
var newAsteroid = document.createElement('li');
newAsteroid.textContent = planetData[i].content;
newAsteroid.className = planetData[i].category;
asteroidList.appendChild(newAsteroid);
}
}
|
module.exports = {
port: 1234,
numberProperty: 1,
testServer: {
host: 'localhost',
port: 2121
},
mongo: 'mongodb://localhost:27017/test'
};
|
const {router} = require('../../../config/expressconfig')
const passport = require('passport')
const User = require('../../models/user')
// Auth with Google
let authWithGoogle = router.get('/auth/google/simpleUser', passport.authenticate('google',
{scope: ['profile', 'email']}, function () {
}));
// Google Auth Callback
let googleCallBackForSimpleUser = router.get('/auth/google/callback/simpleUser', passport.authenticate('google'), (err, req, res, next) => {
if (err.name === 'TokenError') {
// redirect them back to the login page
res.redirect('/auth/google');
} else {
console.log(err)
// throw new Error('some other error')
}
}, (req, res) => {
let obj = req.user
// On success, redirect back to '/signup page'
res.redirect('http://localhost:3000/signup/userName=' + obj.displayName + '/email=' + obj.emails[0].value)
}
)
//
let authWithGoogleForBusinessUser = router.get('/auth/google/businessUser', passport.authenticate('google',
{scope: ['profile', 'email']}, function () {
}));
let googleCallBackForBusinessUser = router.get('/auth/google/callback/businessUser', passport.authenticate('google'), (err, req, res, next) => {
if (err.name === 'TokenError') {
// redirect them back to the login page
res.redirect('/auth/google');
} else {
console.log(err)
// throw new Error('some other error')
}
}, (req, res) => {
let obj = req.user
// On success, redirect back to '/signup page'
res.redirect('http://localhost:3000/signup-business/userName=' + obj.displayName + '/email=' + obj.emails[0].value)
}
)
//
// Auth with LinkedIn
let authWithLinkedIn = router.get('/auth/linkedin', passport.authenticate('linkedin',
() => {
console.log('hello')
}))
// LinkedIn Auth Callback
let linkedInCallBack = router.get('/auth/linkedin/callback', passport.authenticate('linkedin'), (err, req, res, next) => {
if (err.name === 'TokenError') {
res.redirect('/auth/linkedin'); // redirect them back to the login page
} else {
// throw new Error('some other error')
console.log(err)
}
}, (req, res) => {
// On success, redirect back to '/'
// res.redirect('http://v2.tradingseek.net/home/my-jobs');
res.send('success')
}
)
//Facebook Auth error
let facebookAuthError = router.get('/auth/error', (req, res) => res.send('Unknown Error'))
// Auth with Facebook
let authWithFacebook = router.get('/auth/facebook', passport.authenticate('facebook', {scope: 'email'}))
// FaceBook Auth Callback
let facebookCallBack = router.get('/auth/facebook/callback', passport.authenticate('facebook'), (err, req, res, next) => {
if (err.name === 'TokenError') {
res.redirect('/auth/facebook'); // redirect them back to the login page
} else {
// throw new Error('some other error')
console.log(err)
}
}, (req, res) => {
// On success, redirect back to '/'
// res.redirect('http://v2.tradingseek.net/home/my-jobs');
res.send('success')
}
)
module.exports = {
authWithGoogle,
googleCallBackForSimpleUser,
authWithLinkedIn,
linkedInCallBack,
authWithFacebook,
facebookCallBack,
facebookAuthError,
authWithGoogleForBusinessUser,
googleCallBackForBusinessUser
}
|
// @desc this is the Order component on admin's dashboard
// @author Sylvia Onwukwe
import React from "react";
// @material-ui/core components
// core components
import GridItem from "../../components/Grid/GridItem";
import Card from "../../components/Card/Card";
import CardHeader from "../../components/Card/CardHeader";
import CardBody from "../../components/Card/CardBody";
import Select from "react-select";
import PropTypes from "prop-types";
import withStyles from "@material-ui/core/styles/withStyles";
import Table from "@material-ui/core/Table";
import TableBody from "@material-ui/core/TableBody";
import TableCell from "@material-ui/core/TableCell";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import Paper from "@material-ui/core/Paper";
import TablePagination from "@material-ui/core/TablePagination";
import FormControl from "@material-ui/core/FormControl";
const styles = theme => ({
root: {
width: "100%",
marginTop: theme.spacing.unit * 3,
overflowX: "auto",
},
table: {
minWidth: 700,
},
select: {
minWidth: 200
}
});
class AdminOrder extends React.Component {
constructor(props){
super(props);
this.state = {
data: [],
selectedOption: "",
page: 0,
rowsPerPage: 5
}
}
handleChange = (selectedOption) => {
this.setState({ selectedOption: selectedOption ? selectedOption: "" });
}
handleChangePage = (event, page) => {
this.setState({ page });
};
handleChangeRowsPerPage = event => {
this.setState({ rowsPerPage: event.target.value });
};
componentDidMount(){
this.props.fetchOrder();
}
componentWillReceiveProps(newProps){
if(newProps.adminOrder.hasOwnProperty("orders")){
this.setState({
data: newProps.adminOrder.orders
})
}
}
render () {
const { classes } = this.props;
const { selectedOption, data, page, rowsPerPage } = this.state;
const selection = this.state.data.map(n => {
return { value: n.standing, label: n.standing}
});
return (
<Paper>
<div>
<GridItem xs={12} sm={12} md={12}>
<Card>
<CardHeader color="primary">
<h4>All Store Orders</h4>
<p>
List of All Store Orders
</p>
</CardHeader>
<GridItem xs={12} sm={12} md={3}>
<FormControl>
<Select
className={classes.select}
value={selectedOption.value}
onChange={this.handleChange}
options={selection}
/>
</FormControl>
</GridItem>
<CardBody>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Order Number</TableCell>
<TableCell>Customer</TableCell>
<TableCell>Vendor</TableCell>
<TableCell>Kind</TableCell>
<TableCell>Order Status</TableCell>
<TableCell>Standing</TableCell>
</TableRow>
</TableHead>
<TableBody>
{data
.slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
.map(n => {
if(selectedOption === "" || n.name === selectedOption.value){
return (
<TableRow key={n.id}>
<TableCell scope="row">
{n.orderNum}
</TableCell>
<TableCell>{n.customer}</TableCell>
<TableCell>{n.vendor}</TableCell>
<TableCell>{n.kind}</TableCell>
<TableCell>{n.orderStatus}</TableCell>
<TableCell>{n.standing}</TableCell>
</TableRow>
)
}
else {
return null
}
})}
</TableBody>
</Table>
</CardBody>
</Card>
</GridItem>
</div>
<TablePagination
component="div"
count={data.length}
rowsPerPage={rowsPerPage}
page={page}
backIconButtonProps={{
"aria-label": "Previous Page",
}}
nextIconButtonProps={{
"aria-label": "Next Page",
}}
onChangePage={this.handleChangePage}
onChangeRowsPerPage={this.handleChangeRowsPerPage}
/>
</Paper>
);
}
}
AdminOrder.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(AdminOrder);
|
/**
* @author Raoul Harel
* @license The MIT license (LICENSE.txt)
* @copyright 2015 Raoul Harel
* @url https://github.com/rharel/webgl-dm-voronoi
*/
/**
* The 3D context holds the webgl interface (with the help of three.js) and
* exposes only the most general interface to the Diagram component.
*
* @constructor
*/
function Context3D(canvas) {
this._canvas = canvas;
this._scene = new THREE.Scene();
this._camera = new THREE.OrthographicCamera(
0, canvas.width,
canvas.height, 0,
1, Math.max(canvas.width, canvas.height)
);
this._camera.position.z = 2;
this._renderer = new THREE.WebGLRenderer({canvas: canvas});
this._renderer.setClearColor(0x000000);
this._material_cache = {};
}
Context3D.prototype = {
constructor: Context3D,
add: function(mesh) { this._scene.add(mesh); },
remove: function(mesh) { this._scene.remove(mesh); },
render: function() { this._renderer.render(this._scene, this._camera); },
/**
* Call this when the drawing canvas changes size. It reconfigures the
* rendering viewport as well as the camera projection matrix.
*/
resize: function() {
this._renderer.setSize(
this._canvas.width,
this._canvas.height
);
this._camera.right = this._canvas.width;
this._camera.top = this._canvas.height;
this._camera.far = Math.max(this._canvas.width, this._canvas.height) + 1;
this._camera.updateProjectionMatrix();
},
/**
* In case that for some reason the user uses identical colors for multiple
* sites, we cache those here, or retrieved already cached versions if they
* exist.
*/
material: function(color) {
var key = color.getStyle();
if (!this._material_cache.hasOwnProperty(key)) {
this._material_cache[key] =
new THREE.MeshBasicMaterial({color: color});
}
return this._material_cache[key];
}
};
|
import { astish } from '../astish';
describe('astish', () => {
it('regular', () => {
expect(
astish(`
prop: value;
`)
).toEqual({
prop: 'value'
});
});
it('nested', () => {
expect(
astish(`
prop: value;
@keyframes foo {
0% {
attr: value;
}
50% {
opacity: 1;
}
100% {
foo: baz;
}
}
named {
background-image: url('/path-to-jpg.png');
}
opacity: 0;
.class,
&:hover {
-webkit-touch: none;
}
`)
).toEqual({
prop: 'value',
opacity: '0',
'.class, &:hover': {
'-webkit-touch': 'none'
},
'@keyframes foo': {
'0%': {
attr: 'value'
},
'50%': {
opacity: '1'
},
'100%': {
foo: 'baz'
}
},
named: {
'background-image': "url('/path-to-jpg.png')"
}
});
});
it('merging', () => {
expect(
astish(`
.c {
font-size:24px;
}
.c {
color:red;
}
`)
).toEqual({
'.c': {
'font-size': '24px',
color: 'red'
}
});
});
it('regression', () => {
expect(
astish(`
&.g0ssss {
aa: foo;
box-shadow: 0 1px rgba(0, 2, 33, 4) inset;
}
named {
transform: scale(1.2), rotate(1, 1);
}
@media screen and (some-rule: 100px) {
foo: baz;
opacity: 1;
level {
one: 1;
level {
two: 2;
}
}
}
.a{
color: red;
}
.b {
color: blue;
}
`)
).toEqual({
'&.g0ssss': {
aa: 'foo',
'box-shadow': '0 1px rgba(0, 2, 33, 4) inset'
},
'.a': {
color: 'red'
},
'.b': {
color: 'blue'
},
named: {
transform: 'scale(1.2), rotate(1, 1)'
},
'@media screen and (some-rule: 100px)': {
foo: 'baz',
opacity: '1',
level: {
one: '1',
level: {
two: '2'
}
}
}
});
});
it('should strip comments', () => {
expect(
astish(`
color: red;
/*
some comment
*/
transform: translate3d(0, 0, 0);
/**
* other comment
*/
background: peachpuff;
font-size: xx-large; /* inline comment */
/* foo: bar */
font-weight: bold;
`)
).toEqual({
color: 'red',
transform: 'translate3d(0, 0, 0)',
background: 'peachpuff',
'font-size': 'xx-large',
'font-weight': 'bold'
});
});
// for reference on what is valid:
// https://www.w3.org/TR/CSS22/syndata.html#value-def-identifier
it('should not mangle valid css identifiers', () => {
expect(
astish(`
:root {
--azAZ-_中文09: 0;
}
`)
).toEqual({
':root': {
'--azAZ-_中文09': '0'
}
});
});
it('should parse multiline background declaration', () => {
expect(
astish(`
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="white"><path d="M7.5 36.7h58.4v10.6H7.5V36.7zm0-15.9h58.4v10.6H7.5V20.8zm0 31.9h58.4v10.6H7.5V52.7zm0 15.9h58.4v10.6H7.5V68.6zm63.8-15.9l10.6 15.9 10.6-15.9H71.3zm21.2-5.4L81.9 31.4 71.3 47.3h21.2z"/></svg>')
center/contain;
`)
).toEqual({
background: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="white"><path d="M7.5 36.7h58.4v10.6H7.5V36.7zm0-15.9h58.4v10.6H7.5V20.8zm0 31.9h58.4v10.6H7.5V52.7zm0 15.9h58.4v10.6H7.5V68.6zm63.8-15.9l10.6 15.9 10.6-15.9H71.3zm21.2-5.4L81.9 31.4 71.3 47.3h21.2z"/></svg>') center/contain`
});
});
it('should handle inline @media block', () => {
expect(
astish(
`h1 { font-size: 1rem; } @media only screen and (min-width: 850px) { h1 { font-size: 2rem; } }`
)
).toEqual({
h1: {
'font-size': '1rem'
},
'@media only screen and (min-width: 850px)': {
h1: {
'font-size': '2rem'
}
}
});
});
it('should handle newlines as part of the rule value', () => {
expect(
astish(
`tag {
font-size: first
second;
}`
)
).toEqual({
tag: {
'font-size': 'first second'
}
});
});
});
|
const mongoose=require("mongoose");
mongoose.connect("mongodb://localhost:27017/erpDB",{ useNewUrlParser: true, useUnifiedTopology: true});
const studentsSchema=new mongoose.Schema({
reg_no:String,
password:String,
name:String,
phone_no:Number,
gpa:Number,
hostel:String,
image:String,
});
const Student=mongoose.model("Student",studentsSchema);
module.exports =Student;
|
var app = require('../../server/server.js');
function login(email, cb) {
var opts = {
host: 'http://localhost:3005',
};
app.models.Purchaseuser.getLoginUrl(email, opts, cb);
}
module.exports = login;
|
const db = require('../models')
const { sendMail } = require('../sendEmail/nodemailer')
const CheckEmailIfExists = async (email) => {
user = await db.User.findOne({ where: { email: email }, })
if (user) {
const codeRandom = Math.floor(Math.random() * 10000);
sendMail(email , "hi is test ?" , `this is code Random: ${ codeRandom } `)
db.User.update(
{ codeRandom: codeRandom},
{ where: { email : email }}
)
}
return user ? true : false;
}
const CheckCode = async (email ,code ) => {
user = await db.User.findOne({
where: { email: email , codeRandom: code}
})
console.log(user);
return user
}
module.exports = {
CheckEmailIfExists,
CheckCode
};
|
import axios from 'axios'
const { REACT_APP_BASE_URL } = process.env
const BASE_URL = REACT_APP_BASE_URL
// get all events by organization, with nested regsitration, reviews, attendees
const getEventsByOrg = async (orgId) => {
const token = localStorage.getItem('token_org')
const res = await axios(`${BASE_URL}/organizations/${orgId}/events`, {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`
}
})
return res.data
}
const createEvent = async (formInputs) => {
const token = localStorage.getItem('token_org')
const orgId = localStorage.getItem('org_id')
const res = await axios(`${BASE_URL}/organizations/${orgId}/events`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`
},
data: formInputs // formInput is an object
})
return res.data
}
export default { getEventsByOrg, createEvent }
|
/* eslint-disable no-undef */
const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
require('../models/Moedas.model')
const Moeda = mongoose.model('Moedas')
const descritor = require('../crawllers/wikipediaInfos')
const api = require('../apis/apimoeda')
router.get('/valor/:conversao', async (req, res) => {
const { conversao } = req.params
if(!conversao){
return res.json({
err: "Especifique as moedas para conversão"
})
}
try {
const resposta = await api.get(`/last/${conversao}`)
return res.json(resposta.data)
} catch {
return res.status(400).json({
err: "Especifique uma coversão válida"
})
}
})
router.get('/valor/:moeda/:dias', async (req, res) => {
const { moeda, dias } = req.params
if(!moeda || !dias) {
return res.status(400).json({
err: "Especifique os parâmetros"
})
}
try {
const resposta = await api.get(`/json/daily/${moeda}/${dias}`)
return res.json(resposta.data)
} catch {
return res.status(400).json({
err: "Especifique informações válidas"
})
}
})
router.get('/moeda/:moeda', async (req, res) => {
const moeda = await Moeda.findOne({ keySearch: req.params.moeda.toLowerCase() })
if (moeda) {
return res.json(moeda)
} else {
const descricao = await descritor({"articleName": req.params.moeda,
"lang": "pt"})
const novamoeda = await Moeda.create({
keySearch: req.params.moeda.toLowerCase(),
coin: descricao.title,
description: descricao.content,
resume: descricao.summary
})
return res.json(novamoeda)
}
})
router.get('/moedas', async (req, res) => {
const moedas = await Moeda.find()
if (moedas) {
return res.json(moedas)
} else {
return res.status(404).json({
err: 404,
description: 'Não existem moedas registradas no banco de dados ainda'
})
}
})
module.exports = router
|
const moment = require('moment');
const _ = require('lodash');
const { User, Wobj, paymentHistory } = require('models');
const campaignValidation = (campaign) => !!(campaign.reservation_timetable[moment().format('dddd').toLowerCase()]
&& _.floor(campaign.budget / campaign.reward) > _.filter(campaign.users, (user) => user.status === 'assigned'
&& user.createdAt > moment().startOf('month')).length);
exports.requirementFilters = (campaign, user, restaurant) => {
let frequency = [], notBlacklisted = true;
if (user && user.name) {
notBlacklisted = !_.includes(campaign.blacklist_users, user.name);
frequency = _
.chain(campaign.users)
.filter((doer) => doer.name === user.name && doer.status === 'completed')
.orderBy(['updatedAt'], ['desc'])
.compact()
.value();
}
const result = {
can_assign_by_current_day: true,
can_assign_by_budget: campaign.budget > campaign.reward * _.filter(campaign.users, (doer) => doer.status === 'assigned').length,
posts: user ? user.count_posts >= campaign.userRequirements.minPosts : false,
followers: user ? user.count_posts >= campaign.userRequirements.minPosts : false,
expertise: user ? user.wobjects_weight >= campaign.userRequirements.minExpertise : false,
freeReservation: true,
frequency: frequency.length ? moment().startOf('month') > frequency[0].updatedAt : true,
not_blacklisted: notBlacklisted,
};
return restaurant ? [campaignValidation(campaign), ...Object.values(result)] : result;
};
exports.campaignFilter = async (campaigns, user) => {
const validCampaigns = [];
await Promise.all(campaigns.map(async (campaign) => {
if (campaignValidation(campaign)) {
const { result, error } = await Wobj.findOne(campaign.requiredObject);
if (error) return;
campaign.required_object = result;
const { user: guide, error: guideError } = await User.getOne(campaign.guideName);
if (guideError || !guide) return;
const { result: totalPayed } = await paymentHistory.findByCondition(
{ sponsor: campaign.guideName, type: 'transfer' },
);
campaign.assigned = user ? !!_.find(campaign.users, (doer) => doer.name === user.name && doer.status === 'assigned') : false;
campaign.requirement_filters = this.requirementFilters(campaign, user);
campaign.guide = {
name: campaign.guideName,
wobjects_weight: guide.wobjects_weight,
alias: guide.alias,
totalPayed: _.sumBy(totalPayed, (count) => count.amount),
};
validCampaigns.push(campaign);
}
}));
return validCampaigns;
};
|
import React from 'react'
import { shallow } from 'enzyme'
import EpisodeList from './EpisodeList'
describe('EpisodeList Component', () => {
it('should render', () => {
const component = shallow(<EpisodeList />)
expect(component.find('.c-episodelist').exists()).toBe(true)
})
it('should render the correct number of seasons', () => {
const mockProps = {
episodes: [
{
id: 1,
episodeNumber: 1,
seasonNumber: 1,
},
{
id: 2,
episodeNumber: 1,
seasonNumber: 2,
},
],
}
const component = shallow(<EpisodeList {...mockProps} />)
expect(component.state().seasons).toHaveLength(2)
expect(component.find('.c-episodelist-season')).toHaveLength(2)
})
it('should render the correct number of episodes for each season', () => {
const mockProps = {
episodes: [
{
id: 1,
episodeNumber: 1,
seasonNumber: 1,
},
{
id: 2,
episodeNumber: 2,
seasonNumber: 1,
},
{
id: 3,
episodeNumber: 1,
seasonNumber: 2,
},
],
}
const component = shallow(<EpisodeList {...mockProps} />)
expect(component.find('.c-episodelist-season')).toHaveLength(2)
expect(component.find('.c-episodelist-season ol').children()).toHaveLength(3)
})
})
|
module.exports = function(sequelize, DataTypes) {
return sequelize.define(
'article',
{
id: {
autoIncrement: true,
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true
},
title: {
type: DataTypes.STRING(255),
allowNull: false,
defaultValue: ''
},
authorId: {
type: DataTypes.INTEGER,
allowNull: false
},
description: {
type: DataTypes.TEXT,
allowNull: true
},
content: {
type: DataTypes.TEXT,
allowNull: false
},
createAt: {
type: DataTypes.DATE,
allowNull: false
},
updateAt: {
type: DataTypes.DATE,
allowNull: false
},
image: {
type: DataTypes.STRING(255),
allowNull: true
},
isShow: {
type: DataTypes.BOOLEAN,
allowNull: false
}
},
{
sequelize,
tableName: 'article',
timestamps: false,
indexes: [
{
name: 'PRIMARY',
unique: true,
using: 'BTREE',
fields: [{ name: 'id' }]
}
]
}
)
}
|
'use strict';
const express = require('express');
const router = express.Router();
const MatchController = require('../controllers').Matches;
const LobbyController = require('../controllers').Lobby;
const ProfileController = require('../controllers').Profiles;
router.route('/')
.get(MatchController.getAll)
;
router.route('/:id')
.get(MatchController.getUserMatches)
;
router.route('/accept')
.put(MatchController.acceptOther)
;
router.route('/reject')
.put(MatchController.rejectOther)
;
module.exports = router;
|
"use strict";
var Tag = require('../Tag');
var utils = require('../support/utils');
var append = utils.append;
Tag.extend('verbatim', {
block:true,
evaluate: function(template)
{
// Echo the scope inputs.
this.setSource(append(JSON.stringify(this.scope.input)));
}
});
|
$(function(){
var $container = $('#masonry-container');
$container.imagesLoaded( function(){
$container.masonry({
itemSelector: '.post-masonry',
columnWidth: 278,
gutterWidth: 16,
isAnimated: !Modernizr.csstransitions,
isFitWidth: true
});
});
});
|
import React from 'react'
import Icon from './Icon'
const ArrowUpIcon = props => (
<Icon originalWidth={32} originalHeight={32} {...props}>
<g>
<path
d='M27.414 12.586l-10-10c-0.781-0.781-2.047-0.781-2.828 0l-10 10c-0.781 0.781-0.781 2.047
0 2.828s2.047 0.781 2.828 0l6.586-6.586v19.172c0 1.105 0.895 2 2 2s2-0.895 2-2v-19.172l6.586
6.586c0.39 0.39 0.902 0.586 1.414 0.586s1.024-0.195 1.414-0.586c0.781-0.781 0.781-2.047 0-2.828z'
/>
</g>
</Icon>
)
export default ArrowUpIcon
|
/* jshint expr: true */
/* globals it, describe */
'use strict';
var expect = require('chai').expect;
var parseAccountString = require('../lib/utils').parseAccountString;
describe('parseAccountString', function() {
it('should return account info for properly constructed account string', function() {
var returnedValue;
// the most common version used on azure
returnedValue = parseAccountString('BlobEndpoint=http://dummy.blob.core.windows.net/;QueueEndpoint=http://dummy.queue.core.windows.net/;TableEndpoint=http://dummy.table.core.windows.net/;AccountName=dummy;AccountKey=XUpVW5efmPDA42r4VY/86bt9k+smnhdEFVRRGrrt/wE0SmFg==');
expect(returnedValue).to.not.be.null;
expect(returnedValue).to.have.property('accountUrl', 'http://dummy.queue.core.windows.net/');
expect(returnedValue).to.have.property('accountName', 'dummy');
expect(returnedValue).to.have.property('accountKey', 'XUpVW5efmPDA42r4VY/86bt9k+smnhdEFVRRGrrt/wE0SmFg==');
// minimalistic (only required data)
expect(parseAccountString('AccountName=dummy;QueueEndpoint=http://dummy.queue.core.windows.net/;AccountKey=XUpVW5efmPDA42r4VY/86bt9k+smnhdEFVRRGrrt/wE0SmFg==')).to.be.deep.equal(returnedValue);
});
it('should return null for incomplete account string', function() {
expect(parseAccountString('QueueEndpoint=http://dummy.queue.core.windows.net/;AccountKey=XUpVW5efmPDA42r4VY/86bt9k+smnhdEFVRRGrrt/wE0SmFg==')).to.be.null;
expect(parseAccountString('QueueEndpoint=http://dummy.queue.core.windows.net/;AccountName=dummy')).to.be.null;
expect(parseAccountString('AccountName=dummy;AccountKey=XUpVW5efmPDA42r4VY/86bt9k+smnhdEFVRRGrrt/wE0SmFg==')).to.be.null;
});
it('should return null for invalid or not existing account string', function() {
expect(parseAccountString(undefined)).to.be.null;
expect(parseAccountString(null)).to.be.null;
expect(parseAccountString('')).to.be.null;
expect(parseAccountString(' Key=value ')).to.be.null;
});
});
|
import {BrowserRouter as Router, Switch, Route, useHistory,} from "react-router-dom";
import Header from "./components/header/Header";
import NewsPage from "./pages/news/NewsPage"
import Login from "./pages/login/Login";
import Schedule from "./pages/schedule/Schedule";
import Classest from "./pages/lessons/teacher/Classest";
import Editchapter from "./pages/lessons/teacher/Editchapter";
import Editdeadlines from "./pages/lessons/teacher/Editdeadlines";
import Lessont from "./pages/lessons/teacher/Lessont";
import ClassStudent from "./pages/lessons/student/Class";
import ClassesStudent from "./pages/lessons/student/Classes";
import {useDispatch, useSelector} from "react-redux";
import Profile from "./pages/profile/Profile";
import {useEffect} from "react";
import {fetchProfile} from "./actions/profile";
import {fetchLessonsTeacher} from "./actions/lessonsTeacher";
import {fetchLessonsStudent} from "./actions/lessonsStudent";
import {fetchSchedule} from "./actions/schedule";
import {fetchNews} from "./actions/news";
import Tests from "./pages/tests/Tests";
import Grades from "./pages/student_grades/Grades";
import TeacherGrades from "./pages/teacher_grades/TeacherGrades";
function App() {
const history = useHistory()
const dispatch = useDispatch()
const auth = useSelector((state) => state.auth)
useEffect(() => {
if (auth.isLoggedIn) {
dispatch(fetchNews())
dispatch(fetchProfile())
dispatch(fetchLessonsTeacher())
dispatch(fetchLessonsStudent())
dispatch(fetchSchedule())
}
}, [])
if (auth.isLoggedIn) {
return (<>
{auth.isLoggedIn ? <Header/> : ''}
<div className="App">
<Switch>
<Route exact path='/'>
<NewsPage/>
</Route>
<Route path='/tests'>
<Tests/>
</Route>
<Route path='/login'>
<Login/>
</Route>
<Route path='/profile'>
<Profile/>
</Route>
<Route path='/schedule'>
<Schedule/>
</Route>
{/* ОЦІНКИ */}
<Route path='/students-grades'>
<Grades/>
</Route>
<Route path='/teacher-grades'>
<TeacherGrades/>
</Route>
{/*TEACHER*/}
<Route path='/teacher/classest'>
<Classest/>
</Route>
<Route path='/teacher/editchapter'>
<Editchapter/>
</Route>
<Route path='/teacher/editdeadlines'>
<Editdeadlines/>
</Route>
<Route path='/teacher/lessont'>
<Lessont/>
</Route>
{/*STUDENT*/}
<Route path='/student/class'>
<ClassStudent/>
</Route>
<Route path='/student/classes'>
<ClassesStudent/>
</Route>
<Route path='*'>
<div>No page found</div>
</Route>
</Switch>
</div>
</>)
} else {
history.push('/login')
return <Login/>
}
}
export default App;
|
const fs = require("fs");
const map = fs.readFileSync("./map.txt").toString();
let mapByLine = map.split("\n");
let count1 = 0; // Right 3, down 1
let j = 0;
for (let i = 0; i < mapByLine.length; i++) {
if (j > mapByLine[i].length - 1) {
j = (j % (mapByLine[i].length));
}
if (mapByLine[i][j] === '#') {
count1 += 1;
}
j += 3
}
let count2 = 0; // Right 1, down 1
let k = 0;
for (let i = 0; i < mapByLine.length; i++) {
if (k > mapByLine[i].length - 1) {
k = (k % (mapByLine[i].length));
}
if (mapByLine[i][k] === '#') {
count2 += 1;
}
k += 1
}
let count3 = 0; // Right 5, down 1
let x = 0;
for (let i = 0; i < mapByLine.length; i++) {
if (x > mapByLine[i].length - 1) {
x = (x % (mapByLine[i].length));
}
if (mapByLine[i][x] === '#') {
count3 += 1;
}
x += 5
}
let count4 = 0 //Right 7, down 1
let y = 0;
for (let i = 0; i < mapByLine.length; i++) {
if (y > mapByLine[i].length - 1) {
y = (y % (mapByLine[i].length));
}
if (mapByLine[i][y] === '#') {
count4 += 1;
}
y += 7
}
let count5 = 0; // right 1, down 2
let u = 0; // matrix row
let p = 0; //matrix col
while (u < mapByLine.length) {
if (p > mapByLine[u].length - 1) {
p = (p % (mapByLine[u].length));
}
if (mapByLine[u][p] === '#') {
count5 += 1;
}
u += 2
p += 1;
}
console.log(count1 * count2 * count3 * count4 * count5);
|
/*
FUNCTION TO LOG INTO THE BOT
*/
const botLogin = (token, vars, destroy) => {
if(vars.firstRun) {
vars.bot.login(token);
} else {
if(destroy !== null) {
if(destroy === true) {
vars.bot.destroy();
vars.bot.login(token);
} else {
vars.bot.login(token);
}
}
}
}
module.exports = botLogin;
|
#!/usr/bin/env node
const glob = require("glop");
const path = require("path");
const fs = require("fs");
console.log(path.join(process.cwd(), process.argv[2]));
glob(path.join(process.cwd(), process.argv[2]), function (err, file) {
if (err) throw new Error(err);
console.log(file);
fs.writeFileSync(path.join(process.cwd(), "./w.file"), file[0]);
});
|
// カメラ
exports.createWindow = function(_type, _userData){
Ti.API.debug('[func]winCamera.createWindow:');
Ti.API.debug('_type:' + _type);
var offsetX = 0;
var offsetY = 0;
var currentScale = 1;
// 画像のリサイズ・切り抜き
var editImage = function(_image) {
Ti.API.debug('[func]editImage:');
var croppedImage = null;
var cropSize = 0;
var cropX = 0;
// var cropY = 50;
// iOS7の場合
var cropY = 0;
if ( _image.height > _image.width ) {
cropSize = _image.width;
} else {
cropSize = _image.height;
}
if (_type == 'photo_select' || _type == 'icon_select') {
cropX = offsetX;
cropY = offsetY;
}
// imageAsCroppedすると反転するバグがあり、同じサイズでimageAsResizedをしておく反転しない
var resizedImage = _image.imageAsResized(_image.width, _image.height);
croppedImage = resizedImage.imageAsCropped({
width: cropSize,
height: cropSize,
x: cropX * ( _image.height / style.commonSize.screenWidth ),
y: cropY * ( _image.width / style.commonSize.screenWidth )
});
if (cropSize > 640) {
return croppedImage.imageAsResized(640, 640);
} else {
return croppedImage;
}
};
// 写真投稿画面のオープン
var openCameraPostWindow = function(_image) {
Ti.API.debug('[func]openCameraPostWindow:');
var cameraPostWin = win.createCameraPostWindow(_type, _userData, _image);
cameraPostWin.prevWin = cameraWin;
win.openTabWindow(cameraPostWin, {animated:true});
};
// 写真撮影
var startCamera = function() {
Ti.API.debug('[func]startCamera:');
Titanium.Media.showCamera({
success:function(e) {
Ti.API.debug('success:');
var cameraImage = editImage(e.media);
if (_type == 'icon_camera') {
cameraWin.add(actBackView);
actInd.show();
tabGroup.add(actInd);
// ローカルに画像を保存
var fileName = _userData.id;
model.saveLocalImage(cameraImage, util.local.iconPath, fileName);
model.updateCloudUserIcon({
user: _userData.user,
icon: cameraImage
}, function(e) {
Ti.API.debug('[func]updateCloudUserIcon.callback:');
if (e.success) {
_userData.icon = util.local.iconPath + fileName + '.png';
cameraWin.close({animated:true});
// profileWinの更新
var profileWin = win.getTab("profileTab").window;
profileWin.addEventListener('refresh', function(){
actInd.hide();
actBackView.hide();
});
profileWin.fireEvent('refresh', {icon:_userData.icon});
} else {
actInd.hide();
actBackView.hide();
util.errorDialog(e);
}
});
} else {
openCameraPostWindow(cameraImage);
}
},
cancel: function(e) {
Ti.API.debug('cancel:');
cameraWin.close({animated:false});
},
error: function(e) {
Ti.API.debug('error:');
util.errorDialog(e);
},
mediaTypes: Ti.Media.MEDIA_TYPE_PHOTO,
// showControls: true,
overlay: overlayView,
// 縦サイズが撮影前後で変わらないように設定
transform: Ti.UI.create2DMatrix().scale(1),
// iOS7の場合
// 編集画面を省略してfalseにするとボタンを押しても次へ進めなくなるのでtrue
allowEditing: true,
saveToPhotoGallery: false,
});
};
// アルバムから取得
var pickupPhoto = function() {
Ti.API.debug('[func]pickupPhoto:');
Ti.Media.openPhotoGallery({
success: function(e) {
Ti.API.debug('success:');
var pickupImage = e.media;
// 写真の真ん中に合わせる
var scale = 1.0;
if (pickupImage.height > pickupImage.width) {
articleImage.width = style.commonSize.screenWidth + 'dp';
articleImage.height = Ti.UI.SIZE;
scale = style.commonSize.screenWidth / pickupImage.width;
offsetX = 0;
offsetY = ( pickupImage.height * scale - style.commonSize.screenWidth) / 2;
} else {
articleImage.width = Ti.UI.SIZE;
articleImage.height = style.commonSize.screenWidth + 'dp';
scale = style.commonSize.screenWidth / pickupImage.height;
offsetX = ( pickupImage.width * scale - style.commonSize.screenWidth) / 2;
offsetY = 0;
}
articleScrollView.setContentOffset({x:offsetX, y:offsetY}, {animated:false});
articleImage.image = pickupImage;
cameraWin.backgroundColor = 'white';
},
cancel: function(e) {
Ti.API.debug('cancel:');
cameraWin.close({animated:false});
},
error: function(e) {
Ti.API.debug('error:');
},
mediaTypes: Ti.Media.MEDIA_TYPE_PHOTO,
// 縦サイズが撮影前後で変わらないように設定
transform: Ti.UI.create2DMatrix().scale(1),
allowEditing: false,
saveToPhotoGallery: false,
});
};
// ---------------------------------------------------------------------
var cameraWin = Ti.UI.createWindow(style.cameraWin);
// タイトルの表示
var titleLabel = Ti.UI.createLabel(style.cameraTitleLabel);
cameraWin.titleControl = titleLabel;
// 戻るボタンの表示
var backButton = Titanium.UI.createButton(style.commonBackButton);
cameraWin.leftNavButton = backButton;
// 選択ボタンの表示
var selectButton = Titanium.UI.createButton(style.cameraSelectButton);
var articleScrollView = Titanium.UI.createScrollView(style.cameraArticleScrollView);
// フレーム余白 = ( 全体の高さーフレームの高さー(ステータスバー(20)+タイトルバー(44)+下のタブ(44)) ) / 2
var frameSpace = ( style.commonSize.screenHeight - style.commonSize.screenWidth - 108 ) / 2;
// フレームの上部余白部分
var frameHeadView = Titanium.UI.createView(style.cameraFrameSpaceView);
frameHeadView.height = frameSpace + 'dp';
articleScrollView.add(frameHeadView);
// 写真の表示
var articleImage = Ti.UI.createImageView(style.cameraArticleImage);
articleScrollView.add(articleImage);
cameraWin.add(articleScrollView);
// フレームの下部余白部分
var frameFooterView = Titanium.UI.createView(style.cameraFrameSpaceView);
// 下のタブ(44) + 上部余白
frameFooterView.height = (44 + frameSpace) + 'dp';
articleScrollView.add(frameFooterView);
// 撮影時のオーバーレイ
var overlayView = Titanium.UI.createView(style.cameraOverlayView);
// フレーム
var frameView = Titanium.UI.createView(style.cameraFrameView);
if (_type == 'photo_camera') {
titleLabel.text = '取り込み中';
// frameView.top = '50dp';
// iOS7の場合
frameView.top = '88dp';
overlayView.add(frameView);
} else if (_type == 'icon_camera') {
titleLabel.text = '取り込み中';
// frameView.top = '50dp';
// iOS7の場合
frameView.top = '88dp';
// frameView.borderRadius = (Ti.Platform.displayCaps.platformWidth / 2) + 'dp';
overlayView.add(frameView);
} else if (_type == 'photo_select') {
titleLabel.text = 'わんこ写真';
frameView.top = frameSpace + 'dp';
cameraWin.add(frameView);
selectButton.title = '選択',
cameraWin.rightNavButton = selectButton;
} else if (_type == 'icon_select') {
titleLabel.text = 'わんこ写真';
frameView.top = frameSpace + 'dp';
frameView.borderRadius = (Ti.Platform.displayCaps.platformWidth / 2) + 'dp';
cameraWin.add(frameView);
selectButton.title = '登録',
cameraWin.rightNavButton = selectButton;
}
if (_type == 'photo_camera' || _type == 'icon_camera') {
startCamera();
} else if (_type == 'photo_select' || _type == 'icon_select') {
pickupPhoto();
}
// 投稿時のロード用画面
var actInd = Ti.UI.createActivityIndicator(style.commonActivityIndicator);
var actBackView = Titanium.UI.createView(style.commonActivityBackView);
// ---------------------------------------------------------------------
// 戻るボタンをクリック
backButton.addEventListener('click', function(e){
Ti.API.debug('[event]backButton.click:');
if (_type == 'photo_select' || _type == 'icon_select') {
articleImage.image = null;
pickupPhoto();
}
});
// 選択ボタンをクリック
selectButton.addEventListener('click', function(e){
Ti.API.debug('[event]selectButton.click:');
var postImage = editImage(articleImage.toBlob());
if (_type == 'photo_select') {
openCameraPostWindow(postImage);
} else if (_type == 'icon_select') {
selectButton.touchEnabled = false;
cameraWin.add(actBackView);
actInd.show();
tabGroup.add(actInd);
// ローカルに画像を保存
var fileName = _userData.id;
model.saveLocalImage(postImage, util.local.iconPath, fileName);
model.updateCloudUserIcon({
user: _userData.user,
icon: postImage
}, function(e) {
Ti.API.debug('[func]updateCloudUserIcon.callback:');
if (e.success) {
_userData.icon = util.local.iconPath + fileName + '.png';
cameraWin.close({animated:true});
// profileWinの更新
var profileWin = win.getTab("profileTab").window;
profileWin.addEventListener('refresh', function(){
actInd.hide();
actBackView.hide();
selectButton.touchEnabled = true;
});
profileWin.fireEvent('refresh', {icon:_userData.icon});
} else {
actInd.hide();
actBackView.hide();
selectButton.touchEnabled = true;
util.errorDialog(e);
}
});
}
});
// スクロールイベント
articleScrollView.addEventListener('scroll', function(e){
Ti.API.debug('[event]articleScrollView.scroll:');
offsetX = e.x;
offsetY = e.y;
});
/*
// 拡大縮小イベント ※ピンチ後の画像修正が難しいのでやめる
articleScrollView.addEventListener('pinch', function(e){
Ti.API.debug('[event]articleScrollView.pinch:');
Ti.API.info('scale=' + e.scale);
currentScale = e.scale;
});
*/
// 撮影用イベント
cameraWin.addEventListener('openCamera', function(e){
Ti.API.debug('[event]cameraWin.openCamera:');
if (_type == "photo_camera" || _type == 'icon_camera') {
startCamera();
}
});
return cameraWin;
};
|
import logo from './logo.svg';
import './App.css';
import React, {Component} from 'react';
import {Route,Switch} from "react-router-dom";
import GetAll from './GetAll';
import Create from './Create';
import Get from './Get';
import Update from './Update';
import Delete from './Delete';
class App extends Component {
return (
<div className="App">
/* Use Switch to route all the url patterns our app will accept to React components */
<Switch>
<Route path="/" component={GetAll}/>
<Route path="/Get" component={Get}/>
<Route path="/Create" component={Create}/>
<Route path="/Update" component={Update}/>
<Route path="/Delete" component={Delete}/>
</Switch>
</div>
);
}
export default App;
|
'use strict';
var Customer = {
tableName: 'mds_customers',
attributes: {}
}
module.exports = Customer;
|
#!/usr/bin/node
const args = process.argv;
if (!isNaN(args[2])) {
console.log('My number: ' + args[2]);
} else {
console.log('Not a number');
}
|
import express from 'express';
import http from 'http';
import bodyParser from 'body-parser';
import morgan from 'morgan';
import mongoose from 'mongoose';
import cors from 'cors';
import compression from 'compression';
import router from './router';
import { dbConfig } from './config';
const app = express();
// Use Node's default promise instead of Mongoose's promise library
mongoose.Promise = global.Promise;
// Connect to the database
mongoose.connect(dbConfig.db);
let db = mongoose.connection;
db.on('open', () => {
console.log('Connected to the database.');
});
db.on('error', (err) => {
console.log(`Database error: ${err}`);
});
app.use(compression());
app.use(morgan('combined'));
app.use(cors());
app.use(bodyParser.json({ type: '*/*' }));
router(app);
const port = process.env.PORT || 3333;
const server = http.createServer(app);
server.listen(port);
console.log('server listening on:', port);
|
const Computer = require('./int');
module.exports = input => {
let inp = [1];
let out = [];
let map = new Map();
let computer = new Computer(input.split(',').map(Number), inp, out);
let position = [0, 0];
let direction = [0, 1];
const id = ([x, y]) => `${x}#${y}`;
while (!computer.isFinished()) {
computer.run();
computer.run();
let dir = out.pop();
let color = out.pop();
map.set(id(position), color);
direction = dir ? [direction[1], -direction[0]] : [-direction[1], direction[0]];
position[0] += direction[0];
position[1] += direction[1];
inp.push(map.get(id(position)) || 0);
}
let tiles = [...map.keys()].map(k => k.split('#').map(Number));
let maxX = tiles.map(([x, y]) => x).reduce((max, x) => Math.max(max, x));
let minX = tiles.map(([x, y]) => x).reduce((min, x) => Math.min(min, x));
let maxY = tiles.map(([x, y]) => y).reduce((max, y) => Math.max(max, y));
let minY = tiles.map(([x, y]) => y).reduce((min, y) => Math.min(min, y));
let image = '';
for (let y = maxY; y >= minY; y--) {
for (let x = minX; x <= maxX; x++) {
image += (map.get(id([x, y])) || 0) ? '#' : ' ';
}
image += '\n';
}
return image;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.