text
stringlengths 7
3.69M
|
|---|
import React, {useEffect, useState} from 'react';
import Receipe from './Receipe';
import './App.css';
const App = () => {
const API_ID = "63597f7f";
const APP_KEY = "59143a8d960d4b8c07329aa12c11fbe6";
const [receipes, setReceipes] = useState([]);
const [search, setSearch] = useState("");
const [query, setQuery] = useState('chicken');
useEffect(() => {
getReceipe();
},[query]);
const getReceipe = async () => {
const response = await fetch(`https://api.edamam.com/search?q=${query}&app_id=${API_ID}&app_key=${APP_KEY}`);
const data = await response.json();
setReceipes(data.hits);
console.log(data.hits)
};
const updateSearch = e => {
setSearch(e.target.value);
};
const getSearch = e => {
e.preventDefault();
setQuery(search);
setSearch('');
}
return (
<div className="App">
<form onSubmit = {getSearch} className="search-form">
<input
className="search-bar"
type="text"
value={search}
onChange = {updateSearch}
/>
<button className="search-button" type="submit">Search</button>
</form>
<div className = "recipes">
{receipes.map(receipe => (
<Receipe
key = {receipe.recipe.label}
title = {receipe.recipe.label}
calories = {receipe.recipe.calories}
image = {receipe.recipe.image}
ingredients = {receipe.recipe.ingredients}
dietLabel = {receipe.recipe.dietLabels}
/>
))}
</div>
</div>
);
};
export default App;
|
'use strict';
import React from 'react';
import InputForm from "./InputForm.jsx";
import TaskList from './TaskLists.jsx'
class TodoApp extends React.Component {
constructor(props) {
super(props);
this.state = { items: [], text: '' };
this.handleInputChange = this.handleInputChange.bind(this);
this.handleInputSubmit = this.handleInputSubmit.bind(this);
this.deleteTask = this.deleteTask.bind(this);
}
handleInputChange(e){
this.setState({text:e.target.value});
}
handleInputSubmit(e){
e.preventDefault();
document.getElementById("new-todo").value = "";
if(this.state.text.length === 0){
alert("no puedes enviar tareas vacias");
return;
}else{
let newItem ={
text:this.state.text,
id: Date.now()
}
// this.setState(prevState => ({
// items: prevState.items.concat(newItem),
// text: ''
// }));
this.setState(prevState =>({
/*
Por que concat y no push ?
push es para un arreglo que ya existe
concat une el arreglo de un estado anterior con el nuevo
que se esta creando al actualizar el estado.*/
items:prevState.items.concat(newItem),
text:""
}));
}
}
deleteTask(e){
// console.log(e.target.dataset.llave)
e.preventDefault();
let llaveTarea = e.target.dataset.llave;
this.setState(prevState =>({
items:prevState.items.filter(item => !(llaveTarea==item.id))
}));
}
render() {
return (
<div>
<h3>TODO</h3>
<InputForm submit={this.handleInputSubmit} inputChange={this.handleInputChange} inputValue = {this.state.text}/>
<TaskList items = {this.state.items} delete = {this.deleteTask}/>
</div>
);
}
}
export default TodoApp;
|
define('views/new_collection',
['l10n', 'notification', 'requests', 'urls', 'z'],
function(l10n, notification, requests, urls, z) {
var gettext = l10n.gettext;
z.body.on('submit', 'form#new_collection', function(e) {
e.preventDefault();
requests.post(
urls.api.url('collections'),
{
name: $(this).find('[name=name]').val(),
description: $(this).find('[name=description]').val()
}
).done(function(data) {
notification.notification({message: gettext('New collection created.')});
z.page.trigger('navigate', [urls.reverse('collection', [data.id])]);
}).fail(function() {
notification.notification({message: gettext('Failed to create new collection.')})
});
});
return function(builder) {
builder.start('new_collection.html');
builder.z('type', 'leaf');
builder.z('title', gettext('New Collection'));
};
});
|
import { combineReducers } from 'redux';
import { reducer as formReducer } from 'redux-form';
import reducerMessages from './reducerMessages';
const rootReducer = combineReducers({
messages: reducerMessages,
form: formReducer,
});
export default rootReducer;
|
import createDOMElement from './createDOMElement'
import unmountNode from './unmountNode'
export default function mountNativeElement (virtualDOM, container, oldDom) {
// 创建真实dom
let newElement = createDOMElement(virtualDOM)
// 将转换后的元素放置在页面中
if(oldDom) {
container.insertBefore(newElement, oldDom)
}else{
container.appendChild(newElement)
}
// 判断旧dom是否存在 存在则删除
if(oldDom) {
unmountNode(oldDom)
}
// 获取类组件实例对象
const component = virtualDOM.component
// 如果存在
if(component) {
// 将 dom 对象存储在类实例中
component.setDom(newElement)
}
}
|
'use strict';
var f = 16;
// square root f's value
console.log(f*f)
console.log(Math.pow(f, 2))
|
import React from "react";
import "../styles/input.scss";
import { FaUserCheck } from "react-icons/fa";
import { RiLockPasswordLine } from "react-icons/ri";
import { MdEmail } from "react-icons/md";
import { IoMdEyeOff, IoMdEye } from "react-icons/io";
const Inputbox = ({
placeholder,
error,
category,
value,
handler,
isValid,
}) => {
const [blur, setblur] = React.useState(false);
const [passhide, setpass] = React.useState(true);
const passHandler = () => {
setpass((prev) => !prev);
};
return (
<>
<div className="whole_width">
<div className="user_box">
{category === "email" ? (
<MdEmail className="user_icon" />
) : category === "password" ? (
<RiLockPasswordLine className="user_icon" />
) : (
<FaUserCheck className="user_icon" />
)}
<div className="username_container">
<input
className="input"
placeholder={placeholder}
vlaue={value}
onChange={handler}
name={category}
onBlur={() => {
setblur((prev) => true);
}}
type={
category !== "password"
? "text"
: passhide
? "password"
: "text"
}
></input>
</div>
{category != "password" ? null : passhide ? (
<IoMdEyeOff className="eye" onClick={passHandler} />
) : (
<IoMdEye className="eye" onClick={passHandler} />
)}
</div>
</div>
{!blur ? null : isValid ? null : (
<div className="error_container">
<div className="error">
<h5>{error}</h5>
</div>
</div>
)}
</>
);
};
export default React.memo(Inputbox);
|
/*
* 布局模块
* @date:2015-08-23
* @author:kotenei(kotenei@qq.com)
*/
define('km/layout', ['jquery', 'km/panel', 'km/cache'], function($, Panel, cache) {
/**
* 布局模块
* @param {JQuery} $elm - dom
* @param {Object} options - 参数
*/
var Layout = function($elm, options) {
this.$layout = $elm;
this.options = $.extend(true, {
cache: false,
resizeMin: 5,
panel: {
left: { width: 100 },
top: { height: 100 },
right: { width: 100 },
bottom: { height: 100 }
}
}, options);
this.$parent = this.$layout.parent();
this.init();
this._event = {
show: $.noop,
hide: $.noop
};
};
/**
* 初始化
* @return {Void}
*/
Layout.prototype.init = function() {
var self = this;
this.$win = $(window);
this.$panels = this.$layout.children('.k-panel');
this.$leftPanel = this.$panels.filter('.k-panel-left');
this.$topPanel = this.$panels.filter('.k-panel-top');
this.$rightPanel = this.$panels.filter('.k-panel-right');
this.$bottomPanel = this.$panels.filter('.k-panel-bottom');
this.$centerPanel = this.$panels.filter('.k-panel-center');
this.$panels.each(function() {
var $panel = $(this),
type = $panel.attr('data-type'),
$expand = $(self.getExpandHtml(type)).appendTo(self.$layout);
$.data($panel[0], 'expand', $expand);
});
this.setSize();
this.panelInit();
this.watch();
};
/**
* 面板初始化
* @return {Void}
*/
Layout.prototype.panelInit = function() {
var self = this;
this.$panels.each(function() {
var $panel = $(this).show(),
type = $panel.attr('data-type'),
resizable = $panel.attr('data-resizable'),
min = self.options.resizeMin,
options = {
resizable: {
enabled: !resizable || resizable == 'true' ? true : false,
cover: true,
border: {
left: false,
top: false,
right: false,
bottom: false
},
callback: {
stop: function() {
if (self.$centerPanel.length > 0) {
self.$centerPanel.resize();
} else {
self.setSize();
}
}
}
},
width: $panel.width(),
height: $panel.height()
};
switch (type) {
case 'top':
options.minHeight = min;
options.resizable.border.bottom = true;
break;
case 'left':
options.minWidth = min;
options.resizable.border.right = true;
break;
case 'right':
options.minWidth = min;
options.resizable.border.left = true;
break;
case 'bottom':
options.minHeight = min;
options.resizable.border.top = true;
break;
}
var panel = new Panel($panel, options);
$.data($panel[0], 'panel', panel);
});
};
/**
* 事件监控
* @return {Void}
*/
Layout.prototype.watch = function() {
var self = this;
this.$win.on('resize.layout', function() {
self.setSize();
});
this.$panels.on('click.layout', 'span[role=hide]', function() {
self.hide($(this).attr('data-type'));
return false;
});
this.$layout.on('click.layout', 'span[role=show]', function() {
self.show($(this).attr('data-type'));
return false;
});
};
/**
* 事件添加
* @return {Void}
*/
Layout.prototype.on = function(type, callback) {
this._event[type] = callback || $.noop;
return this;
};
/**
* 展开
* @param {String} type - 面板类型
* @return {Void}
*/
Layout.prototype.show = function(type) {
var self = this,
panelsInfo = this.getPanelsInfo(),
info = panelsInfo[type],
$panel = info.$panel.attr('data-isHide', false),
$expand = info.$expand,
css;
$expand.hide();
$panel.show();
switch (type) {
case 'top':
css = { top: 0 };
break;
case 'left':
css = { left: 0 };
break;
case 'right':
css = { right: 0 };
break;
case 'bottom':
css = { bottom: 0 };
break;
}
$panel.stop().animate(css, function() {
self.setSize();
if (self.$centerPanel) {
self.$centerPanel.resize();
}
});
this._event.show.call(this, info);
};
/**
* 隐藏
* @param {String} type - 面板类型
* @return {Void}
*/
Layout.prototype.hide = function(type) {
var self = this,
panelsInfo = this.getPanelsInfo(),
info = panelsInfo[type],
css;
info.$panel.attr('data-isHide', true);
self.setSize();
if (self.$centerPanel) {
self.$centerPanel.resize();
}
switch (type) {
case 'top':
css = { top: -info.height };
break;
case 'left':
css = { left: -info.width };
break;
case 'right':
css = { right: -info.width };
info.$panel.css('right', 0);
break;
case 'bottom':
css = { bottom: -info.height };
info.$panel.css('bottom', 0);
break;
}
info.$panel.stop().animate(css, function() {
info.$panel.hide();
info.$expand.show();
self._event.hide.call(self, info);
});
};
/**
* 获取面板隐藏后占位图层HTML
* @param {String} type - 面板类别
* @return {String}
*/
Layout.prototype.getExpandHtml = function(type) {
var ret = '',
className = '',
faClassName = '';
switch (type) {
case 'left':
className = "panel-expand panel-expand-left";
faClassName = "fa fa-angle-double-right";
break;
case 'top':
className = "panel-expand panel-expand-top";
faClassName = "fa fa-angle-double-down";
break;
case 'right':
className = "panel-expand panel-expand-right";
faClassName = "fa fa-angle-double-left";
break;
case 'bottom':
className = "panel-expand panel-expand-bottom";
faClassName = "fa fa-angle-double-up";
break;
}
return '<div class="' + className + '"><span class="' + faClassName + '" role="show" data-type="' + type + '"></span></div>';
};
/**
* 设置所有面板尺寸
* @return {Void}
*/
Layout.prototype.setSize = function() {
var $parent = this.$parent,
width = $parent.width(),
height = $parent.height(),
info = this.getPanelsInfo(),
t = 0,
l = 0,
w = 0,
h = 0;
if ($parent[0].tagName.toLowerCase() == 'body') {
$parent.addClass('k-layout-body');
height = this.$win.height();
}
this.$layout.css({ width: width, height: height });
if (info.top) {
info.top.$panel.css({ height: info.top.height, width: '100%' });
info.top.setBodyHeight();
if (!info.top.isHide) {
h += info.top.height;
} else {
h += info.top.expandHeight;
}
}
//计算中间面板距离顶部距离
t += h;
if (info.bottom) {
info.bottom.$panel.css({ height: info.bottom.height, width: '100%', top: 'none' });
info.bottom.setBodyHeight();
if (!info.bottom.isHide) {
info.bottom.$panel.css("bottom", 0);
h += info.bottom.height;
} else {
info.bottom.$panel.css("bottom", -info.bottom.height);
h += info.bottom.expandHeight;
}
}
//计算中间面板的高度
h = height - h;
if (info.left) {
info.left.$panel.css({ width: info.left.width, top: t, height: h });
info.left.setBodyHeight();
info.left.$expand.css({ top: t, height: h });
if (!info.left.isHide) {
w += info.left.width;
l += w;
} else {
w += info.left.expandWidth;
l += w;
}
}
if (info.right) {
info.right.$panel.css({ width: info.right.width, top: t, height: h, left: 'none' });
info.right.setBodyHeight();
info.right.$expand.css({ top: t, height: h });
if (!info.right.isHide) {
info.right.$panel.css('right', 0);
w += info.right.width;
} else {
info.right.$panel.css('right', -info.right.width);
w += info.right.expandWidth;
}
}
if (info.center) {
w = width - w;
info.center.$panel.css({ top: t, left: l, width: w, height: h });
info.center.setBodyHeight();
}
};
/**
* 获取所有面板相关信息
* @param {String} type - 面板类别
* @return {Object}
*/
Layout.prototype.getPanelsInfo = function(type) {
var ret = {};
this.$panels.each(function() {
var $panel = $(this),
$expand = $.data($panel[0], 'expand'),
panel = $.data($panel[0], 'panel'),
type = $panel.attr('data-type');
ret[type] = {
left: $panel.position().left,
top: $panel.position().top,
width: $panel.outerWidth(),
height: $panel.outerHeight(),
isHide: $panel.attr('data-ishide') == 'true',
$panel: $panel,
$expand: $expand,
panel: panel,
expandWidth: $expand.outerWidth(),
expandHeight: $expand.outerHeight(),
setBodyHeight: function() {
if (panel) {
panel.setBodyHeight();
}
}
};
});
if (type) {
return ret[type];
}
return ret;
};
/**
* 全局初始化
* @return {Void}
*/
Layout.Global = function($elms) {
$elms = $elms || $('div[data-module=layout]');
$elms.each(function() {
var $el = $(this),
options = $el.attr('data-options'),
onShow = $el.attr('data-onshow'),
onHide = $el.attr('data-onhide'),
data = $.data($el[0], 'layout');
if (!data) {
if (options && options.length > 0) {
options = eval('(0,' + options + ')');
}
onShow = onShow && onShow.length > 0 ? eval('(0,' + onShow + ')') : $.noop;
onHide = onHide && onHide.length > 0 ? eval('(0,' + onHide + ')') : $.noop;
data = new Layout($el, options);
data.on('show', function(info) {
onShow.call(this, info);
}).on('hide', function(info) {
onHide.call(this, info);
});
$.data($el[0], 'layout', data);
}
});
};
return Layout;
});
|
function countMisorderedPairs(pairs = []) {
let count = 0;
if (pairs.length > 0) {
pairs.reduce((pair1, pair2) => {
if (pair2 > pair1) {
count++;
}
return pair2;
})
}
return count;
}
console.log(countMisorderedPairs([1, 3, 2, 5, 4]))
|
import './assets/css/App.css';
import React,{useState,useEffect} from 'react';
import Inicio from './Inicio'
import MenuVar from './Componentes/MenuVar'
import TodoList from './Componentes/TodoList'
import Form from './Componentes/Form'
import {Modal} from 'reactstrap';
import firebase from './firebase';
import ListaAmigos from './Componentes/ListaAmigos';
function App() {
const [user,setUser]=useState ([]);/*Usuario actual*/
const [todo,setTodos]=useState ([]);/*Publicaciones*/
const [inputText,setInputText] = useState ("");/*Nuevo Post*/
const [ingreso,setIngreso]=useState (true);/*Abrir y cerrar Inicio*/
const [ListaUsuarios,setListaUsuarios]=useState ([]);/*Lista Usuarios*/
useEffect (()=>{
const todoRef=firebase.database().ref('User');
todoRef.on("value",(snapshot)=>{
const usuarios=snapshot.val();
const usuariosLista=[];
for(let id in usuarios ){
usuariosLista.push(usuarios[id]);
}
console.log(usuariosLista);
setListaUsuarios(usuariosLista);
});
const todoReff=firebase.database().ref('Apunte');
todoReff.on("value",(snapshot)=>{
const Apuntes=snapshot.val();
const ApuntesLista=[];
for(let id in Apuntes){
ApuntesLista.push(Apuntes[id]);
}
console.log(ApuntesLista)
setTodos(ApuntesLista);
});
},[]);
return (
<div className="App">
<header>
<MenuVar setIngreso={setIngreso}/>
</header>
<Modal isOpen={ingreso}>
<Inicio user={user} setUser={setUser} setIngreso={setIngreso} ListaUsuarios={ListaUsuarios}/>
</Modal>
<div id="Aver">
<div id="Aver2">
<Form todo={todo} setTodos={setTodos} setInputText={setInputText} inputText={inputText} user={user} />
<TodoList todo={todo} user={user}/>
</div>
<ListaAmigos ListaUsuarios={ListaUsuarios} user={user} />
</div>
</div>
);
}
export default App;
|
var morseDictionary = {
".-": "A",
"-...": "B",
"-.-.": "C",
"-..": "D",
".": "E",
"..-.": "F",
"--.": "G",
"....": "H",
".." : "I",
".---": "J",
"-.-": "K",
".-..": "L",
"--": "M",
"-.": "N",
"---": "O",
".--.": "P",
"--.-": "Q",
".-.": "R",
"...": "S",
"-": "T",
"..-": "U",
"...-": "V",
".--": "W",
"-..-": "X",
"-.--": "Y",
"--..": "Z",
".---": "1",
"..---": "2",
"...--": "3",
"....-": "4",
".....": "5",
"-....": "6",
"--...": "7",
"---..": "8",
"----.": "9",
"-----": "0",
"---." : playCurrentText,
"----": backspace,
".-.-": deleteAll,
"..--": takeSuggestion
};
// Switch constants
var DOT = 32;
var DASH = 13;
var PLAY = "---.";
var DELETE = "----";
var CLEAR = ".-.-";
var SUGGEST = "..--";
// User's timing for different spacing
var EL_SPACE;
var CHAR_SPACE;
var WORD_SPACE;
var ESCS_DIVIDE;
var CSWS_DIVIDE;
// User's chosen speaking voice
var LANGUAGE = "UK English Female";
// Timing variables
var spaceTimer = null;
var timerRunning = false;
var timeouts = [];
// Menu variables
var menuVisible = false;
var menuCurrItem = -1;
var items = $('.menuItem');
// Audio elements
var dotAudio = document.createElement('audio');
var dashAudio = document.createElement('audio');
// Keep track of word
var word = "";
// Keep track of backspacing
var menuOpen = false;
$(document).ready(function() {
// Preload audio elements
dotAudio.src = './data/dot.wav'
dotAudio.preload='auto';
dotAudio.load();
dashAudio.src = './data/dash.wav'
dashAudio.preload='auto';
dashAudio.load();
$(".progress-bar").addClass("notransition");
$.get("/getAverageSpaces/" + $('#uid').text().trim(), function(data) {
EL_SPACE = Number(JSON.stringify(data.aveElSpace))
CHAR_SPACE = Number(JSON.stringify(data.aveCharSpace))
WORD_SPACE = Number(JSON.stringify(data.aveWordSpace))
ESCS_DIVIDE = (EL_SPACE + CHAR_SPACE) / 2.0;
CSWS_DIVIDE = (CHAR_SPACE + WORD_SPACE) / 2.0;
})
.then(function() {
$.get("/api/v1/getLanguage/" + $('#uid').text().trim(), function(data) {
LANGUAGE = (String(JSON.stringify(data.language))).slice(1, -1);
});
})
.then(function() {
spaceTimer = new Stopwatch();
/*
Listen for switch inputs
*/
document.addEventListener("keydown", function(event) {
if (event.which == DOT || event.which == DASH) {
if (!menuVisible) {
resetProgressBar();
}
if (timerRunning) {
for (var i = 0; i < timeouts.length; i++) {
clearTimeout(timeouts[i]);
}
var spaceMs = spaceTimer.stop();
timerRunning = false;
}
if (event.which == DOT) {
playDotSound();
}
if (event.which == DASH) {
playDashSound();
}
}
});
document.addEventListener("keyup", function(event) {
if (event.which == DOT || event.which == DASH) {
if (!menuVisible) {
startProgressBar();
}
if (event.which == DOT) {
if(menuVisible) {
scroll();
} else {
word = append(word, ".");
breakStarted = false;
if(!menuOpen) {
resetTime();
}
}
} else if (event.which == DASH) {
if(menuVisible) {
select();
} else {
word = append(word, "-");
breakStarted = false;
if(!menuOpen) {
resetTime();
}
}
}
}
});
/*
Add functions to buttons.
*/
$('#btn-play').click(function() {
playCurrentText();
});
$('#btn-delete').click(function() {
backspace();
});
$('#btn-suggest').click(function() {
if (!$('#btn-suggest').hasClass('disabled')) {
takeSuggestion();
}
});
$('#btn-close').click(function() {
closeMenu();
});
$('#btn-delAll').click(function() {
deleteAll();
});
/*
Disables textarea default action.
*/
$('textarea').on('keydown', function (e) {
e.preventDefault();
});
});
});
// TRANSLATION ///////////////////////////////////////////////////////////
function translate() {
$('#translation').append(morseDictionary[word]);
getSuggestions();
word = "";
}
// PLAY //////////////////////////////////////////////////////////////////
function play(sentence) {
responsiveVoice.speak(sentence, LANGUAGE);
}
function playCurrentText() {
play($('#translation').text());
}
// DELETE ///////////////////////////////////////////////////////////////
function backspace() {
console.log('deletingc')
$('#translation').text($('#translation').text().slice(0, -1));
if($('#translation').val().length == 0) {
$('#suggestionBox').text("TEXT SUGGESTION").toUpperCase();
}
}
function deleteAll() {
$('#translation').text('');
$('#suggestionBox').text("TEXT SUGGESTION").toUpperCase();
}
// TEXT SUGGESTIONS //////////////////////////////////////////////////////
// Suggest words/phrases to the user depending on what they have written so far
function getSuggestions() {
var wordsWritten = $('#translation').val().split(" ");
var lastWord = wordsWritten[wordsWritten.length-1];
if (lastWord != "") {
getSuggestion(lastWord.toLowerCase());
}
}
// If the word written is an abbreviation, then suggest the full version
// Otherwise, call the suggestions API to get a suggested word
function getSuggestion(word) {
var abbrUrl = "/checkAbbreviation/" + $('#uid').text().trim() + "/" + word;
$.get(abbrUrl).then(function(data) {
if (data.exists) {
showSuggestion(data.full);
} else {
var suggUrl = "https://api.datamuse.com/sug?s=" + word
$.get(suggUrl, function(data) {
if (data.length > 0) {
showSuggestion(data[0].word);
} else {
hideSuggestion();
}
});
}
});
}
function showSuggestion(sugg) {
$('#btn-suggest').removeClass('disabled');
$('#suggestionBox').html(sugg);
}
function hideSuggestion() {
$('#btn-suggest').addClass('disabled');
$('#suggestionBox').html(" ");
}
function takeSuggestion() {
// get the words already written in the sentence box
var wordsWritten = $('#translation').val().trim().split(" ");
console.log(wordsWritten)
// since the suggestion corresponds to just the late word, take everything
// else to go in the new sentence
var allButLastWord = wordsWritten.slice(0, -1);
var newSentence = allButLastWord.join(" ");
if (allButLastWord.length > 0) {
newSentence += " ";
}
// get the suggested word and add it to the new sentence
var suggestedWord = $('#suggestionBox').text().toUpperCase();
newSentence += suggestedWord;
// update the textbox with the new sentence
if(suggestedWord != "TEXT SUGGESTION") {
$('#translation').text(newSentence);
}
}
// PROGRESS BAR //////////////////////////////////////////////////////////
function startProgressBar() {
$(".progress-bar").animate({
width: "100%"
}, WORD_SPACE);
}
function resetProgressBar() {
$(".progress-bar").stop(true, false);
$(".progress-bar").css({
'background-color': '#4CAF50'
});
$(".progress-bar").animate({
width: "0%"
}, 0);
$(".progress-bar").stop(true, false);
$("#progressText").text("Element Space");
}
function stopProgressBar() {
$(".progress-bar").css({ width: "0%"});
}
function resetTime() {
spaceTimer.reset();
spaceTimer.start();
timerRunning = true;
timeouts.push(setTimeout(function() {
resetRealTimeText();
translate();
$(".progress-bar").css({
'background-color': '#3F51B5'
});
$("#progressText").text("Character Space");
}, ESCS_DIVIDE));
timeouts.push(setTimeout(function() {
translate();
addSpace();
$(".progress-bar").css({
'background-color': '#F44336'
});
$("#progressText").text("Word Space");
}, CSWS_DIVIDE));
}
function resetRealTimeText() {
$('#text').text('');
$('#correspondingWord').text('');
}
// AUDIO /////////////////////////////////////////////////////////////////
function playDotSound() {
var dotSound = dotAudio.cloneNode();
dotSound.play();
}
function playDashSound() {
var dashSound = dashAudio.cloneNode();
dashSound.play();
}
// HELPER FUNCTIONS //////////////////////////////////////////////////////
// Take the user's input and add it onto the word they are writing
function append(morseCode, input) {
$('#text').append(input);
morseCode += input;
if(morseDictionary[morseCode]) {
if (morseCode == PLAY) {
$('#correspondingWord').text("(PLAY)");
} else if (morseCode == DELETE) {
$('#correspondingWord').text("(DELETE)");
} else if (morseCode == CLEAR) {
$('#correspondingWord').text("(CLEAR)");
} else if (morseCode == SUGGEST) {
$('#correspondingWord').text("(SUGGEST)");
} else {
$('#correspondingWord').text(morseDictionary[morseCode]);
}
}
return morseCode;
}
function addSpace() {
var lastChar = $('#translation').val().slice(-1);
if (lastChar != " ") {
$('#translation').append(" ")
}
}
|
import state from "@project_src/store/modules/kanban/state";
import getters from "@project_src/store/modules/kanban/getters";
import mutations from "@project_src/store/modules/kanban/mutations";
import actions from "@project_src/store/modules/kanban/actions";
export default {
namespaced: true,
state,
getters,
mutations,
actions,
};
|
import React, {Component} from "react";
import {
ENDPOINT_GET_USER_INFO,
ENDPOINT_UPDATE_USER_INFO,
ENDPOINT_UPDATE_USER_MAIL,
makeAPIRequest
} from "../../app/services/apiService";
import {simpleAlert} from "../../app/services/alertService";
import {Body, Container, Content, Footer, FooterTab, Header, Title, Input, Button, Text} from "native-base";
export default class UserInfo extends Component {
constructor(props) {
super(props);
this.state = {
firstName: "",
lastName: "",
mail: "",
country: "",
birthday: ""
};
this.getUserInfo().then((userInfo) => {
if (userInfo) {
this.setState(userInfo);
}
});
}
getUserInfo() {
return makeAPIRequest(ENDPOINT_GET_USER_INFO)
.then((responseJson) => {
console.log(responseJson);
return responseJson;
})
.catch((error) => {
console.error(error);
return null;
});
}
submit() {
this.submitInfo();
}
submitInfo() {
const {firstName, lastName, country, birthday, mail} = this.state;
if (!(firstName && lastName && country && birthday && mail)) {
simpleAlert("Error", "All fields must be filled.", "OK");
return;
}
const body = JSON.stringify({
firstName: firstName,
lastName: lastName,
country: country,
birthday: birthday
});
makeAPIRequest(ENDPOINT_UPDATE_USER_INFO, body)
.then((responseJSON) => {
if (responseJSON["opcode"] === 200)
this.submitMail(mail);
else {
simpleAlert("Update informations error", responseJSON.message + ": " + responseJSON.field, "Try again");
}
}).catch((error) => {
console.error(error);
});
}
submitMail(mail) {
const body = JSON.stringify({
mail: mail
});
makeAPIRequest(ENDPOINT_UPDATE_USER_MAIL, body)
.then((responseJSON) => {
if (responseJSON["opcode"] === 200) {
simpleAlert("Update successful !", null, "OK");
this.props.navigation.goBack();
} else {
simpleAlert("Update mail error", responseJSON.message + ": " + responseJSON.field, "Try again");
}
}).catch((error) => {
console.error(error);
});
}
render() {
const {firstName, lastName, mail, country, birthday} = this.state;
return (
<Container>
<Header>
<Body>
<Title>Personal informations</Title>
</Body>
</Header>
<Content>
<Input
value={firstName}
onChangeText={firstName => this.setState({firstName})}
placeholder="First Name"
returnKeyType="next"
/>
<Input
value={lastName}
onChangeText={lastName => this.setState({lastName})}
placeholder="Last Name"
returnKeyType="next"
/>
<Input
value={mail}
onChangeText={mail => this.setState({mail})}
placeholder="mail"
returnKeyType="next"
/>
<Input
value={country}
onChangeText={country => this.setState({country})}
placeholder="Country"
returnKeyType="next"
/>
<Input
value={birthday}
onChangeText={birthday => this.setState({birthday})}
placeholder="Birthday (yyyy-mm-dd)"
returnKeyType="go"
/>
</Content>
<Footer>
<FooterTab>
<Button onPress={this.submit.bind(this)} full>
<Text>Save</Text>
</Button>
</FooterTab>
</Footer>
</Container>
);
}
}
|
const { Router } = require('express');
const { pedidosGet, pedidosPost, pedidosPut, pedidosDelete } = require('../controllers/pedidos');
const router = Router();
router.get('/', pedidosGet);
router.post('/', pedidosPost);
router.put('/:id', pedidosPut);
router.delete('/', pedidosDelete );
module.exports = router;
|
const http = require('http')
const url='http://www.theplantlist.org/'
//const url='http://www.w3hools.com/' --for error
//with https, code works for https sites.
/*const http = require('https')
const url='https://www.google.com/'
*/
http.get(url,(response)=>{
let buffVar=''
let count=0
response.on('data', (chunk)=>{
buffVar+=chunk
++count
})
response.on('end',()=>{
console.log(buffVar,`\nno of chunks ${count}`)
console.log(`Length of response: ${buffVar.length}`)
})
}).on('error',(error)=>{
console.error(`Got error: ${error.message}`)
})
|
export const A = {
FAILURE: "FAILURE",
ALERT_ERROR: "ALERT_ERROR",
CREATE_COURSE: "CREATE_COURSE",
LOAD_COURSES_SUCCESS: "LOAD_COURSES_SUCCESS",
LOAD_NAVIGATION_REQUEST: "LOAD_NAVIGATION_REQUEST",
LOAD_NAVIGATION_SUCCESS: "LOAD_NAVIGATION_SUCCESS",
LOAD_NAVIGATION_FAILURE: "LOAD_NAVIGATION_FAILURE",
GET_SERVICE_DATA_REQUEST: 'GET_SERVICE_DATA_REQUEST',
GET_SERVICE_DATA_SUCCESS: 'GET_SERVICE_DATA_SUCCESS',
GET_SERVICE_DATA_FAILURE: 'GET_SERVICE_DATA_FAILURE',
};
|
import { Router } from 'express';
import OrdersController from './app/controllers/OrdersController';
const routes = new Router();
routes.get('/', OrdersController.index);
routes.post('/', OrdersController.store);
export default routes;
|
/**
* Created by andy on 1/2/15.
*/
(function(){
var CONSTANTS={
TYPE_NODE: "NODE",
TYPE_LINK: "LINK"
};
var MSG_TYPE={
EVENT_REFRESH_TOPO:"EVENT_REFRESH_TOPO"
};
var MessageBus=function(){
this.__messages = {};
};
MessageBus.prototype.publish=function(msgType, data){
var msgTypeList = this.__messages[msgType];
if($.isArray(msgTypeList)){
$.each(msgTypeList,function(_, obj){
obj.onEvent.call(obj, {
msgType: msgType,
data:data
});
})
}
};
MessageBus.prototype.subscribe = function (msgType,obj) {
var msgTypeList = this.__messages[msgType];
if (!$.isArray(msgTypeList)){
this.__messages[msgType] = [];
msgTypeList = this.__messages[msgType];
}
msgTypeList.push(obj);
};
GrantTopo.MessageBus = MessageBus;
GrantTopo.MSG_TYPE = MSG_TYPE;
GrantTopo.CONSTANTS = CONSTANTS;
})();
|
var arr = ["Есть", "жизнь", "на", "Марсе"];
var arrLength = arr.map(function(name) {
return name.length;
});
console.log(arrLength);
|
import React, { Component } from "react";
import { Menu, Sidebar, Checkbox, Grid, Segment } from "semantic-ui-react";
import Channels from "./Channels";
import UserPanel from "./UserPanel";
import DirectMessages from "./DirectMessages";
import Starred from "./Starred";
export default class SidePanel extends Component {
state = {
visible: false,
width: "",
height: "",
};
getWindowDimensions = () => {
const { innerWidth: width, innerHeight: height } = window;
return this.setState({ width, height });
};
render() {
const { visible, width } = this.state;
const { currentUser, primaryColor, currentChannel } = this.props;
return (
<Menu
size="large"
inverted
fixed="left"
vertical
style={{ background: primaryColor, fontSize: "1.2rem" }}
className="sidepanel--menu"
>
<UserPanel
primaryColor={primaryColor}
currentUser={currentUser}
currentChannel={currentChannel}
className="side-panel-comp"
/>
<Starred currentUser={currentUser} />
<Channels currentUser={currentUser} />
<DirectMessages currentUser={currentUser} />
</Menu>
);
}
}
|
import {
MESSAGES_LOADED_SUCCESS,
MESSAGES_LOAD,
MESSAGES_LOAD_FAIL,
MESSAGE_LOAD,
MESSAGE_INFO_LOADED_SUCCESS,
MESSAGE_INFO_LOADING_FAIL,
MESSAGE_COUNTER_SUCCESS
} from '../actions/types';
const INITIAL_STATE = {
messages: [],
error: null,
loading: false,
loadingMessageInfo: true,
message: null,
messageError: null,
messagesCounter: 0
}
export default (state = INITIAL_STATE, action) => {
switch(action.type) {
case MESSAGES_LOADED_SUCCESS:
var messages = state.messages;
if (action.offset > 0) {
messages = [...state.messages, ...action.payload]
} else {
messages = action.payload;
}
console.log('MESSAGES_LOADED_SUCCESS', messages, action.payload);
return {...state, messages: messages, loading: false};
case MESSAGES_LOAD_FAIL:
return {...state, error: action.payload};
case MESSAGES_LOAD:
return {...state, loading: true};
case MESSAGE_LOAD:
return {...state, loadingMessageInfo: true};
case MESSAGE_INFO_LOADED_SUCCESS:
console.log(MESSAGE_INFO_LOADED_SUCCESS, action.payload)
return {...state, loadingMessageInfo: false, message: action.payload};
case MESSAGE_INFO_LOADING_FAIL:
return {...state, loadingMessageInfo: false, messageError: action.payload};
case MESSAGE_COUNTER_SUCCESS:
return {...state, messagesCounter: action.payload}
default: return state;
}
}
|
var NAVTREEINDEX6 =
{
"class_otter_1_1_u_i_1_1_u_i_list_menu.html#a7ed8217cee07fd82b7ca4cb793913660":[1,0,1,0,3,0],
"class_otter_1_1_u_i_1_1_u_i_list_menu.html#a81d0c972b242e96151109034d984e579":[1,0,1,0,3,4],
"class_otter_1_1_u_i_1_1_u_i_list_menu.html#af91efb317a7bf9851961ef270f5aa2dd":[1,0,1,0,3,1],
"class_otter_1_1_u_i_1_1_u_i_manager.html":[1,0,1,0,4],
"class_otter_1_1_u_i_1_1_u_i_manager.html#a1a7a5fe37753f006f7e590a1e1a45d70":[1,0,1,0,4,9],
"class_otter_1_1_u_i_1_1_u_i_manager.html#a1f3a9cfc392179b6d562ff49fb276eeb":[1,0,1,0,4,7],
"class_otter_1_1_u_i_1_1_u_i_manager.html#a312d2cb901c70414f4e81f20ece9084e":[1,0,1,0,4,3],
"class_otter_1_1_u_i_1_1_u_i_manager.html#a486c0b56faf8006e874c8598371116ac":[1,0,1,0,4,6],
"class_otter_1_1_u_i_1_1_u_i_manager.html#a5ff3f2c14fcb0a953908a379533b19b7":[1,0,1,0,4,13],
"class_otter_1_1_u_i_1_1_u_i_manager.html#a866406edd897bca245f7825350b8fc86":[1,0,1,0,4,12],
"class_otter_1_1_u_i_1_1_u_i_manager.html#a876469f86bab5f1bcabcba8a9541c3df":[1,0,1,0,4,2],
"class_otter_1_1_u_i_1_1_u_i_manager.html#a992dfdd147716bc912a31016fe0eb7c9":[1,0,1,0,4,11],
"class_otter_1_1_u_i_1_1_u_i_manager.html#ab5ad3662f46e4180092e32d5fd54d6f7":[1,0,1,0,4,10],
"class_otter_1_1_u_i_1_1_u_i_manager.html#ab7616a89f96588c057076f804b55a14c":[1,0,1,0,4,5],
"class_otter_1_1_u_i_1_1_u_i_manager.html#abc4a8e78d7fefb4142b4a5470c4cd79d":[1,0,1,0,4,1],
"class_otter_1_1_u_i_1_1_u_i_manager.html#ac3ba5737ca4f7e492ec13e23790d90b2":[1,0,1,0,4,8],
"class_otter_1_1_u_i_1_1_u_i_manager.html#ae652e3cc9aefda2e8622226ed72b319a":[1,0,1,0,4,0],
"class_otter_1_1_u_i_1_1_u_i_manager.html#af5970770051c0dcf0bfb9392e191ed98":[1,0,1,0,4,4],
"class_otter_1_1_u_i_1_1_u_i_menu.html":[1,0,1,0,5],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a0ce9b53d225e2a8abf37025bf3b8d580":[1,0,1,0,5,9],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a1047e12ac37d933188afc2d58679d7e6":[1,0,1,0,5,0],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a1609c3dfe7fb5aacd99b7209c727dab6":[1,0,1,0,5,3],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a256adce22286592b44d4a83579963ffe":[1,0,1,0,5,5],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a31bf739a8034916be99dfa923b3a4d4d":[1,0,1,0,5,7],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a33a879da2271c7b977e8da7fa328beb6":[1,0,1,0,5,2],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a45c2c43b9ed0ca98dc160b77714eeb98":[1,0,1,0,5,4],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a56ade03ae3f0e9edf9bd7b1da950c0f0":[1,0,1,0,5,13],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a61a9561b76ea0dc6d4b04fec700820f0":[1,0,1,0,5,1],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a68fb5b6ec6f7664010904b699d48961b":[1,0,1,0,5,11],
"class_otter_1_1_u_i_1_1_u_i_menu.html#a8aa10ef85ed082a6d24f614764c6830b":[1,0,1,0,5,8],
"class_otter_1_1_u_i_1_1_u_i_menu.html#abdf7f61f3d15ab697aa2bced6ce5b2d0":[1,0,1,0,5,10],
"class_otter_1_1_u_i_1_1_u_i_menu.html#adb0d7208990676fe11bce3ce1f9d75b5":[1,0,1,0,5,12],
"class_otter_1_1_u_i_1_1_u_i_menu.html#af47b7bf1214c4ec375a5b08ffa9d5bbb":[1,0,1,0,5,14],
"class_otter_1_1_u_i_1_1_u_i_menu.html#afd70a65c5f046505a89766f8b0ae75aa":[1,0,1,0,5,6],
"class_otter_1_1_u_i_1_1_u_i_value_menu.html":[1,0,1,0,6],
"class_otter_1_1_u_i_1_1_u_i_value_menu.html#a0963e1e779af5bfc8968c4e5d2cc3386":[1,0,1,0,6,5],
"class_otter_1_1_u_i_1_1_u_i_value_menu.html#a1d59a1b6de36b5ef26ef4eb884a4cee7":[1,0,1,0,6,1],
"class_otter_1_1_u_i_1_1_u_i_value_menu.html#a205a57f64231e119052217e361599d88":[1,0,1,0,6,0],
"class_otter_1_1_u_i_1_1_u_i_value_menu.html#a5f2480150d8b8291197353a031825877":[1,0,1,0,6,4],
"class_otter_1_1_u_i_1_1_u_i_value_menu.html#ace7e8ce83e1cbf49684e0c7aecd7aef5":[1,0,1,0,6,2],
"class_otter_1_1_u_i_1_1_u_i_value_menu.html#adc2436aa6f919d9bc94954e25ec5dac2":[1,0,1,0,6,3],
"class_otter_1_1_util.html":[1,0,1,81],
"class_otter_1_1_util.html#a1746f300f86b0632259328a35b0e185f":[1,0,1,81,4],
"class_otter_1_1_util.html#a245e16231b28772d99f756ccf296f935":[1,0,1,81,2],
"class_otter_1_1_util.html#a721b5a4e1daf5314c28f6a8acaee5857":[1,0,1,81,7],
"class_otter_1_1_util.html#a76d86a3617da720cc8e353935be3a180":[1,0,1,81,1],
"class_otter_1_1_util.html#a8ae4fb43a373155d84ec305b3239f72e":[1,0,1,81,9],
"class_otter_1_1_util.html#a8ef2e9c02c6eaada8b8c8652215585d1":[1,0,1,81,6],
"class_otter_1_1_util.html#aa68aedb3eec0804969bb6c7bbc522bcb":[1,0,1,81,5],
"class_otter_1_1_util.html#ab8343bcda490da29f6226e6d10cffd52":[1,0,1,81,0],
"class_otter_1_1_util.html#ac42cddb6dff2ceaaf1e9a52a00cb26bc":[1,0,1,81,3],
"class_otter_1_1_util.html#aec0116b81eb7bfdb0dfc4b17f0768ffe":[1,0,1,81,8],
"class_otter_1_1_vert.html":[1,0,1,54],
"class_otter_1_1_vert.html#a053b6912868d7ec7fc79c7cc354002b7":[1,0,1,54,5],
"class_otter_1_1_vert.html#a05f4b3968929908c51fe2b9f08fd38e1":[1,0,1,54,8],
"class_otter_1_1_vert.html#a13e0f25dfa5c5b3ada9cbcfd2c737785":[1,0,1,54,0],
"class_otter_1_1_vert.html#a269b777bd13809ea7e463805d382c371":[1,0,1,54,2],
"class_otter_1_1_vert.html#a26ad2ce042d1dab5f0f31e272f9b3814":[1,0,1,54,3],
"class_otter_1_1_vert.html#a51212c76092180f641ca233d291575a1":[1,0,1,54,4],
"class_otter_1_1_vert.html#a5853515f7450e10bad5f2b1d30b2935c":[1,0,1,54,1],
"class_otter_1_1_vert.html#a611224ce50012ffec0e67cc01ec6f50b":[1,0,1,54,7],
"class_otter_1_1_vert.html#aac1d430252bd0fe7c3c270686be0da0c":[1,0,1,54,10],
"class_otter_1_1_vert.html#aaf29dfcf2164c0a02d7e0049c3f3a02b":[1,0,1,54,12],
"class_otter_1_1_vert.html#ab3045e63a631c637c1017a1c77e6b3a5":[1,0,1,54,9],
"class_otter_1_1_vert.html#aefc44779935d5839e6b4e9df2c6e155b":[1,0,1,54,6],
"class_otter_1_1_vert.html#afc67030b640f0e1c1e7beb94b15b43ac":[1,0,1,54,11],
"class_otter_1_1_vertices.html":[1,0,1,55],
"class_otter_1_1_vertices.html#a0142ab082dbeb406c295fbf50af0ab93":[1,0,1,55,8],
"class_otter_1_1_vertices.html#a037a85c1956aad859d64c5ecf7cd577d":[1,0,1,55,7],
"class_otter_1_1_vertices.html#a138b5173fc80322e864498b64c3da9c6":[1,0,1,55,11],
"class_otter_1_1_vertices.html#a2875708f577e7d2a0c57a0904f2b1c45":[1,0,1,55,5],
"class_otter_1_1_vertices.html#a3bfd4f9d1640a463204441a4a833cc43":[1,0,1,55,6],
"class_otter_1_1_vertices.html#a3d7a5dc20d7e0c24e3980b8353162725":[1,0,1,55,9],
"class_otter_1_1_vertices.html#a453046f021b7fa8ab07719ec46b0aee0":[1,0,1,55,12],
"class_otter_1_1_vertices.html#a8579a74ddbe56b44274972ffd98bacc8":[1,0,1,55,1],
"class_otter_1_1_vertices.html#a94d9029c0a6ff2199b695a7f74f6c6bf":[1,0,1,55,13],
"class_otter_1_1_vertices.html#a9c265eebee3dfc0ca1f844d2a7336ced":[1,0,1,55,2],
"class_otter_1_1_vertices.html#ab28143d56e78bd94a7505d428edbc92b":[1,0,1,55,0],
"class_otter_1_1_vertices.html#acec267800c82a499599b813f3565f680":[1,0,1,55,10],
"class_otter_1_1_vertices.html#ad8810cf85091904403e342b77231138e":[1,0,1,55,3],
"class_otter_1_1_vertices.html#adc0ee2cfc3ebb4615a9cd9e8b49e43ac":[1,0,1,55,14],
"class_otter_1_1_vertices.html#ae81f8bf4f58a7986f6b9c6a0093b7a57":[1,0,1,55,4],
"classes.html":[1,1],
"functions.html":[1,3,0,0],
"functions.html":[1,3,0],
"functions_0x62.html":[1,3,0,1],
"functions_0x63.html":[1,3,0,2],
"functions_0x64.html":[1,3,0,3],
"functions_0x65.html":[1,3,0,4],
"functions_0x66.html":[1,3,0,5],
"functions_0x67.html":[1,3,0,6],
"functions_0x68.html":[1,3,0,7],
"functions_0x69.html":[1,3,0,8],
"functions_0x6a.html":[1,3,0,9],
"functions_0x6b.html":[1,3,0,10],
"functions_0x6c.html":[1,3,0,11],
"functions_0x6d.html":[1,3,0,12],
"functions_0x6e.html":[1,3,0,13],
"functions_0x6f.html":[1,3,0,14],
"functions_0x70.html":[1,3,0,15],
"functions_0x71.html":[1,3,0,16],
"functions_0x72.html":[1,3,0,17],
"functions_0x73.html":[1,3,0,18],
"functions_0x74.html":[1,3,0,19],
"functions_0x75.html":[1,3,0,20],
"functions_0x76.html":[1,3,0,21],
"functions_0x77.html":[1,3,0,22],
"functions_0x78.html":[1,3,0,23],
"functions_0x79.html":[1,3,0,24],
"functions_func.html":[1,3,1,0],
"functions_func.html":[1,3,1],
"functions_func_0x62.html":[1,3,1,1],
"functions_func_0x63.html":[1,3,1,2],
"functions_func_0x64.html":[1,3,1,3],
"functions_func_0x65.html":[1,3,1,4],
"functions_func_0x66.html":[1,3,1,5],
"functions_func_0x67.html":[1,3,1,6],
"functions_func_0x68.html":[1,3,1,7],
"functions_func_0x69.html":[1,3,1,8],
"functions_func_0x6a.html":[1,3,1,9],
"functions_func_0x6b.html":[1,3,1,10],
"functions_func_0x6c.html":[1,3,1,11],
"functions_func_0x6d.html":[1,3,1,12],
"functions_func_0x6e.html":[1,3,1,13],
"functions_func_0x6f.html":[1,3,1,14],
"functions_func_0x70.html":[1,3,1,15],
"functions_func_0x72.html":[1,3,1,16],
"functions_func_0x73.html":[1,3,1,17],
"functions_func_0x74.html":[1,3,1,18],
"functions_func_0x75.html":[1,3,1,19],
"functions_func_0x76.html":[1,3,1,20],
"functions_func_0x77.html":[1,3,1,21],
"functions_func_0x78.html":[1,3,1,22],
"functions_prop.html":[1,3,3,0],
"functions_prop.html":[1,3,3],
"functions_prop_0x62.html":[1,3,3,1],
"functions_prop_0x63.html":[1,3,3,2],
"functions_prop_0x64.html":[1,3,3,3],
"functions_prop_0x65.html":[1,3,3,4],
"functions_prop_0x66.html":[1,3,3,5],
"functions_prop_0x67.html":[1,3,3,6],
"functions_prop_0x68.html":[1,3,3,7],
"functions_prop_0x69.html":[1,3,3,8],
"functions_prop_0x6a.html":[1,3,3,9],
"functions_prop_0x6c.html":[1,3,3,10],
"functions_prop_0x6d.html":[1,3,3,11],
"functions_prop_0x6e.html":[1,3,3,12],
"functions_prop_0x6f.html":[1,3,3,13],
"functions_prop_0x70.html":[1,3,3,14],
"functions_prop_0x72.html":[1,3,3,15],
"functions_prop_0x73.html":[1,3,3,16],
"functions_prop_0x74.html":[1,3,3,17],
"functions_prop_0x75.html":[1,3,3,18],
"functions_prop_0x76.html":[1,3,3,19],
"functions_prop_0x77.html":[1,3,3,20],
"functions_prop_0x78.html":[1,3,3,21],
"functions_prop_0x79.html":[1,3,3,22],
"functions_vars.html":[1,3,2],
"functions_vars.html":[1,3,2,0],
"functions_vars_0x62.html":[1,3,2,1],
"functions_vars_0x63.html":[1,3,2,2],
"functions_vars_0x64.html":[1,3,2,3],
"functions_vars_0x65.html":[1,3,2,4],
"functions_vars_0x66.html":[1,3,2,5],
"functions_vars_0x67.html":[1,3,2,6],
"functions_vars_0x68.html":[1,3,2,7],
"functions_vars_0x69.html":[1,3,2,8],
"functions_vars_0x6a.html":[1,3,2,9],
"functions_vars_0x6b.html":[1,3,2,10],
"functions_vars_0x6c.html":[1,3,2,11],
"functions_vars_0x6d.html":[1,3,2,12],
"functions_vars_0x6e.html":[1,3,2,13],
"functions_vars_0x6f.html":[1,3,2,14],
"functions_vars_0x70.html":[1,3,2,15],
"functions_vars_0x71.html":[1,3,2,16],
"functions_vars_0x72.html":[1,3,2,17],
"functions_vars_0x73.html":[1,3,2,18],
"functions_vars_0x74.html":[1,3,2,19],
"functions_vars_0x75.html":[1,3,2,20],
"functions_vars_0x76.html":[1,3,2,21],
"functions_vars_0x77.html":[1,3,2,22],
"functions_vars_0x78.html":[1,3,2,23],
"functions_vars_0x79.html":[1,3,2,24],
"hierarchy.html":[1,2],
"index.html":[],
"namespace_good_stuff.html":[1,0,0],
"namespace_good_stuff.html":[0,0,0],
"namespace_good_stuff_1_1_natural_language.html":[1,0,0,0],
"namespace_good_stuff_1_1_natural_language.html":[0,0,0,0],
"namespace_otter.html":[0,0,1],
"namespace_otter.html":[1,0,1],
"namespace_otter_1_1_u_i.html":[0,0,1,0],
"namespace_otter_1_1_u_i.html":[1,0,1,0],
"namespacemembers.html":[0,1,0],
"namespacemembers_enum.html":[0,1,1],
"namespaces.html":[0,0],
"pages.html":[],
"struct_otter_1_1_matrix.html":[1,0,1,69],
"struct_otter_1_1_matrix.html#a08eef5e2debf409786dbb5d0434450bb":[1,0,1,69,22],
"struct_otter_1_1_matrix.html#a098acd7f6b8f668497e013c6bed1056f":[1,0,1,69,27],
"struct_otter_1_1_matrix.html#a129b0bb27f513d82d25b73ff49c2c525":[1,0,1,69,12],
"struct_otter_1_1_matrix.html#a25f835c88fab87ed4b99f96e5a325dae":[1,0,1,69,0],
"struct_otter_1_1_matrix.html#a3d03191efed9f1c71a09fabf12937ea5":[1,0,1,69,20],
"struct_otter_1_1_matrix.html#a5cd925ab5a415c468c8c615d74aee05f":[1,0,1,69,17],
"struct_otter_1_1_matrix.html#a62fda3e97b11904ea8bbd010b16811e5":[1,0,1,69,21],
"struct_otter_1_1_matrix.html#a6a4c678b29cc77cdad5aa6552856c182":[1,0,1,69,29],
"struct_otter_1_1_matrix.html#a6fdb53037bff2a1e1396487672eda3a0":[1,0,1,69,30],
"struct_otter_1_1_matrix.html#a71bae24279a0ba3c25db671f0c1e00a2":[1,0,1,69,18],
"struct_otter_1_1_matrix.html#a74f7920c6d24e8567a78cafa105d5298":[1,0,1,69,16],
"struct_otter_1_1_matrix.html#a8c1274d0f1faeeb443b83ab18a39ab31":[1,0,1,69,15],
"struct_otter_1_1_matrix.html#a8e664a52d694910ca032c1b088645927":[1,0,1,69,5],
"struct_otter_1_1_matrix.html#a96922de178fd457e9c474a40dea1526d":[1,0,1,69,14],
"struct_otter_1_1_matrix.html#a9985d4b31f2f212335498a8da79396d3":[1,0,1,69,26],
"struct_otter_1_1_matrix.html#a9b541cce4badfd575c525c4d9228ed21":[1,0,1,69,28],
"struct_otter_1_1_matrix.html#a9d47b06330b967d6f3996c148eaf8df0":[1,0,1,69,19],
"struct_otter_1_1_matrix.html#a9e9e2a400b229c35c22007f2e4cdaafa":[1,0,1,69,23],
"struct_otter_1_1_matrix.html#aacce6afa32631ed0ff6bee8ece2a076b":[1,0,1,69,1],
"struct_otter_1_1_matrix.html#aafcff91de1a42dbf747558af698e902b":[1,0,1,69,2],
"struct_otter_1_1_matrix.html#ab30cbc36c3b8726f7b590bb75ca73792":[1,0,1,69,13],
"struct_otter_1_1_matrix.html#ab6d4753df9d4eff1cd1d94bd41c2742f":[1,0,1,69,25],
"struct_otter_1_1_matrix.html#abb784aa92e688da9691f6683126e0f0d":[1,0,1,69,24],
"struct_otter_1_1_matrix.html#ac8d20f976b6c3c4d2314afaed22a7536":[1,0,1,69,11],
"struct_otter_1_1_matrix.html#acbc295252556d95bf94b1b7c98322cdc":[1,0,1,69,3],
"struct_otter_1_1_matrix.html#ad24987740d9a293225bedc5774e2d466":[1,0,1,69,31],
"struct_otter_1_1_matrix.html#ad35fafff6ccdc863786dd905921c1222":[1,0,1,69,7],
"struct_otter_1_1_matrix.html#ad8d0dd97158b90a958e49a2100840805":[1,0,1,69,8],
"struct_otter_1_1_matrix.html#ad992cbc41ad395630a2d17ef2b1b82c3":[1,0,1,69,10],
"struct_otter_1_1_matrix.html#adaf89fd24087ca3b0bbedfadfd085797":[1,0,1,69,9],
"struct_otter_1_1_matrix.html#ae4dd8c8ab742bcc2e9d82b6ee8c47674":[1,0,1,69,4],
"struct_otter_1_1_matrix.html#afde4e25d8e4bef1079a3759a974e7d86":[1,0,1,69,6],
"struct_otter_1_1_point.html":[1,0,1,76],
"struct_otter_1_1_point.html#a2f2db4d54857b1076324c45785b862d4":[1,0,1,76,3],
"struct_otter_1_1_point.html#a56e36b2c44872aaf8ab4b578ee75f5f3":[1,0,1,76,0],
"struct_otter_1_1_point.html#a97c8968e4b25108ab480e7c6f5427e6d":[1,0,1,76,1],
"struct_otter_1_1_point.html#aaf2ca8be82528277b423cdf94e231e36":[1,0,1,76,4],
"struct_otter_1_1_point.html#abe634e66215846ef68352a0e091786b2":[1,0,1,76,5],
"struct_otter_1_1_point.html#ae9cbeec84ab24366a91ac956a332dcdb":[1,0,1,76,2],
"struct_otter_1_1_point.html#aeb25a8fe09bb9d4cb55097391fc1a38d":[1,0,1,76,6],
"struct_otter_1_1_quaternion.html":[1,0,1,70],
"struct_otter_1_1_quaternion.html#a05977844e66518645bfc09d1fac690b3":[1,0,1,70,6],
"struct_otter_1_1_quaternion.html#a07b325c5d2ba9d302d1652c9971f4fab":[1,0,1,70,10],
"struct_otter_1_1_quaternion.html#a0968fa4f5c2c43532202f27ecd4de8cb":[1,0,1,70,2],
"struct_otter_1_1_quaternion.html#a26b96e49f735365d94f301cb8efbbf5f":[1,0,1,70,7],
"struct_otter_1_1_quaternion.html#a51c5b91673b0bc67e9a52ab8ed5fa993":[1,0,1,70,9],
"struct_otter_1_1_quaternion.html#a5df11afec9f15ff4d25bc0c9c3465765":[1,0,1,70,12],
"struct_otter_1_1_quaternion.html#a8c96a9c5c511f13b24a957ecdd1ba675":[1,0,1,70,8],
"struct_otter_1_1_quaternion.html#a9faae27fbb138897239f90056fdc7019":[1,0,1,70,4],
"struct_otter_1_1_quaternion.html#aa5cb3f479612d12acdbdac6ecfceb994":[1,0,1,70,11],
"struct_otter_1_1_quaternion.html#ab3fd1bd6fac8274c20dbd052b4701d78":[1,0,1,70,5],
"struct_otter_1_1_quaternion.html#ab88972f3747fdf3415e93a29cae1c9ad":[1,0,1,70,13]
};
|
import React from 'react'; // eslint-disable-line no-unused-vars
import { __ } from '@wordpress/i18n';
import { PanelBody } from '@wordpress/components';
import { LinkOptions as LinkOptionsComponent } from '../../../components/link/components/link-options';
export const LinkOptions = ({ attributes, actions }) => {
const {
link,
} = attributes;
const {
onChangeLinkUrl,
onChangeLinkStyleColor,
onChangeLinkIsAnchor,
} = actions;
const linkObject = (typeof link === 'undefined') || link;
return (
<PanelBody title={__('Link Details', 'whatever')}>
<LinkOptionsComponent
link={linkObject}
onChangeUrl={onChangeLinkUrl}
onChangeStyleColor={onChangeLinkStyleColor}
onChangeIsAnchor={onChangeLinkIsAnchor}
/>
</PanelBody>
);
};
|
describe('pixi/utils/EventTarget', function () {
'use strict';
var expect = chai.expect;
var Clazz, PClazz, obj, pobj, obj2;
beforeEach(function () {
Clazz = function () {};
PClazz = function () {};
PIXI.EventTarget.mixin(Clazz.prototype);
PIXI.EventTarget.mixin(PClazz.prototype);
obj = new Clazz();
obj2 = new Clazz();
pobj = new PClazz();
obj.parent = pobj;
obj2.parent = obj;
});
it('Module exists', function () {
expect(PIXI.EventTarget).to.be.an('object');
});
it('Confirm new instance', function () {
pixi_utils_EventTarget_confirm(obj);
});
it('simple on/emit case works', function () {
var myData = {};
obj.on('myevent', function (event) {
pixi_utils_EventTarget_Event_confirm(event, obj, myData);
});
obj.emit('myevent', myData);
});
it('simple once case works', function () {
var called = 0;
obj.once('myevent', function() { called++; });
obj.emit('myevent');
obj.emit('myevent');
obj.emit('myevent');
obj.emit('myevent');
obj.emit('myevent');
expect(called).to.equal(1);
});
it('simple off case works', function (done) {
function onMyEvent() {
done(new Error('Event listener should not have been called'));
}
obj.on('myevent', onMyEvent);
obj.off('myevent', onMyEvent);
obj.emit('myevent');
done();
});
it('simple propagation case works', function (done) {
var myData = {};
pobj.on('myevent', function () {
done();
});
obj.emit('myevent');
});
it('simple stopPropagation case works', function (done) {
var myData = {};
pobj.on('myevent', function () {
done(new Error('Event listener should not have been called on the parent element'));
});
obj.on('myevent', function (evt) {
evt.stopPropagation();
});
obj.emit('myevent');
done();
});
it('simple stopImmediatePropagation case works', function (done) {
var myData = {};
pobj.on('myevent', function () {
done(new Error('Event listener should not have been called on the parent'));
});
obj.on('myevent', function (evt) {
evt.stopImmediatePropagation();
});
obj.on('myevent', function () {
done(new Error('Event listener should not have been called on the second'));
});
obj.emit('myevent');
done();
});
it('multiple dispatches work properly', function () {
var called = 0;
function onMyEvent() {
called++;
}
obj.on('myevent', onMyEvent);
obj.emit('myevent');
obj.emit('myevent');
obj.emit('myevent');
obj.emit('myevent');
expect(called).to.equal(4);
});
it('multiple events work properly', function () {
var called = 0;
function onMyEvent() {
called++;
}
obj.on('myevent1', onMyEvent);
obj.on('myevent2', onMyEvent);
obj.on('myevent3', onMyEvent);
obj.emit('myevent1');
obj.emit('myevent2');
obj.emit('myevent3');
expect(called).to.equal(3);
});
it('multiple events one removed works properly', function () {
var called = 0;
function onMyEvent() {
called++;
}
obj.on('myevent1', onMyEvent);
obj.on('myevent2', onMyEvent);
obj.on('myevent3', onMyEvent);
obj.emit('myevent1');
obj.emit('myevent2');
obj.emit('myevent3');
obj.off('myevent2', onMyEvent);
obj.emit('myevent1');
obj.emit('myevent2');
obj.emit('myevent3');
expect(called).to.equal(5);
});
it('multiple handlers for one event with some removed', function () {
var called = 0;
var onMyEvent = function () {
called++;
},
onMyEvent2 = function () {
called++;
};
// add 2 handlers and confirm they both get called
obj.on('myevent', onMyEvent);
obj.on('myevent', onMyEvent);
obj.on('myevent', onMyEvent2);
obj.on('myevent', onMyEvent2);
obj.emit('myevent');
expect(called).to.equal(4);
// remove one of the handlers, emit again, then ensure 1 more call is made
obj.off('myevent', onMyEvent);
obj.emit('myevent');
expect(called).to.equal(6);
});
it('calls to off without a handler do nothing', function () {
var called = 0;
var onMyEvent = function () {
called++;
};
obj.on('myevent', onMyEvent);
obj.on('myevent', onMyEvent);
obj.emit('myevent');
expect(called).to.equal(2);
obj.off('myevent');
obj.emit('myevent');
expect(called).to.equal(4);
obj.off('myevent', onMyEvent);
obj.emit('myevent');
expect(called).to.equal(4);
});
it('handles multiple instances with the same prototype', function () {
var called = 0;
function onMyEvent(e) {
called++;
}
obj.on('myevent1', onMyEvent);
obj.on('myevent2', onMyEvent);
obj2.istwo = true;
obj2.on('myevent1', onMyEvent);
obj2.on('myevent2', onMyEvent);
obj.emit('myevent1');
obj.emit('myevent2');
obj2.emit('myevent1');
obj2.emit('myevent2');
//we emit 4 times, but since obj2 is a child of obj the event should bubble
//up to obj and show up there as well. So the obj2.emit() calls each increment
//the counter twice.
expect(called).to.equal(6);
});
it('is backwards compatible with older .dispatchEvent({})', function () {
var called = 0,
data = {
some: 'thing',
hello: true
};
function onMyEvent(event) {
pixi_utils_EventTarget_Event_confirm(event, obj, data);
called++;
}
obj.on('myevent1', onMyEvent);
obj.on('myevent2', onMyEvent);
obj.on('myevent3', onMyEvent);
data.type = 'myevent1';
obj.emit(data);
data.type = 'myevent2';
obj.emit(data);
data.type = 'myevent3';
obj.emit(data);
obj.off('myevent2', onMyEvent);
data.type = 'myevent1';
obj.emit(data);
data.type = 'myevent2';
obj.emit(data);
data.type = 'myevent3';
obj.emit(data);
expect(called).to.equal(5);
});
it('is backwards compatible with older .call(this)', function () {
var Fn = function() {
PIXI.EventTarget.call(this);
},
o = new Fn();
pixi_utils_EventTarget_confirm(o);
});
it('is backwards compatible with older .addEventListener("")', function () {
var called = 0,
data = {
some: 'thing',
hello: true
};
function onMyEvent(event) {
pixi_utils_EventTarget_Event_confirm(event, obj, data);
called++;
}
obj.addEventListener('myevent1', onMyEvent);
obj.addEventListener('myevent2', onMyEvent);
obj.addEventListener('myevent3', onMyEvent);
data.type = 'myevent1';
obj.emit(data);
data.type = 'myevent2';
obj.emit(data);
data.type = 'myevent3';
obj.emit(data);
obj.off('myevent2', onMyEvent);
data.type = 'myevent1';
obj.emit(data);
data.type = 'myevent2';
obj.emit(data);
data.type = 'myevent3';
obj.emit(data);
expect(called).to.equal(5);
});
it('event remove during emit call properly', function () {
var called = 0;
function cb1() {
called++;
obj.off('myevent', cb1);
}
function cb2() {
called++;
obj.off('myevent', cb2);
}
function cb3() {
called++;
obj.off('myevent', cb3);
}
obj.on('myevent', cb1);
obj.on('myevent', cb2);
obj.on('myevent', cb3);
obj.emit('myevent', '');
expect(called).to.equal(3);
});
});
|
function vocales(arr)
{
var vocales = ['a','e','i','o','u'];
var palabra = arr.join().split("");
var c=0;
for(var i=0 ; i < palabra.length ; i++)
{
for(var j=0 ; j < vocales.length ; j++)
if(palabra[i] == vocales[j])
c++;
}
console.log("se encontro " + c + " vocales");
}
vocales(["ojo","mouse","lapiz"])
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var Observable_1 = require("rxjs/Observable");
require("rxjs/add/observable/of");
require("rxjs/add/operator/delay");
require("rxjs/add/operator/do");
require("rxjs/add/operator/switchMap");
require("rxjs/add/operator/take");
var task_model_1 = require("../entities/task.model");
var InMemoryTaskService = /** @class */ (function () {
function InMemoryTaskService(taskApi, taskStorage) {
this.taskApi = taskApi;
this.taskStorage = taskStorage;
}
InMemoryTaskService.prototype.getListOfTasks = function () {
var tasks = [];
return Observable_1.Observable.of(tasks);
};
InMemoryTaskService.prototype.createNewTask = function (id, name) {
var task = new task_model_1.Task();
task.id = id;
task.name = name;
return task;
};
InMemoryTaskService.prototype.addNewTask = function (taskName) {
var _this = this;
return this.taskApi.post(taskName)
.switchMap(function (taskId) {
var newTask = _this.createNewTask(taskId, taskName);
_this.taskStorage.addNewTask(newTask);
return Observable_1.Observable.of(newTask);
})
.take(1)
.finally(function () { });
};
return InMemoryTaskService;
}());
exports.InMemoryTaskService = InMemoryTaskService;
|
'use strict';
const introduce = document.querySelector('#introduce');
const btn = document.querySelector('.btn');
const number = document.querySelector('.number');
const text = document.querySelector('.text');
const textIn = document.querySelector('.textIn');
//funnction random
function getRandom(num){
return Math.floor(Math.random()*num);
};
const resultRandom = getRandom(100);
console.log(`El número aleatorio es: ${resultRandom}`);
//contador a 0
let counter = 0;
number.innerHTML = counter;
function test(){
console.log('click');
const user = parseInt(introduce.value);
console.log(resultRandom, user)
if(user === resultRandom){
textIn.innerHTML =' ¡¡¡Has ganado!!!';
}else if(user > resultRandom){
textIn.innerHTML = 'Te has pasado';
counter+=1
number.innerHTML = counter;
}else{
textIn.innerHTML = 'Te has quedado corto';
counter+=1
number.innerHTML = counter;
}
}
btn.addEventListener('click', test);
|
import React from 'react';
import {ProductComponent} from './components/product';
import {ListBarang} from './components/product/listbarang';
import renderer from 'react-test-renderer';
import { render } from '@testing-library/react';
const barang = {barang:[
{
kategori:"area memasak",
nama:"Exhaust Hood w/ Filter dan tidak dengan Filter, termasuk lampu penerangan",
img: "img/1.jpg",
deskripsi:"List daftar harga per-meternya adalah sebagai berikut:",
harga:"img/1a.jpg"
},
{
kategori:"area memasak",
nama:"Kwali Range Single, Double dan Triple",
img: "img/2.jpg",
deskripsi:"List daftar harga untuk kwali range adalah sebagai berikut: ",
harga:"img/2a.jpg"
},
{
kategori:"area mencuci",
nama:"Solid dan Slotted Pan Rack 4 Tier",
img: "img/10.jpg",
deskripsi:"List daftar harga per-meternya adalah sebagai berikut: ",
harga:"img/10a.jpg"
},
{
kategori:"area mencuci",
nama:"Sink",
img: "img/11.jpg",
deskripsi:"List daftar harga Sink adalah sebagai berikut : ",
harga:"img/11a.jpg"
},
]}
it('Product is renders correctly', () => {
let component = renderer.create(<ProductComponent/>);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
tree.props._handleChange;
tree = component.toJSON();
expect(tree).toMatchSnapshot();
tree.props.useEffect;
tree = component.toJSON();
expect(tree).toMatchSnapshot();
const { getByText } = render(<ListBarang barang={barang.barang} filter="semua kategori" />);
const linkElement = getByText(/Filter dan tidak dengan Filter, termasuk lampu penerangan/i);
expect(linkElement).toBeInTheDocument();
});
|
import React from 'react';
import TodoItem from "../todoitem/todoitem";
import './todolist.css';
import {List} from "semantic-ui-react";
class TodoList extends React.Component {
render() {
return (
<List>
{this.renderItems(this.props.items)}
</List>
);
}
renderItems = items => items.map(item => <TodoItem todo={item}/>);
}
export default TodoList;
|
/*Functions and effects with jQuery*/
$(document).ready(function()
{
//FUNCTION FOR ACTIVE LINK IN SIDEBAR
$('#sidebarSection1').on('click','li',function(){
$('#sidebarSection1 li.active').removeClass('active');
$('#sidebarSection2 li.active').removeClass('active');
$(this).addClass('active');
});
$('#sidebarSection2').on('click','li',function(){
$('#sidebarSection2 li.active').removeClass('active');
$('#sidebarSection1 li.active').removeClass('active');
$(this).addClass('active');
});
});
/*var idle=0;
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime > 1) { // 20 minutes
window.location.reload();
alert("Logged out, Please login again");
}
}
*/
|
/* eslint-disable strict */
module.exports = `__filename = ${__filename}`;
|
import gray_logo from './gray_logo.png'
import logo_white_name from './logo_white_name.png'
import logo_white_clip from './logo_white_clip.png'
import default_user from './defaultUser.png'
export default {
gray_logo,
logo_white_name,
logo_white_clip,
default_user
}
|
import express from 'express';
import {host} from '../../globalConfig';
import {fetchJsonByNode, postOption, fetchGetObj} from '../../../common/common';
const reportService = `${host}/report-service`;
let api = express.Router();
// 根据模板代码返回报表列表
api.post('/getModeList', async (req, res) => {
const url= `${reportService}/report/list/output`;
res.send(await fetchJsonByNode(req, url, postOption(req.body)));
});
api.post('/sendmail', async (req, res) => {
const url= `${reportService}/report/sendmail`;
res.send(await fetchJsonByNode(req, url, postOption(req.body)));
});
export default api;
|
/*!
* \brief JIRA Attachment Downloader
* \details This extension allows the user to download all attachments of a JIRA ticket with one click.
* \author Thomas Irgang
* \version 1.6
* \date 2017
* \copyright MIT License
Copyright 2017 Thomas Irgang
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/*!
This code is based on the samples from https://developer.chrome.com/extensions/samples. Especially code snippets from the download examples is reused.
*/
var api = browser;
/*! All links contained in the website. */
var all_links = [];
/*! All links displayed as download options. */
var visible_links = [];
/*! Number of triggered downloads. */
var downloads = 0;
/*! Number of running downloads. */
var downloads_running = 0;
/*! JIRA ticket key */
var key = "";
/*! JIRA ticket summary */
var summary = "";
/*! current domain */
var domain = "";
/*! Update popup to show all visible links. */
function showLinks() {
var links_table = document.getElementById('links');
// remove old links
while (links_table.children.length > 1) {
links_table.removeChild(links_table.children[links_table.children.length - 1])
}
// add links
for (var i = 0; i < visible_links.length; ++i) {
var row = document.createElement('tr');
var col0 = document.createElement('td');
var col1 = document.createElement('td');
var checkbox = document.createElement('input');
checkbox.checked = true;
checkbox.type = 'checkbox';
checkbox.id = 'check' + i;
col0.appendChild(checkbox);
col1.innerText = getFile(visible_links[i]);
col1.style.whiteSpace = 'nowrap';
col1.id = "file" + i;
col1.onclick = function () {
checkbox.checked = !checkbox.checked;
}
row.appendChild(col0);
row.appendChild(col1);
links_table.appendChild(row);
}
}
/*! Enable all check boxes. */
function toggleAll() {
var checked = document.getElementById('toggle_all').checked;
for (var i = 0; i < visible_links.length; ++i) {
document.getElementById('check' + i).checked = checked;
}
}
/*! Get file name from URL. */
function getFile(url) {
return decodeURI(url.substring(url.lastIndexOf('/') + 1));
}
/*! Trigger download all visible checked links. */
function downloadCheckedLinks() {
console.log("download links " + domain + ", " + key + ", " + summary);
for (var i = 0; i < visible_links.length; ++i) {
if (document.getElementById('check' + i).checked) {
api.runtime.sendMessage({
"kind": "download",
"url": visible_links[i],
"domain": domain,
"ticket": key,
"summary": summary,
"nr": i
});
downloads = downloads + 1;
}
}
}
/*! Callback for started downloads. */
function downloadStarted(success, index) {
downloads = downloads - 1;
if (downloads == 0) {
console.log("All downloads started.");
}
if (success) {
downloads_running = downloads_running + 1;
}
var file_element = document.getElementById("file" + index);
if (file_element) {
file_element.style.color = success ? "yellow" : "red";
} else {
console.log("Element for file " + index + " not found");
}
}
/*! Callback for finished downloads. */
function downloadDone(url, id) {
var index = indexForUrl(url);
if (index >= 0) {
downloads_running = downloads_running - 1;
if (downloads_running == 0) {
console.log("All downloads finished.");
if (id) {
api.downloads.show(id);
}
window.close();
}
var file_element = document.getElementById("file" + index);
if (file_element) {
file_element.style.color = "green";
} else {
console.log("Element for file " + index + " not found");
}
} else {
console.log("Index not found for " + url);
}
}
/*! Search index of download URL. */
function indexForUrl(url) {
if (url) {
for (var i = 0; i < visible_links.length; i++) {
if (url == visible_links[i]) {
return i;
}
}
}
return -1;
}
/*! Filter all links. Only show JIRA ticket attachments and apply user search expression. */
function filterLinks() {
// get expression to identify external attachment links
var external = document.getElementById('external').value;
// expression to identify JIRA attachment links
var attachment_filter = "/secure/attachment/";
// merge external and internal attachment link expression
if (external) {
attachment_filter = attachment_filter + "|" + external;
}
// reduce links list to attachment links
visible_links = all_links.filter(function (link) {
return link.match(attachment_filter);
});
// apply negative filter, hide strange JIRA created links.
var additional_filter = "fileNameUrlEncoded";
visible_links = visible_links.filter(function (link) {
return !link.match(additional_filter);
});
// apply user filter expression
var filter_value = document.getElementById('filter').value;
if (document.getElementById('regex').checked) {
//apply regex
visible_links = visible_links.filter(function (link) {
return link.match(filter_value);
});
} else {
//apply search terms split by ' '
var terms = filter_value.split(' ');
visible_links = visible_links.filter(function (link) {
for (var termI = 0; termI < terms.length; ++termI) {
var term = terms[termI];
if (term.length != 0) {
var expected = (term[0] != '-');
if (!expected) {
term = term.substr(1);
if (term.length == 0) {
continue;
}
}
var found = (-1 !== link.indexOf(term));
if (found != expected) {
return false;
}
}
}
return true;
});
}
// update popup
showLinks();
}
/*! Extract domain from URL. */
function getDomain(url) {
if (url) {
var url_parts = url.split("/");
if (url_parts.length > 2) {
var domain = url_parts[2];
if (domain) {
return domain;
}
}
}
return "";
}
/*! Get last used filter for external download links. */
function getExternalFilter(url, callback) {
var domain = getDomain(url);
api.storage.sync.get(domain, (items) => {
callback(api.runtime.lastError ? null : items[domain]);
});
}
/*! Save filter for external download links. */
function saveExternalFilter(url) {
var domain = getDomain(url);
var external = document.getElementById('external').value;
var items = {};
items[domain] = external;
api.storage.sync.set(items);
}
/*! Get URL of current tab. */
function getCurrentTabUrl(callback) {
var queryInfo = {
active: true,
currentWindow: true
};
api.tabs.query(queryInfo, (tabs) => {
if (tabs) {
var tab = tabs[0];
if (tab) {
console.log("Tab: " + JSON.stringify(tab));
var url = tab.url;
console.log("URL: " + url);
if (url) {
callback(url);
}
} else {
console.warn("No tab found!");
console.warn(tabs);
}
}
});
}
/*! Update filter for external links. */
function updateExternal() {
filterLinks();
getCurrentTabUrl((url) => {
if (url) {
saveExternalFilter(url);
}
});
}
/*! Update popup info with current tab URL. */
function updateTabUrl(url) {
domain = getDomain(url);
if (document.getElementById('domain')) {
document.getElementById('domain').value = domain;
}
getExternalFilter(url, (external) => {
if (external) {
if (document.getElementById('external')) {
document.getElementById('external').value = external;
}
}
});
}
/*! Callback for link extraction script. */
api.runtime.onMessage.addListener(function (msg) {
if (msg) {
if (msg.kind == "links") {
var links = msg.data;
for (var index in links) {
all_links.push(links[index]);
}
all_links.sort();
filterLinks();
showLinks();
} else if (msg.kind == "key") {
key = msg.data;
document.getElementById('ticket').value = key;
document.getElementById('title').innerText = "JIRA Attachment Downloader";
document.getElementById('content').style.display = "block";
} else if (msg.kind == "summary") {
summary = msg.data;
document.getElementById("summary").value = summary;
} else if (msg.kind == "dl_ok") {
downloadStarted(true, msg["nr"]);
} else if (msg.kind == "dl_err") {
downloadStarted(false, msg["nr"]);
} else if (msg.kind == "dl_succ") {
console.log("Message: dl_succ");
downloadDone(msg["url"], msg["id"]);
}
}
});
function closePopup() {
window.close();
}
/*! Init popup. */
window.onload = function () {
// register form callbacks
if (document.getElementById('external')) {
document.getElementById('external').onkeyup = updateExternal;
}
if (document.getElementById('filter')) {
document.getElementById('filter').onkeyup = filterLinks;
}
if (document.getElementById('regex')) {
document.getElementById('regex').onchange = filterLinks;
}
if (document.getElementById('toggle_all')) {
document.getElementById('toggle_all').onchange = toggleAll;
}
if (document.getElementById('download0')) {
document.getElementById('download0').onclick = downloadCheckedLinks;
}
if (document.getElementById('download1')) {
document.getElementById('download1').onclick = downloadCheckedLinks;
}
if (document.getElementById('x')) {
document.getElementById('x').onclick = closePopup;
}
setTimeout(function () {
// get current tab URL
getCurrentTabUrl((url) => {
updateTabUrl(url);
});
// inject link extraction script in all frames of current tab
api.windows.getCurrent(function (currentWindow) {
api.tabs.query({
active: true,
windowId: currentWindow.id
},
function (activeTabs) {
api.tabs.executeScript(
activeTabs[0].id, {
file: 'send_links.js',
allFrames: true
});
});
});
}, 150);
};
|
var express = require('express');
var config = require('../config');
var router = express.Router();
/*
// setup slack events api
var { createEventAdapter } = require('@slack/events-api');
var slackEvents = createEventAdapter(config.slack.signingSecret);
*/
// setup controllers
var admin = require('../controllers/admin.js');
var index = require('../controllers/index.js');
var chat = require('../controllers/chat.js');
//var slack = require('../controllers/slack.js');
module.exports = function(io){
// setup routes
router.get('/', index.get);
router.post('/', index.post);
router.get('/admin', admin.get);
router.get('/chat', chat.start);
/*
// setup slack event listener
router.use('/bots/slack/events', slackEvents.expressMiddleware());
// add slack event handlers
slackEvents.on('app_mention', slack.handle.mention);
slackEvents.on('message', slack.handle.message);
*/
// setup chatroom socket.io chatroom namespace
const rooms = io.of('/chatroom');
rooms.on('connection', async (socket) => {
socket.on('join', (data) => {
console.log('joined room', data);
socket.join(data.room);
rooms.in(data.room).emit('message', `Hello and welcome to my chat bot! Please tell me your name.`);
});
socket.on('message',async (data) => {
rooms.in(data.room).emit('message', data.message);
var response = await chat.handle.message(data.room,data.message);
if (response.session.context.conversation.complete){
rooms.in(data.room).emit('message', `Thank you ${response.session.context.conversation.entities.contact}, we have successfully saved your information and will call you at ${response.session.context.conversation.entities.phone_number}. Goodbye!`);
socket.disconnect();
} else {
rooms.in(data.room).emit('message', response.text);
}
});
socket.on('disconnect',() => {
console.log('user disconnected');
//rooms.emit('message', "Goodbye! This session has ended.");
});
});
return router;
}
|
const fs = require('fs');
const https = require('https');
const express = require('express');
const cert = {
// Replace private key and cert with the appropriate names of the credentials you use
key: fs.readFileSync('./certs/resourcePrivateKey.key', 'utf8'),
cert: fs.readFileSync('./certs/resourceCert.crt', 'utf8')
};
const app = express();
app.get('/', (request, response) => {
response.end('<h1>Hello world</h1>')
});
const httpsServer = https.createServer(cert, app);
httpsServer.listen(8081, () => {
console.log('Listening to https://localhost:8081/');
console.log('Also available: https://CA-LAB22-MIM:8081/');
});
/*
* Generate SS certificate with the private key
* openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout ./selfsigned.key -out ./selfsigned.crt
*/
/*
* Generate Private key from CA side
* openssl genrsa -des3 -out caPrivateKey.key 2048
*
* Enter pass phrase for caPrivateKey.key: password
* Verifying - Enter pass phrase for caPrivateKey.key: password
*/
/*
* Generate Certificate from CA side
* openssl req -x509 -new -days 365 -sha256 -key ./caPrivateKey.key -sha256 -out ./caCertificate.crt
*
* Enter pass phrase for caPrivateKey.key: password
*
* Country Name (2 letter code) [AU]:BY
* State or Province Name (full name) [Some-State]:Minsk
* Locality Name (eg, city) []:Minsk
* Organization Name (eg, company) [Internet Widgits Pty Ltd]:CA-LAB22
* Organizational Unit Name (eg, section) []:CA-LAB22
* Common Name (e.g. server FQDN or YOUR name) []:CA-LAB22-MIM
* Email Address []:
*/
/*
* Generate Private key from Resource side
* openssl genrsa -out ./resourcePrivateKey.key 2048
*/
/*
* Generate Certificate request from Resource side
* openssl req -new -key ./resourcePrivateKey.key -out ./certRequest.csr -sha256 -config ./certificateConfig.cfg
*/
/*
* Generate Certificate for a Resource from CA side
* openssl x509 -req -days 365 -sha256 -in ./certRequest.csr -CA ./caCertificate.crt -CAkey ./caPrivateKey.key -CAcreateserial -out ./resourceCert.crt -extensions v3_req -extfile ./certificateConfig.cfg
*
* Enter pass phrase for ./caPrivateKey.key: password
*/
|
const initialState = {
business: {},
isRequestingBusiness: false,
isRequestingCreateBusiness: false,
}
export default (state = initialState, {type, payload}) => {
switch (type) {
case 'GET_SINGLE_BUSINESS':
return {
...state,
isRequestingBusiness: true
}
case 'REQUESTING_CREATE_BUSINESS':
return {
...state,
isRequestingCreateBusiness: !state.isRequestingCreateBusiness
}
default:
return state;
}
}
|
$(document).ready(function () {
$("#sections").DataTable();
$("#categories").DataTable();
$("#products").DataTable();
$("#brands").DataTable();
$("#banners").DataTable();
$('.select2').select2()
$('#current_password').keyup(function () {
var current_password = $('#current_password').val();
$.ajax({
type: 'post',
url: '/admin/check-current-password',
data: { current_password: current_password },
success: function (resp) {
if (resp == 'false') {
$('#chkCurrentPwd').html("<font color=red>Current Password is incorect</font>");
} else if (resp == 'true') {
$('#chkCurrentPwd').html("<font color=green>Current Password is corect</font>");
}
}, error: function (e) {
console.log("Error", e);
alert(e);
}
});
});
$('.updateSectionStatus').click(function () {
var status = $(this).children("i").attr('status');
var section_id = $(this).attr('section_id');
$.ajax({
type: 'post',
url: '/admin/update-section-status',
data: { status: status, section_id: section_id },
success: function (resp) {
if (resp['status'] == 0) {
$('#section-' + section_id).html("<i style='color:red' class='fa fa-toggle-off fa-2x' aria-hidden='true' status='Inactive'></i>");
} else if (resp['status'] == 1) {
$('#section-' + section_id).html("<i class='fa fa-toggle-on fa-2x' aria-hidden='true' status='Active'></i>");
}
}
});
});
$('.updateCategoryStatus').click(function () {
var status = $(this).children("i").attr('status');
var category_id = $(this).attr('category_id');
$.ajax({
type: 'post',
url: '/admin/update-category-status',
data: { status: status, category_id: category_id },
success: function (resp) {
if (resp['status'] == 0) {
$('#category-' + category_id).html("<i style='color:red' class='fa fa-toggle-off fa-2x' aria-hidden='true' status='Inactive'></i>");
} else if (resp['status'] == 1) {
$('#category-' + category_id).html("<i class='fa fa-toggle-on fa-2x' aria-hidden='true' status='Active'></i>");
}
}
});
});
$('#section_id').change(function () {
var section_id = $(this).val();
$.ajax({
type: 'post',
url: '/admin/append-categories-level',
data: { section_id: section_id },
success: function (resp) {
$('#appendCategoriesLevel').html(resp);
},
error: function (e) {
console.log(e);
alert(e);
}
});
});
// Confirm Delete with SwwetAlert2
$(".confirmDelete").click(function () {
var record = $(this).attr('record');
var recordid = $(this).attr('recordid');
Swal.fire({
title: 'Are you sure?',
// text: "You won't be able to revert this!",
icon: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
if (result.value) {
window.location.href = "/admin/delete-"+record+"/"+recordid;
}
})
});
$('.updateBannerstatus').click(function () {
var status = $(this).children("i").attr('status');
var banner_id = $(this).attr('banner_id');
$.ajax({
type: 'post',
url: '/admin/update-banner-status',
data: { status: status, banner_id: banner_id },
success: function (resp) {
if (resp['status'] == 0) {
$('#banner-' + banner_id).html("<i style='color:red' class='fa fa-toggle-off fa-2x' aria-hidden='true' status='Inactive'></i>");
} else if (resp['status'] == 1) {
$('#banner-' + banner_id).html("<i class='fa fa-toggle-on fa-2x' aria-hidden='true' status='Active'></i>");
}
}
});
});
$('.updateBrandStatus').click(function () {
var status = $(this).children("i").attr('status');
var brand_id = $(this).attr('brand_id');
$.ajax({
type: 'post',
url: '/admin/update-brand-status',
data: { status: status, brand_id: brand_id },
success: function (resp) {
if (resp['status'] == 0) {
$('#brand-' + brand_id).html("<i style='color:red' class='fa fa-toggle-off fa-2x' aria-hidden='true' status='Inactive'></i>");
} else if (resp['status'] == 1) {
$('#brand-' + brand_id).html("<i class='fa fa-toggle-on fa-2x' aria-hidden='true' status='Active'></i>");
}
}
});
});
$('.updateProductStatus').click(function () {
var status = $(this).children("i").attr('status');
var product_id = $(this).attr('product_id');
$.ajax({
type: 'post',
url: '/admin/update-product-status',
data: { status: status, product_id: product_id },
success: function (resp) {
if (resp['status'] == 0) {
$('#product-' + product_id).html("<i style='color:red' class='fa fa-toggle-off fa-2x' aria-hidden='true' status='Inactive'></i>");
} else if (resp['status'] == 1) {
$('#product-' + product_id).html("<i class='fa fa-toggle-on fa-2x' aria-hidden='true' status='Active'></i>");
}
}
});
});
$('.updateProductImagesStatus').click(function () {
var status = $(this).text();
var product_image_id = $(this).attr('product_image_id');
$.ajax({
type: 'post',
url: '/admin/update-product-image-status',
data: { status: status, product_image_id: product_image_id },
success: function (resp) {
if (resp['status'] == 0) {
$('#image-' + product_image_id).html("<a class='updateProductImagesStatus' href='javascript:void(0)'>Inactive</a>");
} else if (resp['status'] == 1) {
$('#image-' + product_image_id).html("<a class='updateProductImagesStatus' href='javascript:void(0)'>Active</a>");
}
}
});
});
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div style="margin-top:10px;"><input style="width:185px;" id="size" type="text" name="size[]" placeholder="Size" value=""/> <input style="width:185px;" id="sku" type="text" name="sku[]" placeholder="sku" value=""/> <input style="width:185px;" id="price" type="number" min="1" name="price[]" placeholder="price" value=""/> <input style="width:185px;" id="stock" type="number" min="1" name="stock[]" placeholder="stock" value=""/> <a href="javascript:void(0);" class="remove_button" title="Remove field"> <i class="fas fa-minus"></i></a></div>';
var x = 1;
//Once add button is clicked
$(addButton).click(function(){
//Check maximum number of input fields
if(x < maxField){
x++;
$(wrapper).append(fieldHTML);
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function(e){
e.preventDefault();
$(this).parent('div').remove();
x--;
});
$(".editProductAttr").click(function() {
var attr_id = $(this).attr('data-id');
$.ajax({
type: 'post',
url: '/admin/show-product-attributes',
data: { status: 1, attr_id: attr_id },
success: function (resp) {
$("#id").val(resp['data']['id']);
$("#size").val(resp['data']['size']);
$("#sku").val(resp['data']['sku']);
$("#price").val(resp['data']['price']);
$("#stock").val(resp['data']['stock']);
}
});
})
})
|
module.exports = require('./lib/sideload.js');
|
import React from "react";
const HowToPlay = () => {
return(
<div className="howToPlayContainer">
<h1>About This App</h1>
<p>This idea of this app is simple. All this app is doing, is helping players practice counting cards.</p>
<h1>How To Play:</h1>
<h3>Simple instructions:</h3>
<p>If your current card is between 2 and 6 you must raise your count by 1</p>
<p>If your current card is between 1 and 9 keep your count as is</p>
<p>If your current card is a 10 or a face card you must lower your count by 1</p>
<h3>The goal of counting cards:</h3>
<p>The goal of a card counting system is to assign point values that are either high points or low points. While the decks count is high then there is a better chance of getting a blackjack or high cards, and while the deck count is low there is a better chance of getting smaller cards. By understanding how to count cards in blackjack, a player is giving themselves an advantage over the house which can lead to higher winnings or if in a bad scenario it may help a player break even.</p>
</div>
);
}
export default HowToPlay;
|
/* global $, Util, translate */
/* exported EditorTool */
/** Editor Tool
* This folder contains definitions for each type of block which can be used in our content editor.
* This file contains the super class for all those tools, providing common functionality between them all.
*/
class EditorTool {
constructor(data, config, api) {
this.api = api // Save a reference to the EditorJS api
this.data = data // Save data for this tool/block
this.id = config.id // Save the id of this block, so that we can recognize if it changes
this.allowDecoration = Boolean(config.decorations) // Check the configuration as to whether decorations are defined for this tool.
this.allowedDecorations = config.decorations || []
this.fields = config.fields || {}
this.tunes = config.tunes || []
// A convenience to lookup the CSS classes used in the editor
this.CSS = {
baseClass: this.api.styles.block,
container: `cdx-${this.id}`,
settingsWrapper: `cdx-${this.id}-settings`,
settingsButton: this.api.styles.settingsButton,
settingsButtonActive: this.api.styles.settingsButtonActive,
settingsButtonDisabled: `${this.api.styles.settingsButton}--disabled`,
settingsInputWrapper: 'cdx-settings-input-zone',
settingsSelect: 'ce-settings-select',
settingsInput: 'ce-settings-input',
semanticInput: 'cdx-semantic-input',
tunesWrapper: 'ce-settings__tunes',
decorationsWrapper: 'ce-settings__decorations',
decorationInputsWrapper: 'ce-settings__inputs',
tuneButtons: {},
decorationButtons: {},
tunes: {},
fields: {},
input: this.api.styles.input,
inputs: {},
}
// The standard configurations for different types of block decorations
this.decorationsConfig = {
triangle: {
icon: 'counterclockwise rotated play',
inputs: [
{ name: 'alignment', type: 'select', default: 'left', values: ['left', 'right'] },
],
},
gradient: {
icon: 'counterclockwise rotated bookmark',
inputs: [
{ name: 'alignment', type: 'select', default: 'left', values: ['left', 'right'] },
{ name: 'color', type: 'select', default: 'orange', values: ['orange', 'blue', 'gray'] },
],
},
sidetext: {
icon: 'clockwise rotated heading',
inputs: [
{ name: 'text', type: 'text', default: '' },
],
},
circle: { icon: 'circle outline' },
leaves: { icon: 'leaf' },
}
// For every field used by this tool, save a CSS class
for (let key in this.fields) {
this.CSS.fields[key] = `cdx-${this.id}__${key}`
}
// A few special types of inputs also have their own CSS class
['title', 'caption', 'textarea', 'text', 'content', 'button', 'url'].forEach(name => {
this.CSS.inputs[name] = `${this.CSS.input}--${name}`
})
// For each tune used by this tool, save CSS classes
this.tunes.forEach(tune => {
this.CSS.tunes[tune.name] = `${this.CSS.container}--${tune.name}`
this.CSS.tuneButtons[tune.name] = `${this.CSS.settingsButton}__${tune.name}`
})
// For each decoration used by this tool, save CSS classes
this.allowedDecorations.forEach(decoration => {
this.CSS.decorationButtons[decoration] = `${this.CSS.settingsButton}__${decoration}`
})
}
// =============== RENDERING =============== //
// Creates the tool html with inputs
render() {
const container = Util.make('div', [this.CSS.baseClass, this.CSS.container])
// Render the fields which are defined for this tool
for (let key in this.fields) {
const field = this.fields[key]
if (field.input === false) continue
this.renderInput(key, container)
}
// Add the classes for any active tunes
this.tunes.forEach(tune => {
container.classList.toggle(this.CSS.tunes[tune.name], this.isTuneActive(tune))
})
this.container = container // Save a reference to the container
return container
}
// Renders a standard type of input
renderInput(key, container = null) {
let result
let field = this.fields[key]
let type = field.input || 'text'
result = Util.make('div', [this.CSS.input, this.CSS.inputs[type], this.CSS.fields[key]], {
type: 'text',
innerHTML: this.data[key],
contentEditable: true,
}, container)
if (type == 'url') {
// URL inputs should auto-prepend an HTTP protocol if no protocol is defined.
result.addEventListener('blur', event => {
const url = event.target.innerText
if (url) event.target.innerText = (url.indexOf('://') === -1) ? 'http://' + url : url
})
}
if (type == 'text' && field.contained != false) {
// Text fields should prevent EditorJS from splitting pasted content into multiple blocks
result.addEventListener('paste', event => this.containPaste(event))
}
if (field.contained) {
// Any field wiith the contained attriibute set should prevent enter/backspace from creating/deleting blocks.
result.addEventListener('keydown', event => this.inhibitEnterAndBackspace(event, false))
}
// Add the field's label as a placeholder, or use a default placeholder
result.dataset.placeholder = field.label || translate.content.placeholders[key]
if (field.optional) {
// If this field is optional append that to the placeholder
result.dataset.placeholder += ` (${translate.content.placeholders.optional})`
}
return result
}
// This prevents the default EditorJS behaviour for the enter and backspace buttons
inhibitEnterAndBackspace(event, insertNewBlock = false) {
if (event.key == 'Enter' || event.keyCode == 13) { // ENTER
if (insertNewBlock) this.api.blocks.insert() // Insert a block if allowed
event.stopPropagation()
event.preventDefault()
return false
} else if (event.key == 'Backspace' || event.keyCode == 8) { // BACKSPACE
event.stopImmediatePropagation()
return false
} else {
return true
}
}
// This will insert a paragraph break if the enter button is pressed.
insertParagraphBreak(event) {
if (event.key == 'Enter' || event.keyCode == 13) { // ENTER
document.execCommand('insertHTML', false, '\r\n')
event.preventDefault()
event.stopPropagation()
return false
}
}
// Paste content directly into the tool, bypassing EditorJS's normal behaviour.
containPaste(event) {
const clipboardData = event.clipboardData || window.clipboardData
const pastedData = clipboardData.getData('Text')
document.execCommand('insertHTML', false, pastedData)
event.stopPropagation()
event.preventDefault()
return false
}
// =============== SAVING =============== //
// Extract data from the tool element, so that it can be saved.
save(toolElement) {
let newData = {}
// Get the contents of each field for this tool.
for (let key in this.fields) {
newData[key] = toolElement.querySelector(`.${this.CSS.fields[key]}`).innerHTML
newData[key] = newData[key].replace(' ', ' ').trim() // Stip non-breaking whitespace
}
return Object.assign(this.data, newData)
}
// =============== SETTINGS =============== //
// Create this tool's settings menu.
renderSettings() {
const settingsContainer = Util.make('div')
// Render tunes if there is at least one defined.
if (this.tunes.length > 0) {
Util.make('label', '', { innerText: translate.content.settings.tunes }, settingsContainer)
this.tunesWrapper = Util.make('div', [this.CSS.settingsWrapper, this.CSS.tunesWrapper], {}, settingsContainer)
this.renderTunes(this.tunesWrapper)
}
// Render decorations if there is at least one allowed.
if (this.allowedDecorations.length > 0) {
Util.make('label', '', { innerText: translate.content.settings.decorations }, settingsContainer)
this.decorationsWrapper = Util.make('div', [this.CSS.settingsWrapper, this.CSS.decorationsWrapper], {}, settingsContainer)
this.renderDecorations(this.decorationsWrapper)
// Render decoration inputs
this.inputsWrapper = Util.make('div', [this.CSS.settingsWrapper, this.CSS.decorationInputsWrapper], {}, settingsContainer)
this.renderDecorationInputs(this.inputsWrapper)
}
// Lastly, update the settings buttons to reflect the current state of the block.
this.updateSettingsButtons()
return settingsContainer
}
// Updates the appearance of all settings buttons and inputs to reflect the current state of the block.
updateSettingsButtons() {
if (this.tunesWrapper) {
// If tunes are defined, updated them
for (let i = 0; i < this.tunesWrapper.childElementCount; i++) {
const element = this.tunesWrapper.children[i]
const tune = this.tunes[i]
element.classList.toggle(this.CSS.settingsButtonActive, this.isTuneActive(tune))
}
}
if (this.decorationsWrapper) {
// If decorations are defined, updated them
for (let i = 0; i < this.decorationsWrapper.childElementCount; i++) {
const element = this.decorationsWrapper.children[i]
const decorationKey = this.allowedDecorations[i]
const selected = this.isDecorationSelected(decorationKey)
element.classList.toggle(this.CSS.settingsButtonActive, selected)
if (decorationKey == 'sidetext') {
$(this.decorationInputs.sidetext.text).toggle(selected)
} else if (decorationKey == 'triangle') {
$(this.decorationInputs.triangle.alignment).toggle(selected)
} else if (decorationKey == 'gradient') {
$(this.decorationInputs.gradient.alignment).toggle(selected)
$(this.decorationInputs.gradient.color).toggle(selected)
}
}
}
}
// ------ TUNES ------ //
// Render the set of tune buttons
renderTunes(container) {
// Render a button for each tune
this.tunes.map(tune => this.renderTuneButton(tune, container))
}
// Renders one tune button
renderTuneButton(tune, container) {
const button = Util.make('div', [this.CSS.settingsButton, this.CSS.tuneButtons[tune.name]], null, container)
button.dataset.position = 'top right'
button.innerHTML = '<i class="' + tune.icon + ' icon"></i>'
if (tune.group) {
button.dataset.tooltip = translate.content.tunes[tune.group][tune.name]
} else {
button.dataset.tooltip = translate.content.tunes[tune.name]
}
button.addEventListener('click', () => {
if (!event.currentTarget.classList.contains(this.CSS.settingsButtonDisabled)) {
this.selectTune(tune)
this.updateSettingsButtons()
}
})
if (this.isTuneActive(tune)) button.classList.add(this.CSS.settingsButtonActive)
return button
}
// Check if a tune if currently selected.
isTuneActive(tune) {
return tune.group ? tune.name === this.data[tune.group] : this.data[tune.name] == true
}
selectTune(tune) {
if (tune.group) {
this.setTuneValue(tune.group, tune.name)
} else {
this.setTuneBoolean(tune.name, !this.data[tune.name])
}
return this.isTuneActive(tune)
}
setTuneValue(key, value) {
this.container.classList.remove(this.CSS.tunes[this.data[key]])
this.data[key] = value
this.container.classList.add(this.CSS.tunes[value])
}
setTuneBoolean(key, value) {
this.data[key] = value
this.container.classList.toggle(this.CSS.tunes[key], value)
}
setTuneEnabled(key, enabled) {
this.tunesWrapper.querySelector(`.${this.CSS.tuneButtons[key]}`).classList.toggle(this.CSS.settingsButtonDisabled, !enabled)
}
// ------ DECORATIONS ------ //
renderDecorations(_container) {
this.allowedDecorations.forEach(key => {
const decoration = this.decorationsConfig[key]
decoration.name = key
this.renderDecorationButton(decoration, this.decorationsWrapper)
})
}
renderDecorationButton(decoration, container) {
const button = Util.make('div', [this.CSS.settingsButton, this.CSS.decorationButtons[decoration.name]], null, container)
button.dataset.position = 'top right'
button.innerHTML = '<i class="' + decoration.icon + ' icon"></i>'
button.dataset.tooltip = translate.content.decorations[decoration.name]
button.addEventListener('click', () => {
if (!event.target.classList.contains(this.CSS.settingsButtonDisabled)) {
this.setDecorationSelected(decoration, !this.isDecorationSelected(decoration.name))
this.updateSettingsButtons()
}
})
return button
}
renderDecorationInputs(container) {
this.decorationInputs = {}
this.allowedDecorations.forEach(key => {
const decoration = this.decorationsConfig[key]
if (decoration.inputs) {
this.decorationInputs[key] = {}
decoration.inputs.forEach(input => {
this.decorationInputs[key][input.name] = this.renderDecorationInput(key, input, container)
})
}
})
}
renderDecorationInput(key, input, container) {
const value = (this.data.decorations && this.data.decorations[key] && this.data.decorations[key][input.name]) || input.default
let result, inputElement
if (input.type == 'select') {
result = Util.make('div', [this.CSS.settingsSelect, 'ui', 'inline', 'dropdown'], {}, container)
inputElement = Util.make('input', 'text', { type: 'hidden' }, result)
Util.make('div', 'text', { innerText: translate.content.decorations[`${key}_${input.name}`][value] }, result)
Util.make('i', ['dropdown', 'icon'], {}, result)
const menu = Util.make('div', 'menu', {}, result)
input.values.forEach(val => {
const label = translate.content.decorations[`${key}_${input.name}`][val]
const item = Util.make('div', 'item', { innerText: label }, menu)
item.dataset.value = val
})
$(result).dropdown()
} else {
result = Util.make('div', ['ui', 'transparent', 'input'], {}, container)
inputElement = Util.make('input', this.CSS.settingsInput, {
type: input.type,
placeholder: translate.content.decorations[`${key}_${input.name}`],
value: value,
}, result)
}
inputElement.addEventListener('change', event => this.setDecorationOption(key, input.name, event.target.value))
result.style.display = 'none'
return result
}
setDecorationSelected(decoration, selected) {
if (!this.data.decorations) this.data.decorations = {}
if (decoration.inputs && selected) {
if (!this.data.decorations[decoration.name] || this.data.decorations[decoration.name].constructor != Object) {
const data = {}
decoration.inputs.forEach(input => { data[input.name] = input.default })
this.data.decorations[decoration.name] = data
}
} else {
this.data.decorations[decoration.name] = selected
}
}
setDecorationOption(key, option, value) {
if (this.data.decorations[key].constructor != Object) {
this.data.decorations[key] = {}
}
this.data.decorations[key][option] = value
}
isDecorationSelected(key) {
return this.data.decorations && Boolean(this.data.decorations[key])
}
}
|
export default class Route {
constructor (db = {}) {
this.namespace = 'ns'; // TODO create namespace
this.session = {};
this.queryOne = async (proc, params) => {
return db.getOne(proc, params);
};
this.queryAll = async (proc, params) => {
return db.getAll(proc, params);
};
this.queryAffected = async (proc, params) => {
return (await db.call(proc, params)).rows.affectedRows;
}
}
static isRoute () {
return function (target, name, descriptor) {
if (!target.routes) target.routes = [];
target.routes.push(name);
return descriptor;
}
}
setSession (session) {
this.session = session;
}
getSession () {
return this.session;
}
}
|
var aside = document.getElementById("aside");
aside.onclick = function () {
window.scrollTo(0, 0);
}
|
/**
* 用户控制层
*/
Ext.define('eapp.controller.Login',
{
extend:'Ext.app.Controller',
config:
{
refs:
{
mainview: 'mainview',
loginView:'loginView',
registerView:'registerView',
loginButton:{selector: 'loginView formpanel button[name=loginButton]'},
regButton:{selector: 'loginView formpanel button[name=regButton]'},
registerButton:{selector: 'registerView formpanel button[name=registerButton]'},
},
control:
{
loginButton:
{
tap:'OnLoginButtonTap',
},
regButton:
{
tap:'OnRegButtonTap',
},
registerButton:
{
tap:'OnRegisterButtonTap'
}
}
},
/**
* 用户注册
*/
OnRegisterButtonTap:function()
{
var me = this;
var registerView = me.getRegisterView();
if(registerView == null || registerView == 'undefined')
{
registerView = Ext.create('eapp.view.Register');
}
var loginname = Ext.ComponentQuery.query('#loginnameid', registerView)[0].getValue();
var passwordname = Ext.ComponentQuery.query('#passwordid', registerView)[0].getValue();
var username = Ext.ComponentQuery.query('#usernameid', registerView)[0].getValue();
var telname = Ext.ComponentQuery.query('#telid', registerView)[0].getValue();
var emailname = Ext.ComponentQuery.query('#emailid', registerView)[0].getValue();
var numbername = Ext.ComponentQuery.query('#numberid', registerView)[0].getValue();
if(loginname == null || loginname == 'undefined' || loginname.length <= 0)
{
eapp.view.Dialogs.showAlert('智慧潘家园','登录名不能为空');
return;
}
if(passwordname == null || passwordname == 'undefined' || passwordname.length <= 0)
{
eapp.view.Dialogs.showAlert('智慧潘家园','登录密码不能为空');
return;
}
if(username == null || username == 'undefined' || username.length <= 0)
{
eapp.view.Dialogs.showAlert('智慧潘家园','用户名不能为空');
return;
}
if(telname == null || telname == 'undefined' || telname.length <= 0)
{
eapp.view.Dialogs.showAlert('智慧潘家园','手机号不能为空');
return;
}
if(emailname == null || emailname == 'undefined' || emailname.length <= 0)
{
eapp.view.Dialogs.showAlert('智慧潘家园','邮箱不能为空');
return;
}
Ext.Viewport.setMasked({ xtype: 'loadmask', message: '请稍候...'});
var managerService = Ext.create('eapp.business.ResidentuserService');
managerService.register(loginname,passwordname,username,telname,emailname,numbername,
{
success:function(jsonData)
{
if(jsonData != 'false')
{
var backButton = me.getMainview().getNavigationBar().getBackButton();
backButton.fireEvent('tap', backButton, null, null);
eapp.view.Dialogs.showAlert('智慧潘家园','注册成功!~');
}
else
{
eapp.view.Dialogs.showAlert('智慧潘家园','注册失败!~');
}
Ext.Viewport.setMasked(false);
},
failure:function(message)
{
console.log(message);
Ext.Viewport.setMasked(false);
}
});
},
/**
* 用户登录
*/
OnLoginButtonTap:function()
{
var me = this;
var loginView = me.getLoginView();
if(loginView == null || loginView == 'undefined')
{
loginView = Ext.create('eapp.view.Login');
}
var username = Ext.ComponentQuery.query('#usernameLogin', loginView)[0].getValue();
var password = Ext.ComponentQuery.query('#passwordLogin', loginView)[0].getValue();
if(username == null || username == 'undefined' || username.length <= 0)
{
eapp.view.Dialogs.showAlert('智慧潘家园','用户名不能为空');
return;
}
if(password == null || password == 'undefined' || password.length <= 0)
{
eapp.view.Dialogs.showAlert('智慧潘家园','密码不能为空');
return;
}
Ext.Viewport.setMasked({ xtype: 'loadmask', message: '请稍候...'});
var managerService = Ext.create('eapp.business.ResidentuserService');
managerService.login(username,password,
{
success:function(jsonData)
{
console.log(jsonData);
eapp.util.GlobalData.setCurrentUser(Ext.JSON.encode(jsonData));
eapp.util.GlobalData.setUserName(username);
eapp.util.GlobalData.setPassword(password);
if(jsonData != 'null')
{
var backButton = me.getMainview().getNavigationBar().getBackButton();
backButton.fireEvent('tap', backButton, null, null);
eapp.view.Dialogs.showAlert('智慧潘家园','登录成功!~');
}
else
{
eapp.view.Dialogs.showAlert('智慧潘家园','登录失败!~');
}
Ext.Viewport.setMasked(false);
},
failure:function(message)
{
console.log(message);
Ext.Viewport.setMasked(false);
}
});
},
/**
* 跳转到注册页面
*/
OnRegButtonTap:function()
{
var me = this;
var registerView = me.getRegisterView();
if(registerView == null || registerView == 'undefined')
{
registerView = Ext.create('eapp.view.Register');
}
me.getMainview().push(registerView);
eapp.app.pageStack.push('registerview');
},
});
|
var hbs = require('express-hbs');
var chaArr = require('../routes/pageNum.json');
//注册pager handler
hbs.registerHelper('pager',function(pager,options) {
var html = '';
if( pager.totalCount != '0' && pager.totalCount != '' ) {
html += '<div class="page clear-fix">'
html += '<div>';
if (pager.page >= 2) {
html += '<a class="first" href="'+ pager.pageUrl + pager.pageUrlParam + 'page=1">首 页</a>';
html += '<a class="prev" href="'+ pager.pageUrl + pager.pageUrlParam +'page='+ (pager.page - 1) +'"><</a>';
}
if ((pager.page - 2) > 1 && pager.pageNum >=5) {
html += '<span>...</span>';
}
for(var i =0;i < pager.pages.length; i++) {
if(Number(pager.pages[i]) === pager.page) {
html += '<span class="cur">'+ pager.page +'</span>';
}else {
html += '<a href="'+ pager.pageUrl + pager.pageUrlParam +'page='+ Number(pager.pages[i]) +'" target="_self" page="'+ Number(pager.pages[i]) +'">'+ Number(pager.pages[i]) +'</a>';
}
}
if ((pager.page + 2) < pager.pageNum && pager.pageNum >= 5) {
html += '<span>...</span>';
}
if(pager.page< pager.pageNum) {
html += '<a href="'+ pager.pageUrl + pager.pageUrlParam + 'page='+ (pager.page + 1) +'" class="next" target="_self" page="'+ (pager.page + 1) +'">></a>';
html += '<a href="'+ pager.pageUrl + pager.pageUrlParam + 'page='+ (pager.pageNum) +'" class="last" target="_self" page="'+ (pager.pageNum) +'">尾 页</a>';
}
html += '<span page="'+ pager.pageNum +'" class="pagenum">共 '+ pager.pageNum +' 页 第</span>';
html += '<span class="page-input">';
html += '<input class="page-field" type="text" value="'+ pager.page +'">';
html += '<a class="page-go" href="javascript:void(0)" target="_self">GO</a>';
html += '</span>';
html += '<span class="go">页</span>';
html += '</div>';
html += '</div>';
return new hbs.SafeString(html);
}
return '';
});
//注册详情页pager handler
hbs.registerHelper('detailPager',function(pager,options) {
var html = '';
if( pager.totalCount != '0' && pager.totalCount != '' ) {
html += '<div class="detail-page mart20">';
if (pager.page >= 2) {
html += '<a class="prev" href="'+ pager.pageUrl + pager.pageUrlParam +'page='+ (pager.page - 1) +'">上一页</a>';
}
if ((pager.page - 2) > 1 && pager.pageNum >=5) {
html += '<span>...</span>';
}
for(var i =0;i < pager.pages.length; i++) {
if(Number(pager.pages[i]) === pager.page) {
html += '<span class="cur">'+ pager.page +'</span>';
}else {
html += '<a href="'+ pager.pageUrl + pager.pageUrlParam +'page='+ Number(pager.pages[i]) +'" target="_self" page="'+ Number(pager.pages[i]) +'">'+ Number(pager.pages[i]) +'</a>';
}
}
if ((pager.page + 2) < pager.pageNum && pager.pageNum >= 5) {
html += '<span>...</span>';
}
if(pager.page< pager.pageNum) {
html += '<a href="'+ pager.pageUrl + pager.pageUrlParam + 'page='+ (pager.page + 1) +'" class="next" target="_self" page="'+ (pager.page + 1) +'">下一页</a>';
}
html += '</div>';
return new hbs.SafeString(html);
}
return '';
});
//注册索引+1的helper
hbs.registerHelper("addOne",function(index){
//返回+1之后的结果k
return index+1;
});
//注册时尚时装 的helper
hbs.registerHelper("hotNewXia",function(data){
//返回时尚时装html
var html = '';
for(var i = 0 ; i < data.length ; i++){
if(i == 0){
html += '<dt> <a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank"> <img src="'+ data[i].thumbnail +'" /><span>'+ data[i].title +'</span></a></dt>';
}else{
html += '<dd><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </dd>';
}
}
return new hbs.SafeString(html);
});
//注册时尚时装 的helper
hbs.registerHelper("fashionData",function(data){
//返回时尚时装html
var html = '';
for(var i = 0 ; i < data.length ; i++){
if(i == 0){
html += '<dt><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank"><img src="'+ data[i].thumbnail +'" /> <span>'+ data[i].title +'</span></a></dt>';
}else{
html += '<dd><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </dd>';
}
}
return new hbs.SafeString(html);
});
//注册首页美容排行版 的helper
hbs.registerHelper("beautyTips",function(data){
//返回首页美容排行版html
var html = '';
for(var i = 0 ; i < data.length ; i++){
if(i < 3){
html += '<li class="tip"><span>'+ (i + 1) +'.</span><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </li>';
}else{
html += '<li><span>'+ (i + 1) +'.</span><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </li>';
}
}
return new hbs.SafeString(html);
});
//注册美容小banner下侧 的helper
hbs.registerHelper("beautyBanBot",function(data){
//返回美容小banner下侧html
var html = '';
for(var i = 0 ; i < data.length ; i++){
if(i == 0){
html += '<dt> <a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="pic"><img src="'+ data[i].thumbnail +'" /></a> <a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="txt">'+ data[i].title +'</a> </dt>';
}else{
html += '<dd><h3><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </h3> <p class="txt">'+ data[i].summary.substring(0,40) + '...' +' <a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="xq-btn">[详情]</a></p></dd>';
}
}
return new hbs.SafeString(html);
});
//注册家具中间新闻列表 的helper
hbs.registerHelper("houseNews",function(data){
//返回家具中间新闻列表html
var html = '';
html += '<span class="pic"><a href="/'+ chaArr[data[0].category_id] +'/'+ data[0].id +'.html" target="_blank"><img src="'+ data[0].thumbnail +'" /></a></span><dl class="items">';
for(var i = 0 ; i < data.length ; i++){
if(i == 0){
html += '<dt><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </dt>';
}else{
html += '<dd><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </dd>';
}
}
html += '</dl>';
return new hbs.SafeString(html);
});
//注册生活旅行 的helper
hbs.registerHelper("lifeTrip",function(data){
//返回生活旅行html
var html = '';
for(var i = 0 ; i < data.length ; i++){
if(i == 0){
html += '<dt> <a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="pic"><img src="'+ data[i].thumbnail +'" /></a> <a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="txt">'+ data[i].title +'</a> </dt>';
}else{
html += '<dd><h3><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </h3> <p class="txt">'+ data[i].summary.substring(0,40) + '...' +' <a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="xq-btn">[详情]</a></p></dd>';
}
}
return new hbs.SafeString(html);
});
//注册玩乐下侧 的helper
hbs.registerHelper("lifeWanleXiace",function(data){
//返回生活旅行html
var html = '';
html += '<dl class="items-dl cf">';
html += '<dt><a href="/'+ chaArr[data[0].category_id] +'/'+ data[0].id +'.html" target="_blank"><img src="'+ data[0].thumbnail +'"/> </a> </dt>';
html += '<dd><strong><a href="/'+ chaArr[data[0].category_id] +'/'+ data[0].id +'.html" target="_blank" title="'+ data[0].title +'">'+ data[0].title.substring(0,6) +'</a> </strong><p class="txt">'+ data[0].summary.substring(0,30) + '...' +'<a href="/'+ chaArr[data[0].category_id] +'/'+ data[0].id +'.html" target="_blank" class="xq-btn">[详情]</a></p></dd>';
html += '</dl>';
html += '<ul class="items-ul">';
for(var i = 0 ; i < data.length ; i++){
if(i> 0){
html += '<li><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </li>';
}
}
html += '</ul>';
return new hbs.SafeString(html);
});
//注册感情中间新闻 的helper
hbs.registerHelper("emotionNews",function(data){
//返回感情中间新闻html
var html = '';
for(var i = 0 ; i < data.length ; i++){
if(i < 4){
if(i == 0){
html += '<dt><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="tit">'+ data[i].title +'</a><p class="txt">'+ data[i].summary.substring(0,35) + '...' +'<a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="xq-btn">[详情]</a></p></dt>';
}else{
html += '<dd><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </dd>';
}
}else{
if(i == 4){
html += '<dt><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="tit">'+ data[i].title +'</a><p class="txt">'+ data[i].summary.substring(0,35) + '...' +'<a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank" class="xq-btn">[详情]</a></p></dt>';
}else{
html += '<dd><a href="/'+ chaArr[data[i].category_id] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </dd>';
}
}
}
return new hbs.SafeString(html);
});
//注册内页右侧情感世界 的helper
hbs.registerHelper("emotionRight",function(data){
//返回情感世界html
var html = '';
for(var i = 0 ; i < data.length ; i++){
if(i == 0){
html += '<dt><span class="pic"><a href="/'+ chaArr[data[i].channel] +'/'+ data[i].id +'.html" target="_blank"><img src="'+ data[i].thumbnail +'" /> </a></span><h3><a href="/'+ chaArr[data[i].channel] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </h3><p class="txt">'+ data[i].summary.substring(0,35) + '...' +'<a href="/'+ chaArr[data[i].channel] +'/'+ data[i].id +'.html" target="_blank" class="xq-btn">[详情]</a></p></dt>';
}else{
html += '<dd><a href="/'+ chaArr[data[i].channel] +'/'+ data[i].id +'.html" target="_blank">'+ data[i].title +'</a> </dd>';
}
}
return new hbs.SafeString(html);
});
//注册截取字符串个数 的helper
hbs.registerHelper("subStr",function(str,num){
//返回截取字符串个数html
var html = '';
function getStrLength(strs){
var realLength = 0, len = strs.length, charCode = -1;
for (var i = 0; i < len; i++) {
charCode = strs.charCodeAt(i);
if (charCode >= 0 && charCode <= 128) realLength += 1;
else realLength += 2;
}
return realLength;
}
html += str.substring(0, num);
if(getStrLength(str) > num){
html += '...';
};
return new hbs.SafeString(html);
});
//注册identifer 的helper
hbs.registerHelper("blockIdentifer",function(num){
//返回identifer字符串
var html = '';
html = chaArr[num];
return new hbs.SafeString(html);
});
//注册文章详情页内容 的helper
hbs.registerHelper("detailContent",function(data){
//返回文章详情页内容html
var html = '';
if(data == ''){
html += '<div style="text-align: center"><script type="text/javascript">/*女人街详情页广告*/var cpro_id = "u1679972";</script><script src="http://cpro.baidustatic.com/cpro/ui/c.js" type="text/javascript"></script></div>';
}else{
html += data;
}
return new hbs.SafeString(html);
});
//seoIndex"官晶华最新状况"控制显示条数 的helper
hbs.registerHelper("seoIndexList",function(data){
//返回文章详情页内容html
var html = '';
for( var i = 0; i < data.length; i++){
if(i < 7){
var temp=(data[i].datetime=='0000-00-00 00:00:00')?data[i].add_time:data[i].datetime;
html +='<li class="cfx"><span><a href="/mx/article-'+ data[i].docid +'.html" target="_blank"><img alt="'+data[i].title+'" src="'+data[i].images.index_0+'"/></a></span><h3><a href="/mx/article-'+ data[i].docid +'.html" target="_blank">'+ data[i].title +'</a></h3><p class="txt">'+ data[i].summary +'<a class="xq-btn" href="/mx/article-'+ data[i].docid +'.html" target="_blank">[详情]</a> </p><p class="update">'+ temp +'</p></li>';
}
}
return new hbs.SafeString(html);
});
hbs.registerHelper("seoIndexList_2",function(data){
var html = '';
for( var i = 0; i < data.length; i++){
if(i < 7){
html +='<li class="cfx"><span><a href="http://korea.b5m.com/article-'+ data[i].aid +'-1.html" target="_blank"><img alt="'+data[i].title+'" src="'+data[i].pic+'"/></a></span><h3><a href="http://korea.b5m.com/article-'+ data[i].aid +'-1.html" target="_blank">'+ data[i].title +'</a></h3><p class="txt">'+ data[i].summary +'<a class="xq-btn" href="http://korea.b5m.com/article-'+ data[i].aid +'-1.html" target="_blank">[详情]</a> </p><p class="update">'+ data[i].dateline +'</p></li>';
}
}
return new hbs.SafeString(html);
});
//MPS辅助功能
hbs.registerHelper('mpsHelper', function(mps_data,mps_key,level,name,idx) {
var out = "";
if(mps_key){
}else{
mps_key='default';
}
for(var key in mps_data){
if(key==mps_key){
if(level==0){
out = mps_data[key]['h_mps'];
}
else if(level==1){
out = mps_data[key]['p_mps'];
}
else if(level==2){
if(typeof mps_data[key]['m_mps'][name]!='undefined')
out = mps_data[key]['m_mps'][name];
}
else if(level==3){
if(typeof mps_data[key]['a_mps'][name][idx]!='undefined')
out = mps_data[key]['a_mps'][name][idx];
}
}
}
if(out){
if(level==0){
out='content="'+out+'"';
}else{
out='data-mps="'+out+'"';
}
}
return out;
});
//MPS辅助功能
hbs.registerHelper('numHelpPlus', function(num1,num2) {
var out = "";
out = num1 + num2;
return out;
});
|
export { default } from "./CurrentTrend";
|
import React from "react";
import { Spring, animated } from "react-spring/renderprops";
import "./TestMenuStyle.css";
import { BiMenu } from "react-icons/bi";
import useResizeAware from "react-resize-aware";
import { useDispatch } from "react-redux";
import { reportHamburgerMenuSize } from "./actions";
const MenuItems = [
"Login",
"Search For Podcasts",
"Books I've heard",
"Languages To Learn",
];
function TestMenu() {
const [resizeListener, sizes] = useResizeAware();
const dispatch = useDispatch();
//test
React.useEffect(() => {}, []);
React.useEffect(() => {
// console.log("TestMenu Do something with the new size values");
// console.log(sizes.height);
// dispatch(reportHamburgerMenuSize(sizes.height));
}, [sizes.width, sizes.height]);
const [toggle, setToggle] = React.useState(false);
function onToggle() {
setToggle(!toggle);
}
function reportSize(event) {
console.log("reporting size");
// // console.log(event);
// console.log(sizes.height);
dispatch(reportHamburgerMenuSize(sizes.height));
}
return (
<div className="auto-main">
<button onClick={onToggle}>
{" "}
<BiMenu size={40} />
</button>
{/* <button onClick={onAddText}>Add text</button>
<button onClick={onRemoveText}>Remove text</button> */}
<div className="content">
<Spring
native
force
config={{ tension: 2000, friction: 100, precision: 1 }}
from={{ height: toggle ? 0 : "auto" }}
to={{ height: toggle ? "auto" : 0 }}
onRest={reportSize}
>
{(props) => (
<animated.div className="item" style={props}>
{resizeListener}
{MenuItems.map((t, i) => (
<p key={i}>{t}</p>
))}
</animated.div>
)}
</Spring>
</div>
</div>
);
}
export default TestMenu;
|
function save() {
var extensions = document.getElementById('extensions').value;
chrome.storage.sync.set({
extensions: extensions
}, function() {});
}
function load() {
chrome.storage.sync.get({
extensions: 'https://cdn.auth0.com/extensions/develop/extensions.json'
}, function(items) {
document.getElementById('extensions').value = items.extensions;
});
}
document.addEventListener('DOMContentLoaded', load);
document.getElementById('save').addEventListener('click', save);
|
/**
* User functions
*/
const User = require('../models/user');
const Session = require('../models/session');
const encrypt = require('sha256');
function register(req, res) {
let body = req.body;
console.log("req.body");
console.log(req.body);
if (body.username && body.password) {
User.create({
username: body.username,
password: body.password,
name: body.name
}, (err, User) => {
if (!err)
res.json(User);
else
res.json(err);
})
}
}
function login(req, res) {
let body = req.body;
if (body.username && body.password) {
User.findOne({username: body.username}, (err, User) => {
if (!err) {
if (User) {
if (User.password === encrypt(body.password)) {
Session.findOne({userId: User.id}, (err, session) => {
if (!err) {
if (session) {
session.oldToken = session.token;
session.save((err, done) => {
if (!err)
res.json({success: true, token: done.token, name: User.name});
else {
res.status(500);
res.json({success: false, error: "Can't generate token1"})
}
})
} else {
Session.create({
userId: User.id
}, (err, sess) => {
if (!err)
res.json({success: true, token: sess.token});
else {
res.status(500);
res.json({success: false, error: err})
}
})
}
} else {
res.status(500);
res.json({success: false, error: "Can't generate token3"})
}
})
} else {
res.status(403);
res.json({success: false, error: "Username/password is incorrect."});
}
} else {
res.status(403);
res.json({success: false, error: "Username/password is incorrect."});
}
} else {
res.status(403);
res.json({success: false, error: "Username/password is incorrect."});
}
})
}
}
function getUser(req, res) {
if (req.params.userid) {
User.findOne({id: req.params.userid}, (err, User) => {
if (!err) {
if (User) {
Session.findOne({userId: User.id}, (err, session) => {
if (!err) {
if (session) {
res.json({
success: true,
username: User.username,
token: session.token
})
} else {
res.json({
success: true,
msg: "User token not created yet"
})
}
} else {
res.json({success: false, error: err.error});
}
})
} else {
res.json({success: false, error: "User does not exist"});
}
} else {
res.json({success: false, error: err});
}
})
} else {
res.json({success: false, error: "User ID not defined"});
}
}
function index(req, res) {
res.json({success: 1, data: null})
}
module.exports = {
index,
register,
login,
getUser
};
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.signUpFailure = exports.signUpSuccess = exports.signUpStart = exports.signOutFailure = exports.signOutSuccess = exports.signOutStart = exports.checkUserSession = exports.signInFailure = exports.signInSuccess = exports.emailSignInStart = exports.googleSignInStart = void 0;
var user_types_1 = __importDefault(require("./user.types"));
var googleSignInStart = function () { return ({
type: user_types_1.default.GOOGLE_SIGN_IN_START,
}); };
exports.googleSignInStart = googleSignInStart;
var emailSignInStart = function (emailAndPassword) { return ({
type: user_types_1.default.EMAIL_SIGN_IN_START,
payload: emailAndPassword,
}); };
exports.emailSignInStart = emailSignInStart;
var signInSuccess = function (user) { return ({
type: user_types_1.default.SIGN_IN_SUCCESS,
payload: user,
}); };
exports.signInSuccess = signInSuccess;
var signInFailure = function (error) { return ({
type: user_types_1.default.SIGN_IN_FAILURE,
payload: error,
}); };
exports.signInFailure = signInFailure;
var checkUserSession = function () { return ({
type: user_types_1.default.CHECK_USER_SESSION,
}); };
exports.checkUserSession = checkUserSession;
var signOutStart = function () { return ({
type: user_types_1.default.SIGN_OUT_START,
}); };
exports.signOutStart = signOutStart;
var signOutSuccess = function () { return ({
type: user_types_1.default.SIGN_OUT_SUCCESS,
}); };
exports.signOutSuccess = signOutSuccess;
var signOutFailure = function (error) { return ({
type: user_types_1.default.SIGN_OUT_FAILURE,
payload: error,
}); };
exports.signOutFailure = signOutFailure;
var signUpStart = function (userCredentials) { return ({
type: user_types_1.default.SIGN_UP_START,
payload: userCredentials,
}); };
exports.signUpStart = signUpStart;
var signUpSuccess = function (_a) {
var user = _a.user, additionalData = _a.additionalData;
return ({
type: user_types_1.default.SIGN_UP_SUCCESS,
payload: { user: user, additionalData: additionalData },
});
};
exports.signUpSuccess = signUpSuccess;
var signUpFailure = function (error) { return ({
type: user_types_1.default.SIGN_UP_FAILURE,
payload: error,
}); };
exports.signUpFailure = signUpFailure;
|
var express = require('express');
var router = express.Router();
var query = require('../database/query');
var knex = require('../database/knex');
require('dotenv').config();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Grey Delamar' });
});
router.post('/job', function(req, res, next){
var firstname = req.body.firstname;
var lastname = req.body.lastname;
var company = req.body.company;
var email = req.body.email;
var message = req.body.message;
query.addcontact(firstname, lastname, company, email, message)
.then(function(data) {
res.redirect('/')
})
.catch(function(err){
return next(err);
})
})
module.exports = router;
|
const express = require('express');
var session = require('express-session');
var db = require('../database');
var bodyParser = require('body-parser');
var Objects = require('../objects');
var geo_tools = require('geolocation-utils');
var router = express.Router();
var secretString = Math.floor((Math.random() * 10000) + 1);
router.use(session({
secret: secretString.toString(),
resave: false,
saveUninitialized: false
}));
router.use(bodyParser.urlencoded({
extended: 'true'
}));
router.post('/user_profile', (req, res) => {
db.query("SELECT * FROM user_profile WHERE username = ?", [req.body.username], (err, user_info) => {
db.query("SELECT * FROM users WHERE username = ?", [req.body.username], (err, user_email) => {
db.query("SELECT * FROM user_profile WHERE username = ?", [req.session.username], (err, my_info) => {
db.query("SELECT * FROM likes WHERE username = ? AND likes = ?", [req.session.username, req.body.username], (err, liked_or_not) => {
if (err)
res.send("An error has occured!");
else
{
let like_or_nah = 0;
if (liked_or_not.length > 0)
{
like_or_nah = 1;
}
if (user_info.length > 0)
{
//storing data of who viewed my profile
db.query("SELECT * FROM views WHERE username = ? AND visitor = ?", [user_info[0].username, req.session.username], (err, succ) => {
if (err)
console.log("An error has occured!");
else if (succ.length > 0)
{
console.log("Info alrready exists!");
}
else
db.query("INSERT INTO views (username, visitor) VALUES (?, ?)", [user_info[0].username, req.session.username], (err, results) => {
if (err)
res.send("An error has occured!");
});
})
//This if for rendering the user profile and to indicate whether we shoul enable to users to chat or not
db.query("SELECT like_back FROM likes WHERE username = ? AND likes = ?", [req.session.username, req.body.username], (err, results) => {
if (err)
res.send("An error has occured!");
else
{
if (results.length > 0)
{
if (results[0].like_back == 1)
{
res.render('user_profile', {user_info: user_info[0], user_email: user_email, chat: "Enable", my_username: req.session.username, my_profile_pic: my_info[0].profile_pic, liked_or_not: like_or_nah});
}
else
{
res.render('user_profile', {user_info: user_info[0], user_email: user_email, chat: "Disable", my_username: req.session.username, my_profile_pic: my_info[0].profile_pic, liked_or_not: like_or_nah});
}
}
else
{
res.render('user_profile', {user_info: user_info[0], user_email: user_email, chat: "Disable", my_username: req.session.username, my_profile_pic: my_info[0].profile_pic, liked_or_not: like_or_nah});
}
}
})
//res.render('user_profile', {user_info: user_info[0]});
}
}
})
})
})
})
});
module.exports = router;
|
import { combineReducers } from 'redux';
import tomoReducer from './tomoReducers';
const rootReducer = combineReducers({
tomo: tomoReducer
});
export default rootReducer;
|
/*
** (C) Copyright 2009-2010 by Richard Doll, All Rights Reserved.
**
** License:
** You are free to use, copy, or modify this software provided it remains free
** of charge for all users, the source remains open and unobfuscated, and the
** author, copyright, license, and warranty information remains intact and
** clearly visible.
**
** Warranty:
** All content is provided as-is. The user assumes all liability for any
** direct or indirect damages from usage.
*/
/*
** LabeledHorizontalSlider.js
**
** Define a horizontal slider that automatically updates a label when the value changes.
**
** Note that this is placed under the top-level namespace of ocp.* which
** means this can only be loaded *after* ocp.* has been defined.
*/
// Note what we provide
dojo.provide('ocp.widget.LabeledHorizontalSlider');
// We must have access to our parents and mixins
dojo.require('dijit.form.HorizontalSlider');
// Define the widget
dojo.declare('ocp.widget.LabeledHorizontalSlider',
// We are basically a horizontal slider
dijit.form.HorizontalSlider,
// Our class properties
{
// The DOM ID of the label who's value we will set
labelId: '',
// Do we force the values to be integral?
// For OCP, always yes since all player visible values are whole numbers
forceIntegral: true,
// If a label ID is defined, set the label to our current value
_setLabel: function () {
if (this.labelId.length > 0) {
// Use _getValueAttr so value can be made integral if required
dojo.place('<span>' + this._getValueAttr() + '</span>', this.labelId, 'only');
}
},
// Allow the returned value to be forced integral
_getValueAttr: function (/*String*/ value) {
var val = this.inherited(arguments);
return (this.forceIntegral ? Math.floor(val) : val);
},
// Whenever the value of this slider changes, update the corresponding label
_setValueAttr: function (/*Number*/ value, /*Boolean, optional*/ priorityChange) {
// Let the parent set the new value first, then update the label
// TODO: Should force value integral here?
this.inherited(arguments);
this._setLabel();
}
}
);
|
import styled from 'styled-components';
import theme from '../../styles/theme';
export default styled.div`
margin: 0.5rem 0;
position: relative;
.label {
display: block;
position: absolute;
left: 1.2rem;
top: 1.4rem;
transition: transform .3s;
font-family: ${theme.font.section};
font-weight: bold;
color: ${theme.color.dark};
}
.input {
height: 4rem;
font-size: 1.2em;
padding: .8rem 1rem;
border-radius: .5rem;
border: 2px solid ${theme.color.dark};
width: 100%;
color: ${theme.color.dark};
&:focus, &:not([value=""]) {
padding-top: 2rem;
border-color: ${theme.color.active};
& + .label {
color: ${theme.color.active};
transform: translateY(-1rem);
}
&:not([value=""]) + .label {
color: ${theme.color.active};
}
}
`;
|
"use strict";
var ObsidianPackFile = require("obsidian-pack");
var expect = require("expect.js");
var sha = require("sha.js");
var Q = require("q");
var ObsidianAssetsManager = require("../lib/assets-manager");
var AssetsConverter = require("../lib/assets-converter");
var FILES_Url = location.protocol + "//" + location.host + "/files/";
var imageBuffer = new Buffer([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x10,
0x02, 0x03, 0x00, 0x00, 0x00, 0x62, 0x9d, 0x17, 0xf2, 0x00, 0x00, 0x00,
0x09, 0x50, 0x4c, 0x54, 0x45, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0xff,
0xff, 0xff, 0x67, 0x19, 0x64, 0x1e, 0x00, 0x00, 0x00, 0x01, 0x62, 0x4b,
0x47, 0x44, 0x00, 0x88, 0x05, 0x1d, 0x48, 0x00, 0x00, 0x00, 0x09, 0x70,
0x48, 0x59, 0x73, 0x00, 0x00, 0x0e, 0xc4, 0x00, 0x00, 0x0e, 0xc4, 0x01,
0x95, 0x2b, 0x0e, 0x1b, 0x00, 0x00, 0x00, 0x07, 0x74, 0x49, 0x4d, 0x45,
0x07, 0xdf, 0x0b, 0x12, 0x0d, 0x0b, 0x17, 0xca, 0x83, 0x65, 0x00, 0x00,
0x00, 0x00, 0x3d, 0x49, 0x44, 0x41, 0x54, 0x08, 0x1d, 0x0d, 0xc1, 0xc1,
0x0d, 0x00, 0x21, 0x0c, 0x03, 0xc1, 0x2d, 0x07, 0xd1, 0x0f, 0xfd, 0x9c,
0xf2, 0x8a, 0x5c, 0x05, 0xf2, 0x0b, 0xa5, 0xca, 0xf3, 0x0c, 0x27, 0x98,
0xe0, 0xf3, 0x15, 0x6e, 0x15, 0x2e, 0x0b, 0xeb, 0x09, 0xdf, 0x32, 0x13,
0x4c, 0x50, 0x7a, 0x43, 0xeb, 0x0d, 0xa5, 0xb5, 0xe9, 0x6e, 0x51, 0x5a,
0x9b, 0x09, 0x4e, 0xfc, 0x91, 0x4d, 0x22, 0x7f, 0x72, 0xcc, 0xb0, 0x7f,
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82
]);
var imageData64Url = "data:image/png;base64,";
imageData64Url += "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAACVBMVEUAAAD/AAD//";
imageData64Url += "/9nGWQeAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAAOxAAADsQBlSsOGwAAAAd0SU1FB9";
imageData64Url += "8LEg0LF8qDZQAAAAA9SURBVAgdDcHBDQAhDAPBLQfRD/2c8opcBfILpcrzDCeY4PM";
imageData64Url += "VbhUuC+sJ3zITTFB6Q+sNpbXpblFamwlO/JFNIn9yzLB/AAAAAElFTkSuQmCC";
var imageUrl = FILES_Url + "image.png";
var imageBlob;
var pack = new ObsidianPackFile();
pack.packName = "pack";
pack.addAssetFromBuffer(imageBuffer, "image", { mime: "image/png", metadata: { all: "right" } });
var packBuffer = pack.exportAsBuffer();
var packData64Url = pack.exportAsData64Url();
var packUrl = FILES_Url + "pack.opak";
var packBlob;
describe("ObsidianAssetsManager", function() {
before(function() {
var packAsset = { mime: ObsidianPackFile.MIMETYPE, as: { buffer: packBuffer } };
var asset = { mime: "image/png", as: { buffer: imageBuffer } };
return AssetsConverter._bufferToBlob(asset)
.then(function(asset) {
imageBlob = asset.as.blob;
return AssetsConverter._bufferToBlob(packAsset);
})
.then(function(packAsset) {
packBlob = packAsset.as.blob;
return AssetsConverter._blobToBlobUrl(packAsset);
})
.then(function(packAsset) {
packBlob = packAsset.as.blob;
});
});
describe("assets", function() {
it("can add and remove assets", function() {
var assets = new ObsidianAssetsManager();
return assets.addAssetFromBuffer(imageBuffer)
.then(function(id) {
expect(assets.assetExists(id)).to.be.ok();
assets.removeAsset(id);
expect(assets.assetExists(id)).not.to.be.ok();
});
});
it("can add and get assets from buffer", function() {
var assets = new ObsidianAssetsManager();
return assets.addAssetFromBuffer(imageBuffer)
.then(function(id) {
expect(assets.$data.assetList[id].source).to.match(/^buffer:/);
expect(assets.$data.assetList[id].mime).to.be("application/octet-stream");
return assets.getAssetAsBuffer(id);
})
.then(function(assetBuffer) {
expect(assetBuffer).to.be(imageBuffer);
return assets.addAssetFromBuffer(imageBuffer, { id: "asset1", mime: "image/png" });
})
.then(function(id) {
expect(id).to.be("asset1");
expect(assets.$data.assetList[id].mime).to.be("image/png");
expect(assets.$data.assetList[id].as.buffer).to.be(imageBuffer);
});
});
it("can add and get assets from image", function() {
var assets = new ObsidianAssetsManager();
var image = new Image();
return Q.Promise(function(resolve, reject) {
image.onerror = reject;
image.onload = function(event) {
resolve(assets.addAssetFromImage(image));
};
image.src = imageData64Url;
})
.then(function(id) {
expect(assets.$data.assetList[id].source).to.match(/^image:/);
expect(assets.$data.assetList[id].mime).to.equal("image/png");
return assets.getAssetAsImage(id);
})
.then(function(assetImage) {
expect(assetImage).to.be(image);
});
});
it("can add assets from a Url", function() {
var assets = new ObsidianAssetsManager();
return assets.addAssetFromUrl(imageUrl)
.then(function(id) {
expect(id).to.equal("url:" + sha("sha256").update(imageUrl, "utf8").digest("hex"));
expect(assets.$data.assetList[id].source).to.match(/^url:/);
expect(assets.$data.assetList[id].mime).to.equal("image/png");
});
});
it("can add and get assets from a data64Url", function() {
var assets = new ObsidianAssetsManager();
return assets.addAssetFromData64Url(imageData64Url)
.then(function(id) {
expect(assets.$data.assetList[id].source).to.match(/^data64Url:/);
expect(assets.$data.assetList[id].mime).to.equal("image/png");
return assets.getAssetAsData64Url(id);
})
.then(function(assetData64Url) {
expect(assetData64Url).to.be.eql(imageData64Url);
});
});
it("can add and get assets from a blob", function() {
var assets = new ObsidianAssetsManager();
return assets.addAssetFromBlob(imageBlob)
.then(function(id) {
expect(id).to.be.a("string");
expect(assets.$data.assetList[id].source).to.match(/^blob:/);
expect(assets.$data.assetList[id].mime).to.equal("image/png");
return assets.getAssetAsBlob(id);
})
.then(function(assetBlob) {
expect(assetBlob).to.be(imageBlob);
});
});
it("can add and get assets id from a blob url", function() {
var assets = new ObsidianAssetsManager();
var assetID = null;
return assets.addAssetFromBlob(imageBlob)
.then(function(id) {
assetID = id;
return assets.getAssetAsBlobUrl(id);
})
.then(function(assetBlobUrl) {
expect(assets.getAssetIdFromBlobUrl(assetBlobUrl)).to.be(assetID);
});
});
it("can convert to any type from buffer", function() {
var assets = new ObsidianAssetsManager();
return assets.addAssetFromBuffer(imageBuffer, { id: "asset", mime: "image/png" })
.then(function() { return assets.getAssetAsBlob("asset"); })
.then(function(assetBlob) {
expect(assetBlob).to.be.ok();
expect(assetBlob).to.be.a(Blob);
return assets.getAssetAsBlobUrl("asset");
})
.then(function(assetBlobUrl) {
expect(assetBlobUrl).to.be.ok();
expect(assetBlobUrl).to.be.a("string");
return assets.getAssetAsData64Url("asset");
})
.then(function(assetData64Url) {
expect(assetData64Url).to.equal(imageData64Url);
return assets.getAssetAsImage("asset");
})
.then(function(assetImage) {
expect(assetImage).to.be.ok();
expect(assetImage).to.be.an(Image);
});
});
});
describe("packages", function() {
it("can import and remove package", function() {
var assets = new ObsidianAssetsManager();
return assets.importAssetPackageFromBuffer(packBuffer)
.then(function(pack) {
expect(assets.assetPackageExists("pack")).to.be.ok();
expect(assets.assetExists("pack:pack/image")).to.be.ok();
assets.removeAssetPackage("pack");
expect(assets.assetPackageExists("pack")).not.to.be.ok();
expect(assets.assetExists("pack:pack/image")).not.to.be.ok();
});
});
it("can import package from a buffer", function() {
var assets = new ObsidianAssetsManager();
return assets.importAssetPackageFromBuffer(packBuffer)
.then(function(pack) {
return assets.getAssetAsBuffer("pack:pack/image");
})
.then(function(assetBuffer) {
expect(assets.$data.assetList["pack:pack/image"].metadata.all).to.equal("right");
expect(assetBuffer).to.be.eql(imageBuffer);
});
});
it("can import package from a data64Url", function() {
var assets = new ObsidianAssetsManager();
return assets.importAssetPackageFromData64Url(packData64Url)
.then(function(pack) {
return assets.getAssetAsBuffer("pack:pack/image");
})
.then(function(assetBuffer) {
expect(assets.$data.assetList["pack:pack/image"].metadata.all).to.equal("right");
expect(assetBuffer).to.be.eql(imageBuffer);
});
});
it("can import package from a Url", function() {
var assets = new ObsidianAssetsManager();
return assets.importAssetPackageFromUrl(packUrl)
.then(function(pack) {
return assets.getAssetAsBuffer("pack:pack/image");
})
.then(function(assetBuffer) {
expect(assets.$data.assetList["pack:pack/image"].metadata.all).to.equal("right");
expect(assetBuffer).to.be.eql(imageBuffer);
});
});
it("can import package from a blob", function() {
var assets = new ObsidianAssetsManager();
return assets.importAssetPackageFromBlob(packBlob)
.then(function(pack) {
return assets.getAssetAsBuffer("pack:pack/image");
})
.then(function(assetBuffer) {
expect(assets.$data.assetList["pack:pack/image"].metadata.all).to.equal("right");
expect(assetBuffer).to.be.eql(imageBuffer);
});
});
});
});
|
const express = require('express');
const router = express.Router();
const User = require('../models/User.js');
const config = require('../config/server');
const path = require('path');
const ensureAuthenticated = (req, res, next) => {
// req.isAuthenticated() is a Passport.js function
if(req.isAuthenticated()) {
return next();
} else {
req.flash('error_msg', 'You are not logged in');
res.redirect('/users/login');
}
};
router.get('/', ensureAuthenticated, (req, res) => {
res.render('index', {
title: 'Dashboard',
profileimage_path: path.join(config.user_profile_image_path)
});
});
module.exports = router;
|
import React, { Component } from "react";
import { View, Text, FlatList, StyleSheet } from "react-native";
const users = [
{"id":1,"first_name":"Sandro","last_name":"Eustice"},
{"id":2,"first_name":"Britt","last_name":"Lusted"},
{"id":3,"first_name":"Lenee","last_name":"Matanin"},
{"id":4,"first_name":"Audrie","last_name":"Swapp"},
{"id":5,"first_name":"Anderea","last_name":"Minigo"},
{"id":6,"first_name":"Ferd","last_name":"Gimert"},
{"id":7,"first_name":"Milty","last_name":"Vokes"},
{"id":8,"first_name":"Millicent","last_name":"Keough"},
{"id":9,"first_name":"Oliy","last_name":"Torel"},
{"id":10,"first_name":"Toinette","last_name":"Taffee"},
{"id":11,"first_name":"Frieda","last_name":"Benoi"},
{"id":12,"first_name":"Oliy","last_name":"Blanko"},
{"id":13,"first_name":"Dulce","last_name":"Abson"},
{"id":14,"first_name":"Bonnibelle","last_name":"Farryan"},
{"id":15,"first_name":"Elmore","last_name":"Alliott"},
{"id":16,"first_name":"Barnie","last_name":"Coltan"},
{"id":17,"first_name":"Trudie","last_name":"MacFaell"},
{"id":18,"first_name":"Cordi","last_name":"Talby"},
{"id":19,"first_name":"Rowland","last_name":"Harrington"},
{"id":20,"first_name":"Manya","last_name":"Allington"},
{"id":21,"first_name":"Stavro","last_name":"Halliberton"},
{"id":22,"first_name":"Ardenia","last_name":"Brownill"},
{"id":23,"first_name":"Charline","last_name":"Vido"},
{"id":24,"first_name":"Lyman","last_name":"Jahncke"},
{"id":25,"first_name":"Lyn","last_name":"Edgar"},
{"id":26,"first_name":"Nevile","last_name":"Whyberd"},
{"id":27,"first_name":"Tanya","last_name":"Devonshire"},
{"id":28,"first_name":"Willem","last_name":"Hitchens"},
{"id":29,"first_name":"Briny","last_name":"Audley"},
{"id":30,"first_name":"Rudyard","last_name":"Cowdray"},
{"id":31,"first_name":"Flora","last_name":"Schapero"},
{"id":32,"first_name":"Keefe","last_name":"Kanwell"},
{"id":33,"first_name":"Mayor","last_name":"Reignould"},
{"id":34,"first_name":"Kalli","last_name":"Imison"},
{"id":35,"first_name":"Ikey","last_name":"Lunck"},
{"id":36,"first_name":"Barry","last_name":"MacCambridge"},
{"id":37,"first_name":"Rutledge","last_name":"Rishbrook"},
{"id":38,"first_name":"Garvey","last_name":"Tunno"},
{"id":39,"first_name":"Bent","last_name":"Veness"},
{"id":40,"first_name":"Loy","last_name":"Gentry"},
{"id":41,"first_name":"Decca","last_name":"Bird"},
{"id":42,"first_name":"Rourke","last_name":"McBoyle"},
{"id":43,"first_name":"Lyman","last_name":"Grevel"},
{"id":44,"first_name":"Marna","last_name":"Arp"},
{"id":45,"first_name":"Isidora","last_name":"Spaldin"},
{"id":46,"first_name":"Rickie","last_name":"Echallier"},
{"id":47,"first_name":"Harriette","last_name":"Forgan"},
{"id":48,"first_name":"Hoyt","last_name":"Collier"},
{"id":49,"first_name":"Fred","last_name":"Kneebone"},
{"id":50,"first_name":"Ginnie","last_name":"Pamplin"}]
class Exo8 extends Component {
render() {
return(
<View style={styles.container}>
<FlatList
data={users}
keyExtractor={item => item.id.toString()}
renderItem={( {item} ) => (
<View style={styles.card}>
<Text>{item.first_name} {item.last_name}</Text>
</View>
)}/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
card: {
padding: 10,
borderBottomWidth: 1
}
})
export default Exo8;
|
module.exports = {
extends: [
'eslint:recommended'
],
parser: 'babel-eslint',
env: {
node: true,
mocha: true,
browser: true
},
rules: {
'accessor-pairs': [ 'error' ],
'array-callback-return': [ 'error' ],
'block-scoped-var': [ 'error' ],
'brace-style': [ 'error', '1tbs' ],
'consistent-return': [ 'error' ],
'curly': [ 'error' ],
'indent': [
'error',
2,
{
SwitchCase: 1
}
],
'no-alert': [ 'error' ],
'no-div-regex': [ 'error' ],
'no-else-return': [ 'error' ],
'no-empty-function': [ 'error' ],
'no-eq-null': [ 'error' ],
'no-eval': [ 'error' ],
'no-extend-native': [ 'error' ],
'no-floating-decimal': [ 'error' ],
'no-with': [ 'error' ],
'semi': [ 'off' ]
}
}
|
import Axios from "axios";
const axios = Axios.create({
baseURL: 'https://cnodejs.org/api/v1/'
})
// 请求拦截器
axios.interceptors.request.use(config => {
// post请求设置修改config参数
if (config.method === 'post') {
config.data = Object.assign({
accesstoken: ''
}, config.data)
} else if (config.method === 'get') {
// get请求设置修改config参数
config.params = Object.assign({
accesstoken: ''
}, config.params)
}
}, e => {
return Promise.reject(e)
})
// 响应拦截器
axios.interceptors.response.use(res => {
return res
}, e => {
return Promise.reject(e)
})
export default axios
|
import React from 'react';
import { Card, Row, Col } from 'react-bootstrap';
import * as Chartjs from 'react-chartjs-2';
import 'react-rangeslider/lib/index.css';
import 'react-bootstrap-range-slider/dist/react-bootstrap-range-slider.css';
import RangeSlider from 'react-bootstrap-range-slider';
import { formatCurrency } from './helpers'
import {
DonutChart,
ColorListTable,
ColorListTableRow,
ColorListTableCell
} from '@hydrogenapi/react-components';
import '../styles/element/css/element.css';
import '../App.css';
import "nouislider/distribute/nouislider.css";
export const Account = ({ goal, account, curInventorySlider, monthlyDepositSlider, currentAccountInventory, runGoalProjection, goalProjection, allocation, monthlyFunding, modelHoldings, securities }) => {
const colors = ['#28A6F8', '#1856FA', '#327fa8', '#133080', '#335fd6']
const data = (modelHoldings && modelHoldings.length > 0 && securities.length > 0) ? modelHoldings.map((mh, index) => {
const security = securities.find(s => s.id === mh.security_id);
let securityType;
if (security && security.ticker === 'VTI') securityType = 'Stocks';
if (security && security.ticker === 'BND') securityType = 'Bonds';
return {
value: mh.current_weight,
label: securityType,
asset_class: security && security.asset_class ? security.asset_class : '',
color: colors[index],
}
}) : [];
const accountGoal = account && account.id && account.goals.length > 0 ? account.goals[0] : {};
return (
<div>
<Row noGutters className="row-bordered container-m-nx">
<Card className="p-3 m-2 float-left allocation-info-card">
<h4 className='font-weight-light card-allocation-name text-center'>{allocation.name}</h4>
<span className='font-weight-light'>{allocation.description}</span>
{allocation.id &&
<span className='font-weight-light'>Risk level:
<b> {allocation.name.substr(0, allocation.name.indexOf(' '))}</b>,
Performance: <b>{allocation.performance}%</b>,
Volatility: <b>{allocation.volatility}%</b>
</span>}
{monthlyFunding &&
<div className='slider1-account-div'>
<span className="slider1-title">Monthly deposit</span>
<RangeSlider
value={monthlyDepositSlider ? monthlyDepositSlider : monthlyFunding}
variant="info"
tooltip='on'
min={100}
max={5000}
step={10}
onChange={evt => runGoalProjection({ monthlyDeposit: parseInt(evt.target.value) })}
/>
</div>
}
{currentAccountInventory &&
<div className='slider2-account-div'>
<span className="slider2-title">Current account balance</span>
<RangeSlider
value={curInventorySlider ? curInventorySlider : currentAccountInventory}
variant="info"
tooltip='on'
step={100}
min={100}
max={100000}
onChange={evt => runGoalProjection({ curInventory: parseInt(evt.target.value) })}
/>
</div>}
{goalProjection && goalProjection.current_status && Object.values(goalProjection.current_status.return_details).length > 0 &&
<span className='font-weight-light mt-5'>Projected accounts balance in {accountGoal.accumulation_horizon || accountGoal.decumulation_horizon} years:
<b> ${accountGoal.accumulation_horizon ?
(goalProjection.current_status.final_balance && formatCurrency(goalProjection.current_status.final_balance))
: (goalProjection.current_status.accumulation_balance && formatCurrency(goalProjection.current_status.accumulation_balance))}</b>
</span>}
</Card>
<Card className="client-card-dashboard account-card-no-resize m-2 pt-4 flex-grow-1 float-right">
<DonutChart
width={250}
height={300}
data={data.map(d => { return { value: d.value / 100, color: d.color } })}
/>
<div className="client-table-dashboard pt-4">
<ColorListTable data={data.map(d => { return { value: d.value, label: d.label, color: d.color } })}>
{
data.map((d, index) => {
return (
<ColorListTableRow key={index}>
<ColorListTableCell>{d.asset_class}</ColorListTableCell>
<ColorListTableCell>{d.value.toFixed(2)}%</ColorListTableCell>
</ColorListTableRow>
)
})
}
</ColorListTable>
</div>
</Card>
</Row>
<Row noGutters className="row-bordered container-m-nx">
<Col sm={6} md={3} lg={6} xl={3}>
<Card className="m-2 account-info-cards">
<div className="d-flex align-items-center container-p-x py-4">
<div className="icon-vertical-bar-chart display-4 text-primary"></div>
<div className="ml-3">
<div className="text-muted small">Current Account Balance</div>
<div className="text-large">${curInventorySlider ? curInventorySlider : (currentAccountInventory ? formatCurrency(currentAccountInventory.toFixed(2)) : '0')}</div>
{curInventorySlider && <span className="text-muted">{`Original Balance ${currentAccountInventory ? formatCurrency(currentAccountInventory.toFixed(2)) : '0'}`}</span>}
</div>
</div>
</Card>
</Col>
<Col sm={6} md={3} lg={6} xl={3}>
<Card className="m-2 account-info-cards">
<div className="d-flex align-items-center container-p-x py-4">
<div className="icon-circle-dollar display-4 text-primary"></div>
<div className="ml-3">
<div className="text-muted small">Reccuring Deposit</div>
<div className="text-large">${monthlyDepositSlider ? monthlyDepositSlider : (monthlyFunding ? formatCurrency(monthlyFunding.toFixed(2)) : '0')}</div>
{monthlyDepositSlider && <span className="text-muted">{`Original Deposit ${monthlyFunding ? formatCurrency(monthlyFunding.toFixed(2)) : '0'}`}</span>}
</div>
</div>
</Card>
</Col>
<Col sm={6} md={3} lg={6} xl={3}>
<Card className="m-2 account-info-cards">
<div className="d-flex align-items-center container-p-x py-3">
<div className="icon-goal display-4 text-primary"></div>
<div className="ml-3">
<div className="text-muted small">Goal Target</div>
<div className="text-large">${accountGoal.goal_amount ? formatCurrency(accountGoal.goal_amount) : 0}</div>
<span className="text-muted">{`in ${accountGoal.accumulation_horizon || accountGoal.decumulation_horizon} years`}</span>
</div>
</div>
</Card>
</Col>
<Col sm={6} md={3} lg={6} xl={3}>
<Card className="m-2 account-info-cards">
<div className="d-flex align-items-center container-p-x py-4">
<div className={`${goal && goal.metadata && goal.metadata.image ? goal.metadata.image : `icon-education`} display-4 text-primary`}></div>
<div className="ml-3">
<div className="text-muted small">{goal.name}</div>
{goalProjection && goalProjection.current_status && <div className={`text-large ${goalProjection.current_status.on_track ? 'text-success' : 'text-danger'}`}>{goalProjection.current_status.on_track ? 'Is On Track' : 'Is Not On Track'}</div>}
</div>
</div>
</Card>
</Col>
<Card className="p-3 m-2 w-100">
<h5 className="text-muted font-weight-normal mb-4">Projected growth per years</h5>
{goalProjection && goalProjection.current_status && Object.values(goalProjection.current_status.return_details).length > 0 &&
<div className="w-100 dashboard-chart">
<Chartjs.Line
height={200}
data={{
labels: Object.values(goalProjection.current_status.return_details).map(d => d.cumulative_earnings),
datasets: [{
label: 'Cumulative Earnings',
data: Object.values(goalProjection.current_status.return_details).map((d, index) => index),
borderWidth: 2,
backgroundColor: 'rgba(87, 181, 255, .85)',
borderColor: 'rgba(87, 181, 255, 1)',
pointBackgroundColor: 'rgba(0,0,0,0)',
pointBorderColor: 'rgba(0,0,0,0)',
pointRadius: Object.values(goalProjection.current_status.return_details).length
}]
}}
options={{
scales: {
xAxes: [{
gridLines: {
display: false
},
ticks: {
fontColor: '#aaa',
autoSkipPadding: 50
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
fontColor: '#aaa',
maxTicksLimit: 20
}
}]
},
legend: {
display: false
},
responsive: true,
maintainAspectRatio: false
}}
/>
</div>}
</Card>
</Row>
</div>
)
}
|
Meteor.methods({
addComment : function(id, type, text) {
Comments.insert({
"id": id,
"type": type,
"body": text
});
},
updateNameByType :function (itemId, type, newName) {
if( type == "node") {
var node = Nodes.findOne({ "data.id" : itemId });
//update coords in DB
Nodes.update({
_id: node._id
}, {
$set: { "data.name": newName }
});
} else if (type == "edge"){
var edge = Edges.findOne({ "data.id" : itemId });
Edges.update({
_id: edge._id
}, {
$set: { "data.name": newName }
});
}
},
addNode: function (nodeId, name) {
Nodes.insert({
group: 'nodes',
data: {
id: nodeId,
starred : false,
group : _.random(0,5), // add group
name : name
},
position: {
x: Math.random() *800,
y: Math.random() *600
}
});
},
deleteEdge : function(edgeId) {
var edge = Edges.findOne({ "data.id" : edgeId });
Edges.remove(edge);
},
addEdge : function (sourceId, targetId, name) {
Edges.insert({
group: 'edges',
data: {
id: 'edge' + Math.round( Math.random() * 1000000 ),
"source" :sourceId,
"target" :targetId,
"name" : name
}
});
},
deleteNode: function (nodeId) {
var node = Nodes.findOne({ "data.id" : nodeId });
// console.log(node);
Nodes.remove(node);
},
// selectNode: function (nodeId) {
// var node = Nodes.findOne({ "data.id" : nodeId });
// },
updateNodePosition : function(nodeId, position){
var node = Nodes.findOne({ "data.id" : nodeId });
//update coords in DB
Nodes.update({
_id: node._id
}, {
$set: { position: position }
});
},
lockNode : function(nodeId, position){
var node = Nodes.findOne({ "data.id" : nodeId });
var locked = node.locked ? false : true;
Nodes.update({
_id: node._id
}, {
$set: { "locked": locked, "position" : position }
});
},
starNode : function(nodeId) {
var node = Nodes.findOne({ "data.id" : nodeId });
var starred = node.data.starred ? false : true;
console.log(node.data.starred, starred);
Nodes.update({
_id: node._id
}, {
$set: { "data.starred": starred }
});
},
createRandomNetworkData : function(){
// add random Nodes
for(i = 0; i < 20; i++){
var name = getRandomWord();
var nodeId = 'node' + Math.round( Math.random() * 1000000 );
Meteor.call("addNode", nodeId, name);
}
// add Edges
for(i = 0; i < 25; i++){
var name = getRandomWord();
var source = Random.choice(Nodes.find().fetch());
var target = Random.choice(Nodes.find({_id:{$ne:source._id}}).fetch());//make sure we dont connect to the source
Meteor.call("addEdge", source.data.id, target.data.id, name);
}
},
destroyNetworkData: function() {
// console.log("delete all existing nodes and edges");
Nodes.remove({})
Edges.remove({})
},
resetNetworkData : function() {
Meteor.call("destroyNetworkData");
Meteor.call("createRandomNetworkData");
}
});
|
(function (threadId) {
return function () {
var firstNew = _.getFirstNewPost(threadId);
$.emit('expand', threadId)();
requestAnimationFrame(function () {
var post = document.getElementById("post_" + firstNew);
window.scrollBy(0, post.getBoundingClientRect().top);
})
}
})
|
$(document).ready(function () {
//add new ticket
$('#data-table-ticket').on('click', '.btn-remove', function () {
Lobibox.confirm({
msg: "Bạn có chắc muốn xóa ?",
callback: function ($this, type, ev) {
if (type === 'yes') {
var id_tick = $(this).attr("data-val");
$.ajax({
url: "delete_ticket",
type: "post",
data: { "id_ticket": id_tick },
success: function (result) {
var a = JSON.parse(result);
if (a.code == 0) {
Lobibox.notify('success', {
msg: a.msg
});
}
else {
Lobibox.notify('error', {
msg: a.msg
});
}
}
});
}
}
});
});
});
|
function fun(num){
if (!isNaN(num)) {
if (num==100) {
return "pass";
}
else{
return "true";
}
}else{
return"no";
}}
document.write(fun("baraa"));
console.log(fun(100));
|
// error message handle module
const formatError = (code) => {
var txt;
switch (code) {
case 200:
txt = 'request success';
break;
case 10000:
txt = 'name,account,password,phone or email can not be empty!';
break;
case 10001:
txt = '用户名或账户已经存在。';
break;
case 10002:
txt = '该用户曾经存在但现在处于失效状态';
break;
case 10003:
txt = '数据库内部错误';
break;
case 10004:
txt = '目标用户信息不正确';
break;
}
return txt
}
module.exports = {formatError};
|
const axios = require('axios');
// Docs on event and context https://www.netlify.com/docs/functions/#the-handler-method
const handler = async (event) => {
try {
const { MAPBOX_TOKEN } = process.env;
return {
statusCode: 200,
body: JSON.stringify(MAPBOX_TOKEN)
}
} catch (error) {
return { statusCode: 500, body: error.toString() }
}
}
module.exports = { handler }
|
import React from 'react';
import PropTypes from 'prop-types';
export const CartProductListItem = (props) =>
<React.Fragment>
<li key={props.product.id} onClick={e => props.onClick(e, props.product)} className={`cat-${props.product.category}`}>
<div>{props.product.name}</div>
<div>{props.product.price.toFixed(2)} €</div>
</li>
</React.Fragment>;
CartProductListItem.propTypes = {
product: PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
price: PropTypes.number.isRequired
}).isRequired,
onClick: PropTypes.func.isRequired
};
|
import { createSlice } from '@reduxjs/toolkit';
const initialState = {
loginModalOpen: false,
postModalOpen: false,
};
const modalSlice = createSlice({
name: 'modal',
initialState,
reducers: {
toggleLoginModalOpen(state) {
state.loginModalOpen = !state.loginModalOpen;
},
togglePostModalOpen(state) {
state.postModalOpen = !state.postModalOpen;
},
closeAllModals(state) {
state.loginModalOpen = false;
state.postModalOpen = false;
},
},
});
export const { toggleLoginModalOpen, togglePostModalOpen, closeAllModals } = modalSlice.actions;
export default modalSlice.reducer;
|
import "./App.css";
import Home from "./compnents/home";
import NavBar from "./compnents/navBar"
import CoverPage from "./compnents/coverPage"
import MainPage from "./compnents/mainPage"
import NavBar2 from "./compnents/navBar2"
function App() {
return (
<div>
<NavBar/>
<CoverPage />
<NavBar2/>
<MainPage/>
{/* <Home /> */}
</div>
);
}
export default App;
|
var regex = /Start new|Outlook|Admin|Compliance/;
var tiles = $('.tiles__container').toArray();
for (var i = 0; i < tiles.length; i++) {
if (tiles[i].children[0].children[0].children[0].outerText) {
var outerText = tiles[i].children[0].children[0].children[0].outerText;
if (!outerText.match(regex)) {
//console.log(outerText);
tiles[i].hidden = true;
}
}
}
|
const timeout = time =>
new Promise(resolve => void setTimeout(resolve, time)).catch(console.error);
const sort = async arr => {
if (!Array.isArray(arr)) return [];
const result = [];
arr.forEach(async ele => {
await timeout(ele * arr.length);
result.push(ele);
});
await timeout(Math.max(...arr));
return result;
};
const test = async () => {
const result = await sort([2, 3, 1, 4, 5, 56, 61, 1, 2, 4, 5, 6, 21, 2, 12]);
console.log(result);
};
test();
|
var homeController = (function() {
'use strict';
function all(context){
var sort = context.params.sort;
var category = context.params.category
var template;
partialsHelper.getTemplate('home')
.then(function(templateHtml){
template = templateHtml;
return data.cookies.all();
})
.then(function(res){
var cookies = res.result;
_.map(cookies, function(cookie){
cookie.shareDate = moment(cookie.shareDate).format("MMMM Do YYYY, HH:mm");
})
if(sort){
if(sort.toLowerCase() == "likes"){
cookies = _.sortBy(cookies, function(cookie){
return cookie.likes;
})
} else if(sort.toLowerCase() == "share date"){
cookies = _.sortBy(cookies, function(cookie){
return new Date(cookie.shareDate);
})
}
cookies.reverse();
}
var grouped = _.chain(cookies)
.groupBy('category')
.map(function(items, category) {
return {
category,
items
}
})
.value();
if(category){
grouped = _.filter(grouped, function(group){
return group.category == category;
})
}
var html = htmlRenderer.render(template, {
cookies: grouped,
isLogged: data.users.isLogged()
});
context.$element().html(html);
if(sort){
$('#sort').val(sort);
}
attachEvents(context);
return data.cookies.categories();
})
.then(function(res){
$('#category-filter').autocomplete({
source: res.result
});
});
}
function attachEvents(context){
$('#filter').click(function(){
if(context.params.sort){
context.redirect('#/home?category=' + $('#category-filter').val() + '&sort=' + context.params.sort);
} else {
context.redirect('#/home?category=' + $('#category-filter').val());
}
})
$('#btn-sort').click(function(){
if(context.params.category){
context.redirect('#/home?sort=' + $('#sort').val() + '&category=' + context.params.category);
} else {
context.redirect('#/home?sort=' + $('#sort').val());
}
})
$('.like').click(function(){
var like = this;
var cookieId = $(like).siblings('.cookie-id').text();
data.cookies.like(cookieId)
.then(function(res){
if(res){
var likes = $(like).children('.likes').text();
likes++;
$(like).children('.likes').text(likes);
}
});
});
$('.dislike').click(function(){
var dislike = this;
var cookieId = $(dislike).siblings('.cookie-id').text();
data.cookies.dislike(cookieId)
.then(function(res){
if(res){
var dislikes = $(dislike).children('.dislikes').text();
dislikes++;
$(dislike).children('.dislikes').text(dislikes);
}
});
});
$('.reshare').click(function(){
var $this = $(this);
var text = $this.siblings('.text').text();
var category = $this.siblings('.category').text();
var img = $this.siblings('.image').attr('src');
data.cookies.share(text, category, img)
.then(function(res) {
if(res){
toastr.success('Cookie shared!');
context.redirect('#/home');
setTimeout(function(){
document.location.reload(true);
}, 1000);
}
});
});
}
return {
all: all
};
}());
|
const m = require('mithril')
var Globals = {
flash: {}
}
module.exports = Globals
|
import JassEventId from './eventid';
/**
* type widgetevent
*/
export default class JassWidgetEvent extends JassEventId {}
|
import { connect } from 'react-redux'
import { fetchLeaveTypes,loaddAdd,valueChangeForm,saveFailedForm,
linkidvalueChangeForm, saveLeaveType,loadEdit,
loadDeleteDialog, cancelDelete} from './actions'
import List from './components/list'
import LtForm from './components/ltForm'
const mapStateToProps = (state)=>{
return{
isFetching: state.leavetype.isFetching,
isFetchFailed: state.leavetype.isFetching,
hasError: state.leavetype.hasError,
message: state.leavetype.message,
data: state.leavetype.data,
deleteSuccess: state.leavetype.deleteSuccess,
deletemsg: state.leavetype.deletemsg
}
}
const mapDispatchToProps= (dispatch)=>{
return {
fetch: ()=>{
dispatch(fetchLeaveTypes())
}
}
}
export const Lt_List_Container = connect(mapStateToProps, mapDispatchToProps)(List)
const mapStateToPropsForm=(state)=>{
return{
editMode : state.leavetypeForm.editMode,
isFetching : state.leavetypeForm.isFetching,
isSaving : state.leavetypeForm.isSaving,
hasError : state.leavetypeForm.hasError,
message : state.leavetypeForm.message,
data : state.leavetypeForm.data,
title: state.leavetypeForm.title,
payaccounts: state.leavetypeForm.payaccounts,
saveAddSuccess: state.leavetypeForm.saveAddSuccess,
updateSuccess: state.leavetypeForm.updateSuccess
}
}
const mapDispatchToPropsForm = (dispatch)=>{
const blankdata = {
"id": 0,
"leavecode":'',
"description":'',
"linkId": ''
}
return {
add: ()=>{
dispatch(loaddAdd(blankdata, "Create new leave type"))
},
save: (data,editMode)=>{
dispatch(saveLeaveType(data, editMode))
},
valueChanged: (data, field, value)=>{
dispatch(valueChangeForm(data, field, value))
},
saveFailed: (message)=>{
dispatch(saveFailedForm(message))
},
linkidChange: (val)=>{
dispatch(linkidvalueChangeForm(val))
},
edit: (id)=>{
dispatch(loadEdit(id,"Edit leave type"))
}
}
}
export const Lt_Form_Container = connect(mapStateToPropsForm, mapDispatchToPropsForm)(LtForm)
|
import { createBusValidation } from "../validation";
class createBusServices {
constructor(db) {
this.db = db;
}
async execute(bus) {
if (bus.placa) {
const response = await this.db.findOne({ where: { placa: bus.placa } });
if (response) {
throw new Error(
"this bus already cadastred please try cadastre other bus"
);
}
}
await createBusValidation(bus);
const response = await this.db.create({ ...bus });
return response;
}
}
export default createBusServices;
|
//////////JOBS\\\\\\\\\\\\
export const getJobs = (id) => {
return {
type: 'GET_JOBS',
id: id
}
}
export const setUserJobs = (jobs, sort) => {
return {
type: 'SET_USER_JOBS',
jobs: jobs,
sort
}
}
export const getSomeJobs = (id, jobIds) => {
return {
type: 'GET_SEVERAL_JOBS',
id: id,
jobIds: jobIds
}
}
export const deleteOneJob = (userId, jobId) => {
return {
type: 'DELETE_JOB',
userId: userId,
jobId: jobId
}
}
export const deleteAllJobs = (userId) => {
return {
type: 'DELETE_ALL_JOBS',
userId: userId
}
}
export const createOneJob = (id, ref, data) => {
return {
type: 'ADD_JOB',
id: id,
ref: ref,
data: data
}
}
export const editOneJob = (id, jobId, data) => {
return {
type: 'EDIT_JOB',
id: id,
jobId: jobId,
data: data
}
}
export const reorderJobs = (id, order, jobs) => {
return {
type: 'REORDER_USER_JOBS',
id: id,
order: order,
jobs: jobs
}
}
///////////SORT STATE\\\\\\\\\\\\\
export const getSortState = (id) => {
return {
type: 'GET_SORT_STATE',
id
}
}
export const updateSortState = (id, data) => {
return {
type: 'UPDATE_SORT_STATE',
data,
id
}
}
export const toggleSortState = (order) => {
return {
type: 'SET_SORT_STATE',
order
}
}
///////////INACTIVE STATE\\\\\\\\\\\\\
export const getInactiveState = (id) => {
return {
type: 'GET_INACTIVE_STATE',
id
}
}
export const updateInactiveState = (id, data) => {
return {
type: 'UPDATE_INACTIVE_STATE',
data,
id
}
}
export const toggleInactiveState = (order) => {
return {
type: 'SET_INACTIVE_STATE',
order
}
}
///////////USER\\\\\\\\\\\\\
export const getUser = (id) => {
return {
type: 'GET_USER',
id
}
}
export const setUser = (user) => {
return {
type: 'USER_SET',
user: user
}
}
export const resetUsername = (id, username) => {
return {
type: 'RESET_USERNAME',
id,
username
}
}
//////////UI PANEL\\\\\\\\\\\\
export const toggleUiPanel = (order, data) => {
return {
type: 'TOGGLE_UI_CONTROLS',
order,
data
}
}
//////////INTERACTIONS\\\\\\\\\\\\
export const setInteractions = (interactions) => {
return {
type: 'SET_INTERACTIONS',
interactions: interactions
}
}
export const getInteractions = (id) => {
return {
type: 'GET_INTERACTIONS',
id: id
}
}
export const addInteraction = (id, jobId, ref, data) => {
return {
type: 'ADD_INTERACTION',
id: id,
jobId: jobId,
ref: ref,
data: data
}
}
export const updateInteraction = (id, jobId, ref, data) => {
return {
type: 'UPDATE_INTERACTION',
id,
jobId,
ref,
data
}
}
export const deleteInteraction = (id, application, ref) => {
return {
type: 'DELETE_INTERACTION',
id,
application,
ref
}
}
//////////WISHLIST ACTIONS\\\\\\\\\\\\
export const setWishlistItems = (items) => {
return {
type: 'SET_WISHLIST',
items
}
}
export const addWishlistItem = (id, data) => {
return {
type: 'ADD_WISHLIST_ITEM',
id,
data
}
}
export const updateWishlistItem = (id, ref, data) => {
return {
type: "UPDATE_WISHLIST_ITEM",
id,
ref,
data
}
}
export const deleteWishlistItem = (id, ref) => {
return {
type: "DELETE_WISHLIST_ITEM",
id,
ref
}
}
export const getWishlistItems = (id) => {
return {
type: "GET_WISHLIST_ITEMS",
id
}
}
//////////MODAL ACTIONS\\\\\\\\\\\\
export const toggleModal = (jobOrder, interactionOrder, job, interaction) => {
return {
type: 'SET_MODAL_STATE',
jobModal: jobOrder,
interactionModal: interactionOrder,
job: job,
interaction: interaction
}
}
|
const Sequelize = require('sequelize');
module.exports = (sequelize, DataTypes) => {
return Secretary.init(sequelize, DataTypes);
}
class Secretary extends Sequelize.Model {
static init(sequelize, DataTypes) {
super.init({
id: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
field: 'IDSecretary',
},
userId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'IDUserSecretary',
},
fullName: {
type: DataTypes.VIRTUAL,
get() {
const first = this.firstName == null ? "" : this.firstName;
const second = this.lastName == null ? "" : this.lastName;
return `${first} ${second}`;
},
set(value) {
throw new Error('This value cannot be set.');
}
},
firstName: {
type: DataTypes.STRING(100),
allowNull: false,
field: 'FNameSecretary',
},
lastName: {
type: DataTypes.STRING(100),
allowNull: true,
field: 'LNameSecretary',
},
nationalId: {
type: DataTypes.STRING(50),
allowNull: false,
field: 'NIDSecretary',
},
phone: {
type: DataTypes.STRING(50),
allowNull: false,
field: 'PhoneSecretary',
defaultValue: "",
set(value) {
this.setDataValue('phone', value || "");
}
},
email: {
type: DataTypes.STRING(100),
allowNull: false,
field: 'EmailSecretary',
defaultValue: "",
set(value) {
this.setDataValue('email', value || "");
}
},
}, {
sequelize,
tableName: 'SecretaryTbl',
schema: 'dbo',
timestamps: false,
indexes: [
{
name: "PK__Secretar__AA161EF60AD2A005",
unique: true,
fields: [
{ name: "IDSecretary" },
]
},
]
});
return Secretary;
}
}
|
'use strict'
import {s3Service} from './../service/S3Service'
import logger from './../core/logger'
const get = async (event, context, callback) => {
try {
const objectName = getParams(event, 'name')
logger.info(`Handler: Received a request to get the "${objectName}" object.`)
logger.debug(JSON.stringify(event))
const s3Object = await s3Service.getFromS3(objectName)
logger.info(`Handler: Returning ${objectName}`)
logger.debug(JSON.stringify(s3Object))
callback(null, {
statusCode: 200,
body: s3Object
})
} catch(error) {
logger.error(`Handler: Error occurred: ${JSON.stringify(error)}`)
callback(null, {
statusCode: 500,
body: JSON.stringify(error)
})
}
}
const put = async (event, context, callback) => {
try {
logger.info(`Handler: Adding the test object.`)
if (!event.body) {
callback(null, {
statusCode: 500,
body: JSON.stringify({error: 'Could not add object. Please provide the required name and data params.'})
})
return;
}
const body = JSON.parse(event.body)
const resp = await s3Service.addToS3(getObjectNameFromEvent(body), getObjectDataFromEvent(body))
logger.info(`Handler: Test object added.`)
callback(null, {
statusCode: 200,
body: resp
})
} catch(error) {
logger.error(`Handler: Error occurred: ${JSON.stringify(error)}`)
callback(null, {
statusCode: 500,
body: JSON.stringify(error)
})
}
}
const getParams = (event, name) => {
return event.pathParameters[name]
}
const getObjectNameFromEvent = (body) => {
if (body && body.name) {
return body.name
} else {
throw Error('Could not add object. The required "name" field has not been provided in the request.')
}
}
const getObjectDataFromEvent = (body) => {
if (body && body.data) {
return body.data
} else {
throw Error('Could not add object. The required "data" field has not been provided in the request.')
}
}
export {put, get}
|
import React from 'react'
import Link from 'gatsby-link'
import Card from '../components/Card';
const IndexPage = () => (
<div>
<div className="Hero">
<div className="HeroGroup">
<h1>香港燈塔教育國際</h1>
<h2>网络授课 让地域不再成为一种限制</h2>
<p>汇聚了全球顶尖院校的在校生和毕业生<br />机构的老师均来自该专业世界前五十的名校</p>
<div className="Logos">
<img src={require("../images/AP.png")} height="50" />
<img src={require("../images/ALEVEL.png")} height="50" />
<img src={require("../images/IGCSE.png")} height="50" />
</div>
</div>
</div>
<div className="Cards">
<h2>9 门课程,即将推出更多</h2>
<div className="CardGroup">
<Card
title="数学"
text="Mathematics"
image={require('../images/math-pic.jpg')} />
<Card
title="物理"
text="Physics"
image={require('../images/math-pic.jpg')} />
<Card
title="化学"
text="Chemistry"
image={require('../images/math-pic.jpg')} />
<Card
title="生物"
text="Biology"
image={require('../images/math-pic.jpg')} />
<Card
title="经济"
text="Economy"
image={require('../images/math-pic.jpg')} />
<Card
title="地理"
text="Geology"
image={require('../images/math-pic.jpg')} />
<Card
title="心理"
text="Psychology"
image={require('../images/math-pic.jpg')} />
<Card
title="社会"
text="Sociology"
image={require('../images/math-pic.jpg')} />
<Card
title="历史"
text="History"
image={require('../images/math-pic.jpg')} />
</div>
</div>
</div>
)
export default IndexPage
|
function f (arr) {
var evenNumbers = 0;
var oddNumbers = 0;
var zero = 0;
for (i=0; i < arr.length; i++) {
if (arr[i] % 2 === 0 && arr[i] !== 0) {
evenNumbers = evenNumbers + 1;
} else if (arr[i] % 2 !== 0) {
oddNumbers = oddNumbers + 1;
} else if (arr[i] === 0) {
zero = zero + 1;
};
};
console.log("четные: " + evenNumbers + "; нечетные: " + oddNumbers + "; ноль: " + zero);
};
f([1, 2, 3, 4]);
f([1, 2, 3, 0]);
|
let buttons = document.getElementById("buttons")
let row = document.getElementsByClassName("row")
let display = document.getElementById("display")
let rowbox = document.getElementsByClassName("rowbox")
let equal = document.getElementById("equal")
let sqrt = document.getElementById("sqrt")
let X = document.getElementById("X")
let mod = document.getElementById("mod")
display.innerHTML = [];
let displaytext = display.innerHTML
console.log(displaytext);
function play() {
var audio = document.getElementById("audio");
audio.play();
}
function wow() {
var wow = document.getElementById("wow");
wow.play();
}
let equation = [];
function array() {
for (var i = 0; i < row.length; i++) {
equation.push(row[i].innerHTML)
}
console.log(equation)
return equation
}
array(row)
let test = "";
const sum = eval(test)
for (var i = 0; i < row.length; i++) {
let rowbutton = row[i]
rowbutton.onclick = function() {
wow();
test += rowbutton.innerHTML
for (var i = 0; i < test.length; i++) {
if (test[i] === "C") {
test = "";
}
equal.onclick = function() {
display.innerHTML = eval(test);
play();
}
sqrt.onclick = function() {
display.innerHTML = Math.sqrt(parseInt(test));
}
mod.onclick = function() {
test += "%"
display.innerHTML = test
}
X.onclick = function() {
test += "*"
display.innerHTML = test
}
}
display.textContent = test;
console.log(test);
}
}
|
import React, { Component } from 'react';
import Login from './Pages/Login/Login';
import { Route } from 'react-router-dom';
import Register from './Pages/Register/Register';
import Checklist from './Pages/Checklist/Checklist';
class App extends Component {
state = {}
render() {
return (
<div>
<Route path = "/" component ={Login} exact/>
<Route path = "/register" component ={Register} />
<Route path = "/checklist" component ={Checklist} />
</div>
);
}
}
export default App;
|
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Alert,
Dimensions,
ScrollView,
Image,FlatList,DeviceEventEmitter
} from 'react-native';
import {Actions} from 'react-native-router-flux';
import ActionButton from 'react-native-action-button';
import Icon from 'react-native-vector-icons/Ionicons';
import { CardViewWithIcon,CardViewWithImage} from "react-native-simple-card-view";
export default class DashBoard extends Component{
constructor(props){
super(props);
this.state ={ isLoading: true, dataSource : [] }
}
async componentWillMount() {
//Have a try and catch block for catching errors.
try {
//Assign the promise unresolved first then get the data using the json method.
const response = await fetch('http://192.168.2.21/vanns/App/image.php');
const pokemon = await response.json();
this.setState({dataSource: pokemon, isLoading: false});
} catch(err) {
console.log("Error fetching data-----------", err);
}
}
renderItem(data) {
const miniCardStyle = {
shadowColor : '#000000',
shadowOffsetWidth : 2,
shadowOffsetHeight: 2,
shadowOpacity : 0.1,
hadowRadius : 5,
bgColor : '#ffffff',
padding : 5,
margin : 5,
borderRadius : 3,
elevation : 3,
width : (Dimensions.get("window").width / 2) - 10
};
return (
<View style={ {alignItems: "center",flexDirection: "row",flexWrap: 'wrap',} }>
<CardViewWithImage
width={(Dimensions.get("window").width / 2) - 10}
height={ 30 }
source={ {uri: data.item.image} }
title={ data.item.id }
titleFontSize={ 16 }
style={ miniCardStyle }
roundedImage={ false }
imageWidth={100}
imageHeight={ 100 }
onPress={Actions.DisplayBuilding}
imageMargin={ {top: 10} }
/>
</View>
);
}
render() {
if(!this.state.isLoading){
return(
<View style={styles.container}>
<Text style= {styles.welcome}> Your Buildings </Text>
<View style={ {alignItems: "center",flexDirection:"row",flexWrap: 'wrap',}}>
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
keyExtractor={({id}, index) => id}
horizontal={false}
numColumns={ 2 }
/>
</View>
<ActionButton buttonColor="rgba(231,76,60,1)">
<ActionButton.Item buttonColor='#9b59b6' title="Add Building" onPress={Actions.AddBuilding}>
<Icon name="md-add" style={styles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item onPress={Actions.AddTenant} buttonColor='#3498db' title="Add Tenant">
<Icon name="md-add" style={styles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item buttonColor='#1abc9c' title="View Tenant" onPress={Actions.DisplayTenant}>
<Icon name="md-list" style={styles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item buttonColor='#f4427d' title="Payments" onPress={Actions.pay1}>
<Icon name="md-cash" style={styles.actionButtonIcon} />
</ActionButton.Item>
</ActionButton>
</View>
);
}
else
{
const miniCardStyle = {
shadowColor : '#000000',
shadowOffsetWidth : 2,
shadowOffsetHeight: 2,
shadowOpacity : 0.1,
hadowRadius : 5,
bgColor : '#ffffff',
padding : 5,
margin : 5,
borderRadius : 3,
elevation : 3,
width : (Dimensions.get("window").width / 2) - 10
};
return (
<View style={styles.container}>
<View style={styles.container}>
<Text style= {styles.welcome}> Your buildings are displayed here </Text>
<View style={ {alignItems : "center",justifyContent: "center",flexDirection: "row",flexWrap : 'wrap',} }>
<CardViewWithIcon
withBackground={ false }
androidIcon={ 'md-home' }
iconHeight={ 40 }
iconColor={ '#333' }
title={ 'Building 1' }
contentFontSize={ 20 }
titleFontSize={ 16 }
style={ miniCardStyle }
/>
<CardViewWithIcon
withBackground={ false }
androidIcon={ 'md-home' }
iconHeight={ 40 }
iconColor={ '#333' }
title={ 'Building 1' }
contentFontSize={ 20 }
titleFontSize={ 16 }
style={ miniCardStyle }
/>
<CardViewWithIcon
withBackground={ false }
androidIcon={ 'md-home' }
iconHeight={ 40 }
iconColor={ '#333' }
title={ 'Building 1' }
contentFontSize={ 20 }
titleFontSize={ 16 }
style={ miniCardStyle }
/>
<CardViewWithIcon
withBackground={ false }
androidIcon={ 'md-home' }
iconHeight={ 40 }
iconColor={ '#333' }
title={ 'Building 1' }
contentFontSize={ 20 }
titleFontSize={ 16 }
style={ miniCardStyle }
/>
</View>
</View>
<ActionButton buttonColor="rgba(231,76,60,1)">
<ActionButton.Item buttonColor='#9b59b6' title="Add Building" onPress={Actions.AddBuilding}>
<Icon name="md-add" style={styles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item onPress={Actions.AddTenant} buttonColor='#3498db' title="Add Tenant">
<Icon name="md-add" style={styles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item buttonColor='#1abc9c' title="View Tenant" onPress={Actions.DisplayTenant}>
<Icon name="md-list" style={styles.actionButtonIcon} />
</ActionButton.Item>
<ActionButton.Item buttonColor='#f4427d' title="Payments" onPress={Actions.pay1}>
<Icon name="md-cash" style={styles.actionButtonIcon} />
</ActionButton.Item>
</ActionButton>
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#E0F0EC',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
color: 'black',
},
actionButtonIcon: {
fontSize: 20,
height: 22,
color: 'white',
},
try: {alignItems : "center",flexDirection: "row",flexWrap : 'wrap',},
});
|
var net = require('net');
var host = process.argv[2];
var port = Number(process.argv[3]);
console.log(process);
var socket = net.connect({host: host, port: port});
//var socket = net.connect(host, 22);
socket.setEncoding('utf8');
socket.on('connect', function(){
process.stdin.pipe(socket);
socket.pipe(process.stdout);
process.stdin.resume();
});
socket.on('end', function(){
process.stdin.pause();
});
// socket.once('data', function(chunk){
// console.log('SSH server version: %j', chunk.trim());
// socket.end();
// });
|
/*
Ejercicio 71
Crear un documento con el nombre ej71.js
Mostrar en consola la tabla de multiplicar del 9 (de 1 a 10) utilizando la estructura while
*/
let numero =0;
let resultado = 0;
while ( resultado < 90) {
resultado = numero*9;
console.log(resultado);
numero++;
}
|
import React, { Component } from 'react';
import NavBar from '../NavBar';
import Footer from '../Footer';
import Body from './Body'
import './Projects.css'
class Projects extends Component {
state = { }
render() {
return (
<React.Fragment>
<NavBar />
<Body />
<Footer />
</React.Fragment>
);
}
}
export default Projects;
|
'use stritc'
//modules
var bcrypt = require('bcrypt-nodejs');
//models
var User = require('../models/user');
//jwt service
var jwt = require('../services/jwt');
//nodejs file system
var fs = require('fs');
var path = require('path');
function create (req, res){
var params = req.body;
if(params.password && params.name && params.email && params.role){
var entity = new User();
entity.name = params.name;
entity.surname = params.surname;
entity.email = params.email;
entity.password = params.password;
entity.role = params.role;
// encrypt password
bcrypt.hash(params.password, null, null, function(err, hash) {
entity.password = hash;
});
User.findOne({email: entity.email.toLowerCase()}, (err, result) => {
if(err){
res.status(500).send({message: "Server Error"});
}else{
if(!result){
entity.save((err, saved) => {
if(err){
res.status(500).send({message: "Server Error"});
}else{
if(!saved){
res.status(404).send({message: "Error create"});
}else{
res.status(200).send({message: "Success to create", create: saved});
}
}
});
}else{
res.status(400).send({message: "Duplicate data"});
}
}
});
} else{
res.status(400).send({message: "Missing data"});
}
}
function update (req, res){
var id = req.params.id;
// encrypt password
if(req.body.password){
req.body.password = bcrypt.hashSync(req.body.password);
console.log("cryppassword: "+ req.body.password);
/* bcrypt.hash(req.body.password, null, null, function(err, hash) {
req.body.password = hash;
console.log("cryppassword: "+ req.body.password);
});*/
}
if(id != req.user.sub){
res.status(403).send({message: "Do not have permissions to update data from other users"});
}else{
User.findByIdAndUpdate(id, req.body, {new: true}, (err, updated) => {
if(err){
res.status(500).send({message: "Error to update", update: id});
}else{
res.status(200).send({message: "Success to update", update: updated});
}
});
}
}
function remove (req, res){
var id = req.params.id;
User.findById(id, (err, entity) => {
if(err){
res.status(500).send({message: "Error to get entity", id: id});
}
if(!entity){
res.status(404).send({message: "No found"});
}else{
entity.remove(err => {
if(err){
res.status(500).send({message: "Error to delete ", id: id});
}else{
res.status(200).send({message: "Success to delete", remove: entity});
}
});
}
});
}
function getAll (req, res){
User.find({}).sort('name').exec((err, results) => {
if(err){
res.status(500).send({message: "Error to get all"});
}else{
if(!results){
res.status(404).send({message: "Empty collection"});
}else{
res.status(200).send({items: results});
}
}
});
}
function getById (req, res){
var id = req.params.id;
User.findById(id, (err, result) => {
if(err){
res.status(500).send({message: "Error to get entity", id: id});
}else{
if(!result){
res.status(404).send({message: "No found"});
}else{
res.status(200).send({item: result});
}
}
});
}
function uploadImage(req, res) {
var id = req.params.id;
var file_name = 'Not Upload..';
if(req.files){
var file_path = req.files.image.path;
var file_split = file_path.split('\\');
var file_name = file_split[2];
var ext_split = file_name.split('\.');
var file_ext = ext_split[1];
if(file_ext == 'png' || file_ext == 'jpg' || file_ext == 'gif' || file_ext == 'jpeg' ){
if(id != req.user.sub){
res.status(403).send({message: "Do not have permissions"});
}else{
User.findByIdAndUpdate(id, {image: file_name}, {new: true}, (err, updated) => {
if(err){
res.status(500).send({message: "Error to update", update: id});
}else{
res.status(200).send({message: "Success to update", update: updated, image: file_name});
}
});
}
}else{
fs.unlink(file_path, (err) => {
if(err){
res.status(500).send({message: "File no valid and error to delete bad file"});
}else{
res.status(400).send({message: "File no valid"});
}
});
}
//res.status(200).send({file_path: file_path, file_split, file_split, file_name, file_name});
}else{
res.status(404).send({message: "File no found"});
}
}
function getImageFile(req, res) {
var imageFile = req.params.imageFile;
var file_path = './uploads/users/'+imageFile;
fs.exists(file_path, function(exists){
if (exists) {
res.sendFile(path.resolve(file_path));
} else {
res.status(404).send({message: "File no found"});
}
});
//res.status(200).send({ message: 'get image file' });
}
function login(req, res) {
var params = req.body;
var email = params.email;
var password = params.password;
if(params.password && params.email){
User.findOne({email: email.toLowerCase()}, (err, user) => {
if(err){
res.status(500).send({message: "Server Error"});
}else{
if(user){
bcrypt.compare(password, user.password, (err, check) => {
if (check) {
//check and generate token
if (params.gettoken) {
//token generated
res.status(200).send({
token: jwt.createToken(user)
});
} else {
res.status(200).send({ user });
}
} else {
res.status(404).send({message: "Incorrect username or password "});
}
});
}else{
res.status(404).send({message: "User no found"});
}
}
});
}else{
res.status(400).send({message: "Missing data"});
}
}
module.exports = {
getById,
create,
update,
remove,
getAll,
uploadImage,
getImageFile,
login
}
|
import Mixin from '@ember/object/mixin';
import { computed } from '@ember/object';
import moment from 'moment';
export default Mixin.create({
fullDate: computed('timestamp', function () {
return new Date(this.timestamp * 1000).toString();
}),
dayMonth: computed('timestamp', function () {
return new Date(this.timestamp * 1000).toLocaleDateString('en-US', {
day: '2-digit',
month: 'short',
year: 'numeric'
});
}),
formattedDate: computed('timestamp', function () {
return moment.unix(this.timestamp).format('MMMM DD, YYYY');
}),
sinceDate: computed('timestamp', function () {
return moment(moment.unix(this.timestamp)).fromNow();
})
});
|
import React , {useContext} from 'react';
import {Link} from 'react-router-dom';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';
import {AuthContext} from '../../contexts/AutnContext';
import './menu.sass'
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1,
},
menuButton: {
marginRight: theme.spacing(2),
},
title: {
flexGrow: 1,
},
}));
const bool= false;
const Menu = () => {
const classes = useStyles();
const{austate,logOut}= useContext(AuthContext);
const toggleLogin=()=>{
logOut();
}
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<Typography variant="h6" className={classes.title}> <Link className="menu-item"to="/"><h3>Home</h3></Link> </Typography>
{austate.isAutentificated &&<Link className="menu-item"to="/users"><h3>Користувачі</h3></Link>}
{austate.isAutentificated &&<Link className="menu-item"to="/profile"><h3>Profile</h3></Link>}
{austate.role=="admin" &&<Link className="menu-item"to="/admin"><h3>Admin</h3></Link>}
{!austate.isAutentificated && <Link className="menu-item" to="/login"><h3>Login</h3></Link>}
{austate.isAutentificated &&< a className="menu-item" onClick={toggleLogin}>LogOut</a>}
</Toolbar>
</AppBar>
</div>
)
}
export default Menu
|
module.exports = {
WatsonVisualRecognition: require('./watsonVisualRecognition')
};
|
"use strict";
class Transition {
constructor(current, input, output, next) {
this.current = current;
this.input = input;
this.output = output;
this.next = next;
}
match(current, input) {
return this.current === current && this.input === input;
}
}
class FiniteStateMachine {
constructor(initial_state) {
this.initial_state = initial_state;
}
add_transitions(transitions) {
this.transitions = transitions;
}
get_next(current, input) {
for (let rule of this.transitions) {
if (rule.match(current, input)) {
let log = document.getElementById("log");
log.innerHTML = rule.output;
return rule.next;
}
}
}
accepts(sequence) {
console.log(`Initial state is ${this.initial_state}`);
let current = this.get_next(this.initial_state, sequence[0]);
console.log(`State is ${current}`);
for (let input of sequence.slice(1)) {
current = this.get_next(current, input);
console.log(`State is ${current}`);
}
return current;
}
}
const sleep = function (ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
document.addEventListener("DOMContentLoaded", function (e) {
// Finite State Machine initialisation
let transitions = [
new Transition("W", "00", "Waiting", "W"),
new Transition("W", "10", "Player1 Won", "W1"),
new Transition("W", "01", "Player2 Won", "W2"),
new Transition("W", "11", "Draft", "D"),
];
let fsm = new FiniteStateMachine("W");
fsm.add_transitions(transitions);
let score1 = 0;
let score2 = 0;
// Find interface elements
let lamp = document.getElementById("lamp-on");
let score1_el = document.getElementById("score1");
let score2_el = document.getElementById("score2");
document.getElementById("restart-btn").addEventListener("click", function(_e) {
// Set random delay
let delay = 500 + Math.floor(Math.random() * 3000);
sleep(delay).then(() => {
// Turn-on lamp
lamp.style.color = "#ffff00";
// Decide who was faster
let rnd = Math.random();
let input;
if (rnd < 0.4) {
input = "10";
} else if (rnd > 0.6) {
input = "01";
} else {
input = "11";
}
sleep(700).then(() => {
// Process input with FSM
let res = fsm.accepts([input]);
// Add score to winner
if (res === "W1") {
score1++;
} else if (res === "W2") {
score2++;
} else {
score1++;
score2++;
}
// Update score elements
score1_el.innerHTML = score1;
score2_el.innerHTML = score2;
// Turn-off lamp
lamp.style.color = "#000000";
});
});
})
});
|
function Actor(x, y) {
var self = this instanceof Actor ? this : Object.create(Actor.prototype);
self.x = x || 0;
self.y = y || 0;
return self;
}
Actor.prototype.moveN = function (step) {
step = step === parseInt(step, 10) ? step : 1;
this.y += step;
};
Actor.prototype.moveS = function (step) {
step = step === parseInt(step, 10) ? step : 1;
this.y -= step;
};
Actor.prototype.moveE = function (step) {
step = step === parseInt(step, 10) ? step : 1;
this.x += step;
};
Actor.prototype.moveW = function (step) {
step = step === parseInt(step, 10) ? step : 1;
this.x -= step;
};
var inherits = require("util").inherits;
function GodModeActor(x, y, power) {
var self = this instanceof GodModeActor ? this : Object.create(GodModeActor.prototype);
Actor.call(self, x, y);
self.power = power;
return self;
}
inherits(GodModeActor, Actor);
GodModeActor.prototype.moveNW = function (step) {
step = step === parseInt(step, 10) ? step : 1;
this.x -= step * this.power;
this.y += step * this.power;
};
GodModeActor.prototype.moveNE = function (step) {
step = step === parseInt(step, 10) ? step : 1;
this.x += step * this.power;
this.y += step * this.power;
};
GodModeActor.prototype.moveSW = function (step) {
step = step === parseInt(step, 10) ? step : 1;
this.x -= step * this.power;
this.y -= step * this.power;
};
GodModeActor.prototype.moveSE = function (step) {
step = step === parseInt(step, 10) ? step : 1;
this.x += step * this.power;
this.y -= step * this.power;
};
var actor = Actor(9, 15);
console.log(actor instanceof Actor); // true
console.log(actor.x, actor.y); // 9 15
actor.moveS(3);
console.log(actor.x, actor.y); // 9 12
actor.moveE(7);
console.log(actor.x, actor.y); // 16 12
var gmActor = GodModeActor(22, 8, 2);
console.log(gmActor instanceof GodModeActor); // true
console.log(gmActor instanceof Actor); // true
console.log(gmActor.x, gmActor.y); // 22 8
gmActor.moveN(13);
console.log(gmActor.x, gmActor.y); // 22 21
gmActor.moveW(-4);
console.log(gmActor.x, gmActor.y); // 26 21
gmActor.moveNE(6);
console.log(gmActor.x, gmActor.y); // 38 33
gmActor.moveSE(-8);
console.log(gmActor.x, gmActor.y); // 22 49
|
import React from 'react';
import { useContext, useRef } from 'react';
import { AuthContext } from '../../store/auth-context';
import classes from './RegisterForm.module.css';
export const RegisterForm = (props) => {
const authCtx = useContext(AuthContext);
const firstNameInputRef = useRef();
const lastNameInputRef = useRef();
const usernameInputRef = useRef();
const passwordInputRef = useRef();
// TODO: add LoadingSpinner
// const [isLoading, setIsLoading] = useState(false);
const onCancelHandler = () => {
props.onFinishAuth();
};
const onRegisterHandler = (event) => {
event.preventDefault();
const enteredFirstName = firstNameInputRef.current.value;
const enteredLastName = lastNameInputRef.current.value;
const enteredUsername = usernameInputRef.current.value;
const enteredPassword = passwordInputRef.current.value;
// setIsLoading(true);
fetch('http://localhost:8080/register', {
method: 'POST',
body: JSON.stringify({
firstName: enteredFirstName,
lastName: enteredLastName,
username: enteredUsername,
password: enteredPassword,
}),
headers: {
'Content-Type': 'application/json',
},
})
.then(async (response) => {
// setIsLoading(false);
if (response.ok) {
return response.json();
} else {
// const data = await response.json();
throw new Error('Error');
}
})
.then((data) => {
authCtx.login(data, new Date(new Date().getTime() + 3600000));
props.onFinishAuth();
})
.catch((err) => {
alert(err.message);
});
};
return (
<form onSubmit={onRegisterHandler}>
<div className={classes.inputGroup}>
<div className={classes.inputField}>
<label htmlFor="firstName">First name</label>
<input type="text" id="firstName" ref={firstNameInputRef} required />
</div>
<div className={classes.inputField}>
<label htmlFor="lastName">Last name</label>
<input type="text" id="lastName" ref={lastNameInputRef} required />
</div>
</div>
<div className={classes.inputGroup}>
<div className={classes.inputField}>
<label htmlFor="username">Username</label>
<input type="text" id="username" ref={usernameInputRef} required />
</div>
<div className={classes.inputField}>
<label htmlFor="password">Password</label>
<input
type="password"
id="password"
ref={passwordInputRef}
required
/>
</div>
</div>
<div className={classes.actions}>
<button onClick={onCancelHandler} type="button">
Cancel
</button>
<button>Register</button>
</div>
</form>
);
};
|
var classes________________3________8js____8js__8js_8js =
[
[ "classes________3____8js__8js_8js", "classes________________3________8js____8js__8js_8js.html#a398ac5bec58c24cc6f28b134d8a3cf93", null ]
];
|
var questions = [
{
title: "Select the property used to set the background color of an image",
choices: ["background-color", "background:color", "color:background", "color"],
answer: "background-color"
},
{
title: "Select the property that is used to create spacing between HTML elements?:",
choices: ["padding", "border", "spacing", "margin"],
answer: "margin"
},
{
title: " What is the property used to set the class’ text color?",
choices: ["text-color", "text:color", "color", "font-color"],
answer: "color"
},
{
title: " What is the property used to set the class’s text color?",
choices: ["line-spacing", "line-height", "spacing", "letter-spacing"],
answer: "line-height"
},
{
title: "How do you add a background color for all <h1> elements?",
choices: ["h1.all {background-color: #FFFFFF;}", "h1 {background-color: #FFFFFF;}", "all.h1 {background-color: #FFFFFF;}"],
answer: "h1 {background-color: #FFFFFF;}"
},
{
title: "What is the correct way to write a JavaScript array?",
choices: ["var colors= ['red', 'green', 'blue']", "var colors = 1= (red), 2= (green), 3= (blue)", "var colors= 'red', 'green', 'blue'"],
answer: "parentheses"
},
];
|
import React, {Component} from 'react'
import {connect} from 'react-redux'
import './InformationView.scss'
import { ThemeProvider as MuiThemeProvider } from '@material-ui/core/styles';
import Grid from "@material-ui/core/Grid";
import Paper from "@material-ui/core/Paper";
import { withStyles } from '@material-ui/core/styles';
import Button from "@material-ui/core/Button";
import {ADD_FLASH_MESSAGE, MESSAGE_LOG_IN_SUCCESSFULY} from "../../../../api/flash/flashActions";
import TextField from "@material-ui/core/TextField";
import {CHANGE_USER_NAME} from "../../../../api/login/loginActions";
const styles = theme => ({
root: {
flexGrow: 1,
},
paper: {
padding: 20,
textAlign: 'center',
color: theme.palette.text.secondary,
margin: '10px',
},
});
class InformationView extends Component {
constructor(props) {
super(props);
this.state = {
score: 0,
name: this.props.auth.user.name
}
}
componentWillMount() {
}
componentWillUnmount() {
}
shouldComponentUpdate() {
return true;
}
componentWillUpdate() {
}
componentDidUpdate() {
}
componentDidMount() {
}
componentWillReceiveProps (nextprops) {
if (nextprops.auth !== this.props.auth) {
this.setState({auth: nextprops.auth.user});
this.setState({name: nextprops.auth.user.name});
}
}
onChangeMessage = (e) => {
this.setState({name: e.target.value});
};
changeUsername = () => {
this.props.changeUserName({
data: {
id: this.props.auth.user.id,
name: this.state.name,
email: this.props.auth.user.email,
password: this.props.auth.user.password,
userRole: this.props.auth.user.userRole
},
credentials: {emailAddress: this.props.auth.user.email, password: this.props.auth.user.password}
});
this.setState({message: ''});
};
render = () => {
const {classes, auth} = this.props;
return (
<div style={{height: '700px', marginLeft: '200px', marginTop: '75px'}}>
<MuiThemeProvider>
{auth.isAuthenticated ?
(
<Grid container spacing={0}>
<Grid item xs={12} sm={3}>
<Paper className={classes.paper}>
Name
</Paper>
</Grid>
<Grid item xs={12} sm={9}>
<Paper className={classes.paper}>
{this.props.auth.user.userRole === 'DRIVER' ?
<TextField
underlineStyle={{borderColor: '#1eb1da', color: '#1eb1da'}}
style={{}}
onChange={this.onChangeMessage}
name='addMessage'
value={this.state.name}
/>
:
<div>{this.state.name}</div>
}
</Paper>
</Grid>
<Grid item xs={12} sm={3}>
<Paper className={classes.paper}>Id</Paper>
</Grid>
<Grid item xs={12} sm={9}>
<Paper className={classes.paper}>{auth.user.id}</Paper>
</Grid>
<Grid item xs={12} sm={3}>
<Paper className={classes.paper}>Email</Paper>
</Grid>
<Grid item xs={12} sm={9}>
<Paper className={classes.paper}>{auth.user.email}</Paper>
</Grid>
<Grid item xs={12} sm={3}>
<Paper className={classes.paper}>Role</Paper>
</Grid>
<Grid item xs={12} sm={9}>
<Paper className={classes.paper}>{auth.user.userRole === 'DRIVER' ? 'USER' : 'ADMIN'}</Paper>
</Grid>
{auth.user.userRole === 'USER' && (
<React.Fragment>
<Grid item xs={12} sm={3}>
<Paper className={classes.paper}>Status</Paper>
</Grid>
<Grid item xs={12} sm={9}>
<Paper className={classes.paper}>{auth.user.userStatus}</Paper>
</Grid>
</React.Fragment>
)
}
<Grid item xs={12} sm={3}>
</Grid>
<Grid item xs={12} sm={9}>
<Paper className={classes.paper}>
{this.state.name !== this.props.auth.user.name &&
<Button variant="contained" color="primary" onClick={this.changeUsername}>
Change user data
</Button>}
</Paper>
</Grid>
</Grid>
)
:
(
<div></div>
)
}
</MuiThemeProvider>
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
return {
auth: state.auth || {},
}
};
const mapDispatchToProps = (dispatch, ownProps) => {
return {
showFlashMessage: (data) => dispatch({type: ADD_FLASH_MESSAGE, data}),
changeUserName: (data) => dispatch({type: CHANGE_USER_NAME, data})
}
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(withStyles(styles)(InformationView));
|
import React, { Component } from 'react';
import { Alert } from 'antd';
import { getMainVersion } from './../common/utils';
const version = '0.1.0';
export default class UpgradeNote extends Component {
state = {
currentVersion: version,
latestVersion: version
};
compareVersion = (v1, v2) => {
let vl1 = getMainVersion(v1);
let vl2 = getMainVersion(v2);
return (vl1[0] * 100 + vl1[1] - vl2[0] * 100 - vl2[1]) > 0;
};
componentDidMount = ()=> {
let _component = this;
setTimeout(function () {
//fetch latestVersion and then set this.state
const fetchData = '0.1.1';
_component.setState({
latestVersion: fetchData,
message: (
<div>
uuchat { fetchData } is available! <a href="/" target="_blank">Click here</a> to upgrade.
</div>
)
});
}, 1000);
};
render() {
const { currentVersion, latestVersion,message } = this.state;
if (this.compareVersion(latestVersion, currentVersion)) {
return (
<Alert
type="info"
message="Upgrade Note"
description={ message }
showIcon
closable
banner
/>
);
} else {
return <div/>;
}
}
}
|
module.exports.newick = require('./newick');
module.exports.extended = require('./extended_newick');
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.