text stringlengths 7 3.69M |
|---|
import Post from './post';
import {connect} from '../data';
export default connect(({match}) => `${match.url}/data.json`)(Post);
|
'use strict'
var map, infoclientpos, marker, infoWindow;
var ERRSTRING = "<strong>Error! </strong>";
var SUCCSTRING ="<strong>Success! </strong>";
var HIDEMARKER = true;
var lat0=44;
var lng0=8;
var lat1=45;
var lng1=9;
function clean_str(str){
str=str.replace(/è/gi,'e\'');
str=str.replace(/é/gi,'e\'');
str=str.replace(/ò/gi,'o\'');
str=str.replace(/ù/gi,'u\'');
str=str.replace(/ì/gi,'i\'');
str=str.replace(/à/gi,'a\'');
return str;
}
var variable="";
var str ="";
if(location.pathname.split("/")[2] == "area.php") marker_in_area(variable);
function back_in_area(){
location.reload();
}
function marker_in_area(str){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("marker_in_area").innerHTML = this.responseText;
}
};
xhttp.open("GET", "database/marker_in_area.php?q="+str, true);
xhttp.send();
}
function change_info_area_marker(idmarker) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info-area-marker").innerHTML = this.responseText;
}
};
xhttp.open("GET", "database/change_info_area_marker.php?idmarker="+idmarker, true);
xhttp.send();
}
function name_marker(string){
str = string;
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 44.4029887,
lng: 8.9726596
},
zoom: 16
});
infoclientpos = new google.maps.InfoWindow;
infoWindow=new google.maps.InfoWindow;
google.maps.event.addListener(map, 'bounds_changed', function() {
lat1 = map.getBounds().getNorthEast().lat();
lng1 = map.getBounds().getNorthEast().lng();
lat0 = map.getBounds().getSouthWest().lat();
lng0 = map.getBounds().getSouthWest().lng();
var arl='database/downloadreport.php?lat0=' + lat0 + '&lat1=' + lat1 + '&lng0=' + lng0 + '&lng1=' + lng1 + "&str=" + str ;
downloadUrl(arl,null, function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName('marker');
Array.prototype.forEach.call(markers, function(markerElem) {
var point = new google.maps.LatLng(
parseFloat(markerElem.getAttribute('lat')),
parseFloat(markerElem.getAttribute('lng')));
var infowincontent = document.createElement('div');
var strong = document.createElement('strong');
strong.textContent = markerElem.getAttribute('name');
infowincontent.appendChild(strong);
infowincontent.appendChild(document.createElement('br'));
var text = document.createElement('text');
text.textContent = markerElem.getAttribute('address');
infowincontent.appendChild(text);
var marker = new google.maps.Marker({
map: map,
position: point,
});
marker.addListener('click', function() {
infoWindow.setContent(infowincontent);
infoWindow.open(map, marker);
var id=markerElem.getAttribute('idmarker');
change_info_area_marker(id);
});
});
},false);
});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoclientpos.setPosition(pos);
infoclientpos.setContent('You are Here!');
infoclientpos.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoclientpos, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoclientpos, map.getCenter());
}
if(location.pathname.split("/")[2] == "area.php"){
google.maps.event.addListener(map, 'click', function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
$('#insert').modal('show');
});
}
}
function handleLocationError(browserHasGeolocation, infoclientpos, pos) {
infoclientpos.setPosition(pos);
infoclientpos.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed. Try with HTTPS' :
'Error: Your browser doesn\'t support geolocation.');
infoclientpos.open(map);
}
function bad(message){
$('#insert').modal('hide');
HIDEMARKER=true;
marker.setMap(null);
$('#message').empty();
$('#message').append(ERRSTRING+message);
$('.message').removeClass('alert-success');
$('.message').addClass('alert-danger');
$('.message').removeClass('hide');
return false;
}
function saveData() {
$('.message').addClass('hide');
var reportname=clean_str($('#reportname').val());
var description=clean_str($("#description").val());
var reportcity=clean_str($('#reportcity').val());
var reportaddress=clean_str($('#reportaddress').val());
if(reportname.length===0){
bad("Please insert report name");
return false;
}
if(description.length===0){
bad("Please insert description");
return false;
}
if(reportaddress.length===0){
bad("Please insert address");
return false;
}
if(reportcity.length===0){
bad("Please insert city");
return false;
}
var fd=new FormData();
var x=document.getElementById("fileToUpload");
for(var i=0;i<x.files.length;i++)
fd.append(i.toString(),x.files[i]);
reportname=escape(reportname);
description=escape(description);
reportaddress=escape(reportaddress);
reportcity=escape(reportcity);
var latlng = marker.getPosition();
var url = 'database/uploadreport.php?lat=' + latlng.lat() + '&lng=' + latlng.lng() + '&reportname='+reportname + '&description='+description+"&address="+reportaddress+"&city="+reportcity;
downloadUrl(url,fd, function(data, responseCode) {
if (responseCode == 200 && data.length <= 1) {
$('#insert').modal('hide');
HIDEMARKER=false;
$('#message').empty();
$('#message').append(SUCCSTRING);
$('.message').removeClass('alert-danger');
$('.message').addClass('alert-success');
$('.message').removeClass('hide');
return false;
};
bad("Error: Internal Server Error");
return false;
},true);
}
$(document).ready(function(){
$(".close").click(function(){
$("#message").empty();
$(".message").addClass('hide');
});
});
function downloadUrl(url,fd,callback,upload) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
if(upload)
callback(request.responseText, request.status);
else
callback(request, request.status);
}
};
if(upload){
request.open('POST', url, true);
request.send(fd);
}
else{
request.open('GET', url, true);
request.send(null);
}
}
function doNothing() {
return false;
}
$('#insert').on('hidden.bs.modal',function(){
if (HIDEMARKER)
marker.setMap(null);
HIDEMARKER=true;
});
|
function validate(){
alert("start..");
var employee_name = $("#employee_name").val();
if (employee_name == null || employee_name == "") {
$("#employee_namemsg").html("<font color='red'>用户名不能为空</font>");
return false;
} else {
$("#employee_namemsg").html("");
return true;
}
var employee_loginname = $("#employee_loginname").val();
if (employee_loginname == null || employee_loginname == "") {
$("#employee_loginnamemsg").html("<font color='red'>用户名不能为空</font>");
return false;
} else {
$("#employee_loginnamemsg").html("");
return true;
}
alert("end..");
$("#form1").submit();
} |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const mongoose = require("mongoose");
const DataAccess_1 = require("../DataAccess");
class GroupExpenseSchema {
static get schema() {
let schemaDefinition = {
reportType: {
type: Number,
required: true
},
code: {
type: Number,
required: true,
min: 1
},
groupId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'GroupReport',
required: true
},
isCreditAsPositive: {
type: Boolean,
default: true
}
};
let schema = DataAccess_1.DataAccess.initSchema(schemaDefinition);
schema.index({ reportType: 1, code: 1, groupId: 1 }, { unique: true });
return schema;
}
}
exports.default = DataAccess_1.DataAccess.connection.model('SettingReport', GroupExpenseSchema.schema);
|
import path from 'path';
import tape from 'tape';
import av from 'av';
import AudioInFile from '../src/node/source/AudioInFile';
import Logger from '../src/common/sink/Logger';
// class Asserter extends BaseLfo {
// constructor(asserter, sampleRate, frameSize, buffer) {
// super();
// this.asserter = asserter;
// this.sampleRate = sampleRate;
// this.frameSize = frameSize;
// this.buffer = buffer;
// this.frameIndex = 0;
// this.expectedTime = 0;
// }
// processSignal(frame) {
// const time = frame.time;
// const data = frame.data;
// const sampleIndex = this.frameIndex * this.frameSize;
// const extract = this.buffer.subarray(sampleIndex, sampleIndex + this.frameSize);
// const expectedValues = new Float32Array(this.frameSize);
// expectedValues.set(extract);
// const expectedTime = sampleIndex / this.sampleRate;
// this.asserter.equal(time.toFixed(9), this.expectedTime.toFixed(9), 'Should have same time');
// this.asserter.looseEqual(data, expectedValues, 'Should have same data');
// this.expectedTime += this.frameSize / this.sampleRate;
// this.frameIndex += 1;
// }
// }
tape('AudioInFile', (t) => {
t.comment('implement proper test');
t.comment('particularly with `channels`');
const filename = path.join(__dirname, './audio/sine-172.265625-44.1kHz-1sec.wav');
const frameSize = 512;
const nbrSamples = 44100;
const nbrFrames = Math.ceil(nbrSamples / frameSize);
let i = 0;
const audioInFile = new AudioInFile({
filename: filename,
frameSize: frameSize,
progressCallback: (ratio) => {
i += 1;
t.equal(i / nbrFrames, ratio, 'should call progressCallback with proper ratio');
}
});
const logger = new Logger({ data: true, });
// last frame should contain 68 non zero samples
audioInFile.connect(logger);
audioInFile.start();
t.end();
});
|
'use strict';
const https = require('https');
const fs = require('fs');
const qs = require('querystring');
const crypto = require('crypto');
const exec = require('child_process').execSync;
const property = require('@rokid/property');
const context = require('@rokid/context');
const logger = require('@rokid/logger')('apis');
const uuid = property.get('ro.boot.serialno');
const seed = property.get('ro.boot.rokidseed');
let secret, buffer;
let retry = 0;
function md5(str) {
return crypto.createHash('md5').update(str).digest('hex').toUpperCase();
}
if (uuid && seed) {
const _seed = exec(`test-stupid ${seed} ${uuid}`);
secret = md5(_seed.toString('base64'));
}
function login(callback) {
if (!secret) {
return callback(null);
}
const config = require('/data/system/openvoice_profile.json');
if (config && config.disableAutoRefresh) {
return callback(null);
}
const req = https.request({
method: 'POST',
host: 'device-account.rokid.com',
path: '/device/login.do',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
}
}, (response) => {
const list = [];
response.on('data', (chunk) => list.push(chunk));
response.once('end', () => {
const body = Buffer.concat(list).toString();
try {
const location = '/data/system/openvoice_profile.json';
const data = JSON.parse(JSON.parse(body).data);
const config = require(location);
config['device_id'] = data.deviceId;
config['device_type_id'] = data.deviceTypeId;
config['key'] = data.key;
config['secret'] = data.secret;
context.config = config;
fs.writeFile(location, JSON.stringify(config, null, 2), (err) => {
logger.info(`updated the ${location}`);
// fsync for update
execSync(`fsync ${location}`);
callback(err, data);
});
} catch (err) {
logger.error(err && err.stack);
callback(err);
}
});
});
req.on('error', (err) => {
if (retry <= 10) {
retry += 1;
logger.info('invalid certificate, try again once');
return setTimeout(() => login(callback), 3000);
}
});
let type = config['device_type_id'] || '';
if (type === 'rokid_test_type_id')
type = '';
const time = Math.floor(Date.now() / 1000);
const sign = md5(`${secret}${type}${uuid}${time}${secret}`);
req.write(qs.stringify({
deviceId: uuid,
deviceTypeId: type ? type : undefined,
time,
sign,
}));
req.end();
}
module.exports = function() {
return new Promise((resolve, reject) => {
login((err, data) => {
err ? reject(err) : resolve(data);
});
});
};
|
'use strict';
const Controller = require('egg').Controller;
class ruleController extends Controller {
async list() {
const ctx = this.ctx;
ctx.body = await ctx.service.rule.list({ ...ctx.request.body });
}
}
module.exports = ruleController;
|
"use strict";
(function() {
angular
.module("softCity")
.controller("showController", [
'$scope',
'$http',
'$stateParams',
'auth',
'$timeout',
'greenBar',
ShowControllerFunction
]);
function ShowControllerFunction($scope, $http, $stateParams, auth, $timeout, greenBar) {
var id = $stateParams.id;
$scope.url = 'https://soft-city.herokuapp.com/api/projects/' + id;
var vm = this;
vm.mydata = {};
var getProject = function() {
$http.get($scope.url)
.then(function(res) {
greenBar.helloWorld();
$timeout(function(){
vm.mydata = res.data;
greenBar.goodbyeWorld();
console.log('from show controller');
}, 500);
});
};
getProject();
$scope.auth = auth;
$scope.updateProject = function() {
$http({
method: 'PUT',
url: $scope.url,
data: $.param(vm.mydata),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function(data) {
console.log(data);
getProject();
});
};
$scope.removeField = function(){
vm.mydata.img.pop();
};
$scope.addField = function(){
vm.mydata.img.push('');
};
}
}());
|
'use strict';
module.exports = (sequelize, DataTypes) => {
const Config = sequelize.define('Config', {
scene: DataTypes.INTEGER,
gaslimit: DataTypes.INTEGER,
gasprice: DataTypes.INTEGER
}, {
tableName: 'config',
comment: "配置",
sequelize
});
Config.associate = function(models) {
// associations can be defined here
};
return Config;
}; |
import messages from './messages';
import connection from './connection';
import events from './events';
export default {
messages,
connection,
events,
};
|
/**
* Created by Osvaldo on 20/10/15.
*/
var Manager = require('./manager.js');
var utility = require('util');
var Model = require('../model/dispositivo.js');
var hub = require('../../hub/hub.js');
var Mensagem = require('../../util/mensagem.js');
utility.inherits(DispositivoManager, Manager);
/**
* @constructor
*/
function DispositivoManager(){
var me = this;
Manager.call(me);
me.model = Model;
me.listeners = {};
me.wiring();
}
/**
* Inicia o tratamento dos namespace dos eventos, method recebe o nome da função
* que vai ser executada por meio da herança.
*
* @param msg
*/
DispositivoManager.prototype.executaCrud = function(msg){
var me = this;
var method = msg.getEvento().substr(msg.getEvento().lastIndexOf('.')+1);
console.log(method, msg.getFlag());
try {
me[method](msg);
}catch (e){
hub.emit('error.manager.dispositivo', e);
}
};
/**
* Funcao que busca no banco os dispositivos e popula situacao, modelo e mapa.
*
* @param msg
*/
DispositivoManager.prototype.getDispComplete = function(msg){
var me = this;
var dados = msg.getRes();
this.model.find()
.populate('situacao modelo mapa')
.exec(function(err, res){
if(err){
me.emitManager(msg, '.error.readed', {err: er});
} else{
me.emitManager(msg, '.readed', {res: res});
}
});
};
DispositivoManager.prototype.pedesituacao = function (msg) {
var me = this;
hub.emit('getsituacaogaurdado', msg);
};
DispositivoManager.prototype.completeguardadisps = function (msg, quantos) {
var me = this;
var conterro = 0;
var maparet = msg.getRes();
var arrdisps = maparet.disps;
if(quantos > 0){
var disp = arrdisps[quantos - 1];
disp.mapa = null;
disp.x = 0;
disp.y = 0;
this.model.findByIdAndUpdate(disp._id, {$set: disp}, function(err, res){
if(res){
conterro = 0;
me.completeguardadisps(msg, quantos -1);
} else{
if(conterro < 3){
me.completeguardadisps(msg, quantos);
} else {
console.log('errou demais', msg.getRes(), quantos);
}
}
})
} else {
console.log('terminou aqui');
hub.emit('dispsguardados', msg);
}
};
DispositivoManager.prototype.guardadisp = function (msg) {
var me = this;
var mapa = msg.getRes();
var quantos = mapa.disps.length;
me.completeguardadisps(msg, quantos);
};
/**
* Faz a ligacao dos evendos que essa classe vai escutar, e liga as funcoes que serao executadas
*/
DispositivoManager.prototype.wiring = function(){
var me = this;
me.listeners['banco.dispositivo.*'] = me.executaCrud.bind(me);
me.listeners['rtc.dispositivocomplete.read'] = me.getDispComplete.bind(me);
me.listeners['guardadisps'] = me.pedesituacao.bind(me);
me.listeners['retguardado'] = me.guardadisp.bind(me);
for(var name in me.listeners){
hub.on(name, me.listeners[name]);
}
};
module.exports = new DispositivoManager(); |
/******************************************************************************
*
* PROJECT: Flynax Classifieds Software
* VERSION: 4.1.0
* LICENSE: FL43K5653W2I - http://www.flynax.com/license-agreement.html
* PRODUCT: Real Estate Classifieds
* DOMAIN: avisos.com.bo
* FILE: PHOTO_GALLERY.JS
*
* The software is a commercial product delivered under single, non-exclusive,
* non-transferable license for one domain or IP address. Therefore distribution,
* sale or transfer of the file in whole or in part without permission of Flynax
* respective owners is considered to be illegal and breach of Flynax License End
* User Agreement.
*
* You are not allowed to remove this information from the file without permission
* of Flynax respective owners.
*
* Flynax Classifieds Software 2013 | All copyrights reserved.
*
* http://www.flynax.com/
******************************************************************************/
$(document).ready(function(){
/* enable fancybox */
$('div.photos div.preview a, div#imgSource a').fancybox({
padding: 10,
removeFirst: true,
customIndex: true,
// prevEffect: 'fade',
// nextEffect: 'fade',
//autoPlay: true,
mouseWheel: true,
closeBtn: fb_slideshow_close,
playSpeed: fb_slideshow_delay,
helpers: {
title: {
type: 'over'
},
overlay: {
opacity: 0.5
},
buttons: fb_slideshow
}
});
if ( $('div.slider').length <= 0 )
return;
var marginCss = rlLangDir == 'ltr' ? 'marginRight' : 'marginLeft';
/* set sizes */
var slider_width = $('div.photos div.slider').width();
var item_width = $('div.photos div.slider ul li:first').width();
var items = $('div.photos div.slider ul img').length;
var pages = $('div.photos div.slider ul li').length;
var items_per_slide = $('div.photos div.slider ul li:first img').length;
var moving_width = item_width * items;
var slider_position = 0;
$('div.photos div.slider').width(slider_width);
$('div.photos div.slider ul').width(moving_width).fadeIn();
for ( var i=0; i<pages; i++ )
{
var attr_class = i == 0 ? ' class="active"' : '';
$('div.photos div.navigation').append('<a'+attr_class+' id="imgnav_'+i+'" href="javascript:void(0)"><span> </span></a>');
}
var currentImage = 0;
/* thumbnail click handler */
$('div.photos div.slider ul img').click(function(){
loadImage(this);
});
var loadImage = function(obj){
var index = $(obj).index('div.photos div.slider ul img');
if ( currentImage == index )
{
return;
}
currentImage = index;
$(obj).after('<div class="img_loading"></div>');
var width = $(obj).width();
var height = $(obj).height();
var border = $(obj)[0].clientLeft;
$(obj).next().width(width).height(height).css({opacity: 0.5});
var photo_src = rlConfig['files_url'] + $(obj).attr('class');
// $(obj).children().next().after('<div class="img_loading"></div>');
// var style = $(obj).children().next().attr('style');
// $(obj).children().next().next().attr('style', style).css('opacity', 0.6);
// var photo_src = rlConfig['files_url'] + $(obj).attr('class');
$.fancybox.setIndex(currentImage);
var img = new Image();
img.onload = function(){
$('div.photos div.preview img').attr('src', photo_src);
// var width = $('div.photos div.preview img').width();
// var height = Math.round(img.height * width / img.width);
// var border = $('div.photos div.preview img')[0].clientTop;
// var new_margin = (height + border) * -1;
//
// $('div.photos div.preview img').next().width(width);
// $('div.photos div.preview img').next().height(height).css({marginTop: new_margin});
$(obj).next().fadeOut('normal', function(){
$(this).remove();
});
}
img.src = photo_src;
}
/* navigation click handler */
$('div.photos div.navigation a').click(function(){
var point = parseInt($(this).attr('id').split('_')[1]);
if ( slider_position == point )
{
return;
}
slider_position = point;
moveSlider();
});
$('div.photos div.next').click(function(){
if ( slider_position + 1 < pages)
{
slider_position++;
moveSlider();
}
});
$('div.photos div.prev').click(function(){
if ( slider_position )
{
slider_position--;
moveSlider();
}
});
var moveSlider = function(){
var new_pos = (slider_position * item_width) * -1;
if ( rlLangDir == 'ltr' )
{
$('div.photos div.slider ul').animate({marginLeft: new_pos});
}
else
{
$('div.photos div.slider ul').animate({marginRight: new_pos});
}
$('div.photos div.navigation a').removeClass('active');
$('div.photos div.navigation a:eq('+slider_position+')').addClass('active');
var index = slider_position * items_per_slide;
loadImage($('div.photos div.slider ul img:eq('+index+')'));
if ( !slider_position )
{
$('div.photos div.prev').fadeOut();
}
else
{
$('div.photos div.prev').fadeIn();
}
if ( slider_position + 1 == Math.ceil(pages) )
{
$('div.photos div.next').fadeOut();
}
else
{
$('div.photos div.next').fadeIn();
}
};
}); |
// head {
var __nodeId__ = "std_layouts_cp__main";
var __nodeNs__ = "std_layouts_cp";
// }
(function (__nodeNs__, __nodeId__) {
$.widget(__nodeNs__ + "." + __nodeId__, {
options: {},
_create: function () {
this.bind();
},
_setOption: function (key, value) {
$.Widget.prototype._setOption.apply(this, arguments);
},
bind: function () {
var widget = this;
$(window).rebind("keyup", function (e) {
if (e.keyCode == 120) {
request(widget.options.paths.toggleHeaderHidden);
}
});
ewma.delay(function () {
$(".header", widget.element).css({overflow: 'visible'});
});
var vt = 0;
$(window).resize(function () {
$(".header", widget.element).css({overflow: 'hidden'});
clearTimeout(vt);
vt = ewma.delay(function () {
$(".header", widget.element).css({overflow: 'visible'});
}, 400);
});
}
});
})(__nodeNs__, __nodeId__);
|
import httpClient, { buildPath } from './api.service'
const baseUrl = 'comics'
/**
* Get Comic List
* @param {Object} params
* @returns {Promise}
*/
export const getComics = (params = {}) => httpClient.get(baseUrl, { params })
/**
* Retrieve a comic resource by id
* @param {Number|String} id Comic id
* @param {Object} params Request Params
* @returns {Promise}
*/
export const getComicById = (id, params = {}) =>
httpClient.get(buildPath(baseUrl, id), { params })
/**
* Retrieve a comic's characters
* @param {Number|String} id Comic id
* @param {Object} params Request params
* @returns {Promise}
*/
export const getComicCharacters = (id, params = {}) =>
httpClient.get(buildPath(baseUrl, id, 'characters'), { params })
/**
* Retrieve a comic's creators
* @param {Number|String} id Comic id
* @param {Object} params Request params
* @returns {Promise}
*/
export const getComicCreators = (id, params = {}) =>
httpClient.get(buildPath(baseUrl, id, 'creators'), { params })
/**
* Retrieve a comic's stories
* @param {Number|String} id Comic id
* @param {Object} params Request params
* @returns {Promise}
*/
export const getComicStories = (id, params = {}) =>
httpClient.get(buildPath(baseUrl, id, 'stories'), { params })
/**
* Retrieve a comic's events
* @param {Number|String} id Comic id
* @param {Object} params Request params
* @returns {Promise} Promise
*/
export const getComicEvents = (id, params = {}) =>
httpClient.get(buildPath(baseUrl, id, 'events'), { params })
|
const { Client } = require('@elastic/elasticsearch')
const client = new Client({ node: 'http://localhost:9200' })
const startTheMagic = async () => {
//const pingResult = await client.ping();
//console.log(pingResult);
//const pingResult = await client.cluster.health();
//console.log(pingResult);
//client.indices.create({index: "tracker"});
// const result = await client.index({index:"trackers" , type:"cars" , body:{
// color:'red', year:1990, desc: "im yoni goldberg and i live in haifa"
// }})
const result = await client.search({index: 'trackers',
type: 'cars',
body: {
query: {
wildcard:{desc:"yoni"}
},
}});
console.log(result);
}
startTheMagic() |
const chai = require("chai");
const assert = chai.assert;
const proxyquire = require("proxyquire");
describe("/lib/strategies/webapp-strategy", function(){
console.log("Loading webapp-strategy-test.js");
var WebAppStrategy;
var webAppStrategy;
before(function(){
WebAppStrategy = proxyquire("../lib/strategies/webapp-strategy", {
"./../utils/token-util": require("./mocks/token-util-mock"),
"request": require("./mocks/request-mock")
});
webAppStrategy = new WebAppStrategy({
tenantId: "tenantId",
clientId: "clientId",
secret: "secret",
authorizationEndpoint: "https://authorizationEndpointMock",
tokenEndpoint: "https://tokenEndpointMock",
redirectUri: "https://redirectUri"
});
});
describe("#properties", function(){
it("Should have all properties", function(){
assert.isFunction(WebAppStrategy);
assert.equal(WebAppStrategy.STRATEGY_NAME, "appid-webapp-strategy");
assert.equal(WebAppStrategy.DEFAULT_SCOPE, "appid_default");
assert.equal(WebAppStrategy.ORIGINAL_URL, "APPID_ORIGINAL_URL");
assert.equal(WebAppStrategy.AUTH_CONTEXT, "APPID_AUTH_CONTEXT");
});
});
describe("#logout", function(done){
it("Should be able to successfully logout", function(done){
var req = {
logout: function(){
assert.isUndefined(this[WebAppStrategy.ORIGINAL_URL]);
assert.isUndefined(this[WebAppStrategy.AUTH_CONTEXT]);
done();
},
session: {
APPID_ORIGINAL_URL: "url",
APPID_AUTH_CONTEXT: "context"
}
};
WebAppStrategy.logout(req);
});
});
describe("#ensureAuthenticated", function(done){
it("Should be able to detect unauthenticated request with explicit notAuthenticatedRedirect", function(done){
var req = {
isAuthenticated: function(){
return false;
},
url: "originalUrl",
session: {}
};
var res = {
redirect: function (url) {
assert.equal(url, "explicitUrl");
assert.equal(req.session[WebAppStrategy.ORIGINAL_URL], "originalUrl");
done();
}
};
WebAppStrategy.ensureAuthenticated("explicitUrl")(req, res);
});
it("Should be able to detect unauthenticated request with default redirect", function(done){
var req = {
isAuthenticated: function(){
return false;
},
url: "originalUrl",
session: {}
};
var res = {
redirect: function (url) {
assert.equal(url, "/");
assert.equal(req.session[WebAppStrategy.ORIGINAL_URL], "originalUrl");
done();
}
};
WebAppStrategy.ensureAuthenticated()(req, res);
});
it("Should be able to detect authenticated request and call next()", function(done){
var req = {
isAuthenticated: function(){
return true;
}
};
var next = function(){
done();
}
WebAppStrategy.ensureAuthenticated()(req, null, next());
});
});
describe("#authenticate()", function(){
it("Should fail if request doesn't have session", function(done){
webAppStrategy.error = function(err){
assert.equal(err.message, "Can't find req.session");
done();
}
webAppStrategy.authenticate({});
});
it("Should fail if error was returned in callback", function(done){
webAppStrategy.fail = function(){
done();
};
webAppStrategy.authenticate({
session: {},
query: {
error: "test error"
}
});
});
it("Should handle callback if request contains grant code. Fail due to tokenEndpoint error", function(done){
webAppStrategy.fail = function(err){
assert.equal(err.message, "Failed to obtain tokens");
done();
}
var req = {
session: {},
query: {
code: "FAILING_CODE"
}
}
webAppStrategy.authenticate(req);
});
it("Should handle callback if request contains grant code. Success with options.successRedirect", function(done){
webAppStrategy.success = function(user){
assert.equal(options.successRedirect, "redirectUri");
assert.isObject(req.session[WebAppStrategy.AUTH_CONTEXT]);
assert.isString(req.session[WebAppStrategy.AUTH_CONTEXT].accessToken);
assert.equal(req.session[WebAppStrategy.AUTH_CONTEXT].accessToken, "access_token_mock");
assert.isObject(req.session[WebAppStrategy.AUTH_CONTEXT].accessTokenPayload);
assert.equal(req.session[WebAppStrategy.AUTH_CONTEXT].accessTokenPayload.scope, "appid_default");
assert.isString(req.session[WebAppStrategy.AUTH_CONTEXT].identityToken);
assert.equal(req.session[WebAppStrategy.AUTH_CONTEXT].identityToken, "id_token_mock");
assert.isObject(req.session[WebAppStrategy.AUTH_CONTEXT].identityTokenPayload);
assert.equal(req.session[WebAppStrategy.AUTH_CONTEXT].identityTokenPayload.scope, "appid_default");
assert.isObject(user);
assert.equal(user.scope, "appid_default");
done();
};
var req = {
session: {},
query: {
code: "WORKING_CODE"
}
};
var options = {
successRedirect: "redirectUri"
};
webAppStrategy.authenticate(req, options);
});
it("Should handle callback if request contains grant code. Success with WebAppStrategy.ORIGINAL_URL", function(done){
webAppStrategy.success = function(user){
assert.equal(options.successRedirect, "originalUri");
done();
};
var req = {
session: {
APPID_ORIGINAL_URL: "originalUri"
},
query: {
code: "WORKING_CODE"
}
};
var options = {};
webAppStrategy.authenticate(req, options);
});
it("Should handle callback if request contains grant code. Success with redirect to /", function(done){
webAppStrategy.success = function(user){
assert.equal(options.successRedirect, "/");
done();
};
var req = {
session: {
},
query: {
code: "WORKING_CODE"
}
};
var options = {};
webAppStrategy.authenticate(req, options);
});
it("Should handle authorization redirect to AppID /authorization endpoint", function(done){
webAppStrategy.redirect = function(url){
assert.equal(url, "https://authorizationEndpointMock?client_id=clientId&response_type=code&redirect_uri=https://redirectUri&scope=appid_default");
done();
}
webAppStrategy.authenticate({
session: {}
});
});
});
});
|
var $btnTop = $('.scrollTopBtn')
$('window').on('scroll', function(){
if ($(window).scrollTop() >= 100) {
$btnTop.fadeIn();
} else {
$btnTop.fadeOut();
}
});
$btnTop.on('click', function () {
$('html,body').animate({scrollTop:0}, 1000)
}); |
export default class instaService {
constructor() {
this._apiBase = "http://localhost:3000"; // _- это неизменяемое значение
}
//поля классов, нативный api
//ассинхронная функция es7 => async - await
// fetch - это api, который делает запрос к серверу
getResource = async url => {
const res = await fetch(`${this._apiBase}${url}`);
//проверка прошел ли запрос
if (!res.ok) {
throw new Error(`Could not fetch ${url}; received ${res.status}`);
}
//все ответы приходят в формате json -> в fetch есть свойство .json, который преобразует json в обычный оъект, с котрым мы можем работать дальше в ФАЙЛЕ
// .json это ассинхронная фунция, которая возвращает promise, чтобы ответ записался необходимо поставить await, чтобы подаждать окончание выполнения опреации
return await res.json();
};
//метод который поможет получить все посты
getAllPosts = async () => {
const res = await this.getResource("/posts/");
return res;
};
}
|
import React from 'react';
import './Card.css';
const Card = (props) => {
console.log(props);
return (
<div className="info">
<img src={props.avatar_url} alt="profile pic" width="75"/>
<div className="name">
<h2>{props.name}</h2>
</div>
<div className="company">
<span>Company : @{props.company}</span>
</div>
<div className="location">
<span>Location : {props.location}</span>
</div>
<div className="blog">
<span><a href={props.blog} target={"_blank"} rel="noreferrer">Personal Blog</a></span>
</div>
</div>
)
};
export default Card; |
function sumOfMissingNums (arr) {
const numberArr = arr.filter(x => x.match(/\d+/g))
const maxNum = Math.max(...numberArr)
const minNum = Math.min(...numberArr)
const range = [...Array(maxNum - minNum + 1)].map((_, i) => minNum + i)
return range.length - numberArr.length
}
const result = sumOfMissingNums(['1', '78', 'B', '9', 'z'])
console.log(result)
const resultAnzeige = (document.getElementById('demo').innerHTML = result)
// function sumOfMissingNums(arr) {
// const numbers = arr.filter(v => !isNaN(v));
// return Math.max(...numbers) - Math.min(...numbers) + 1 - numbers.length;
// }
// function sumOfMissingNums(arr) {
// return Array(arr.filter(x=>Number.isInteger(+x)).map(x=>+x).sort((a,b)=>a-b).slice(-1)[0]-arr.filter(x=>Number.isInteger(+x)).map(x=>+x).sort((a,b)=>a-b)[0]+1).fill().map((_,idx)=>arr.filter(x=>Number.isInteger(+x)).map(x=>+x).sort((a,b)=>a-b)[0]+idx).length-arr.filter(x=>Number.isInteger(+x)).map(x=>+x).sort((a,b)=>a-b).length
// }
// function sumOfMissingNums(arr) {
// let nums = arr.filter(x => /\d/.test(x)).map(x => +x).sort((a, b) => a - b),
// len = nums.length;
// return nums[len-1] - nums[0] + 1 - len;
// }
// const sumOfMissingNums = arr => {
// const nums = arr
// .map(Number)
// .filter(Boolean)
// .sort((a, b) => a - b);
// return nums
// .slice(1)
// .reduce((total, curr, i) => total + (curr - nums[i] - 1), 0);
// };
|
import { toast } from 'react-toastify';
const success = (message, url) => {
url ?
toast.success(`${message}`, {
onClose: () => window.location.href=`/${url}`,
autoClose: 1000
}) :
toast.success(`${message}`, {
autoClose: 1000
})
}
const error = message => {
toast.error(`${message}`,{
autoClose: 1000
})
}
export { success, error };
|
import { connect } from "react-redux";
import { HistoryPopup } from "../../../components/utils/popups/HistoryPopup";
import { clearAllTransactions } from "../../../state/actions/customer-actions";
import { STATUS_LOADING, STATUS_SAVE_COMPLETE } from "../../../state/actions";
const mapStateToProps = state => {
return {
users: state.users.list
};
};
const mapDispatchToProps = (dispatch) => ({
onClear: (customerId) => dispatch(clearAllTransactions(customerId)),
onLoadStart: () => dispatch({
type: STATUS_LOADING
}),
onLoadComplete: () => dispatch({
type: STATUS_SAVE_COMPLETE
})
});
export const HistoryPopupContainer = connect(
mapStateToProps,
mapDispatchToProps,
null,
{ forwardRef: true }
)(HistoryPopup);
|
import React from "react";
const _404 = () => {
return (
<div id="error">
<h1>404 Error!!</h1>
<p>You are on the wrong path.</p>
</div>
);
}
export default _404;
|
var path = require('path');
var webpack = require('webpack');
var Dotenv = require('dotenv-webpack');
var combineLoaders = require('webpack-combine-loaders');
module.exports = {
entry: [
'webpack-hot-middleware/client',
path.resolve(process.cwd(), 'app/entry')
],
output: {
path: path.resolve(process.cwd(), 'dist'),
filename: 'bundle.js',
publicPath: '/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new Dotenv({
path: './.env'
})
],
module: {
loaders: [
// js
{
test: /\.js$/,
loader: 'babel',
include: path.resolve(process.cwd(), 'app')
},
// SCSS
{
test: /\.scss$/,
loader: combineLoaders([
{
loader: 'style-loader'
},
{
loader: 'css-loader',
query: {
modules: true,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
loader: 'sass-loader'
},
])
},
// {
// test: /\.(jpg|png)$/,
// loader: 'url?limit=25000',
// include: path.resolve(process.cwd(), 'app/images')
// },
{
test: /\.(jpg|png|gif)$/,
loader: 'file-loader'
// include: path.resolve(process.cwd(), 'app/images')
}
]
},
sassLoader: {
includePaths: [ 'app/Shared/styles' ]
},
devtool: 'source-map',
target: 'web',
stats: true,
progress: true,
resolve: {
root: [
path.resolve('./app')
]
}
};
|
var net = require("net");
var server = net.createServer(function (c) {
console.log("Server connected");
});
server.listen(8080, function () {
console.log("Server started on port 8080");
});
|
const path = require('path')
const assert = require('assert')
const {DataFlow, IdentityError, DataError} = require('../lib')
describe('class DataFlow', () => {
flow = null
it('constructor()', () => {
let schema_dir1 = path.join(__dirname, 'schema1')
let schema_dir2 = path.join(__dirname, 'schema2')
flow = new DataFlow([schema_dir1, schema_dir2])
})
it('constructor(directory does not exist) => Error, code=ENOENT', () => {
assert.throws(() => {
new DataFlow(['path/to/not/exist/directory'])
}, {
code: 'ENOENT'
})
})
it('get existed schema', () => {
let schema = flow.get('//atom/int')
assert.notEqual(schema, null)
assert.equal(typeof schema, 'object')
assert.equal(schema.$id, '//atom/int')
assert.equal(schema.type, 'integer')
})
it('get not existed schema', () => {
let schema = flow.get('//atom/abc')
assert.equal(schema, undefined)
})
it('verify(personal)', () => {
let e = flow.verify('//trop/front/personal', {
name: 'kevin',
age: 18,
gender: 'male'
})
assert.equal(e, undefined)
})
it('verify(invalid_name, invalid_age) => error', () => {
let e = flow.verify('//trop/front/personal', {
name: 100,
age: 'kevin'
})
assert(e instanceof Array)
assert(e.length > 0)
})
it('verify(does not exist schema) => IdentityError', () => {
assert.throws(() => {
flow.verify('//trop/front/does_not_exist', null)
}, IdentityError)
})
it('verify(hero)', () => {
let e = flow.verify('//trop/hero', {
name: 'hulk',
strength: 69
})
assert.equal(e, undefined)
})
it('verify(hero by null) => error', () => {
let e = flow.verify('//trop/hero', null)
assert(e instanceof Array)
assert(e.length > 0)
})
})
|
export { default as Typography } from './Typography'
export { default as Button } from './Button'
export { default as ThemeProvider } from './ThemeProvider'
|
export default {
route: {
currentPage: 'Dashboard'
},
user: {
login: {
ok: true
}
}
};
|
export const AUTH_LOGIN = 'auth/login';
export const AUTH_LOGIN_SUCCESS = 'auth/loginSuccess';
export const AUTH_LOGIN_FAILED = 'auth/loginFailed';
export const AUTH_SIGN_UP = 'auth/signUp';
export const AUTH_SIGN_UP_SUCCESS = 'auth/signUpSuccess';
export const AUTH_SIGN_UP_FAILED = 'auth/signUpFailed';
export const AUTH_CLEAR = 'auth/clear';
|
module.exports = {
presets: ['@babel/preset-typescript', '@babel/preset-env'],
plugins: ['remove-template-literals-whitespace']
};
|
import React from 'react'
import { Link } from 'react-router-dom'
export default function SearchBox({ location, history }) {
const searchformInput = React.createRef()
function handleSubmit(event) {
event.preventDefault()
const query = searchformInput.current.value
if (query !== '') {
history.push(`/items?search=${query}`)
}
}
function searchformInputValue() {
const params = new URLSearchParams(location.search)
const hasSearch = params.has('search')
if (hasSearch) {
return params.get('search')
}
return ''
}
return (
<div className="search-box">
<div className="search-box-contents container container--meli">
<div className="columns is-centered is-vcentered is-mobile">
<div className="column is-1">
<Link to="/" className="meli-logo">
<span className="is-sr-only">Mercado Libre</span>
</Link>
</div>
<div className="column is-9">
<div className="search-box-form">
<form role="search" onSubmit={handleSubmit}>
<div className="field has-addons">
<div className="control is-expanded">
<input
className="search-box-input input"
id="search-box-input"
aria-label="Escribe lo que quieres encontrar"
type="text"
defaultValue={searchformInputValue()}
placeholder="Nunca dejes de buscar"
ref={searchformInput}
/>
</div>
<div className="control">
<button className="search-box-button button" type="submit">
<span className="search-box-button-icon" aria-hidden="true"></span>
<span className="is-sr-only">Buscar</span>
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
|
var sp = require("serialport");
var fs = require("fs");
require("sugar");
module.exports = function SerialPort(io) {
var port;
var baud = require("./baudrate.json").baudrate;
var openCallback = function() {};
io.on('connection', function (socket) {
sendState(socket);
socket.on('serial-connect', function(data) {
connect(data.baudrate, socket);
});
socket.on('serial-write', function(data) {
writeData(data.char);
});
});
function sendState(socket) {
socket.emit("serial-baudrate", baud);
if(port && port.isOpen())
socket.emit('serial-read', "@@@ The serial port is connected at "+baud+" baud @@@\n");
else
socket.emit('serial-read', "@@@ The serial port is not connected @@@\n");
}
function connect(baudrate, socket) {
if(port)
port.close();
saveBaudrate(baudrate);
port = new sp.SerialPort("/dev/ttyAMA0", {
baudrate: baudrate,
parser: sp.parsers.raw
});
port.on("open", function() {
console.log("open serial port");
port.on('data', onRead);
port.on('error', function (err) {
console.log("Connection error");
});
if(socket)
sendState(socket);
});
}
function onRead(symbol) {
io.emit('serial-read', symbol+"");
}
function getPortList(callback) {
sp.list(function(err, ports) {
callback(ports);
});
}
function writeData(buffer) {
if(port && port.isOpen()) {
port.write(buffer);
}
}
function saveBaudrate(baudrate) {
baud = baudrate;
fs.writeFile( "./baudrate.json", JSON.stringify({ baudrate: baudrate}), "utf8");
}
//connect(9600);
} |
/* Functionality */
/* Search functionality */
function enableSearch() {
search.addEventListener('keyup', function() {
if (search.value != '') {
pageTitle.innerHTML = 'Searching...' + search.value;
ajaxGet('api/search/?key=' + this.value, addProducts);
} else {
pageTitle.innerHTML = 'All Products';
ajaxGet('api/products/', addProducts);
}
}, true);
}
/* Displays an individual product */
function showProduct(response) {
clearHTML(pageTitle);
search.value = '';
// there should be only one result
var product = JSON.parse(response)[0];
ajaxGet('inc/product.php', function(response) {
content.innerHTML = response;
// popluates text fields
setElementText(elementWithId('productName'), product.productName);
setElementText(elementWithId('productDesc'), product.productDesc);
setElementText(elementWithId('productPrice'), '£' + product.productPrice);
// populates image
elementWithId('productImage').setAttribute('src', 'cms/images/' +
product.productImage);
// calculates the remaining stock
if (quantityInBasket(product.productID)) {
var remainingStock = product.productStock -
quantityInBasket(product.productID);
} else {
var remainingStock = product.productStock;
}
// checks if out of stock
if (remainingStock != 0) {
setElementText(elementWithId('productStock'), remainingStock);
} else {
setElementText(elementWithId('productStock'),
'Sorry this product is out of stock!');
// hide the add to basket options
elementWithId('quantity').style.display = 'none';
elementWithId('addToBasket').style.display = 'none';
}
elementWithId('quantity').setAttribute('max', remainingStock);
elementWithId('addToBasket').addEventListener('click', function() {
addToBasket(product);
});
});
}
/* Creates an individual product */
function createListProduct(productObj) {
var product = createElement('li');
setElementId(product, 'product_' + productObj.productID);
setElementClass(product, 'product');
// populates the product name
var productName = createElement('h1');
setElementText(productName, productObj.productName);
// add div to ensure sizing is correct
var sizingDiv = createElement('div');
setElementClass(sizingDiv, 'imgSize');
var imageElement = createElement('img');
if (productObj.productImage != null) {
// populates the product image
imageElement.setAttribute('src', 'cms/images/' + productObj.productImage);
} else {
// populates a default image
imageElement.setAttribute('src', 'cms/images/noImage.jpg');
}
var productPrice = createElement('p');
setElementText(productPrice, '£' + productObj.productPrice);
sizingDiv.appendChild(imageElement);
product.appendChild(sizingDiv);
product.appendChild(productName);
product.appendChild(productPrice);
// shows product when clicked
product.addEventListener('click', function() {
ajaxGet('api/product/?productID=' + productObj.productID, showProduct);
});
return product;
}
/* Creates and displays all products */
function addProducts(response) {
clearContent();
if (response !== null) {
var products = JSON.parse(response);
if (products.length != 0) {
// create product list
var productList = createElement('ul');
setElementId(productList, 'product-list');
content.appendChild(productList);
// loops over products
for (var i = 0; i < products.length; i++) {
productList.appendChild(createListProduct(products[i]));
}
} else {
content.innerHTML = 'Sorry, there are no products to display!';
}
}
}
/* Creates a category button */
function createCategoryButton(categoryName) {
var categoryButton = createButton(categoryName, categoryName);
setElementClass(categoryButton, 'navBtn');
elementWithId('categories').appendChild(categoryButton);
categoryButton.addEventListener('click', function(e) {
pageTitle.innerHTML = e.target.id;
ajaxGet('api/products/?categoryName=' + e.target.id, addProducts);
});
}
/* Populates the category menu */
function addCategories(response) {
clearHTML(elementWithId('categories'));
var categories = JSON.parse(response);
// sorts categories alphabetically
categories.sort(sort_by('categoryName', true));
for (var i = 0; i < categories.length; i++) {
createCategoryButton(categories[i].categoryName);
}
}
/* Loads / setup the store */
function loadStore() {
clearContent();
getStyle();
ajaxGet('api/categories/', addCategories);
ajaxGet('api/products/', addProducts);
updateBasketCost();
enableSearch();
}
/* Event Listeners */
/* loads all products on click */
elementWithId('products').addEventListener('click', function() {
pageTitle.innerHTML = 'All Products';
loadStore();
});
/* displays the customers basket on click */
elementWithId('basket').addEventListener('click', function() {
pageTitle.innerHTML = 'Basket';
ajaxGet('inc/basket.php', loadBasket);
});
/* Loads the store */
window.addEventListener('load', loadStore);
|
$(document).ready(function () {
var issaKnife = document.createElement('audio');
issaKnife.setAttribute('src', 'issaknife.mp3');
function makeNewPosition(){
var nh = Math.floor(Math.random() * $(window).height());
var nw = Math.floor(Math.random() * $(window).width());
return [nh,nw];
}
function makeNewPosition2(){
var nh = Math.floor(Math.random() * $(window).height()) - 100;
var nw = Math.floor(Math.random() * $(window).width()) - 100;
return [nh,nw];
}
function animateDiv(){
var newq = makeNewPosition2();
$('.savage').animate({ top: newq[0], left: newq[1]}, 3000, function(){
animateDiv();
});
};
animateDiv();
$(".savage").click(function () {
document.body.style.background = "black";
setTimeout(function(){
document.body.style.background = "grey";
}, 750);
$('.savage').attr('src','21savage.png');
setTimeout(function(){
$('.savage').attr('src','bird.png');
}, 750);
issaKnife.play();
});
var printTweets = function (context) {
var source;
if (context === 'all') {
source = streams.home;
} else if (context) {
source = streams.users[context];
};
for (var i = source.length - 1; i >= 0; i--) {
var tweet = source[i];
var $tweet = $('<div class = "tweet"></div>');
$tweet.css({top: makeNewPosition()[0], left: makeNewPosition()[1]});
var $user = $('<a></a>');
$user.attr({'href': '#', 'data-user': tweet.user, 'class': 'username'});
$user.text('@' + tweet.user);
$user.appendTo($tweet);
$tweet.append(tweet.message + "<br>");
var $tweetTime = $('<div class = "timestamp"></div>');
var readableTime = moment(tweet.created_at).fromNow();
$tweetTime.text(readableTime);
$tweetTime.appendTo($tweet);
$tweet.appendTo(".divbody");
};
$('.username').on('click', function() {
$(".tweet").remove()
printTweets($(this).data('user'));
});
};
$('.savage').on('click', function() {
printTweets('all');
});
});
|
// JavaScript Document
//讓捲軸用動畫的方式移動到到指定的位罝======================
$(function(){
$(".scrollgo").click(function(){
var sGoTo = $(this).attr("rel"); //取得目標物的id class
var $body = (window.opera) ? (document.compatMode === "CSS1Compat" ? $('html') : $('body')) : $('html,body'); //修正 Opera 問題
$body.animate({
scrollTop: $(sGoTo).offset().top
}, 1000);
return false;
});
});
//gototop
$(function(){
var iScrollPointA = 0; //回到某一個點
var iScrollPointB = 700; //滾到某一個點
var sGototopHtml = '<div class="gototop">TOP</div>';
$("body").append(sGototopHtml);
$(".gototop").hide();
$(window).scroll(function(){
if( $(window).scrollTop() > iScrollPointB) {
$(".gototop").show();
} else {
$(".gototop").hide();
};
});
// 讓捲軸用動畫的方式移動到到指定id位罝
$(".gototop").click(function(){
var $body = (window.opera) ? (document.compatMode == "CSS1Compat" ? $('html') : $('body')) : $('html,body'); //修正 Opera 問題
$body.animate({scrollTop: iScrollPointA}, 1000);
return false;
});
});
//地圖
$(document).ready(function () {
$('iframe[src*="map.htm"]').wrap('<div class="mapcontent" />');
}); |
const express = require("express");
const mongoose = require("mongoose");
const router = express.Router();
const returnRouter = function(io, auth) {
// Load message model
require("../models/Message");
const Message = mongoose.model("messages");
// Getting index page and loading messages
router.get("/", auth, (req, res) => {
Message.find({})
.sort({ date: 1 })
.then(messages => {
res.render("messages/index", {
messages: messages,
username: req.user.username
});
});
});
// Posting messages and emitting to client
router.post("/", auth, (req, res) => {
const NewMessage = {
name: req.body.name,
message: req.body.message
};
io.emit("message", NewMessage);
new Message(NewMessage).save(err => {
res.sendStatus(200);
});
});
return router;
};
module.exports = returnRouter;
|
// Generated by CoffeeScript 1.4.0
(function() {
$(function() {
var CIRCLE, ELLIPSE, FIRST_POINT, LINE, NUM_CANVAS, POLYGON, POLYLINE, RECT, SECOND_POINT, WAIT, actionCircle, actionEllipse, actionLine, actionPolygon, actionPolyline, actionRect, dist, ellipsePlot, getMousePos, i, performAction, _i, _ref, _results;
LINE = 1;
CIRCLE = 2;
ELLIPSE = 3;
RECT = 4;
POLYGON = 5;
POLYLINE = 6;
WAIT = 0;
FIRST_POINT = 1;
SECOND_POINT = 2;
NUM_CANVAS = 6;
window.drawStatus = {
line: {
status: WAIT,
p1: {
x: 0,
y: 0
},
p2: {
x: 0,
y: 0
}
},
circle: {
status: WAIT,
p1: {
x: 0,
y: 0
},
radius: 0
},
ellipse: {
status: WAIT,
p1: {
x: 0,
y: 0
},
a: 0,
b: 0
},
rect: {
status: WAIT,
p1: {
x: 0,
y: 0
},
p2: {
x: 0,
y: 0
}
},
polygon: {
status: WAIT,
pts: []
},
polyline: {
status: WAIT,
pts: []
}
};
window.drawLine = function(cnvs, x0, x1, y0, y1) {
var deltaerr, deltax, deltay, error, x, y, _i, _results;
x0 = Math.floor(x0);
x1 = Math.floor(x1);
y0 = Math.floor(y0);
y1 = Math.floor(y1);
deltax = x1 - x0;
deltay = y1 - y0;
error = 0;
if (deltax === 0) {
x = x0;
y = y0;
while (y !== y1) {
plot(cnvs, x, y);
y = y + ((y1 - y0) > 0 ? 1 : -1);
}
return;
}
deltaerr = Math.abs(deltay / deltax);
y = y0;
_results = [];
for (x = _i = x0; x0 <= x1 ? _i <= x1 : _i >= x1; x = x0 <= x1 ? ++_i : --_i) {
plot(cnvs, x, y);
error = error + deltaerr;
_results.push((function() {
var _results1;
_results1 = [];
while (error >= 0.5 && y1 - y !== 0) {
plot(cnvs, x, y);
y = y + ((y1 - y0) > 0 ? 1 : -1);
_results1.push(error = error - 1.0);
}
return _results1;
})());
}
return _results;
};
window.drawCircle = function(cnvs, x0, y0, radius) {
var radiusError, x, y, _results;
x0 = Math.floor(x0);
y0 = Math.floor(y0);
radius = Math.floor(radius);
x = radius;
y = 0;
radiusError = 1 - x;
_results = [];
while (x >= y) {
plot(cnvs, x + x0, y + y0);
plot(cnvs, y + x0, x + y0);
plot(cnvs, -x + x0, y + y0);
plot(cnvs, -y + x0, x + y0);
plot(cnvs, -x + x0, -y + y0);
plot(cnvs, -y + x0, -x + y0);
plot(cnvs, x + x0, -y + y0);
plot(cnvs, y + x0, -x + y0);
y++;
if (radiusError < 0) {
radiusError += 2 * y + 1;
continue;
}
radiusError += 2 * (y - x) + 1;
_results.push(x--);
}
return _results;
};
ellipsePlot = function(cnvs, x0, y0, x, y) {
plot(cnvs, x0 + x, y0 + y);
plot(cnvs, x0 - x, y0 + y);
plot(cnvs, x0 + x, y0 - y);
return plot(cnvs, x0 - x, y0 - y);
};
window.drawEllipse = function(cnvs, x0, y0, a, b) {
var asq, bsq, p, px, py, twoasq, twobsq, x, xhalfsq, y, ymin1sq, _results;
x0 = Math.floor(x0);
y0 = Math.floor(y0);
a = Math.floor(a);
b = Math.floor(b);
asq = a * a;
bsq = b * b;
twoasq = 2 * asq;
twobsq = 2 * bsq;
x = 0;
y = b;
px = 0;
py = twoasq * y;
ellipsePlot(cnvs, x0, y0, x, y);
p = Math.round(bsq - (asq * b) + (0.25 * asq));
while (px < py) {
x++;
px += twobsq;
if (p < 0) {
p += bsq + px;
} else {
y--;
py -= twoasq;
p += bsq + px - py;
}
ellipsePlot(cnvs, x0, y0, x, y);
}
xhalfsq = (x + 0.5) * (x + 0.5);
ymin1sq = (y - 1) * (y - 1);
p = Math.round(bsq * xhalfsq + asq * ymin1sq - asq * bsq);
_results = [];
while (y > 0) {
y--;
py -= twoasq;
if (p > 0) {
p += asq - py;
} else {
x++;
px += twobsq;
p += asq - py + px;
}
_results.push(ellipsePlot(cnvs, x0, y0, x, y));
}
return _results;
};
window.drawRect = function(cnvs, p1, p2) {
drawLine(cnvs, p1.x, p2.x, p1.y, p1.y);
drawLine(cnvs, p1.x, p2.x, p2.y, p2.y);
drawLine(cnvs, p1.x, p1.x, p1.y, p2.y);
return drawLine(cnvs, p2.x, p2.x, p1.y, p2.y);
};
window.drawPolygon = function(cnvs, pts) {
var last;
drawPolyline(cnvs, pts);
last = pts[pts.length - 1];
return drawLine(cnvs, pts[0].x, last.x, pts[0].y, last.y);
};
window.drawPolyline = function(cnvs, pts) {
var i, pt, _i, _len, _results;
_results = [];
for (i = _i = 0, _len = pts.length; _i < _len; i = ++_i) {
pt = pts[i];
if (i < pts.length - 1) {
_results.push(drawLine(cnvs, pt.x, pts[i + 1].x, pt.y, pts[i + 1].y));
}
}
return _results;
};
window.plot = function(cnvs, x, y) {
var ctx, size;
ctx = cnvs.getContext('2d');
ctx.fillStyle = $('#line-color')[0].value;
size = $('#line-thickness')[0].value;
return ctx.fillRect(x, y, size, size);
};
window.clearCnvs = function(cnvs) {
var ctx;
ctx = cnvs.getContext('2d');
return ctx.clearRect(0, 0, cnvs.width, cnvs.height);
};
$('.clear-btn').click(function() {
var cnvs;
cnvs = $(this).closest('.centered').find('canvas')[0];
return clearCnvs(cnvs);
});
$('#btn-draw-line').click(function() {
var c;
c = cnvs[LINE];
$(c).addClass('crosshair');
return drawStatus.line.status = FIRST_POINT;
});
$('#btn-draw-circle').click(function() {
var c;
c = cnvs[CIRCLE];
$(c).addClass('crosshair');
return drawStatus.circle.status = FIRST_POINT;
});
$('#btn-draw-ellipse').click(function() {
var c;
c = cnvs[ELLIPSE];
$(c).addClass('crosshair');
return drawStatus.ellipse.status = FIRST_POINT;
});
$('#btn-draw-rect').click(function() {
var c;
c = cnvs[RECT];
$(c).addClass('crosshair');
return drawStatus.rect.status = FIRST_POINT;
});
$('#btn-draw-pgon').click(function() {
var c;
c = cnvs[POLYGON];
if (drawStatus.polygon.status === WAIT) {
$(this).removeClass('btn-primary');
$(this).addClass('btn-success');
$(c).addClass('crosshair');
$(this).text('Finish Polygon');
drawStatus.polygon.status = FIRST_POINT;
return;
}
$(this).removeClass('btn-success');
$(this).addClass('btn-primary');
$(c).removeClass('crosshair');
$(this).text('Draw Polygon');
drawStatus.polygon.status = WAIT;
drawPolygon(c, drawStatus.polygon.pts);
drawStatus.polygon.pts = [];
return clearCnvs(cnvs[POLYGON + NUM_CANVAS]);
});
$('#btn-draw-pline').click(function() {
var c;
c = cnvs[POLYLINE];
if (drawStatus.polyline.status === WAIT) {
$(this).removeClass('btn-primary');
$(this).addClass('btn-success');
$(c).addClass('crosshair');
$(this).text('Finish Polyline');
drawStatus.polyline.status = FIRST_POINT;
return;
}
$(this).removeClass('btn-success');
$(this).addClass('btn-primary');
$(c).removeClass('crosshair');
$(this).text('Draw Polyline');
drawStatus.polyline.status = WAIT;
drawPolyline(c, drawStatus.polyline.pts);
drawStatus.polyline.pts = [];
return clearCnvs(cnvs[POLYLINE + NUM_CANVAS]);
});
getMousePos = function(cnvs, e) {
var rect, ret;
rect = cnvs.getBoundingClientRect();
return ret = {
x: e.clientX - rect.left,
y: e.clientY - rect.top
};
};
actionLine = function(cnvs, m, commit) {
var action, p1, p2;
action = drawStatus.line;
switch (action.status) {
case FIRST_POINT:
if (commit) {
action.p1 = m;
return action.status = SECOND_POINT;
}
break;
case SECOND_POINT:
action.p2 = m;
p1 = action.p1;
p2 = action.p2;
drawLine(cnvs, p1.x, p2.x, p1.y, p2.y);
if (commit && (p1.x !== p2.x || p1.y !== p2.y)) {
action.status = WAIT;
$(cnvs).removeClass('crosshair');
return clearCnvs(this.cnvs[LINE + NUM_CANVAS]);
}
break;
}
};
dist = function(p0, p1) {
var d1, d2;
d1 = p1.x - p0.x;
d2 = p1.y - p0.y;
return Math.sqrt(d1 * d1 + d2 * d2);
};
actionCircle = function(cnvs, m, commit) {
var action;
action = drawStatus.circle;
switch (action.status) {
case FIRST_POINT:
if (commit) {
action.p1 = m;
return action.status = SECOND_POINT;
}
break;
case SECOND_POINT:
action.radius = Math.floor(dist(action.p1, m));
if (!commit) {
drawCircle(cnvs, action.p1.x, action.p1.y, action.radius);
return;
}
if (action.radius > 0) {
drawCircle(cnvs, action.p1.x, action.p1.y, action.radius);
action.status = WAIT;
$(cnvs).removeClass('crosshair');
return clearCnvs(this.cnvs[CIRCLE + NUM_CANVAS]);
}
break;
}
};
actionEllipse = function(cnvs, m, commit) {
var action;
action = drawStatus.ellipse;
switch (action.status) {
case FIRST_POINT:
if (commit) {
action.p1 = m;
return action.status = SECOND_POINT;
}
break;
case SECOND_POINT:
action.a = Math.abs(m.x - action.p1.x);
action.b = Math.abs(m.y - action.p1.y);
if (!commit) {
drawEllipse(cnvs, action.p1.x, action.p1.y, action.a, action.b);
return;
}
if (action.a !== 0 || action.b !== 0) {
drawEllipse(cnvs, action.p1.x, action.p1.y, action.a, action.b);
action.status = WAIT;
$(cnvs).removeClass('crosshair');
return clearCnvs(this.cnvs[ELLIPSE + NUM_CANVAS]);
}
break;
}
};
actionRect = function(cnvs, m, commit) {
var action, p1, p2;
action = drawStatus.rect;
switch (action.status) {
case FIRST_POINT:
if (commit) {
action.p1 = m;
return action.status = SECOND_POINT;
}
break;
case SECOND_POINT:
action.p2 = m;
if (!commit) {
drawRect(cnvs, action.p1, action.p2);
return;
}
p1 = action.p1;
p2 = action.p2;
if (p1.x !== p2.x || p1.y !== p2.y) {
drawRect(cnvs, action.p1, action.p2);
action.status = WAIT;
$(cnvs).removeClass('crosshair');
return clearCnvs(this.cnvs[RECT + NUM_CANVAS]);
}
break;
}
};
actionPolygon = function(cnvs, m, commit) {
var action, pts;
action = drawStatus.polygon;
if (action.status === FIRST_POINT) {
if (!commit) {
pts = action.pts.slice();
pts.push(m);
drawPolygon(cnvs, pts);
return;
}
return action.pts.push(m);
}
};
actionPolyline = function(cnvs, m, commit) {
var action, pts;
action = drawStatus.polyline;
if (action.status === FIRST_POINT) {
if (!commit) {
pts = action.pts.slice();
pts.push(m);
drawPolyline(cnvs, pts);
return;
}
return action.pts.push(m);
}
};
performAction = function(id, cnvs, m, commit) {
if (commit == null) {
commit = false;
}
if (id > 6) {
id -= 6;
}
switch (id) {
case LINE:
return actionLine(cnvs, m, commit);
case CIRCLE:
return actionCircle(cnvs, m, commit);
case ELLIPSE:
return actionEllipse(cnvs, m, commit);
case RECT:
return actionRect(cnvs, m, commit);
case POLYGON:
return actionPolygon(cnvs, m, commit);
case POLYLINE:
return actionPolyline(cnvs, m, commit);
}
};
window.cnvs = {};
_results = [];
for (i = _i = 1, _ref = NUM_CANVAS * 2; 1 <= _ref ? _i <= _ref : _i >= _ref; i = 1 <= _ref ? ++_i : --_i) {
cnvs[i] = document.getElementById("canvas-" + i);
$(cnvs[i]).data({
id: i
});
if (i <= NUM_CANVAS) {
$(cnvs[i]).mousedown(function(e) {
var id, m;
id = Number($(this).data('id'));
m = getMousePos(this, e);
return performAction(id, this, m, true);
});
$(cnvs[i]).mouseup(function(e) {
var id, m;
id = Number($(this).data('id'));
m = getMousePos(this, e);
return performAction(id, this, m, true);
});
_results.push($(cnvs[i]).mousemove(function(e) {
var c, id, m;
id = Number($(this).data('id')) + 6;
m = getMousePos(this, e);
c = cnvs[id];
clearCnvs(c);
return performAction(id, c, m);
}));
} else {
_results.push(void 0);
}
}
return _results;
});
}).call(this);
|
// Copyright 2012 Dmitry Monin. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Zipcode Validator.
* Validates post code for correct format.
*/
goog.provide('morning.validation.ZipcodeValidator');
goog.require('morning.validation.Validator');
/**
* Validates post code for correct format.
*
* @constructor
* @param {string} fieldName
* @param {string} errorMessage
* @param {Array=} opt_countries Allowed countries, default: any
* @extends {morning.validation.Validator}
*/
morning.validation.ZipcodeValidator = function(fieldName, errorMessage, opt_countries)
{
goog.base(this, fieldName, errorMessage);
/**
* List of regular expression patterns for different countries.
* Source: Wikipedia
*
* @type {Object}
* @private
*/
this.zipcodesRegexp_ = {
'ar': /^[B-T]{1}[0-9]{4}[A-Z]{3}$/i,
'at': /^[0-9]{4}$/i,
'au': /^[0-9]{4}$/i,
'be': /^[1-9][0-9]{3}$/i,
'ca': /^[a-z][0-9][a-z][\s\t\-]*[0-9][a-z][0-9]$/i,
'ch': /^[0-9]{4}$/i,
'cn': /^[0-9]{6}$/,
'de': /^[0-9]{5}$/i,
'dk': /^(DK-)?[0-9]{4}$/i,
'ee': /^[0-9]{5}$/,
'es': /^[0-4][0-9]{4}$/,
'fi': /^(FI-)?[0-9]{5}$/i,
'fr': /^(0[1-9]|[1-9][0-9])[0-9][0-9][0-9]$/i,
'in': /^[1-9]{1}[0-9]{2}(\s|-)?[0-9]{3}$/i,
'it': /^[0-9]{5}$/,
'is': /^[0-9]{3}$/,
'lv': /^(LV-)?[1-9][0-9]{3}$/i,
'mx': /^[0-9]{5}$/,
'nl': /^[0-9]{4}.?[a-z]{2}$/i,
'no': /^[0-9]{4}$/,
'nz': /^[0-9]{4}$/,
'pl': /^[0-9]{2}-[0-9]{3}$/,
'pt': /^[0-9]{4}-[0-9]{3}$/,
'ru': /^[0-9]{6}$/,
'se': /^[0-9]{3}\s?[0-9]{2}$/,
'tr': /^[0-9]{5}$/,
'uk': /^[a-z][a-z0-9]{1,3}\s?[0-9][a-z]{2}$/i,
'us': /^[0-9]{5}((-| )[0-9]{4})?$/
};
/**
* List of allowed countries
*
* @type {Array.<string>}
* @private
*/
this.countries_ = null;
if (opt_countries)
{
this.countries_ = opt_countries;
}
};
goog.inherits(morning.validation.ZipcodeValidator,
morning.validation.Validator);
/** @inheritDoc */
morning.validation.ZipcodeValidator.prototype.validate = function(formData)
{
if (!formData || typeof formData[this.fieldName] != 'string')
{
if (goog.DEBUG)
{
console.warn(formData, this.fieldName);
}
throw new Error('RegexValidator: Couldn\'t get control value.');
}
var value = formData[this.fieldName];
if (this.isEmpty(value))
{
this.isValid = true;
this.dispatchEvent(morning.validation.Validator.EventType.VALIDATOR_COMPLETE);
return;
}
var countries = this.countries_ || goog.object.getKeys(this.zipcodesRegexp_),
regExp;
this.isValid = false;
for (var i = 0; i < countries.length; i++)
{
regExp = this.zipcodesRegexp_[countries[i]];
this.isValid = this.isValid || !!value.match(regExp);
}
this.dispatchEvent(morning.validation.Validator.EventType.VALIDATOR_COMPLETE);
};
|
import fetch from 'isomorphic-fetch'
const fetchLogsState = (path) => {
return {
types: ['FETCH_STATE_REQUEST', 'FETCH_STATE_SUCCESS', 'FETCH_STATE_FAILURE'],
shouldCallAPI: (state) => true,
callAPI: () => fetch(path, {
credentials: 'same-origin',
}),
payload: {}
}
}
const fetchLogsDate = (path) => {
return {
types: ['FETCH_DATE_REQUEST', 'FETCH_DATE_SUCCESS', 'FETCH_DATE_FAILURE'],
shouldCallAPI: (state) => true,
callAPI: () => fetch(path, {
credentials: 'same-origin',
}),
payload: {}
}
}
const fetchLogsTotal = (path) => {
return {
types: ['FETCH_TOTAL_REQUEST', 'FETCH_TOTAL_SUCCESS', 'FETCH_TOTAL_FAILURE'],
shouldCallAPI: (state) => true,
callAPI: () => fetch(path, {
credentials: 'same-origin',
}),
payload: {}
}
}
const fetchLogsLog = (path) => {
return {
types: ['FETCH_LOG_REQUEST', 'FETCH_LOG_SUCCESS', 'FETCH_LOG_FAILURE'],
shouldCallAPI: (state) => true,
callAPI: () => fetch(path, {
credentials: 'same-origin',
}),
payload: {}
}
}
export { fetchLogsState, fetchLogsDate, fetchLogsTotal, fetchLogsLog }
|
global.api.String = {};
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import Layout from './components/Layout'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import IndexPage from './pages/index'
import DetailPage from './pages/detail'
import DetailAnaPage from './pages/details/analysis'
import DetailCouPage from './pages/details/count'
import DetailPubPage from './pages/details/publish'
import DetailForPage from './pages/details/forecast'
import OrderListPage from './pages/orderList'
Vue.use(VueRouter)
Vue.use(VueResource)
let router = new VueRouter({
routes: [{
path: '/',
name:'IndexPage',
component: IndexPage
}, {
path:'/orderList',
component:OrderListPage,
name:'OrderListPage'
},
{
path: '/detail',
component: DetailPage,
redirect:'/detail/analysis',
children: [
{
path:'analysis',
component:DetailAnaPage
},
{
path:'count',
component:DetailCouPage
},
{
path:'forecast',
component:DetailForPage
},
{
path:'publish',
component:DetailPubPage
}
]
}]
})
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<Layout/>',
components: {
Layout
}
})
|
import {CHANGE_THEME, DECREMENT, DISABLE_BUTTONS, ENABLE_BUTTONS, INCREMENT} from './types.js'
export const increment = () => {
return {
type: INCREMENT
}
}
export const decrement = () => {
return {
type: DECREMENT
}
}
export const asyncIncrement = (dispatch) => {
dispatch(disable_buttons())
setTimeout(() => {
dispatch(increment())
dispatch(enable_buttons())
}, 2000)
}
export const changeTheme = (value) => {
return {
type: CHANGE_THEME,
value: value
}
}
export const disable_buttons = () => {
return {
type: DISABLE_BUTTONS
}
}
export const enable_buttons = () => {
return {
type: ENABLE_BUTTONS
}
}
|
//グローバル
var facility = new Array(); //施設
//施設クラス
function Facility(_name, _lat, _lng, _address, _tel, _url, _num ){
this.name = _name;
this.lat = _lat;
this.lng = _lng;
this.address = _address;
this.tel = _tel;
this.url = _url;
this.num = _num;
}
//マップ描画
function drawMap(){
//numのパラメーターの受け取り
var param = location.search; // アドレスの「?」以降の引数(パラメータ)を取得
param = param.substring(1); //先頭の?をカット
var temp = "";
temp = param.split("="); //num=を=で分割
var num = decodeURIComponent(temp[1]);
//マップオブジェクト設定
var mapObj;
//大阪市役所を緯度・軽度の初期値に設定
var posX=34.694062;
var posY=135.502154;
//マップ作成
var map = document.getElementById("map_canvas");
var options = {
zoom: 12,
center: new google.maps.LatLng(posX, posY),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
mapObj = new google.maps.Map(map, options);
//csvファイル読み込み
var xhr = new XMLHttpRequest();
xhr.onload = function(){
var tempArray = xhr.responseText.split("\n");
var csvArray = new Array();
//データの数だけループ
for(var i=0;i<tempArray.length;i++){
csvArray[i] = tempArray[i].split(",");
var data = csvArray[i];
//マーカー作成 画像ファイルを読み込み
var image;
var j = 3 + Number(num);
if (data[j]=="1") {
image = 'png/icon_location.png';
} else {
image = 'png/icon_location2.png';
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng( parseFloat(data[1]), parseFloat(data[2]) ),
map: mapObj,
icon: image,
title: data[0]
});
google.maps.event.addListener(marker, 'click', (function(num){ return function(){ clickMarker(num); };})(i));
//InfoWindow内にボタン生成
createInfoWindow(marker, data[0]);
//読み込んだデータをfacilityクラスの配列に格納 ページ遷移時にパラメータ渡しで使います
facility[i] = new Facility(data[0], data[1], data[2], data[15], data[16], data[17], num);
}
};
xhr.open("get", "facilities2017.csv", true);
xhr.send(null);
}
function createInfoWindow(getmarker, name){
var infowindow = new google.maps.InfoWindow({ content: name });
google.maps.event.addListener(getmarker, "mouseover", function(){
infowindow.open(getmarker.getMap(), getmarker);
});
}
function clickMarker(num){
//window.confirm(facility[num].name+"がクリックされた");
//var name = escape(facility[num].name); 非推奨
var name = encodeURIComponent(facility[num].name);
var lat = encodeURIComponent(facility[num].lat);
var lng = encodeURIComponent(facility[num].lng);
var address = encodeURIComponent(facility[num].address);
var tel = encodeURIComponent(facility[num].tel);
var url = encodeURIComponent(facility[num].url);
var top = encodeURIComponent(facility[num].num);
var param = "name="+name+"&lat="+lat+"&lng="+lng+"&address="+address+"&tel="+tel+"&url="+url+"&num="+top;
location.href = "./facility.html?"+param;
}
|
import React from 'react';
export default class ToDoList extends React.Component {
constructor(props){
super(props);
this.state = {
todos: ["Learn JS", "Learn Redux", "Learn React"],
todos2: ["Learn JS", "Learn Redux", "Learn React"],
todos3: ["Learn JS", "Learn Redux", "Learn React"],
inputVal: ""
}
}
render(){
const todosItems = this.state.todos.map(todo => {
return <li key = { todo }> { todo } </li>;
});
return(
<div>
<div>
<input type="text" value = { this.state.inputVal } onChange= {this.handleInput}/>
<button onClick={ this.addTodo } >Add Todo</button>
</div>
<div>
<ul>
{ todosItems }
{ this.renderTodos() }
{this.state.todos3.map(todo => {
return <li key = { todo }> { todo } </li>;
}) }
</ul>
</div>
</div>
);
}
renderTodos (){
return this.state.todos2.map(todo => {
return <li key = { todo }> { todo } </li>;
})
}
addTodo = () => {
const newTodos = [...this.state.todos ];
newTodos.push(this.state.inputVal);
this.setState({
todos: newTodos,
inputVal: ""
})
}
handleInput = (e) => {
this.setState({
inputVal: e.currentTarget.value
})
}
}
|
import { exec } from "child_process"
import test from "tape"
import cliBin from "./utils/cliBin"
import { fixturePath } from "./utils"
test("wrong input file", (t) => {
exec(
`${ cliBin }/testBin ${ fixturePath }/nonexistent`,
(err, stdout, stderr) => {
t.ok(
err,
"should return an error when input file is unreadable"
)
t.equal(
stderr.trim(),
"You provided 1 input file but nothing seems to be valid",
"should show that no input file or stdin was found"
)
t.end()
}
)
})
|
"use strict";
class EqnElementScalar {
constructor(equation, callbackBase, idPrefix, options) {
this.equation = equation;
this.callbackBase = callbackBase;
this.idPrefix = idPrefix;
this.$elem = undefined;
const defaults = {
value: 0,
};
this.options = {...defaults, ...options};
}
render() {
let text = this.options.value;
text = '\\color{black}{'+text+'}';
text = '\\href{javascript:'+this.callbackBase+')}{'+text+'}';
return text;
}
postRender($elem) {
$elem.popover({
html: true,
content: '<p><form onsubmit="'+this.callbackBase+',1); return false;"><span style="vertical-align:center;">k: <input id="'+this.idPrefix+'_val" type="number" value="'+this.options.value+'" step="0.5" min="-10" max="10"></span> '+
'<button style="vertical-align:center;" type="submit" class="btn btn-primary">OK</button></form></p>',
title: undefined, //"Edit coefficient",
placement: 'auto bottom',
container: 'body'
});
this.$elem = $elem;
}
callback(args) {
console.log('callback!', args);
if (args === 1) { // OK clicked
this.options.value = parseFloat($('#'+this.idPrefix+'_val').val());
this.$elem.popover('hide');
return true;
}
return false;
}
getValues() {
return {val: this.options.value};
}
}
class EqnElementTF {
constructor(equation, callbackBase, idPrefix, options) {
this.equation = equation;
this.callbackBase = callbackBase;
this.idPrefix = idPrefix;
this.$elem = undefined;
const defaults = {
re: 0,
im: 0,
enabled: true,
};
this.options = {...defaults, ...options};
}
render() {
let text = '\\Big(s-('+ (this.options.re<0?'':'+') + this.options.re+(this.options.im !== 0.0 ? (this.options.im<0?'':'+')+this.options.im+'j' : '') + ')\\Big)';
if (this.options.enabled)
text = '\\color{black}{'+text+'}';
else
// text = '\\quad'; //'\\color{lightgray}{'+text+'}';
text = '\\color{lightgray}{\\square}';
text = '\\href{javascript:'+this.callbackBase+')}{'+text+'}';
return text;
}
postRender($elem) {
$elem.popover({
html: true,
content: '<form onsubmit="'+this.callbackBase+',1); return false;"><p>'+
'<input id="'+this.idPrefix+'_re" type="number" value="'+this.options.re+'" step="0.5" min="-10" max="10"></span> + '+
'<input id="'+this.idPrefix+'_im" type="number" value="'+this.options.im+'" step="0.5" min="-10" max="10"></span> j</p>'+
'<p><span style="vertical-align:center; float:left;" class="checkbox"><label><input id="'+this.idPrefix+'_enabled" type="checkbox"'+(true || this.options.enabled ? ' checked="checked"' : '')+'>enabled</label></span><button style="vertical-align:center; float:right;" type="submit" class="btn btn-primary">OK</button></p></form><div style="clear: both;"></div>',
title: undefined, //"Edit coefficient",
placement: 'auto bottom',
container: 'body'
});
this.$elem = $elem;
}
callback(args) {
if (args === 1) { // OK clicked
const re = parseFloat($('#'+this.idPrefix+'_re').val());
const im = parseFloat($('#'+this.idPrefix+'_im').val());
const enabled = $('#'+this.idPrefix+'_enabled').prop('checked');
this.updateValues(re, im, enabled);
this.$elem.popover('hide');
return true;
}
return false;
}
updateValues(re, im, enabled) {
console.log('updateValues:', re, im, enabled);
if (isNaN(re))
re = 0.0;
if (isNaN(im))
im = 0.0;
// determine name of this element in the InteractiveEquation class (e.g. Kz1/Gp0)
let name;
for (let e of this.equation.elements) {
if (e[1] === this) {
name = e[0];
break;
}
}
// find out if there is another pole/zero that will be cancelled out
const c = (name[1] === 'z') ? 'p' : 'z';
let cancelled = false;
for (let e of this.equation.elements) {
if (e[0].length !== 3 || e[0][1] !== c)
continue;
if (enabled && e[1].options.enabled && re === e[1].options.re && (im === e[1].options.im || im === -e[1].options.im)) {
e[1].options.enabled = false;
cancelled = true;
}
}
if (cancelled) {
alert(tr('Pole-zero cancellation!'));
enabled = false;
}
// if the pole/zero is/was complex and is enabled, ensure there is another one which is its conjugate
if (enabled && (im !== 0.0 || (this.options.enabled && this.options.im !== 0.0))) {
const elems = [];
// first, find the two corresponding elements (e.g. Kz1 and Kz3 if the name == "Kz2")
for (let e of this.equation.elements) {
if (e[0].length !== 3 || e[0].substring(0, 2) !== name.substring(0, 2) || e[0] === name)
continue;
elems.push(e[1]);
}
console.assert(elems.length === 2, elems);
let elem = undefined;
// find the element to update. first: is there an enabled complex one?
if (elems[0].options.enabled && elems[0].options.im !== 0.0) {
elem = elems[0];
if (elems[1].options.enabled && elems[1].options.im !== 0.0) {
alert(tr('Imaginary part of third pole/zero set to zero!'));
elems[1].options.im = 0.0;
}
} else if (elems[1].options.enabled && elems[1].options.im !== 0.0) {
elem = elems[1];
// if not, is there a disabled one?
} else if (!elems[0].options.enabled) {
elem = elems[0];
} else if (!elems[1].options.enabled) {
elem = elems[1];
} else {
elem = elems[0]; // whatever...
}
// this element has to enabled and be the complex conjugate
elem.options.re = re;
elem.options.im = -im;
elem.options.enabled = true;
}
// if the pole/zero was complex and is now disabled, look for other complex poles/zeros and disable them
if (!enabled && this.options.enabled && this.options.im !== 0.0) {
for (let e of this.equation.elements) {
if (e[0].length !== 3 || e[0].substring(0, 2) !== name.substring(0, 2) || e[0] === name)
continue;
if (e[1].options.im !== 0)
e[1].options.enabled = false;
}
}
this.options.re = re;
this.options.im = im;
this.options.enabled = enabled;
// count the number of enabled poles and zeros
let pCount = 0;
let zCount = 0;
for (let e of this.equation.elements) {
if (e[0].length !== 3 || !e[1].options.enabled)
continue;
if (e[0][1] === 'p')
pCount++;
else {
console.assert(e[0][1] === 'z', e[0]);
zCount++;
}
}
console.log(zCount, pCount);
if (zCount > pCount) {
alert(tr('Warning: The total number of zeros is greater than the number of poles!'));
}
}
getValues() {
return {re: this.options.re, im: this.options.im, enabled: this.options.enabled};
}
}
class EquationEditor extends Emitter {
// note that for the callback to work, id must also be the global variable name of the object
constructor(id, template, elements) {
super();
this.id = id;
this.template = template;
this.elements = elements;
this.math = undefined;
this.values = {};
for(let i in this.elements) {
const name = this.elements[i][0];
const cls = this.elements[i][1];
const opts = this.elements[i][2];
const callbackBase = this.id + '.callback('+i;
this.elements[i] = [name, new cls(this, callbackBase, this.id+'_'+name, opts), callbackBase];
}
MathJax.Hub.Queue(this.setup.bind(this));
this.updateValues();
}
callback(id, args) {
console.log('callback', id);
if (this.elements[id][1].callback(args)) {
this.updateValues();
this.render();
}
}
setup() {
this.math = MathJax.Hub.getAllJax(this.id)[0];
this.render();
}
preRenderHook(template) {
return template;
}
render() {
let text = this.preRenderHook(this.template);
for(let i in this.elements) {
const name = this.elements[i][0];
const obj = this.elements[i][1];
text = text.replace('<'+name+'/>', obj.render());
}
MathJax.Hub.Queue(["Text", this.math, text]);
MathJax.Hub.Queue(this.postRender.bind(this));
}
postRender() {
console.log('post render');
for (let i in this.elements) {
const obj = this.elements[i][1];
const callbackBase = this.elements[i][2];
const $elem = $('[href="javascript:' + callbackBase + ')"]');
obj.postRender($elem);
}
}
updateValues() {
for (let i in this.elements) {
const name = this.elements[i][0];
const obj = this.elements[i][1];
const vals = obj.getValues();
for (let valName in vals) {
this.values[name+'_'+valName] = vals[valName];
}
}
this.emit('change');
console.log(this.values)
}
applyPreset(preset) {
for(let i in this.elements) {
const name = this.elements[i][0];
const obj = this.elements[i][1];
if (preset[name] !== undefined) {
obj.options = preset[name];
}
}
this.updateValues();
this.render();
}
}
class EqPresetDropdown extends DropdownMenu {
constructor(container, eq, presets) {
const values = presets.map(p => p.name);
super(container, values);
this.eq = eq;
this.presets = presets;
this.on('change', this._apply.bind(this));
}
_apply(index) {
this.eq.applyPreset(this.presets[index]);
}
}
|
var ColladaLoader = function ()
{
this.ready = false;
this.initialized = false;
this.data = {
'indices' : [],
'positions' : [],
'textureCoords' : [],
'normals' : [],
'vertexColors' : [],
}
this.loader = null;
this.rawModel = null;
}
ColladaLoader.prototype.loadColladaModel = function ( filepath, loader )
{
this.loader = loader;
this.readFile( filepath );
}
ColladaLoader.prototype.onLoad = function ( rawText )
{
this.parseFile( rawText );
this.rawModel = this.loader.loadToVAO( this.data, true );
this.ready = true;
console.log( 'Collada model is ready!' );
}
ColladaLoader.prototype.readFile = function ( filepath )
{
// save 'this'; https://stackoverflow.com/a/6985358
var instance = this;
var request = new XMLHttpRequest();
request.open( 'GET', filepath, true );
request.onreadystatechange = function ()
{
if ( request.readyState === 4 )
{
if ( request.status === 200 || request.status === 0 )
{
instance.onLoad( request.responseText );
}
}
}
request.send( null );
}
ColladaLoader.prototype.parseFile = function ( rawText )
{
scene = Collada.parse( rawText ); // See 3rd party library collada.js
console.log( scene );
for ( var meshName in scene.meshes )
{
mesh = scene.meshes[ meshName ];
// console.log( mesh );
this.data[ 'indices' ] = mesh.triangles;
this.data[ 'positions' ] = mesh.vertices;
if ( 'coords' in mesh )
{
this.data[ 'textureCoords' ] = mesh.coords;
}
if ( 'normals' in mesh )
{
this.data[ 'normals' ] = mesh.normals;
}
if ( 'color' in mesh )
{
this.data[ 'vertexColors' ] = mesh.color;
}
console.log( this.data );
// Exit after first mesh
break;
}
}
|
import {remote} from 'webdriverio';
const start = async () => {
const browser = await remote({
capabilities: {
browserName: 'chrome'
}
});
browser.url('http://10.24.48.120/bee/');
const login_input = await browser.$('input[name="j_username"]');
await login_input.setValue('crm0260');
const password_input = await browser.$('input[name="j_password"]');
await password_input.setValue('Cedacri1');
const sumbit = await browser.$('#submit');
await sumbit.click();
setTimeout(async () => {
const timestamp = () => new Date().toString().substring(0, 24).replaceAll(':', '_');
await browser.saveScreenshot(`./assets/${timestamp()}_before.png`);
const btn_track = await browser.$(
'img[src="/bee/VAADIN/themes/bee/img/start-icon.png"]'
);
await btn_track.click();
await browser.saveScreenshot(`./assets/${timestamp()}.png`);
}, 6000);
};
export default start;
|
function etsiSarjoja() {
const haku = document.getElementById('hakuteksti').value
fetch(`https://api.tvmaze.com/search/shows?q=${haku}`)
.then(vastaus => vastaus.json())
.then(series => {
console.log(series);
const app = document.getElementById('app');
app.innerHTML = series.map(({show}) => `
<div class="container">
<div id="kuva">
${show.image ? `<img src="${show.image.medium}">` : '<img style="z-index: -1" src="photo.png">'}
</div>
<div>
<h4>${show.name}</h4>
<h7><a href="${show.url}">${show.url}</a></h7><br>
<h7>${show.genres}</h7>
<h7>${show.summary}</h7><br>
</div>
</div>
`).join('');
})
}
const nappi = document.getElementById('hakunappi');
nappi.addEventListener('click', etsiSarjoja);
|
import React, { Component } from 'react';
import { Layer, Feature } from "react-mapbox-gl";
class FeatureLayer extends Component {
render() {
return (
<Layer
type="symbol"
id="marker"
layout={{"icon-allow-overlap": true, "icon-image": "circle-stroked-15","visibility":this.props.visible ? "visible" : "none" }}
paint={{"icon-color": "#ffff00"}}>
<Feature coordinates={[-73,21]}/>
<Feature coordinates={[-74,21]}/>
</Layer>
);
}
}
export default FeatureLayer; |
var input=[['0001','Roman Alamsyah','Bandar Lampung', '21/05/1989','Membaca'],
['0002','Dika Sembiring','Medan','10/10/1992','Bermain gitar'],
['0003','Winona','Ambon','25/12/1965','Memasak'],
['0004','Bintang Senjaya','Martapura','6/4/1970','Berkebun']]
function dataHandling(){
var index=0
while(index<input.length){
var nomorID=input[index][0]
var namaLengkap=input[index][1]
var ttl=input[index][2]+' '+input[index][3]
var hobi=input[index][4]
console.log('Nomor ID: '+nomorID)
console.log('Nama Lengkap: '+namaLengkap)
console.log('TTL: '+ttl)
console.log('Hobi: '+hobi)
console.log('')
index++
}
}
dataHandling() |
import React from 'react';
import {StyleSheet} from 'react-native';
import theme from '../constants/theme';
import { Input } from 'react-native-elements';
export default AppInput = (props) => {
const { color, placeholder, action, keyboardType, icon } = props
return (
<Input
placeholder={placeholder}
style={{
borderWidth: 0,
borderRadius: 10,
width: '90%',
backgroundColor: color
}}
inputStyle={styles.inputStyle}
placeholderTextColor='white'
inputContainerStyle={{ borderBottomWidth: 0 }}
onChangeText={action}
multiline={true}
autoFocus={true}
keyboardType={keyboardType}
leftIcon={icon}
/>
)
}
const styles = StyleSheet.create({
inputStyle: {
color: 'black',
fontFamily: theme.fonts.bold,
padding: 10,
margin: 10,
fontSize: theme.fontSizes.cardTitle,
},
}); |
const express = require("express");
const router = express.Router();
const BetterDB = require("better-sqlite3");
const getProjectNew = require("../library/getProjectNew");
const getExperiment = require("../library/getExperiment");
const buildProjectView = require("../library/buildProjectView");
/**
* Express.js router for /projectview. Unfinished
*
* Render project share page to users
*/
const projectview = router.get('/projectview', function (req,res) {
console.log("hello projectview");
const pid = req.query.pid;
let resultDb = new BetterDB("./db/projectDB.db");
let stmt = resultDb.prepare(`SELECT *
FROM Project
WHERE pid = ?;`);
let projectInfo = stmt.get(pid);
// resultDb.close();
console.log(projectInfo);
let projectPermission = projectInfo.permission;
let projectUid = projectInfo.uid;
let node = buildProjectView(pid);
console.log("node:", node);
if (req.session.passport === undefined){
if (projectPermission === 0) {
res.render('pages/projectShare', {
info: uid,
projectList: projectList
});
}
if (projectPermission === 1) {
if (!req.session.passport) {
let uid = req.session.passport.user.profile.id;
if (uid === projectUid) {
res.render();
}
} else {
// Deny
}
}
if (projectPermission === 2) {
console.log("not owner!");
res.render('pages/projectShare', {
password: projectInfo.password,
treeviewNode: node
});
/*if (!req.session.passport) {
let uid = req.session.passport.user.profile.id;
if (uid === projectUid) {
// render
}
}*/
// ask password
}
}
else {
//console.log(req.session.passport.user.profile);
let uid = req.session.passport.user.profile.id;
// console.log(pid);
if(uid === projectUid) {
console.log("owner!");
res.render('pages/projectShare', {
treeviewNode: node
});
}
}
});
module.exports = projectview; |
const arr = [1,2,3,4,5,6,7,7,8,6,10];
const findDupes = (arr) => {
const observed = {};
for(let i = 0; i < arr.length; i++) {
if(observed[arr[i]]) {
return arr[i]
} else {
observed[arr[i]] = arr[i];
}
}
return false;
}
console.log(findDupes(arr)); // Returns 7
const findDupes2 = (arr) => {
return arr.filter((item, i)=> arr.indexOf(item)!==i);
}
console.log(findDupes2(arr)); // Returns [7, 6]
|
import React from 'react';
import { Table, Button, Modal, Checkbox } from 'antd';
import httpSevice from '../utill/httpservice';
import configreducer from '../configreducer';
import configactions from '../configactions';
import { withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import invioceListactions from "./invioceListactions";
class TableComponet extends React.Component {
invoice = {};
state = {
visible: false,
filteredInfo: null,
sortedInfo: null,
};
handleChange = (pagination, filters, sorter) => {
this.setState({
filteredInfo: filters,
sortedInfo: sorter,
});
};
clearFilters = () => {
this.setState({ filteredInfo: null });
};
clearAll = () => {
this.setState({
filteredInfo: null,
sortedInfo: null,
});
};
setAgeSort = () => {
this.setState({
sortedInfo: {
order: 'descend',
columnKey: 'age',
},
});
};
componentDidUpdate(prevProp) {
console.log(this.props?.config?.config?.dataEndPoints?.call2)
if (this.props?.config?.config?.dataEndPoints?.call2 != prevProp?.config?.config?.dataEndPoints?.call2)
httpSevice.getURL(this.props?.config?.config?.dataEndPoints?.call2).then(res => {
this.props.setInvoiceList(res.data)
})
if (this.props?.config?.config?.dataEndPoints?.call3 != prevProp?.config?.config?.dataEndPoints?.call3)
httpSevice.getURL(this.props?.config?.config?.dataEndPoints?.call3).then(res => {
this.props.setVendorsList(res.data)
})
}
showModal = (invoice, vendor) => {
this.invoice = { ...invoice, ...vendor };
this.setState({
visible: true,
});
};
handleOk = e => {
console.log(e);
this.setState({
visible: false,
});
this.props.history.push('/payment');
httpSevice.post(this.props?.config?.config?.paymentPost, {
...this.invoice,
}).then((res) => {
console.log(res.data)
})
};
handleCancel = e => {
console.log(e);
this.setState({
visible: false,
});
};
render() {
let { sortedInfo, filteredInfo } = this.state;
sortedInfo = sortedInfo || {};
filteredInfo = filteredInfo || {};
let vendorsList = [...(this.props?.invoicelist?.vendorslist || [])];
let dataSource = [...(this.props?.invoicelist?.invoicelist || [])].map((invoice, index) => {
let UI = { ...invoice, key: index + 'invoiceList' };
let vendor = vendorsList.find((vendor) => vendor.vendorId == invoice.vendorId);
console.log(vendor)
if (this.props?.config?.config?.tableConfig?.paymentEnabled &&
+invoice.amountDue > 0
) {
UI.payUI = <React.Fragment key={`payUI${index}`}>
<button onClick={() => this.showModal(vendor, invoice)}>Pay</button>
</React.Fragment>
}
return UI;
});
let columns = [];
[...(this.props?.config?.config?.tableConfig?.columns || [])].forEach((column) => {
let data = {
title: column.displayName || undefined,
dataIndex: column.fieldName || undefined,
key: column.fieldName || undefined,
};
if (column.filteringEnabled) {
data.filteredValue = filteredInfo.name || null;
data.onFilter = (value, record) => record?.[column.fieldName]?.indexOf(value) === 0;
}
if (column.sortingEnabled) {
data.sortOrder = sortedInfo.columnKey === column.fieldName && sortedInfo.order;
data.sorter = (a, b) => a?.[column.fieldName]?.length - b?.[column.fieldName]?.length;
}
if (column.display)
columns.push(data);
});
if (this.props?.config?.config?.tableConfig?.paymentEnabled) {
columns.push({
title: 'Pay',
dataIndex: 'payUI',
key: 'payUI',
})
}
return <React.Fragment>
<Table dataSource={dataSource} columns={columns} onChange={this.handleChange} />
<Modal
title={this.invoice["name"]}
visible={this.state.visible}
onOk={this.handleOk}
okText="Pay Now"
onCancel={this.handleCancel}
>
<p>InvoiceId:{this.invoice["invoiceId"]}</p>
<p>Vendor Name:{this.invoice["vendorName"]}</p>
<p>product:{this.invoice["product"]}</p>
<p>amountBal:{this.invoice["amountBal"]}</p>
<p>amountDue:{this.invoice["amountDue"]}</p>
{+this.invoice["creditBal"] > 0 && <React.Fragment>
<Checkbox onChange={(event) => {
httpSevice.post(this.props?.config?.config?.creditPost, {
...this.invoice,
creditPost: event.target.value
}).then((res) => {
console.log(res.data)
})
}}></Checkbox> Use Credit </React.Fragment>}
</Modal>
</React.Fragment>
}
}
export default connect(configreducer, { ...configactions, ...invioceListactions })(withRouter(TableComponet)); |
import { useParams, Route } from "react-router";
import Comments from "../components/comments/Comments";
import HighlightedQuote from "../components/quotes/HighlightedQuote";
const DUMMY_DATA = [
{ id: "q1", author: "sam", text: "Learning code is not easy" },
{ id: "q2", author: "jhon", text: "Learning react is fun !" },
];
const QuoteDetail = () => {
const param = useParams();
const quote = DUMMY_DATA.find((quote) => quote.id === param.quoteId);
if (!quote) {
return <p>No quote found...</p>;
}
return (
<div>
<HighlightedQuote text={quote.text} author={quote.author} />
<Route path={`/quotes/${param.quoteId}/comments`}>
<Comments />
</Route>
</div>
);
};
export default QuoteDetail;
|
const rp = require("request-promise");
const errors = require('request-promise/errors');
const fs = require("fs");
//認証情報定義
const clientId = "input client id here";
const clientSecret = "input client secret here";
//接続先定義
const oauthUrl = "https://api.ce-cotoha.com/v1/oauth/accesstokens"
const ttsUrl = "https://api.ce-cotoha.com/api/tts/v1/tts"
// アクセストークン取得
function getToken(postUrl, cId, cSecret){
let options = {
method: "POST",
uri: postUrl,
headers: {
"Content-Type": "application/json;charset=UTF-8"
},
json: {
"grantType": "client_credentials",
"clientId": cId,
"clientSecret": cSecret
}
}
let request = rp(options).catch(errors.StatusCodeError, function(err){
console.log('[ERROR!(@getToken)] status: ' + err.response.body.status + ', message: ' + err.response.body.message);
process.exit(1);
});
return request;
}
// JSON ファイルの読み込み
// データをポストし合成音声を取得
// 音声ファイルを出力
function postAndRecieve(postUrl, accessToken, inputFilePath, outputFilePath){
const jsonObject = JSON.parse(fs.readFileSync(inputFilePath, "utf8"));
let postJson = {
"text": jsonObject.text,
"speakerId": jsonObject.speakerId
};
if(jsonObject.textType){
postJson.textType = jsonObject.textType;
}
if(jsonObject.speechRate){
postJson.speechRate = jsonObject.speechRate;
}
if(jsonObject.powerRate){
postJson.powerRate = jsonObject.powerRate;
}
if(jsonObject.intonation){
postJson.intonation = jsonObject.intonation;
}
if(jsonObject.pitch){
postJson.pitch = jsonObject.pitch;
}
console.log("post data: " + (JSON.stringify(postJson)).toString());
let options = {
method: "POST",
uri: postUrl,
headers: {
"Authorization": "Bearer " + accessToken,
"Content-Type": "application/json;charset=UTF-8",
"Accept": "audio/wav"
},
json: postJson
}
let request = rp(options).on("response", (response) => {
response.pipe(fs.createWriteStream(outputFilePath));
}).catch(errors.StatusCodeError, function(err){
console.log("[ERROR!(@postAndRecieve)] status: " + err.statusCode + ", code: " + err.response.body.code + ", detail: " + err.response.body.detail);
process.exit(1);
});
return request;
}
// main の処理
// コマンドライン引数1 : 音声合成設定を記入したjsonファイル
// コマンドライン引数2(option) : 出力wavファイル名
// 出力 : 合成音声wavファイル
async function main() {
if(process.argv.length <= 2){
console.log("usage: node sample_nodejs [input_json_file] [(option)output_wav_file]");
process.exit(1);
}
let inputFilePath = process.argv[2];
let outputFilePath;
if(process.argv.length > 3){
outputFilePath = process.argv[3];
}
else{
outputFilePath = "output.wav";
}
let tokenJson = await getToken(oauthUrl, clientId, clientSecret);
let accessToken = tokenJson.access_token;
console.log("getToken completed successfully.");
await postAndRecieve(ttsUrl, accessToken, inputFilePath, outputFilePath);
console.log("postAndRecieve completed successfully.");
console.log(outputFilePath + " has been generated.");
}
main() |
import React, { Component } from 'react';
import api from '../../services/auth';
import imgmedicos from '../../assets/imagens/img-medicos-2.png'
import barrinha from '../../assets/imagens/1x/barrinha.png'
import imgprontuario from '../../assets/imagens/ambulance-architecture-building-263402.jpg';
import imgApp from '../../assets/imagens/1x/Ativo 2.png'
import Cabecalho from '../Componentes/Cabecalho';
import CabecalhoLogado from '../Componentes/CabecalhoLogado';
import Rodape from '../Componentes/Rodape';
import img from '../../assets/imagens/appointment-book-blur-care-40568.jpg'
class App extends Component {
constructor(props) {
super(props);
this.state = {
lista: [],
id: "",
nomeFantasia: "",
razaoSocial: "",
cnpj: "",
endereço: ""
}
}
checar(){
const token =localStorage.getItem("spmed-usuario");
if (token==null) {
return(
<Cabecalho />
);
}
else{
return(
<CabecalhoLogado />
);
}
}
Listar(){
api.get('/clinicas')
.then(data => {
console.log(data)
this.setState({ lista: data.data });
})
.catch(erro => console.log(erro))
}
componentDidMount(){
this.Listar();
}
render() {
return (
<div>{
this.checar()
}
<br/>
<br/>
<br/>
<br/>
<section className="banner">
<img src={imgmedicos} alt="medicos" />
<h2>SPMEDICALGROUP</h2>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet
dolore magna ag elit, sed diam nonummy nibh euismod magna ag elit, sed diam nonummy nibh euismod ti magna ag
elit, sed diam nonummy nibh euismod titincidunt ut laoreet dolore magna aibh euismod tincidunt
ut laoreet dolore magnibh euiit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod orem ipsum
dolor sit amet, consectetuer adipiscinsmod tincidunt ut laoreet dolore magnibh euismod tincidunt ut laoreet dolore
magn</p>
</section>
<div className="barrinha">
<img src={barrinha} alt="" />
</div>
<section className="sobre" id="flex-container">
<div className="flex">
<article className="clinica">
<h3>SOBRE A CLÍNICA</h3>
<img src={img} />
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod orem ipsum
dolor sit amet, consectetuer adipiscing elit,orem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonumm sed diam nonumm</p>
</article>
</div>
<div className="flex">
<article className="app">
<h3>Applicativo SPMEDICALGROUP</h3>
<img src={imgApp} />
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod orem ipsum
dolor sit amet, consectetuer adipiscing elit,orem ipsum dolor sit amet, consectetuer adipiscing
elit, sed diam nonumm sed diam nonumm</p>
</article>
</div>
<div className="flex">
<article className="medicos">
<h3>OS MELHORES MÉDICOS</h3>
<p>Lorem ipsum dolor sit amet, consectetudolor sit amet, consectetudolor sit amet, consectetudolor sit
amet, consectetudolor sit amet, consectetudolor sit amet, consectetudolor sit amet, consectetudolor
sit amet, consectetudolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod </p>
</article>
</div>
</section>
<section className="local">
<img src={imgprontuario} />
<div className="local-txt">
<h3>LOCALIZAÇÃO</h3>
<div className="local-clinica">
{
this.state.lista.map(function (clinica) {
return(
<tr key={clinica.id}>
<td>{clinica.endereço}</td>
</tr>
);
})
}
</div>
</div>
<div className="contato">
<div className="contato-txt">
<h3>CONTATO</h3>
</div>
<p>Telefone: 2002-0606</p>
<p>Email: SpmedicalGroup@gmail.com</p>
</div>
</section>
<Rodape />
</div>
);
}
}
export default App;
|
const express = require('express')
const bodyParser = require('body-parser')
const session = require('express-session')
const passport = require('passport')
const TwitterStrategy = require('passport-twitter')
const uuid = require('uuid/v4')
const security = require('./helpers/security')
const auth = require('./helpers/auth')
const cacheRoute = require('./helpers/cache-route')
const socket = require('./helpers/socket')
const twitterbot = require('./twitterbot');
module.exports = function(twitterbot){
const app = express()
app.set('port', (process.env.PORT || 5000))
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(passport.initialize());
app.use(session({
secret: `${process.env.BASIC_AUTH_USER}${process.env.BASIC_AUTH_PASSWORD}`,
resave: false,
saveUninitialized: true
}))
// start server
const server = app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'))
})
// initialize socket.io
socket.init(server)
// form parser middleware
var parseForm = bodyParser.urlencoded({ extended: false })
/**
* Receives challenge response check (CRC)
**/
app.get('/webhook/twitter', function(request, response) {
var crc_token = request.query.crc_token
if (crc_token) {
var hash = security.get_challenge_response(crc_token, auth.twitter_oauth.consumer_secret)
response.status(200);
response.send({
response_token: 'sha256=' + hash
})
} else {
response.status(400);
response.send('Error: crc_token missing from request.')
}
})
/**
* Receives Account Acitivity events
**/
app.post('/webhook/twitter', function(request, response) {
twitterbot.handle_event(request.body);
socket.io.emit(socket.activity_event, {
internal_id: uuid(),
event: request.body
})
response.send('200 OK')
})
/**
* Serves the home page
**/
app.get('/', function(request, response) {
response.render('index')
})
/**
* Subscription management
**/
app.get('/subscriptions', auth.basic, cacheRoute(1000), require('./routes/subscriptions'))
/**
* Starts Twitter sign-in process for adding a user subscription
**/
app.get('/subscriptions/add', passport.authenticate('twitter', {
callbackURL: `https://${process.env.PROJECT_DOMAIN}.glitch.me/callbacks/addsub`
}));
/**
* Starts Twitter sign-in process for removing a user subscription
**/
app.get('/subscriptions/remove', passport.authenticate('twitter', {
callbackURL: `https://${process.env.PROJECT_DOMAIN}.glitch.me/callbacks/removesub`
}));
/**
* Webhook management routes
**/
var webhook_view = require('./routes/webhook')
app.get('/webhook', auth.basic, auth.csrf, webhook_view.get_config)
app.post('/webhook/update', parseForm, auth.csrf, webhook_view.update_config)
app.post('/webhook/validate', parseForm, auth.csrf, webhook_view.validate_config)
app.post('/webhook/delete', parseForm, auth.csrf, webhook_view.delete_config)
/**
* Activity view
**/
app.get('/activity', auth.basic, require('./routes/activity'))
/**
* Handles Twitter sign-in OAuth1.0a callbacks
**/
app.get('/callbacks/:action', passport.authenticate('twitter', { failureRedirect: '/' }),
require('./routes/sub-callbacks'))
}
|
/* global THREE */
let renderer, scene, camera
let controls
let magenta
let light1
let water
setup()
draw()
function setup () {
scene = new THREE.Scene()
// scene.background = new THREE.Color(0xF7BDFF)
const ar = window.innerWidth / window.innerHeight
camera = new THREE.PerspectiveCamera(75, ar, 0.1, 1000)
camera.position.set(7, 7, 3)
scene.add(camera)
//lights
const light = new THREE.HemisphereLight(0x8F6BFF, 0x8F6BFF, 1)
scene.add(light)
const sphere = new THREE.SphereGeometry(0.2, 16, 8)
const mat = new THREE.MeshBasicMaterial({ color: 0xFFCF67})
const lightSphere = new THREE.Mesh(sphere, mat)
light1 = new THREE.PointLight(0xFFCF67, 1, 50)
light1.add(lightSphere)
scene.add(light1)
light1.position.set(0, 10, 0)
// ground
// const geometry = new THREE.PlaneGeometry(50, 50, 50, 50)
// const material = new THREE.MeshBasicMaterial({
// side: THREE.DoubleSide,
// color: 0xFF67D3,
// wireframe: true
// })
// const plane = new THREE.Mesh(geometry, material)
// scene.add(plane)
// plane.rotation.x = Math.PI / 2
// lotus flowers
const loader = new THREE.GLTFLoader().setPath('models/')
loader.load('lf-magenta.gltf', (gltf) => {
// console.log(gltf)
//const magenta = gltf.scene.children[0]
magenta = gltf.scene
scene.add(magenta)
magenta.scale.set(20, 20, 20)
magenta.position.x = 3
})
// const loader = new THREE.GLTFLoader().setPath('models/')
// loader.load('lf-violet.gltf', (gltf) => {
// violet = gltf.scene
// scene.add(violet)
// violet.scale.set(20, 20, 20)
// violet.position.x = 9
// })
// Water
// const waterGeometry = new THREE.PlaneGeometry( 10000, 10000 );
// water = new THREE.Water(waterGeometry,
// { textureWidth: 512,
// textureHeight: 512,
// waterNormals: new THREE.TextureLoader().load('textures/waternormals.jpg', function(texture) {
// texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
// })
// alpha: 1.0,
// sunDirection: new THREE.Vector3(),
// sunColor: 0xffffff,
// waterColor: 0x001e0f,
// distortionScale: 3.7,
// fog: scene.fog !== undefined
// })
// water.rotation.x = - Math.PI / 2;
// scene.add(water)
renderer = new THREE.WebGLRenderer({
alpha: true
})
// renderer.autoClearColor = 0xF7BDFF
renderer.setSize(window.innerWidth, window.innerHeight)
document.body.appendChild(renderer.domElement)
controls = new THREE.OrbitControls(camera, renderer.domElement)
controls.target.set(0, 0, 0)
controls.minDistance = 20
controls.maxDistance = 50
controls.update()
}
function draw () {
window.requestAnimationFrame(draw)
const time = Date.now() * 0.0005
light1.position.x = Math.sin(time) * 5
light1.position.x = Math.sin(time * 0.2) * 4
light1.position.z = Math.cos(time * 0.3) * 10
renderer.render(scene, camera)
}
|
const {Plane, Vec3, Polyline3d, shaders} = spritejs.ext3d;
const vertex = `
precision highp float;
attribute vec3 position;
attribute vec3 next;
attribute vec3 prev;
attribute float side;
attribute vec4 color;
attribute float seg;
uniform mat4 modelViewMatrix;
uniform mat4 projectionMatrix;
uniform vec2 uResolution;
uniform float uDPR;
uniform float uThickness;
uniform float uMiter;
varying vec4 vColor;
varying float fSeg;
vec4 getPosition() {
mat4 mvp = projectionMatrix * modelViewMatrix;
vec4 current = mvp * vec4(position, 1);
vec4 nextPos = mvp * vec4(next, 1);
vec4 prevPos = mvp * vec4(prev, 1);
vec2 aspect = vec2(uResolution.x / uResolution.y, 1);
vec2 currentScreen = current.xy / current.w * aspect;
vec2 nextScreen = nextPos.xy / nextPos.w * aspect;
vec2 prevScreen = prevPos.xy / prevPos.w * aspect;
vec2 dir1 = normalize(currentScreen - prevScreen);
vec2 dir2 = normalize(nextScreen - currentScreen);
vec2 dir = normalize(dir1 + dir2);
vec2 normal = vec2(-dir.y, dir.x);
normal /= mix(1.0, max(0.3, dot(normal, vec2(-dir1.y, dir1.x))), uMiter);
normal /= aspect;
float pixelWidthRatio = 1.0 / (uResolution.y / uDPR);
float pixelWidth = current.w * pixelWidthRatio;
normal *= step(0.05, seg) * clamp(0.0, seg, 1.0) * pixelWidth * uThickness;
current.xy -= normal * side;
return current;
}
void main() {
gl_Position = getPosition();
vColor = color;
fSeg = seg;
}
`;
const fragment = `
precision highp float;
uniform float uTotalLength;
uniform float uTime;
uniform float uDuration;
varying vec4 vColor;
varying float fSeg;
void main() {
float p = clamp(0.0, 1.0, uTime / uDuration) * 2.0;
float sp = fSeg / uTotalLength;
float ep;
if(p < 1.0) {
ep = 1.0 - step(p, sp);
}
else {
ep = step(p - 1.0, sp);
}
gl_FragColor = vColor * ep;
}
`;
const spotFragment = `
precision highp float;
precision highp int;
varying vec3 vNormal;
varying vec4 vColor;
varying vec2 vUv;
void main() {
float r = 1.0 - 2.0 * distance(vUv, vec2(0.5));
gl_FragColor.rgb = vColor.rgb;
gl_FragColor.a = vColor.a * smoothstep(0.0, 0.6, r);
}
`;
let spotProgram = null;
let _spot = null;
let _spotEnd = null;
export function launchMissile(parent, points, {colors}) {
const layer = parent.layer;
if(layer) {
const spotColors = ['rgb(245,250,113)', 'rgb(56,154,70)'];
const spotPos = new Vec3().copy(points[0]).normalize().scale(1.015);
const spotEndPos = new Vec3().copy(points[points.length - 1]).normalize().scale(1.015);
if(!spotProgram) {
spotProgram = layer.createProgram({
transparent: true,
vertex: shaders.GEOMETRY_WITH_TEXTURE.vertex,
fragment: spotFragment,
});
_spot = new Plane(spotProgram, {
width: 0.05,
height: 0.05,
});
_spotEnd = new Plane(spotProgram, {
width: 0.05,
height: 0.05,
});
}
const spot = _spot.cloneNode();
spot.attr({
colors: spotColors[0],
pos: spotPos,
});
const spotEnd = _spotEnd.cloneNode();
spotEnd.attr({
colors: spotColors[1],
pos: spotEndPos,
});
const sp = new Vec3().copy(spotPos).scale(2);
spot.lookAt(sp);
const sp2 = new Vec3().copy(spotEndPos).scale(2);
spotEnd.lookAt(sp2);
parent.append(spot, spotEnd);
const curveProgram = layer.createProgram({
transparent: true,
vertex,
fragment,
uniforms: {
uThickness: {value: 3},
uTime: {value: 0},
uDuration: {value: 1.0},
},
depthTest: true,
});
layer.bindTime(curveProgram);
const pe = points[points.length - 1];
const _points = points.map((p, i) => [p[0] - pe[0], p[1] - pe[1], p[2] - pe[2]]);
const p = new Polyline3d(curveProgram, {
points: _points,
colors,
pos: pe, // 曲线要设在结束点的位置,否则的话计算zDepth会导致透明度叠加出问题
});
parent.append(p);
setTimeout(() => {
layer.unbindTime(curveProgram);
p.remove();
spot.remove();
spotEnd.remove();
}, 1000);
}
} |
require('../build/build.js')
|
import express from 'express';
import cors from 'cors';
import bodyParser from 'body-parser';
import * as users from './users';
console.log(users);
const app = express();
const usersRouter = express.Router('/api/users');
usersRouter
.post('/api/users/register', users.createAccount)
app
.use(cors()) // connexion front back
.use(bodyParser.urlencoded({ extended: false }))
.use(bodyParser.json())
.use('/public', express.static(`${__dirname}/../public`))
.use(usersRouter)
app.listen(8080, () => {
console.log('Example app listening on port 8080!');
});
|
'use strict';
(function () {
var Url = {
UPLOAD: 'https://js.dump.academy/kekstagram',
LOAD: 'https://js.dump.academy/kekstagram/data'
};
var Method = {
POST: 'POST',
GET: 'GET'
};
var Status = {
SUCCESS: 200,
NOT_FOUND: 404,
NOT_AUTHORIZED: 401,
INVALID_REQUEST: 400
};
var backend = function (url, method, onSuccess, data, onError) {
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.open(method, url);
xhr.addEventListener('load', function () {
switch (xhr.status) {
case Status.SUCCESS:
onSuccess(xhr.response);
break;
case Status.NOT_FOUND:
onError('Cтатус ответа: ' + xhr.status + ' Ничего не найдено');
break;
case Status.INVALID_REQUEST:
onError('Cтатус ответа: ' + xhr.status + ' Неверный запрос');
break;
case Status.NOT_AUTHORIZED:
onError('Cтатус ответа: ' + xhr.status + ' Пользователь не авторизован');
break;
default:
onError('Ошибка:' + xhr.status);
}
});
xhr.send(data);
};
backend(Url.LOAD, Method.GET, window.renderPhotos.onSuccessLoad);
var form = document.querySelector('.img-upload__form');
form.addEventListener('submit', function (evt) {
backend(Url.UPLOAD, Method.POST, window.form.onSuccessUpload, new FormData(form), window.form.onErrorUpload);
evt.preventDefault();
});
})();
|
import keyBy from 'lodash/keyBy'
import {connect} from 'react-redux'
import PropTypes from 'prop-types'
import PatientDetail from '../common/PatientDetail'
import {getSessionPatientDetail} from '../../actions/patients'
import React, { Component } from 'react'
class PatientHome extends Component {
static propTypes = {
session: PropTypes.object.isRequired
}
componentDidMount() {
this.props.dispatch(getSessionPatientDetail())
}
render() {
const { props: { session, patient, doctorsById, appointments }} = this
const dataReady = !!(patient)
return (
<div>
{dataReady
? <PatientDetail
session = {session}
patient = {patient}
doctorsById = {doctorsById}
appointments = {appointments}
onAppointmentUpdate = {this.handleAppointmentUpdate}
/>
: <div className="App-loading" />
}
</div>
)
}
}
export default connect(
(state) => ({
session : state.session,
patient : state.patients.detailResult,
doctorsById : keyBy(state.doctors.all, d => d.id),
appointments : state.patients.detailAppointments,
})
)(PatientHome)
|
$("#card").flip({
axis: 'y',
trigger: 'manual'
});
// finish this
$(document).ready(function() {
// show share link
$(".card-share").click(function() {
console.log("blueberries are wonderful.");
$(".share-input").toggleClass('active');
});
// change english / other language button
$(".show-english").click(function() {
$("#card").flip('toggle');
if ($(".show--otherlang").hasClass('show')){
$(".show--otherlang").removeClass('show');
$(".show--english").removeClass('hide');
$(".show--otherlang").addClass('hide');
$(".show--english").addClass('show');
} else {
$(".show--otherlang").removeClass('hide');
$(".show--english").removeClass('show');
$(".show--otherlang").addClass('show');
$(".show--english").addClass('hide');
}
});
});
// background image change when refreshed
// function randomImage(){
// var images = [
// '{% static "draw/img/bg_01.jpg" %}',
// '{% static "draw/img/bg_02.jpg" %}',
// ];
// var size = images.length;
// var x = Math.floor(size * Math.random());
// console.log(x);
// var element = document.getElementsByClassName('background');
// console.log(element);
// element[0].style["background-image"] = "url("+ images[x] + ")";
// }
//
// document.addEventListener("DOMContentLoaded", randomImage);
|
import React from 'react';
import "../i18n";
import { useTranslation } from 'react-i18next';
function Header({styleA, styleB, text, subtext}){
const { t } = useTranslation();
return (
<div className={styleA}>
{t(text)}
<p className={styleB}>
{t(subtext)}</p>
</div>
);
}
export default Header;
|
import React from 'react'
function StartGameBtn (props) {
let {startGame, gameStatus} = props
let color = gameStatus === 'begin' ? '#96908d' : '#79421e'
return (
<button className="begin-btn"
onClick={startGame}
disabled={gameStatus === 'begin'}
style={{
color: color
}}
>开始游戏
</button>
)
}
export default StartGameBtn |
/*global define */
(function() {
"use strict";
var jsav, // The JSAV object
jsavGraph,
solArr,
Answer,
gnodes,
guessedAns,
From,
To,
Solution,
userInput; // Boolean: Tells us if user ever did anything
var visited;
var hamiltonianCycle_KA = {
userInput: null,
// Initialise the exercise
initJSAV: function (nnodes, nedges) {
hamiltonianCycle_KA.userInput = false;
jsav = new JSAV("jsav");
// jsav.recorded();
if (jsavGraph) {
jsavGraph.clear();
}
jsavGraph = jsav.ds.graph({width: 400, height: 280, layout: "automatic",
directed: true});
graphUtils.generate(jsavGraph,{weighted:false,nodes:nnodes,edges:nedges});
var edges = jsavGraph.edges();
for(i=0;i<edges.length;i++)
edges[i].css({"stroke-width":"1.5px","border": "5px solid transparent"});
jsavGraph.layout();
gnodes = jsavGraph.nodes();
From=new Array(gnodes.length);
To=new Array(gnodes.length);
visited=new Array(gnodes.length);
for(var i=0;i<gnodes.length;i++){
From[i]=0;
To[i]=0;
visited[i]=0;
}
// Bind the clickHandler to handle click events on the array
//jsavGraph.click(clickHandler ,{edge:true});
$(".jsavedge").on("click", clickHandler )
jsavGraph.mouseleave(function() { this.removeClass("over")},
// only for edges, don't record the changes
{edge: true, node: false, record: false});
jsavGraph.mouseenter(function() { this.addClass("over")},
{edge: true, node: false, record: false});
var nodes = jsavGraph.nodes();
guessedAns = true;
if(getSol(0,[])==false){
Answer=false;
Solution="No Hamiltonian Cycle";
//console.log("no Cyccle");
}
else{
Answer=true;
Solution=gnodes[solArr[0]].value();
for(i=1;i<solArr.length;i++)
Solution=Solution+"->"+gnodes[solArr[i]].value();
//console.log(str);
}
jsav.displayInit();
// Set up handler for reset button
$("#reset").click(f_reset);
},
// Check user's answer for correctness: User's array must match answer
checkAnswer: function() {
if(document.getElementById("noSol").checked==true){
if(Answer)
return false;
else
return true;
}
if(Answer){
for(var i=0;i<gnodes.length;i++)
if(From[i]!=1 || To[i]!=1)
return false;
return true;
}
return false;
},
// return the solution
getSolution: function() {
return Solution;
},
};
// Click event handler on the graph, intended for edges
function clickHandler () {
var node;
var c_edge = $(this).data("edge");
if(c_edge.hasClass('selected')){
From[gnodes.indexOf(c_edge.start())]-=1;
To[gnodes.indexOf(c_edge.end())]-=1;
c_edge.css({"stroke":"black"});
c_edge.removeClass('selected');
}
else {
From[gnodes.indexOf(c_edge.start())]+=1;
To[gnodes.indexOf(c_edge.end())]+=1;
c_edge.css({"stroke":"red"});
c_edge.addClass('selected');
}
hamiltonianCycle_KA.userInput = true;
};
function getSol(curr,path){
visited[curr]=1;
path.push(curr);
for(var i=0;i<gnodes.length;i++)
if(visited[i]==0)
break;
if(i==gnodes.length){
if(jsavGraph.hasEdge(gnodes[curr],gnodes[0])){
path.push(0);
solArr=path.slice(0);
return true;
}
else
path.pop();
visited[curr]=0;
return false;
}
var nextarr = gnodes[curr].neighbors();
for(var j=0;j<nextarr.length;j++){
i = gnodes.indexOf(nextarr[j]);
if(visited[i]==1){
continue;
}
if(getSol(i,path))
return true;
}
path.pop();
visited[curr]=0;
return false;
};
// reset function definition
function f_reset() {
if (jsavGraph) {
var nodes = jsavGraph.nodes();
for(var i=0;i<nodes.length;i++){
From[i]=0;
To[i]=0;
visited[i]=0;
}
var edges = jsavGraph.edges();
for(var i=0;i<edges.length;i++){
edges[i].removeClass('selected');
edges[i].css({"stroke":"black"});
}
}
hamiltonianCycle_KA.userInput = false;
};
function f_noHC() {
for(var i=0;i<gnodes.length;i++){
From[i]=0;
From[i]=1;
}
var edges = jsavGraph.edges();
for(var i=0;i<edges.length;i++){
edges[i].removeClass('selected');
edges[i].css({"stroke":"black"});
}
guessedAns = false;
};
function showSolution(){
if(Answer){
for(i=0;i<solArr.length;i++)
solArr[i].css({"stroke":"blue"});
return "The Hamiltonian Cycle is shown in blue on the graph.";
}
else
return "The graph consists of no Hamiltonian Cycle";
};
window.hamiltonianCycle_KA = window.hamiltonianCycle_KA || hamiltonianCycle_KA;
}()); |
WMS.module('Articles.List', function(List, WMS, Backbone, Marionette, $, _) {
var Views = List.Views;
List.Controller = Marionette.Controller.extend({
prefetchOptions: [
{ request: 'get:article:list', name: 'articles' }
]
, regions: [{
name: 'panelRegion'
, viewName: '_panel'
, View: List.Views.Panel
, options: {
criterion: "@criterion"
}
, events: {
"articles:new": 'newArticle',
'articles:filter': 'filterArticle'
}
}, {
name: 'listRegion'
, viewName: '_articles'
, View: List.Views.List
, options: {
criterion: "@criterion"
, collection: "@articles"
}
, events: {
'article:selected': 'selectArticle'
}
}, {
name: 'paginatorRegion',
View: List.Views.Paginator,
options: {
collection: "@articles",
}
}]
, initialize: function() {
var self = this;
WMS.vent.on("article:created", function(article) {
self.options.articles.add(article);
});
WMS.vent.on("article:updated", function(article) {
var model = self.options.articles.find({id: article.get('id')});
if (model) {
model.set(article.attributes);
}
});
}
, listArticles: function(criterion) {
this.options.criterion = criterion || "";
var self = this;
this.start().then(function() {
if (self._layout && !self._layout.isDestroyed) {
self.setupRegions(self._layout);
} else {
self._layout = new Views.FilterLayout();
self._layout.on('show', function() {
self.setupRegions(self._layout);
});
WMS.mainRegion.show(self._layout);
}
});
}
, filterArticle: function(criterion) {
WMS.trigger("articles:filter", criterion);
}
, newArticle: function() {
var klass = WMS.Models.Article;
if (klass.canCreate()) {
var model = new klass()
, view = new List.Views.New({ model: model });
WMS.showModal(view);
} else {
WMS.showError('Operazione non consentita!');
}
}
, selectArticle: function(childView) {
var article = childView.model;
if (article.canRead()) {
WMS.trigger("articles:show", article.get("id"));
}
}
});
}); |
'use strict'
angular.module('tutorialize')
.component('tutolist', {
templateUrl: './components/tuto-list/tuto-list.html',
controller: TutoList,
bindings: {
tutos: '<'
}
})
function TutoList($resource, $scope) {
this.focusedTuto = -1;
this.onTutorialClick = (index) => {
if (index == this.focusedTuto) {
this.focusedTuto = -1;
} else {
this.focusedTuto = index;
}
}
} |
// pages/answer/index.js
const app = getApp();
import api from '../../utils/api/api.js';
/***
* 判断用户滑动
* 左滑还是右滑
*/
const getTouchData = (endX, endY, startX, startY) => {
let turn = "";
if (endX - startX > 50 && Math.abs(endY - startY) < 50) { //右滑
turn = "right";
} else if (endX - startX < -50 && Math.abs(endY - startY) < 50) { //左滑
turn = "left";
}
return turn;
}
Page({
/**
* 页面的初始数据
*/
data: {
statusBarHeight: app.globalData.statusBarHeight,
navH:'',
answerid:'',
listData:'',
currentPage:0, //默认一进去页面为第1页
currentPage_Url:'',//默认第一张图,
cataLogShow:false,//目录
touchX:'',
touchY:'',
catalogueClassName:'catalogue2'
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.setData({
navH: app.globalData.navHeight
})
console.log(options);
let answerid=options.answerid;
this.setData({
answerid: answerid
})
this.getAnswerData();
},
getAnswerData(){
let answerid=this.data.answerid;
api.request(`/book/answer/${answerid}`,'GET').then(res=>{
console.log(res);
this.setData({
listData:res.data,
currentPage:0,
currentPage_Url:res.data[0].url,
})
}).catch(err=>{
console.log(err);
})
},
preview(e){
console.log(e);
let thisImgSrc = e.currentTarget.dataset.src;
wx.previewImage({
current: thisImgSrc, // 当前显示图片的http链接
urls: [`${thisImgSrc}`] // 需要预览的图片http链接列表
})
},
//上一页
lastPage(e){
console.log('上一页');
//判断是否第一页
if(this.data.currentPage==0){
wx.showToast({
icon:'none',
title: '已经是第一页了',
})
}else{
let lastCurrentPage=this.data.currentPage-1;
let lastcurrentPage_Url = this.data.listData[lastCurrentPage].url;
this.setData({
currentPage: lastCurrentPage,
currentPage_Url: lastcurrentPage_Url
})
}
},
//下一页
nextPage(e){
console.log('下一页');
console.log(this.data.currentPage);
if (this.data.currentPage+1 == this.data.listData.length){
wx.showToast({
icon:'none',
title: '已经是最后一页了',
})
}else{
let nextCurrentPage = this.data.currentPage + 1;
let nextcurrentPage_Url = this.data.listData[nextCurrentPage].url;
//console.log(nextCurrentPage);
this.setData({
currentPage: nextCurrentPage,
currentPage_Url: nextcurrentPage_Url
})
}
},
//展开目录
showCatalogue(){
this.setData({
cataLogShow:true,
catalogueClassName:'catalogueBack2'
})
},
//关闭目录
hideCato(e){
console.log(e);
this.setData({
cataLogShow: false,
catalogueClassName: 'catalogue2'
})
},
//切换答案页
changePage(e){
let changeUrl=e.currentTarget.dataset.url;
let changePage=e.currentTarget.dataset.page;
this.setData({
currentPage: changePage-1,
currentPage_Url: changeUrl
})
},
touchStart(e) {
console.log(e)
this.setData({
touchX: e.changedTouches[0].clientX,
touchY: e.changedTouches[0].clientY
});
},
touchEnd(e) {
console.log(e);
let x = e.changedTouches[0].clientX;
let y = e.changedTouches[0].clientY;
let direction=getTouchData(x,y,this.data.touchX,this.data.touchY);
console.log('向' + direction +'滑动');
if (direction=='left'){
console.log('下一页');
this.nextPage();
}else if(direction=='right'){
this.lastPage();
console.log('上一页');
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
// 返回上一页
navBack: function () {
wx.navigateBack({
delta: 1
})
},
navHome: function () {
wx.reLaunch({
url: '../index/index'
})
}
}) |
// TODO: Step 1
// 'use strict'
// const Hapi = require('hapi')
//
// const server = new Hapi.Server()
// server.connection({
// host: 'localhost',
// port: 8000
// })
//
// server.route({
// method: 'GET',
// path: '/',
// handler: (request, reply) => {
// reply('hello hapi!')
// }
// })
//
// server.route({
// method: 'GET',
// path: '/{name}',
// handler: (request, reply) => {
// reply(`hello ${request.params.name}!`)
// }
// })
//
// server.start(() => console.log('Started at:', server.info.uri))
// use this with nodemon
// currently this is working only after running as superuser
// sudo su
// using: $ nodemon -w ./ index.js
// TODO: Step 2
// now we will install good and good console
// good is a process monitor for hapi , it listens to different event types and passes events on
// to reporters , good console output reports to stdout
// 'use strict'
// const Hapi = require('hapi')
//
// const server = new Hapi.Server()
// server.connection({
// host: 'localhost',
// port: 8000
// })
//
// let goodOptions = {
// // reporters: [{
// // reporter: require('good-console'),
// // events: { log: ['error'], response: '*' }
// // }]
// reporters: {
// console: [{
// module: 'good-console',
// args: [{ log: '*', response: '*' }]
// }, 'stdout'],
// }
// }
//
// server.register({
// register: require('good'),
// options: goodOptions
// }, err => {
//
// server.route({
// method: 'GET',
// path: '/',
// handler: (request, reply) => {
// server.log('error', 'Oh no!')
// server.log('info', 'replying')
// reply('hello hapi')
// }
// })
//
// server.route({
// method: 'GET',
// path: '/{name}',
// handler: (request, reply) => {
// reply(`hello ${request.params.name}`)
// }
// })
//
// server.start(() => console.log(`Started at: ${server.info.uri}`))
//
// })
// TODO: step 3
// 'use strict'
// const Hapi = require('hapi')
//
// const server = new Hapi.Server()
// server.connection({ port: 8800 })
//
// function handler(request, reply) {
// reply(request.params)
// }
//
//
// // wildcard parameter
// // so if : http://localhost:8800/stuff/a/a/a
// // our stuff parameter has value : stuff/a/a/a
// // server.route({
// // method: 'GET',
// // path: '/{stuff*}',
// // handler: handler
// // })
//
// // {userID} It expects user id parameter, if not found it throws the error
// // {userID?} userID is optional parameter here if not found it still loads with no 404 error
// server.route({
// method: 'GET',
// path: '/users/{userId?}',
// handler: handler
// })
//
// // number of matching segments specified file * 2(# of matching segments)
// // after 2 segments if any extra segment is supplied it would throw out an error
// server.route({
// method: 'GET',
// path: '/files/{file*2}',
// handler: handler
// })
//
//
// // partial segments , segments with specified postfix will be accepted only
// server.route({
// method: 'GET',
// path: '/some/{some}.jpeg',
// handler: handler
// })
//
// server.start(() => console.log(`Started at: ${server.info.uri}`))
// TODO: step 4
// 'use strict'
// const Hapi = require('hapi')
//
// const server = new Hapi.Server()
// server.connection({ port: 8800 })
//
// function handler(request, reply) {
// reply(request.params)
// }
//
//
// // wildcard parameter
// // so if : http://localhost:8800/stuff/a/a/a
// // our stuff parameter has value : stuff/a/a/a
// server.route({
// method: 'GET',
// path: '/{stuff*}',
// handler: handler
// })
//
// // {userID} It expects user id parameter, if not found it throws the error
// // {userID?} userID is optional parameter here if not found it still loads with no 404 error
// server.route({
// method: 'GET',
// path: '/users/{userId?}',
// handler: handler
// })
//
// // number of matching segments specified file * 2(# of matching segments)
// // after 2 segments if any extra segment is supplied it would throw out an error
// server.route({
// method: 'GET',
// path: '/files/{file*2}',
// handler: handler
// })
//
//
// // partial segments , segments with specified postfix will be accepted only
// server.route({
// method: 'GET',
// path: '/some/{some}.jpeg',
// handler: handler
// })
//
// server.start(() => console.log(`Started at: ${server.info.uri}`))
// TODO: Step 5
// 'use strict'
// const Hapi = require('hapi')
// const Boom = require('boom')
// const server = new Hapi.Server()
// server.connection({ port: 8000 })
//
// server.route({
// method: 'GET',
// path: '/',
// handler: function(request, reply) {
// reply()
// // reply(null, 'hello world')
// // reply('hello world')
// // reply({ hello: 'world' })
// // reply(Promise.resolve('hello world'))
// // reply(require('fs').createReadStream(__filename))
//
// // internal server 500
// // reply(new Error('oops'))
//
// // 404 not found handler Boom
// //reply(Boom.notFound())
// }
// })
//
// server.start(() => {})
// TODO: Step 6
// 'use strict'
// const Hapi = require('hapi')
// const Boom = require('boom')
// const server = new Hapi.Server()
// server.connection({ port: 8000 })
//
// server.route({
// method: 'GET',
// path: '/',
// handler: function(request, reply) {
// let resp = reply('hello world')
// // we can change the status code of the response
// resp.code(418)
//
// // we can also change the content type of the reponse
// resp.type('text/plain')
// // we can also change the headers
// // first argument is the header name and the second is header value
// resp.header('hello', 'world')
//
// // we can set the cookies using the method state
// resp.state('hello', 'world')
//
// // reponses are chainable so it would work without resp just supplying more chains in the reply
// // reply('hello world')
// // .code(418)
// // .type('text/plain')
// // .header('hello', 'world')
// // .state('hello', 'world')
// }
// })
//
// server.start(() => {})
// TODO: Step 7
// 'use strict'
// const Hapi = require('hapi')
// const Path = require('path')
//
// const server = new Hapi.Server()
// server.connection({ port: 8000 })
//
// server.register(require('inert'), () => {
//
// server.route({
// method: 'GET',
// path: '/hapi.png',
// handler: function(request, reply) {
// var path = Path.join(__dirname, 'public/hapi.png')
// reply.file(path)
// }
// })
//
// server.route({
// method: 'GET',
// path: '/hapi2.png',
// handler: {
//
// // this is one way of readin files
// // var path = Path.join(__dirname, 'public/hapi2.png')
// // reply.file(path)
//
// file: Path.join(__dirname, 'public/hapi2.png')
// }
// })
//
// server.route({
// method: 'GET',
// path: '/{param*}',
// handler: {
// // serving multiple files just by name so it directoy property would find the files and show
// directory: {
// path: Path.join(__dirname, 'public')
// }
// }
// })
//
// server.start(() => console.log(`Started at: ${server.info.uri}`))
// })
// TODO: Step 8
// 'use strict'
// const Hapi = require('hapi')
// const server = new Hapi.Server()
// server.connection({ port: 8000 })
//
// server.register(require('vision'), () => {
//
// server.views({
// engines: {
// hbs: require('handlebars')
// },
// relativeTo: __dirname,
// layout: true,
// path: 'views'
// })
//
// server.route({
// method: 'GET',
// path: '/{name?}',
// handler: function(request, reply) {
// reply.view('home', { name: request.params.name || 'World' })
// }
// })
//
// server.start(() => console.log(`Started at: ${server.info.uri}`))
// })
// post and put request payloads
// TODO: Step 9
// 'use strict'
// const Hapi = require('hapi')
// const server = new Hapi.Server()
// server.connection({ port: 8000 })
//
// server.route({
// // If parse is set to False and then request and response would have the same content type until explicitely allowed it would throw
// // unsupported media type error
// method: ['POST', 'PUT'],
// path: '/',
// // config: {
// // payload: {
// // output: 'data',
// // parse: false,
// // allow: 'application/json'
// // }
// // },
// handler: function(request, reply) {
// // this would simply print the requested data and handles content type
// // http -v POST localhost:8000 fname=Chitrank lname=dixit (this would print the reponse with correct content type on the console)
// // http -v PUT localhost:8000 fname=Chitrank lname=dixit (this would print the reponse with correct content type on the console) (data is handled the same way)
// // http -v --form PUT localhost:8000 fname=Chitrank lname=dixit (makes the content type of request to application/x-www-form-urlencoded)
// reply(request.payload)
// }
// })
//
// server.start(() => console.log(`Started at: ${server.info.uri}`))
// extending the request with life cycle events
// TODO: Step 10
// 'use strict'
// const Hapi = require('hapi')
// const Boom = require('boom')
// const server = new Hapi.Server()
// server.connection({ port: 8000 })
//
// server.ext('onRequest', (request, reply) => {
// request.setUrl('/')
// request.setMethod('GET')
// reply.continue()
// })
//
// server.ext('onRequest', (request, reply) => {
// console.log('onRequest')
// reply.continue()
// })
//
// server.ext('onPreAuth', (request, reply) => {
// console.log('onPreAuth')
// reply.continue()
// })
//
// server.ext('onPostAuth', (request, reply) => {
// console.log('onPostAuth')
// reply.continue()
// })
//
// server.ext('onPreHandler', (request, reply) => {
// console.log('onPreHandler')
// reply.continue()
// })
//
// server.ext('onPostHandler', (request, reply) => {
// console.log('onPostHandler')
// reply.continue()
// })
//
// server.ext('onPreResponse', (request, reply) => {
// console.log('onPreResponse')
// reply.continue()
// })
//
// server.route({
// method: 'GET',
// path: '/',
// handler: function(request, reply) {
// console.log('handler')
// reply('hello world')
// }
// })
//
// server.start(() => {})
// TODO: Step 11
// Friendly error pages with extension events
// 'use strict'
// const Hapi = require('hapi')
// const Boom = require('boom')
// const server = new Hapi.Server()
// server.connection({ port: 8000 })
//
// server.register(require('vision'), () => {
//
// server.views({
// engines: { hbs: require('handlebars') },
// relativeTo: __dirname,
// path: 'views'
// })
//
// server.ext('onPreResponse', (request, reply) => {
// let resp = request.response
// if (resp.isBoom) {
// return reply.view('error', resp.output.payload)
// .code(resp.output.statusCode)
// }
// reply.continue()
// })
//
// server.route({
// method: 'GET',
// path: '/',
// handler: function(request, reply) {
// reply(Boom.badRequest())
// }
// })
//
// server.start(() => {})
//
// })
// TODO: Step 12
// 'use strict'
// const Hapi = require('hapi')
// const Joi = require('joi')
// const server = new Hapi.Server()
// server.connection({ port: 8000 })
//
//
// // request : http -v POST localhost:8000/user/123 id=123
// server.route({
// method: ['POST','PUT'],
// path: '/user/{id?}',
// config: {
// validate: {
// params: Joi.object().keys({
// id: Joi.number()
// }),
// payload: Joi.object().keys({
// id: Joi.number(),
// email: Joi.string()
// }).unknown(),
// query: Joi.object().keys({
// id: Joi.number()
// })
// },
// handler: function(request, reply) {
// reply({
// params: request.params,
// query: request.query,
// payload: request.payload
// })
// }
// }
// })
//
// server.start(() => console.log(`Started at: ${server.info.uri}`))
// TODO: Step 13
// Managing state with cookies
// State can be set using the cookies
'use strict'
const Hapi = require('hapi')
const server = new Hapi.Server()
server.connection({ port: 8000 })
server.state('hello', {
ttl: 60 * 60 * 1000,
isHttpOnly: true,
isSecure: false,
encoding: 'iron',
password: 'a5LewP10pXNbWUdYQakUfVlk1jUVuLuUU6E1WEE302k'
})
server.route({
method: 'GET',
path: '/',
config: {
// handler: function(request, reply) {
// reply(`Cookies! world`)
// .state('hello', 'world')
// }
handler: function(request, reply) {
let hello = request.state.hello
reply(`Cookies! ${hello}`)
.state('hello', 'world')
}
}
})
server.start(() => console.log(`Started at: ${server.info.uri}`))
|
import React, { Component } from 'react'
export default class FormGroup extends Component {
render() {
const { inputId, title, value, handleInputChange} = this.props;
return (
<div>
<label className='label' htmlFor={inputId}>{title}</label>
<input
value={value}
onChange={handleInputChange}
name={inputId}
className='input'
id={inputId}
type='text'
/>
</div>
)
}
}
|
import {map, omit} from 'lodash'
// local libs
import {PropTypes, assertPropTypes, plainProvedGet as g} from 'src/App/helpers'
const
sponsorsModel = process.env.NODE_ENV === 'production' ? null :
PropTypes.objectOf(PropTypes.shape({name: PropTypes.string}))
export default (sponsors) => {
sponsors = omit(sponsors, 'all')
if (process.env.NODE_ENV !== 'production') {
assertPropTypes(sponsorsModel, sponsors, 'getSponsorsList', 'sponsors')
}
return map(
sponsors,
x => g(x, 'name')
)
}
|
import React, { Component } from 'react'
import meme from '../../img/meme.png'
import './header.css';
export class Header extends Component {
render() {
return (
<header>
<img src={meme} alt="mem" />
<h1>Mem Generator</h1>
</header>
)
}
}
export default Header; |
require(['../main'], function() {
require(['login']);
}); |
var formulario = $("#form_reg")
function isValidForm(form){
var config = {}
var rcheck = 0
var ccheck = 0
for (var i = 0; i < form[0].length; i++) {
if (form[0][i]['tagName'] == 'INPUT' || form[0][i]['tagName'] == 'TEXTAREA' || form[0][i]['tagName'] == 'SELECT') {
if (form[0][i]['type'] !== 'reset' && form[0][i]['type'] !== 'submit' && form[0][i]['type'] !== 'button' && form[0][i]['type'] !== 'url' && form[0][i]['type'] !== 'tel') {
config[i] = form[0][i]
config[i]['estado'] = false
if (config[i]['tagName'] == 'SELECT') {
if (config[i]['value'] !== config[i][0]['value'] || config[i]['value'] !== config[i][0]['textContent']) {
config[i]['estado'] = true
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).addClass('has-success has-feedback')
}else {
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).addClass('has-error has-feedback')
}
}
switch (config[i]['type'].toLowerCase()) {
case 'email':
if (isEmail(config[i]['value'])) {
config[i]['estado'] = true
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-success has-feedback').append(`<span id="icon" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>`)
}else {
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-error has-feedback').append(`<span id="icon" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>`)
}
break;
case 'number':
if (isNumber(config[i]['value'])) {
config[i]['estado'] = true
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-success has-feedback').append(`<span id="icon" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>`)
}else {
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-error has-feedback').append(`<span id="icon" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>`)
}
break;
case 'checkbox':
if (ccheck > 0) {
config[i]['estado'] = true
}else {
if (config[i]['checked']) {
config[i]['estado'] = true
ccheck += 1
}
}
break;
case 'radio':
if (rcheck > 0) {
config[i]['estado'] = true
}else {
if (config[i]['checked']) {
config[i]['estado'] = true
rcheck += 1
}
}
break;
case 'date':
if (config[i]['value'] !== "") {
config[i]['estado'] = true
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-success has-feedback').append(`<span id="icon" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>`)
}else {
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-error has-feedback').append(`<span id="icon" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>`)
}
break;
case 'text':
case 'password':
case 'search':
var data = config[i]['value'].trim()
if (data !== "") {
config[i]['estado'] = true
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-success has-feedback').append(`<span id="icon" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>`)
}else {
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-error has-feedback').append(`<span id="icon" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>`)
}
break;
case 'range':
config[i]['estado'] = true
break;
case 'textarea':
var data = config[i]['value'].trim()
if (data !== "") {
config[i]['estado'] = true
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-success has-feedback').append(`<span id="icon" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>`)
}else {
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-error has-feedback').append(`<span id="icon" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>`)
}
case 'file':
var data = config[i]['value'].trim()
if (data !== "") {
config[i]['estado'] = true
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-success has-feedback').append(`<span id="icon" class="glyphicon glyphicon-ok form-control-feedback" aria-hidden="true"></span>`)
}else {
$(form[0][i]['parentElement']).removeClass('has-error has-success has-feedback')
$(form[0][i]['parentElement']).find('span#icon').remove()
$(form[0][i]['parentElement']).addClass('has-error has-feedback').append(`<span id="icon" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>`)
}
break;
default:
}
}
}
}
function isEmail(p) {
var email = /^([a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+(\.[a-z\d!#$%&'*+\-\/=?^_`{|}~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+)*|"((([ \t]*\r\n)?[ \t]+)?([\x01-\x08\x0b\x0c\x0e-\x1f\x7f\x21\x23-\x5b\x5d-\x7e\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|\\[\x01-\x09\x0b\x0c\x0d-\x7f\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))*(([ \t]*\r\n)?[ \t]+)?")@(([a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\d\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.)+([a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]|[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF][a-z\d\-._~\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]*[a-z\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])\.?$/i;
return email.test(p);
}
function isNumber(p){
return $.isNumeric(p)
}
function cantidad(p) {
return Object.keys(p).length
}
}
$("#btn_enviar").on('click', function(){
isValidForm(formulario)
})
|
module.exports = function(db){
console.log(db);
}; |
let userName;
let userAge;
let userSurname;
let newUser;
let shoppingList;
let userOnline;
let userSalary;
let cursorCoordinates;
console.log('Hello world');
userName = 'Kazimir94';
console.log('userName' , userName);
const userAdress = 'UA';
console.log('useruserAdress' , userAdress); |
/*
Given an array of integers.
Find maximum product obtained from multiplying 2 adjacent numbers.
Notes:
Array will contain at least 2 elements.
Aarray may contain positive/negative numbers and zeroes.
Input >> Output Examples
adjacentElementsProduct([1,2,3]) ==> return 6
Explanation:
Max product obtained from multiplying 3 * 2 = 6 .
adjacentElementsProduct([9, 5, 10, 2, 24, -1, -48]) ==> return 50
Explanation:
Max product obtained from multiplying 5 * 10 = 50 .
adjacentElementsProduct([-23, 4, -5, 99, -27, 329, -2, 7, -921]) ==> return -14
Explanation:
Max product obtained from multiplying -2 * 7 = -14 .
*/
function adjacentElementsProduct(arr) {
let max = arr[0] * arr[1];
for (let i = 1; i < arr.length - 1; i++) {
let curr = arr[i];
let folo = arr[i+1];
let product = curr * folo;
if (product > max) {
max = product;
}
}
return max;
}
|
$(function() {
$("#modal-recipeNotes").focus(function(event) {
// Erase text from inside textarea
$(this).text("");
// Disable text erase
$(this).unbind(event);
});
});
$('#btnSaveRecipe').click(function(e) {
e.preventDefault();
let title = $('#title').text()
let recipeNotes = $('#recipeNotes-display').text()
let host = $("#host").text()
$('#saveModal').find('.modal-title').text('Save Recipe');
$('#saveModal').find('.recipe-title-source').text(title + ' | ' + host);
if (recipeNotes !== '') {
$('#modal-recipeNotes').text(recipeNotes)
} else {
$('#modal-recipeNotes').text('Enter recipe notes here...')
}
$('#saveModal').modal('show');
});
$('#btnSaveConfirm').click(function(e) {
e.preventDefault();
let user = $( "#username" ).text()
let title = $("#title").text().trim()
let host = $("#host").text()
let url = $("#recipeURL").val()
var ingredients = [];
$('#ingredients-list').each(function(){
ingredients.push($(this).text());
});
let instructions = $("#instructions-list").text()
if ($("#modal-recipeNotes").val() == 'Enter recipe notes here...') {
var recipeNotes = ""
} else {
var recipeNotes = $("#modal-recipeNotes").val()
$('#recipeNotes-title').text('Recipe Notes:')
$('#recipeNotes-display').text(recipeNotes)
};
let data = JSON.stringify({
user,
title,
host,
url,
ingredients,
instructions,
recipeNotes
})
// Setup our AJAX request
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/save", true);
xhttp.setRequestHeader("Content-type", "application/json");
// Tell our AJAX request how to resolve
xhttp.onreadystatechange = () => {
if (xhttp.readyState == 4 && xhttp.status == 200) {
console.log("Recipe Saved!\n" + xhttp.response)
} else if (xhttp.readyState == 4 && xhttp.status != 200) {
console.log("There was an error with the input.")
}
}
// Send the request and wait for the response
xhttp.send(data);
$('#saveModal').modal('hide');
}); |
'use strict';
var ghpages = require('gh-pages'),
path = require('path');
ghpages.publish(
path.join(__dirname, 'src'), {
dotfiles: true,
message: 'Auto-generated commit'
},
function(err) {
if (err) {
throw err;
} else {
console.log('Site has been deployed!');
}
}
);
|
const readline = require('readline')
const input = readline.createInterface(process.stdin)
console.log("Загадано число в диапазоне от 0 до 100")
let rnd = Math.floor(Math.random()*(100+1)) // случайное число
input.on('line', (data) =>
{
if (data>rnd) {console.log("Больше")}
if (data<rnd) {console.log("Меньше")}
if (data==rnd) {console.log("Отгадано число " + rnd)}
})
|
//функция создание астероида
function creatureAsteroid() {
//создаем элемент div
asteroid = document.createElement("div");
//присвамваем ему класс asteroid для задания свойств css
asteroid.className = "asteroid";
//добавляем на поле
full.appendChild(asteroid);
}
//функция определения количества астероидов
function asteroids(min, max) {
//определяем рандомное число астероидов
let quantityAsteroid = random(min, max);
//указываем текущее количество астероидов
let currentQuantityAsteroid = 0;
//пока текущее количество астероидов меньше заданого
while (currentQuantityAsteroid < quantityAsteroid) {
//вызываем функцию создания астероида
creatureAsteroid();
//заносим созданый астероид в массив
allAsteroids[currentQuantityAsteroid] = asteroid;
//определяем исходную позицию астероида
positionAsteroid();
//увеличиваем текущее их количество
currentQuantityAsteroid++;
}
}
//функция определения положения астероида
function positionAsteroid() {
//обьявляем переменные уникальности числа и позиции астероида
let unic, positionAsteroid;
//выполняем действия
do {
//определяем рандомное число в пределах размеров поля
positionAsteroid = random(20, 720);
//указываем что число уникально
unic = true;
//запускаеи перебор массива с астероидами
for (a = 0; a < allAsteroids.length; a++) {
//определяем позиции астероидов из массива
let positionNowAsteroid = parseInt(allAsteroids[a].style.left);
//если позиция нового астероида пересикается с уже существующими
if(positionAsteroid < (positionNowAsteroid + asteroid.offsetWidth) && positionAsteroid > (positionNowAsteroid - 30)) {
//задаем что такое число уже было
unic = false;
//и выходим с перебора массива
break;
}
}
//пока переменная unic не будет уникальной
} while (!unic);
//задаем исходное положение астероида относительно левого края
asteroid.style.left = positionAsteroid + "px";
}
//функция падения астероида
function moveAsteroid(getAsteroid) {
let speed;
if(min < 1) {
speed = 30;
} else if (min == 0 && sec == 30) {
speed = 25;
} else if (min == 1 && sec < 30) {
speed = 15;
} else {
speed = 10;
}
//каждые 10 милисекунд
let moveIntervalAsteroid = setInterval(() => {
//увеличиваем отступ астероида сверху на 1 px
getAsteroid.style.top = getAsteroid.offsetTop + 1 + "px";
//вызываем функцию проверки на столкновение астероида с кораблем
crashAsteroid(getAsteroid, ship);
//если вдлина массива с пулями больше 0
if(shots.length > 0) {
//перебираем все пули
shots.forEach(function(value) {
//и вызываем функцию проверки на столкновение астероида с пулей
crashAsteroid(getAsteroid, value);
});
}
// если id астероида explode - вызвалась функция взрыва
if (getAsteroid.id == 'explode' ) {
//останавливаем движение астероида
clearInterval(moveIntervalAsteroid);
//если отступ превышает 720 рх
} else if (getAsteroid.offsetTop > 720) {
//останавливаем движение астероида
clearInterval(moveIntervalAsteroid);
//удаляем астероид
getAsteroid.remove();
}
}, speed);
}
//функция запуска движения всех астероидов
function getAsteroids() {
//пербираем массив с астероидами
allAsteroids.forEach(function(element, i) {
//вызываем функция падения астероида
moveAsteroid(element);
//удаляем с массива астероид
delete allAsteroids[i];
});
} |
import './App.css';
import Roller from './components/Roller/Roller'
function App() {
return (
<div className="App">
<Roller />
</div>
);
}
export default App;
|
// Require mongoose package
const mongoose = require('mongoose');
//Define RecipeSchema
const RecipeSchema = new mongoose.Schema({
name: {
type: String,
trim: true
},
ingredients: {
type: String,
trim: true
},
description: {
type: String,
trim: true
}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'updated_at'
}
});
mongoose.model('Recipe', RecipeSchema);
const Recipe = module.exports = mongoose.model('Recipe');
// Recipe.find() returns all the recipes
module.exports.getAllRecipes = (callback) => {
Recipe.find(callback);
};
// Recipe.findById() returns one recipe by Id
module.exports.getRecipeById = (id, callback) => {
Recipe.findById(id, callback);
};
// newRecipe.save is used to insert the document into MongoDB
module.exports.addRecipe = (newRecipe, callback) => {
newRecipe.save(callback);
};
// Here we need to pass an id parameter to Recipe.remove
module.exports.deleteRecipeById = (id, callback) => {
let query = { _id: id };
Recipe.remove(query, callback);
} |
angular.module("internship").directive("unorderedList", function() {
return function(scope, element, attrs) {
var data = scope[attrs["unorderedList"]];
var propertyName = attrs["listProperty"];
if (angular.isArray(data)) {
var listElem = angular.element("<ul>");
element.append(listElem);
var propertyExpression = attrs["listProperty"]; //new
for (var i=0; i < data.length; i++) {
(function() {
//console.log("Item: " + data[i][propertyName]);
var itemElement = angular.element("<li>");
listElem.append(itemElement);
var index = i;
//new
var watcherFn = function(watchScope) {
//console.log("data");
//console.log(data);
return watchScope.$eval(propertyExpression, data[index]);
};
scope.$watch(watcherFn, function(newValue, oldValue) {
console.log("newValue : " + newValue);
itemElement.text(newValue);
});
var buttons = element.find("button");
buttons.on("click", function(e) {
element.find("li").toggleClass("bold");
});
}());
}
//console.log(listElem);
}
else {
console.log("Not an array");
}
}
}).directive("unorderedLists", function() {
return {
//scope: {
//
//},
link: function(scope, element, attrs) {
scope.data = scope[attrs["unorderedLists"]];
},
restrict: "A", //Allows use as E: Element, A: Attribute, C: Class, M: Comment
templateUrl: "templates/editorFor/textTemplate.html"
}
}).directive("editorFor", function() {
return {
scope: {
modelData: '='
},
replace: true,
link: function(scope, element, attrs) {
scope.type = attrs["type"];
},
restrict: "E", //Allows use as E: Element, A: Attribute, C: Class, M: Comment
templateUrl: function(elem, attrs) {
if (attrs["type"] == "checkbox") {
return "templates/editorFor/checkboxTemplate.html"
}
else if (attrs["type"] == "textarea") {
return "templates/editorFor/textareaTemplate.html"
}
else {
return "templates/editorFor/textTemplate.html"
}
}
}}
); |
export { default as sayHello } from './components/sayHello'
|
/* eslint-disable react/prefer-stateless-function */
import React, { Component } from 'react';
import { Container, Row, Col } from 'reactstrap';
import { connect } from 'react-redux';
import ScrollAnimation from 'react-animate-on-scroll';
import colors from '../config';
import '../App.css';
const email = 'anto.sauvage@gmail.com';
class AboutMe extends Component {
render() {
const { language } = this.props;
return (
<div style={style.container} id="aboutme">
<Container>
<Row>
<Col xs="12" className="text-center">
{language === 'fr' ? (
<h3 className="sectionTitle">Profil</h3>
) : (
<h3 className="sectionTitle">Profile</h3>
)}
</Col>
</Row>
<Row>
<Col xs="12" md="4" className="text-center flex-column justify-content-center">
<ScrollAnimation animateIn="bounceIn">
<img style={style.logo} src={require('../images/story.svg')} alt="Logo" />
</ScrollAnimation>
{language === 'fr' ? (
<div>
<h4 className="sectionSubtitle">À propos</h4>
<p>
"Après 7 années comme ingénieur du son et 3 comme artisan menuisier, j'ai décidé
de me reconvertir.
</p>
<p>
{' '}
À travers ces métiers à première vue très différents, j’ai acquis les mêmes
compétences et qualités qui me permettent aujourd’hui d’être à l’aise dans ce
nouveau métier : rigoureux, curieux, organisé, logique, positif, responsable et
consciencieux."
</p>
</div>
) : (
<div>
<h4 className="sectionSubtitle">About me</h4>
<p>
"After 7 years as a sound engineer and 3 as a carpenter, I decided to retrain.
</p>
<p>
{' '}
Through these very different professions at first glance, I acquired the same
skills and qualities that allow me today to be comfortable in this new
profession: rigorous, curious, organized, logical, positive, responsible and
conscientious."
</p>
</div>
)}
</Col>
<Col xs="12" md="4" className="text-center">
<img
className="shadow rounded rounded-circle"
style={style.image}
src={require('../images/as_square.jpg')}
alt="Antoine"
/>
</Col>
<Col xs="12" md="4" className="text-center">
<ScrollAnimation className="md-mt" animateIn="bounceIn">
<img style={style.logo} src={require('../images/resume.svg')} alt="Logo" />
</ScrollAnimation>
{language === 'fr' ? (
<div>
<h4 className="sectionSubtitle">Informations </h4>
<p style={style.infoText}>Nom : Antoine Sauvage</p>
<p style={style.infoText}>Âge : 35 ans</p>
<p style={style.infoText}>
Email :{' '}
<a className="aMail" href={`mailto:${email}`}>
anto.sauvage@gmail.com
</a>
</p>
</div>
) : (
<div>
<h4 className="sectionSubtitle">Personal Details </h4>
<p style={style.infoText}>Full name : Antoine Sauvage</p>
<p style={style.infoText}>Age : 35 years old</p>
<p style={style.infoText}>
Email :{' '}
<a className="aMail" href={`mailto:${email}`}>
anto.sauvage@gmail.com
</a>
</p>
</div>
)}
</Col>
</Row>
</Container>
</div>
);
}
}
const style = {
container: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
marginTop: 50,
marginBottom: 50,
fontFamily: 'Montserrat',
},
image: {
borderRadius: '50%',
width: 220,
height: 220,
},
infoText: {
color: colors.greyColor,
margin: '0 0 16 0',
// padding: '13px 0px',
borderBottom: 'solid #AB9B96 1px',
textAlign: 'left',
},
logo: {
width: 60,
margin: '0px 0px 20px 0px',
},
};
function mapStateToProps(state) {
return {
language: state.language,
};
}
export default connect(
mapStateToProps,
null,
)(AboutMe);
|
import React,{Component} from 'react'
import ButtonBox from '../../../shareComponent/ButtonBox'
export default class AddGroupModal extends Component {
addMoreGroupConfirm = () =>{
const value = this.refs.groups.value
const {addMoreGroupConfirm} = this.props
addMoreGroupConfirm(value)
}
render(){
const {addMoreGroupClick} = this.props
return (
<div className="modalWrapper">
<div className="modalBox addBox">
<div className="titleBox">
<span>新增多群</span>
<span style={{color: '#B5BDC6',fontSize:'14px'}}>*每排默认一个群名称</span>
</div>
<textarea ref='groups' className='groupInput' autoFocus={true} placeholder='编辑或粘贴你的名称吧'></textarea>
<div className="buttonBox">
<ButtonBox
btnTxt={"取消"}
isCancel={true}
btnFunc={addMoreGroupClick}
/>
<ButtonBox
btnTxt={'确定'}
isCancel={false}
btnFunc={this.addMoreGroupConfirm}
/>
</div>
<div className="closeBtn" onClick={addMoreGroupClick}></div>
</div>
</div>
)
}
} |
$(function($){
templateLoader.loadRemoteTemplate("ab-variation", "/templates/ab-variation.html", function(data){
new Views.ABExperimentView();
});
});
|
import React, { Component } from 'react';
import { Segment,
Grid, Icon, Divider } from 'semantic-ui-react'
import { CardComponent,
StatisticComponent,
ContentComponent,
ItemComponent } from 'components';
class MainContainer extends Component {
constructor(props) {
super(props);
this.state = { }
}
render() {
return (
<div>
<div className="title_heading">
<h1>Bus Routes Analysis</h1>
</div>
<Segment textAlign="left" raised>
<Grid columns={2}>
<Grid.Column width={3}>
<CardComponent style={{"margin-right":"10px"}} />
</Grid.Column>
<Grid.Column width={12}>
<ContentComponent/>
</Grid.Column>
</Grid>
</Segment>
<Segment className="height_370" raised>
<Grid columns={2}>
<Grid.Column verticalAlign="middle" >
<Grid.Row centered columns={4}>
<ItemComponent/>
</Grid.Row>
</Grid.Column>
<Grid.Column verticalAlign="middle">
<Grid.Row centered columns={4}>
<StatisticComponent/>
</Grid.Row>
</Grid.Column>
</Grid>
<Divider vertical>
<Icon name='map marker alternate' color="grey" />
</Divider>
</Segment>
</div>
);
}
}
export default MainContainer; |
const posts = [
{title: 'Post One', body: 'Post one body'},
{title: 'Post Two', body: 'Post two body'}
];
//* ============= Synchronous way
// const createPost = (post) => {
// setTimeout(() =>{
// posts.push(post);
// },2000);
// };
// const getPosts = () => {
// setTimeout(() => {
// let output = '';
// posts.forEach(post => {
// output += `<li>${post.title}</li>`
// });
// document.getElementById('app').innerHTML = output;
// }, 1000);
// }
// createPost({title: 'New Post', body: 'This is a new post'})
// getPosts();
//* ============= Asynchronous way
const createPost = (post, cb) => {
setTimeout(() => {
posts.push(post);
cb(); // getPost will be called here
}, 2000);
};
const getPosts = () => {
setTimeout(() => {
let output = "";
posts.forEach((post) => {
output += `<li>${post.title}</li>`;
});
document.getElementById("app").innerHTML = output;
}, 1000);
};
// Calling createPost and passing getPosts as a callback
createPost({ title: "New Post", body: "This is a new post" }, getPosts); |
var makeQueue = function(){
// Hey! Copy your code from src/functional/queue.js and paste it here
var instance = Object.create(queueMethods);
// Use an object with numeric keys to store values
instance._storage = {};
instance._size = 0;
// Implement the methods below
return instance;
};
var queueMethods = {};
queueMethods.enqueue = function(value){
this._storage[this._size] = value;
this._size++;
};
queueMethods.dequeue = function(){
var result = this._storage[0];
delete this._storage[0];
for(var i=1;i<this._size;i++){
this._storage[i-1]=this._storage[i];
}
this._size && this._size--;
delete this._storage[this._size];
return result;
};
queueMethods.size = function(){
return this._size;
};
|
import EmberObject from '@ember/object';
import Component from '@ember/component';
import { A } from '@ember/array';
import { resolve, reject } from 'rsvp';
import { module } from 'qunit';
import { setupRenderingTest } from 'ember-qunit';
import { render, click, fillIn, triggerKeyEvent, triggerEvent, waitFor, waitUntil, settled, focus, blur } from '@ember/test-helpers';
import {
formFeedbackClass,
test,
testRequiringFocus,
testBS3,
testBS4,
validationErrorClass,
formFeedbackElement, validationSuccessClass
} from '../../helpers/bootstrap-test';
import hbs from 'htmlbars-inline-precompile';
import { defer } from 'rsvp';
import { next, run } from '@ember/runloop';
import setupNoDeprecations from '../../helpers/setup-no-deprecations';
import RSVP from 'rsvp';
import a11yAudit from 'ember-a11y-testing/test-support/audit'
/* global Ember */
const nextRunloop = function() {
return new Promise((resolve) => {
next(() => {
resolve();
});
});
};
module('Integration | Component | bs-form', function(hooks) {
setupRenderingTest(hooks);
setupNoDeprecations(hooks);
hooks.beforeEach(function() {
this.actions = {};
this.send = (actionName, ...args) => this.actions[actionName].apply(this, args);
});
testBS3('form has correct CSS class', async function(assert) {
let classSpec = {
vertical: 'form',
horizontal: 'form-horizontal',
inline: 'form-inline'
};
for (let layout in classSpec) {
this.set('formLayout', layout);
await render(hbs`{{#bs-form formLayout=formLayout}}Test{{/bs-form}}`);
assert.dom('form').hasClass(classSpec[layout], `form has expected class for ${layout}`);
}
});
testBS4('form has correct markup', async function(assert) {
let classSpec = {
vertical: ['form', false],
horizontal: ['form-horizontal', false],
inline: ['form-inline', true]
};
for (let layout in classSpec) {
this.set('formLayout', layout);
await render(hbs`{{#bs-form formLayout=formLayout}}Test{{/bs-form}}`);
let expectation = classSpec[layout];
assert.equal(this.element.querySelector('form').classList.contains(expectation[0]), expectation[1], `form has expected markup for ${layout}`);
}
});
test('it yields form element component', async function(assert) {
await render(hbs`{{#bs-form as |form|}}{{form.element}}{{/bs-form}}`);
assert.dom('.form-group').exists({ count: 1 }, 'form has element');
});
test('Submitting the form calls onBeforeSubmit and onSubmit action', async function(assert) {
let submit = this.spy();
let before = this.spy();
let invalid = this.spy();
let model = {};
this.set('model', model);
this.actions.before = before;
this.actions.submit = submit;
this.actions.invalid = invalid;
await render(
hbs`{{#bs-form model=model onBefore=(action "before") onSubmit=(action "submit") onInvalid=(action "invalid")}}Test{{/bs-form}}`
);
await triggerEvent('form', 'submit');
assert.ok(before.calledWith(model), 'onBefore action has been called with model as parameter');
assert.ok(submit.calledWith(model), 'onSubmit action has been called with model as parameter');
assert.notOk(invalid.called, 'onInvalid action has not been called');
});
test('Clicking a submit button submits the form', async function(assert) {
let submit = this.spy();
this.actions.submit = submit;
await render(
hbs`{{#bs-form onSubmit=(action "submit")}}{{#bs-button buttonType="submit"}}Submit{{/bs-button}}{{/bs-form}}`
);
await click('button');
assert.ok(submit.calledOnce, 'onSubmit action has been called');
assert.deprecations(1);
});
test('Submit event bubbles', async function(assert) {
let TestComponent = Component.extend({
submit() {
assert.step('bubbles');
}
});
this.owner.register('component:test-component', TestComponent);
await render(hbs`
{{#test-component}}
{{#bs-form}}
<button type="submit">submit</button>
{{/bs-form}}
{{/test-component}}
`);
await click('button');
assert.verifySteps(['bubbles']);
});
test('Submitting the form with valid validation calls onBeforeSubmit and onSubmit action', async function(assert) {
let submit = this.spy();
let before = this.spy();
let invalid = this.spy();
let model = {};
this.set('model', model);
this.actions.before = before;
this.actions.submit = submit;
this.actions.invalid = invalid;
this.set('validateStub', function() {
return resolve('SUCCESS');
});
await render(
hbs`{{#bs-form model=model hasValidator=true validate=validateStub onBefore=(action "before") onSubmit=(action "submit") onInvalid=(action "invalid") as |form|}}Test{{/bs-form}}`
);
await triggerEvent('form', 'submit');
assert.ok(before.calledWith(model), 'onBefore action has been called with model as parameter');
assert.ok(submit.calledWith(model, 'SUCCESS'), 'onSubmit action has been called with model and validation result as parameter');
assert.notOk(invalid.called, 'onInvalid action has not been called');
});
test('Submitting the form with invalid validation calls onBeforeSubmit and onInvalid action', async function(assert) {
let submit = this.spy();
let before = this.spy();
let invalid = this.spy();
let rejectsWith = new Error();
let model = {};
this.set('model', model);
this.actions.before = before;
this.actions.submit = submit;
this.actions.invalid = invalid;
this.set('validateStub', this.fake.rejects(rejectsWith));
await render(
hbs`{{#bs-form model=model hasValidator=true validate=validateStub onBefore=(action "before") onSubmit=(action "submit") onInvalid=(action "invalid") as |form|}}Test{{/bs-form}}`
);
await triggerEvent('form', 'submit');
assert.ok(before.calledWith(model), 'onBefore action has been called with model as parameter');
assert.ok(invalid.calledWith(model, rejectsWith), 'onInvalid action has been called with model and validation result');
assert.notOk(submit.called, 'onSubmit action has not been called');
});
test('Submitting the form with invalid validation shows validation errors', async function(assert) {
let model = {};
this.set('model', model);
this.set('errors', A(['There is an error']));
this.set('validateStub', this.fake.rejects());
await render(
hbs`{{#bs-form model=model hasValidator=true validate=validateStub as |form|}}{{form.element hasValidator=true errors=errors}}{{/bs-form}}`
);
assert.dom(formFeedbackElement()).hasNoClass(
validationErrorClass(),
'validation errors aren\'t shown before user interaction'
);
await triggerEvent('form', 'submit');
assert.dom(formFeedbackElement()).hasClass(
validationErrorClass(),
'validation errors are shown after form submission'
);
assert.dom(`.${formFeedbackClass()}`).hasText('There is an error');
});
test('Submitting the form with invalid validation shows validation errors only after onInvalid promise resolves', async function(assert) {
let model = {};
this.set('model', model);
this.set('errors', A(['There is an error']));
this.set('validateStub', this.fake.rejects());
let deferredInvalidAction = defer();
this.set('invalid', () => deferredInvalidAction.promise);
await render(
hbs`{{#bs-form model=model hasValidator=true validate=validateStub onInvalid=this.invalid as |form|}}{{form.element hasValidator=true errors=errors}}{{/bs-form}}`
);
await triggerEvent('form', 'submit');
assert.dom(formFeedbackElement()).hasNoClass(
validationErrorClass(),
'validation errors aren\'t shown before onInvalid is settled'
);
deferredInvalidAction.resolve();
await settled();
assert.dom(formFeedbackElement()).hasClass(
validationErrorClass(),
'validation errors are shown after onInvalid is settled'
);
assert.dom(`.${formFeedbackClass()}`).hasText('There is an error');
});
test('it does not catch errors thrown by onSubmit action', async function(assert) {
let onErrorStub = this.stub();
let expectedError = new Error();
this.set('submitAction', this.fake.rejects(expectedError));
Ember.onerror = onErrorStub;
await render(hbs`
{{#bs-form onSubmit=submitAction}}
<button type="submit">submit</button>
{{/bs-form}}
`);
await click('button');
assert.ok(onErrorStub.calledOnceWith(expectedError));
});
test('form with validation has novalidate attribute', async function(assert) {
let model = {};
this.set('model', model);
await render(
hbs`{{#bs-form model=model hasValidator=true as |form|}}Test{{/bs-form}}`
);
assert.dom('form').hasAttribute('novalidate');
});
test('form with validation allows overriding novalidate attribute', async function(assert) {
let model = {};
this.set('model', model);
await render(
hbs`{{#bs-form model=model hasValidator=true novalidate=false as |form|}}Test{{/bs-form}}`
);
assert.dom('form').doesNotHaveAttribute('novalidate');
assert.deprecationsInclude(`Argument novalidate of <BsForm> component is deprecated.`);
});
testRequiringFocus('Submitting a form continues to show validations', async function(assert) {
let model = {};
this.set('model', model);
this.set('errors', A([]));
this.set('validateStub', () => this.get('errors.length') > 0 ? reject() : resolve());
let deferredSubmitAction = defer();
this.set('submitAction', () => {
return deferredSubmitAction.promise;
});
await render(
hbs`
{{#bs-form model=model onSubmit=submitAction hasValidator=true validate=validateStub as |form|}}
{{form.element property="dummy" hasValidator=true errors=errors}}
{{/bs-form}}`
);
assert.dom(formFeedbackElement()).hasNoClass(
validationErrorClass(),
'validation errors aren\'t shown before user interaction'
);
await focus('input');
await blur('input');
await triggerEvent('form', 'submit');
assert.dom(formFeedbackElement()).hasClass(
validationSuccessClass(),
'validation succcess is shown when form signals to show all validations'
);
// simulate validation errors being added while a submission is ongoing
run(() => this.get('errors').pushObject('There is an error'));
await settled();
assert.dom(formFeedbackElement()).hasClass(
validationErrorClass(),
'validation errors are shown while submitting'
);
deferredSubmitAction.resolve();
await settled();
assert.dom(formFeedbackElement()).hasClass(
validationErrorClass(),
'validation errors are shown after submitting'
);
});
testRequiringFocus(
'Submitting a hideValidationsOnSubmit form with an async onSubmit does not show validation errors when submitting',
async function(assert) {
let model = {};
this.set('model', model);
this.set('errors', A([]));
this.set('validateStub', () => this.get('errors.length') > 0 ? reject() : resolve());
let deferredSubmitAction = defer();
this.set('submitAction', () => {
return deferredSubmitAction.promise;
});
await render(
hbs`
{{#bs-form hideValidationsOnSubmit=true model=model onSubmit=submitAction hasValidator=true validate=validateStub as |form|}}
{{form.element property="dummy" hasValidator=true errors=errors}}
{{/bs-form}}`
);
assert.dom(formFeedbackElement()).hasNoClass(
validationErrorClass(),
'validation errors aren\'t shown before user interaction'
);
await focus('input');
await blur('input');
await triggerEvent('form', 'submit');
// simulate validation errors being added while a submission is ongoing
run(() => this.get('errors').pushObject('There is an error'));
await settled();
assert.dom(formFeedbackElement()).hasNoClass(
validationErrorClass(),
'validation errors aren\'t shown while submitting'
);
deferredSubmitAction.resolve();
await settled();
assert.dom(formFeedbackElement()).hasNoClass(
validationErrorClass(),
'validation errors aren\'t shown after submitting'
);
await focus('input');
await blur('input');
// form element has been changed, and has errors now, so validations must show up
assert.dom(formFeedbackElement()).hasClass(
validationErrorClass(),
'validation errors are shown after form submission'
);
assert.dom(`.${formFeedbackClass()}`).hasText('There is an error');
});
testRequiringFocus(
'Submitting a hideValidationsOnSubmit form does not show validation errors when submitting',
async function(assert) {
let model = {};
this.set('model', model);
this.set('errors', A([]));
this.set('validateStub', () => this.get('errors.length') > 0 ? reject() : resolve());
this.set('submitAction', () => {
});
await render(
hbs`
{{#bs-form hideValidationsOnSubmit=true model=model onSubmit=submitAction hasValidator=true validate=validateStub as |form|}}
{{form.element property="dummy" hasValidator=true errors=errors}}
{{/bs-form}}`
);
assert.dom(formFeedbackElement()).hasNoClass(
validationErrorClass(),
'validation errors aren\'t shown before user interaction'
);
await focus('input');
await blur('input');
await triggerEvent('form', 'submit');
// simulate validation errors being added while a submission is ongoing
run(() => this.get('errors').pushObject('There is an error'));
await settled();
assert.dom(formFeedbackElement()).hasNoClass(
validationErrorClass(),
'validation errors aren\'t shown after submitting'
);
await focus('input');
await blur('input');
// form element has been changed, and has errors now, so validations must show up
assert.dom(formFeedbackElement()).hasClass(
validationErrorClass(),
'validation errors are shown after form submission'
);
assert.dom(`.${formFeedbackClass()}`).hasText('There is an error');
});
test('it supports hash helper as model', async function(assert) {
this.set('submitAction', function(model) {
assert.step('submit');
assert.equal(model.name, 'Moritz');
});
await render(hbs`
<BsForm @model={{hash name="Max"}} @onSubmit={{this.submitAction}} as |form|>
<form.element @property="name" />
</BsForm>
`);
await fillIn('input', 'Moritz');
await triggerEvent('form', 'submit');
assert.verifySteps(['submit']);
});
test('it yields submit action', async function(assert) {
let submit = this.spy();
this.actions.submit = submit;
await render(hbs`
{{#bs-form onSubmit=(action "submit") as |form|}}
<a role="button" onclick={{action form.submit}}>submit</a>
{{/bs-form}}
`);
await click('a');
assert.ok(submit.calledOnce, 'onSubmit action has been called');
});
test('yielded submit action returns a promise', async function(assert) {
let TestComponent = Component.extend({
tagName: 'button',
click() {
let ret = this.get('onClick')();
assert.ok(ret instanceof RSVP.Promise);
}
});
this.owner.register('component:test-component', TestComponent);
await render(hbs`
{{#bs-form as |form|}}
{{test-component onClick=form.submit}}
{{/bs-form}}
`);
await click('button');
});
test('yielded submit action resolves for expected scenarios', async function(assert) {
let scenarios = [
{ onSubmit() {} },
{ onSubmit: this.fake.resolves() },
{ onSubmit() {}, validate: this.fake.resolves() },
{ onSubmit: this.fake.resolves(), validate: this.fake.resolves() },
];
let TestComponent = Component.extend({
tagName: 'button',
async click() {
try {
let ret = await this.get('onClick')();
assert.ok(true, 'resolves');
assert.strictEqual(ret, undefined, 'resolves with undefined');
} catch(err) {
assert.ok(false, err);
}
}
});
this.owner.register('component:test-component', TestComponent);
assert.expect(scenarios.length * 2);
for (let i = 0; i < scenarios.length; i++) {
this.setProperties(scenarios[i]);
await render(hbs`
{{#bs-form onSubmit=onSubmit validate=validate as |form|}}
{{test-component onClick=form.submit}}
{{/bs-form}}
`);
await click('button');
}
});
test('yielded submit action rejects for expected scenarios', async function(assert) {
let scenarios = [
{ validate: this.fake.rejects('rejected value') },
{ onSubmit: this.fake.rejects('rejected value') },
];
let TestComponent = Component.extend({
tagName: 'button',
click() {
assert.rejects(
this.get('onSubmit')(),
'rejected value'
);
}
});
this.owner.register('component:test-component', TestComponent);
assert.expect(scenarios.length);
for (let i = 0; i < scenarios.length; i++) {
this.setProperties(scenarios[i]);
await render(hbs`
{{#bs-form onSubmit=onSubmit validate=validate as |form|}}
{{test-component onSubmit=form.submit}}
{{/bs-form}}
`);
await click('button');
}
});
test('Yields #isSubmitting', async function(assert) {
let deferredSubmitAction = defer();
this.set('submitAction', () => {
return deferredSubmitAction.promise;
});
await this.render(hbs`{{#bs-form onSubmit=submitAction as |form|}}
<div class='state {{if form.isSubmitting 'is-submitting'}}'></div>
{{/bs-form}}`);
assert.dom('form .state').doesNotHaveClass('is-submitting');
triggerEvent('form', 'submit');
await waitFor('form .state.is-submitting');
deferredSubmitAction.resolve();
await settled();
assert.dom('form .state').doesNotHaveClass('is-submitting');
});
test('Yielded #isSubmitting is never true if neither validate nor onSubmit returns Promise', async function(assert) {
this.set('submitAction', () => {});
this.set('validate', () => {});
this.set('hasValidator', true);
await this.render(hbs`{{#bs-form onSubmit=submitAction validate=validate hasValidator=hasValidator as |form|}}
<div class='state {{if form.isSubmitting 'is-submitting'}}'></div>
{{/bs-form}}`);
assert.dom('form .state').doesNotHaveClass('is-submitting');
triggerEvent('form', 'submit');
await nextRunloop();
assert.dom('form .state').doesNotHaveClass('is-submitting');
});
test('Yielded #isSubmitting is true as long as Promise returned by onSubmit is pending', async function(assert) {
let deferredSubmitAction = defer();
this.set('submitAction', () => {
return deferredSubmitAction.promise;
});
await this.render(hbs`{{#bs-form onSubmit=submitAction as |form|}}
<div class='state {{if form.isSubmitting 'is-submitting'}}'></div>
{{/bs-form}}`);
assert.dom('form .state').doesNotHaveClass('is-submitting');
triggerEvent('form', 'submit');
await waitFor('form .state.is-submitting');
deferredSubmitAction.resolve();
await settled();
assert.dom('form .state').doesNotHaveClass('is-submitting');
});
test('Yielded #isSubmitting is true as long as Promise returned by onInvalid is pending', async function(assert) {
let deferredSubmitAction = defer();
this.set('submitAction', () => {
return deferredSubmitAction.promise;
});
this.set('validate', function() {
return reject();
});
await this.render(hbs`{{#bs-form onInvalid=submitAction hasValidator=true validate=validate as |form|}}
<div class='state {{if form.isSubmitting 'is-submitting'}}'></div>
{{/bs-form}}`);
assert.dom('form .state').doesNotHaveClass('is-submitting');
triggerEvent('form', 'submit');
await waitFor('form .state.is-submitting');
deferredSubmitAction.resolve();
await settled();
assert.dom('form .state').doesNotHaveClass('is-submitting');
});
test('Yielded #isSubmitting is true as long as Promise returned by validate is pending', async function(assert) {
let deferredValidateAction = defer();
this.set('hasValidator', true);
this.set('validateAction', () => {
return deferredValidateAction.promise;
});
await this.render(hbs`{{#bs-form hasValidator=hasValidator validate=validateAction as |form|}}
<div class='state {{if form.isSubmitting 'is-submitting'}}'></div>
{{/bs-form}}`);
assert.dom('form .state').doesNotHaveClass('is-submitting');
triggerEvent('form', 'submit');
await waitFor('form .state.is-submitting');
deferredValidateAction.resolve();
await settled();
assert.dom('form .state').doesNotHaveClass('is-submitting');
});
test('Yielded #isSubmitting is true as long as Promises returned by onSubmit and validate are pending', async function(assert) {
let deferredSubmitAction = defer();
let deferredValidateAction = defer();
this.set('submitAction', () => {
return deferredSubmitAction.promise;
});
this.set('validateAction', () => {
return deferredValidateAction.promise;
});
await this.render(hbs`{{#bs-form onSubmit=submitAction validate=validateAction hasValidator=true as |form|}}
<div class='state {{if form.isSubmitting 'is-submitting'}}'></div>
{{/bs-form}}`);
assert.dom('form .state').doesNotHaveClass('is-submitting');
triggerEvent('form', 'submit');
await waitFor('form .state.is-submitting');
deferredValidateAction.resolve();
await waitFor('form .state.is-submitting');
deferredSubmitAction.resolve();
await settled();
assert.dom('form .state').doesNotHaveClass('is-submitting');
});
test('Yielded #isSubmitting stays true until all pending submit have been fulfilled', async function(assert) {
let deferredSubmitActions = [];
this.set('submitAction', () => {
let deferred = defer();
deferredSubmitActions.push(deferred);
return deferred.promise;
});
await this.render(hbs`{{#bs-form onSubmit=submitAction preventConcurrency=false as |form|}}
<div class='state {{if form.isSubmitting 'is-submitting'}}'></div>
{{/bs-form}}`);
assert.dom('form .state').doesNotHaveClass('is-submitting');
triggerEvent('form', 'submit');
await waitFor('form .state.is-submitting');
triggerEvent('form', 'submit');
await waitUntil(() => {
// assumption: submit action has been fired twice
return deferredSubmitActions.length === 2;
});
deferredSubmitActions[0].resolve();
await waitFor('form .state.is-submitting');
deferredSubmitActions[1].resolve();
await settled();
assert.dom('form .state').doesNotHaveClass('is-submitting');
});
test('Yielded #isSubmitted is true if onSubmit resolves', async function(assert) {
this.actions.submit = this.fake.resolves();
await render(hbs`{{#bs-form onSubmit=(action "submit") as |form|}}
<button type="submit" class={{if form.isSubmitted "is-submitted"}}>submit</button>
{{/bs-form}}`);
await triggerEvent('form', 'submit');
assert.dom('form button').hasClass('is-submitted');
});
test('Yielded #isSubmitted is true if onSubmit is undefined', async function(assert) {
await render(hbs`{{#bs-form as |form|}}
<button type="submit" class={{if form.isSubmitted "is-submitted"}}>submit</button>
{{/bs-form}}`);
await triggerEvent('form', 'submit');
assert.dom('form button').hasClass('is-submitted');
});
test('Yielded #isSubmitted is true if validation passes', async function(assert) {
this.actions.validate = this.fake.resolves();
await render(hbs`{{#bs-form validate=(action "validate") hasValidator=true as |form|}}
<button type="submit" class={{if form.isSubmitted "is-submitted"}}>submit</button>
{{/bs-form}}`);
await triggerEvent('form', 'submit');
assert.dom('form button').hasClass('is-submitted');
});
test('A change to a form elements resets yielded #isSubmitted', async function(assert) {
this.actions.submit = this.fake.resolves();
await render(hbs`{{#bs-form onSubmit=(action "submit") model=(hash) as |form|}}
{{form.element property="foo"}}
<button type="submit" class={{if form.isSubmitted "is-submitted"}}>submit</button>
{{/bs-form}}`);
await triggerEvent('form', 'submit');
assert.dom('form button').hasClass('is-submitted', 'assumption');
await fillIn('input', 'bar');
assert.dom('form button').doesNotHaveClass('is-submitted');
});
test('Yielded #isRejected is true if onSubmit action rejects', async function(assert) {
// tests fail by default on unhandled errors
let expectedError = new Error();
Ember.onerror = (error) => {
if (error !== expectedError) {
throw error;
}
};
this.actions.submit = this.fake.rejects(expectedError);
await render(hbs`{{#bs-form onSubmit=(action "submit") as |form|}}
<button type="submit" class={{if form.isRejected "is-rejected"}}>submit</button>
{{/bs-form}}`);
await triggerEvent('form', 'submit');
assert.dom('form button').hasClass('is-rejected');
});
test('Yielded #isRejected is true if validation fails', async function(assert) {
this.actions.validate = this.fake.rejects();
await render(hbs`{{#bs-form validate=(action "validate") hasValidator=true as |form|}}
<button type="submit" class={{if form.isRejected "is-rejected"}}>submit</button>
{{/bs-form}}`);
await triggerEvent('form', 'submit');
assert.dom('form button').hasClass('is-rejected');
});
test('A change to a form elements resets yielded #isRejected', async function(assert) {
// tests fail by default on unhandled errors
let expectedError = new Error();
Ember.onerror = (error) => {
if (error !== expectedError) {
throw error;
}
};
this.actions.submit = this.fake.rejects(expectedError);
await render(hbs`{{#bs-form onSubmit=(action "submit") model=(hash) as |form|}}
{{form.element property="foo"}}
<button type="submit" class={{if form.isRejected "is-rejected"}}>submit</button>
{{/bs-form}}`);
await triggerEvent('form', 'submit');
assert.dom('form button').hasClass('is-rejected', 'assumption');
await fillIn('input', 'bar');
assert.dom('form button').doesNotHaveClass('is-rejected');
});
test('Triggering resetSubmissionState resets submission state of form', async function(assert) {
this.actions.submit = this.fake.resolves();
await render(hbs`{{#bs-form onSubmit=(action "submit") model=(hash) as |form|}}
<input onchange={{form.resetSubmissionState}}>
<button type="submit" class={{if form.isSubmitted "is-submitted"}}>submit</button>
{{/bs-form}}`);
await triggerEvent('form', 'submit');
assert.dom('form button').hasClass('is-submitted', 'assumption');
await fillIn('input', 'bar');
assert.dom('form button').doesNotHaveClass('is-submitted');
});
test('Adds default onChange action to form elements that updates model\'s property', async function(assert) {
let model = EmberObject.create({
name: 'foo'
});
this.set('model', model);
await render(hbs`{{#bs-form model=model as |form|}}
{{form.element property="name"}}
{{/bs-form}}`);
assert.dom('input').hasValue('foo', 'input has model property value');
await fillIn('input', 'bar');
await triggerEvent('input', 'input');
assert.equal(model.get('name'), 'bar', 'model property was updated');
});
testRequiringFocus('Pressing enter on a form with submitOnEnter submits the form', async function(assert) {
let submit = this.spy();
this.actions.submit = submit;
await render(hbs`{{#bs-form onSubmit=(action "submit") submitOnEnter=true as |form|}}{{/bs-form}}`);
await triggerKeyEvent('form', 'keypress', 13);
assert.ok(submit.calledOnce, 'onSubmit action has been called');
});
test('prevents submission to be fired concurrently', async function(assert) {
let deferredSubmitAction = defer();
let submitActionHasBeenExecuted = false;
this.set('submitAction', () => {
submitActionHasBeenExecuted = true;
return deferredSubmitAction.promise;
});
this.set('beforeAction', () => {});
this.set('validate', () => { return resolve(); });
await render(hbs`
{{#bs-form onSubmit=submitAction onBefore=beforeAction validate=validate hasValidator=true}}{{/bs-form}}
`);
triggerEvent('form', 'submit');
await waitUntil(() => submitActionHasBeenExecuted);
this.set('submitAction', () => {
assert.ok(false, 'onSubmit action is not executed concurrently');
});
this.set('beforeAction', () => {
assert.ok(false, 'onBefore action is not executed if concurrent submission has been dropped');
});
this.set('validate', () => {
assert.ok(false, 'validate is not executed if concurrent submission has been dropped');
});
await triggerEvent('form', 'submit');
deferredSubmitAction.resolve();
await settled();
this.set('submitAction', () => {
assert.step('onSubmit action');
});
this.set('beforeAction', () => {});
this.set('validate', () => { return resolve(); });
await triggerEvent('form', 'submit');
assert.verifySteps(['onSubmit action'], 'onSubmit action is fired again after pending submission is settled');
});
test('preventConcurrency=false allows submission to be fired concurrently', async function(assert) {
let deferredSubmitAction = defer();
let submitActionExecutionCounter = 0;
let beforeActionFake = this.fake();
let validateFake = this.fake();
this.set('submitAction', () => {
submitActionExecutionCounter++;
return deferredSubmitAction.promise;
});
this.set('beforeAction', beforeActionFake);
this.set('validate', validateFake);
await render(hbs`
{{#bs-form preventConcurrency=false onSubmit=submitAction onBefore=beforeAction validate=validate hasValidator=true}}
{{/bs-form}}
`);
await triggerEvent('form', 'submit');
assert.equal(submitActionExecutionCounter, 1);
await triggerEvent('form', 'submit');
assert.equal(submitActionExecutionCounter, 2);
assert.ok(beforeActionFake.calledTwice);
assert.ok(validateFake.calledTwice);
deferredSubmitAction.resolve();
});
test('supports novalidate attribute', async function(assert) {
await render(hbs`{{bs-form}}`);
assert.dom('form').doesNotHaveAttribute('novalidate');
await render(hbs`{{bs-form novalidate=true}}`);
assert.dom('form').hasAttribute('novalidate');
assert.deprecationsInclude(`Argument novalidate of <BsForm> component is deprecated.`);
});
test('disabled property propagates to all its elements', async function(assert) {
await render(
hbs`
{{#bs-form model=this disabled=true as |form|}}
{{form.element property="dummy"}}
{{/bs-form}}`
);
assert.dom('.form-group input').hasAttribute('disabled');
});
test('readOnly property propagates to all its elements', async function(assert) {
await render(
hbs`
{{#bs-form model=this readonly=true as |form|}}
{{form.element property="dummy"}}
{{/bs-form}}`
);
assert.dom('.form-group input').hasAttribute('readonly');
});
test('it passes accessibility checks', async function (assert) {
await render(
hbs`
{{#bs-form model=this as |form|}}
{{form.element property="dummy" label="Dummy"}}
{{/bs-form}}`
);
await a11yAudit();
assert.ok(true, 'A11y audit passed');
});
});
|
// mw {name:'', opt: {}, middleware: () => {}}
class MiddlewareChain {
constructor(mw) {
this.mw = mw
}
_indexOf(name) {
for (let index = 0; index < this.mw.length; index++) {
if(name === this.mw[index].name) {
return index
}
}
return -1
}
value() {
return this.mw
}
getMiddlewares() {
return this.mw.map(mw => mw.middleware(mw.opt))
}
add(mw, index) {
if(index !== undefined && index >= 0) {
this.mw.splice(index, 0, mw)
} else {
this.mw.push(mw)
}
}
before(name, mw) {
let index = this._indexOf(name)
this.add(mw, index)
}
after(name, mw) {
let index = this._indexOf(name)
this.add(mw, index + 1)
}
set(name, cb) {
let index = this._indexOf(name)
let mw = this.mw[index]
if(typeof cb === 'function') {
this.mw[index] = cb(mw) || mw
} else {
this.mw[index] = cb
}
}
setOpt(name, opt) {
this.set(name, (mw) => {
if(typeof opt === 'function') {
mw.opt = opt(mw.opt) || opt
} else {
mw.opt = opt
}
return mw
})
}
}
module.exports = MiddlewareChain
|
import React from "react";
import Logo from "./img/índice.jpg";
import MisionTic from "./img/logoMisionTic2022UdeA.png";
function FooterComponent() {
return (
<footer>
<div class="container-fluid">
<div class="row">
<div class="col">
<img class='imagenEquipo' src={Logo} alt="logo Ada Team"/>
</div>
<div class="col">
<div>Ada-Dev-Team</div>
<div>MisionTic 2022 UdeA</div>
<div>2021</div>
</div>
<div class="col">
<img class='imagenMintic2022' src={MisionTic} alt="logoMisionTic2022UdeA"/>
</div>
</div>
</div>
</footer>
);
}
export default FooterComponent; |
var dbparse = require('./dbparser');
/**
* Testing
**/
// removeUser('Patrick');
var patrick = {
username: "Patrick",
password: "Test",
location: "Oakland",
email: "Pavtran2@gmail.com"
}
// console.log(patrick);
// addUser(patrick);
var talents = {
'Piano': 5,
'Guitar': 7,
'Trumpet': 5
}
// User.find(function(err, results){
// console.log(results);
// });
//
// addTalents('Patrick', talents);
// removeUser({'username': 'Patrick'});
// (User.find(function(err, results){
// console.log(results);
// }));
// var request = new Request({
// requester: "Patrick",
// talents: {'Piano': 4},
// location: 'Oakland'
// })
// request.save(function(err){
// if(err) console.log(err);
// console.log('successful!');
// })
// Request.find(function(err, results){
// console.log(results);
// })
// getReqTalents('Fwewetlute', function(results){
// console.log("People who can play the Piano" + results);
// });
var requestOne;
// Request.findOne(function(err, results){
// requestOne = results;
// console.log(requestOne);
// parseReq(requestOne, function(results){
// console.log("People who meet the request criteria" + results);
// })
// });
// console.log(requestOne);
// parseReq(requestOne, function(results){
// console.log("People who meet the request criteria" + results);
// })
dbparse.getRequests(function(result){
console.log(result);
}) |
const axios = require('axios');
const fs = require('fs');
(async () => {
const url = 'https://iam.cloud.ibm.com/identity/token';
const params = new URLSearchParams();
params.append('grant_type', 'urn:ibm:params:oauth:grant-type:apikey');
params.append('apikey', process.env.OW_IAM_NAMESPACE_API_KEY);
const res = await axios.post(url, params);
const data = `${process.env.WSKPROPS}\nAPIGW_ACCESS_TOKEN=${res.data['access_token']}`;
fs.writeFile('.wskprops', data, err => {
if (err) throw err;
console.log('正常に書き込みが完了しました');
});
})();
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.