text
stringlengths 7
3.69M
|
|---|
const express = require('express');
const app = express();
const static = express.static(__dirname + '/public');
const configRoutes = require('./routes');
const exphbs = require('express-handlebars');
const session = require('express-session');
const handleBars = exphbs.create({
defaultLayout: 'main',
helpers: {
asJSON: (obj, spacing) => {
if (typeof spacing === 'number')
return new Handlebars.SafeString(
JSON.stringify(obj, null, spacing)
);
return new Handlebars.SafeString(JSON.stringify(obj));
},
},
});
app.use('/public', static);
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
session({
name: 'AuthCookie',
secret: 'the secret string!',
resave: false,
saveUninitialized: true,
})
);
app.engine('handlebars', handleBars.engine);
app.set('view engine', 'handlebars');
app.use((req, res, next) => {
const auth = req.session.user ? '' : 'Non-';
console.log(
`[${new Date().toUTCString()}]: ${req.method} ${
req.originalUrl
} (${auth}Authenticated User)`
);
next();
});
app.use('/private', (req, res, next) => {
if (!req.session.user) {
res.status(403).render('unauthorized', { title: 'Not logged in!' });
return;
}
next();
});
configRoutes(app);
app.listen(3000, () => {
console.log('server running on port 3000');
});
|
describe("Profit Loss Spec", function() {
var profitLoss, request, onSuccess, $el;
beforeEach(function() {
// Append template to DOM
$el = document.getElementsByTagName('body')[0].innerHTML += TestResponses.profitLossData.template;
// AJAX setup
jasmine.Ajax.install();
onSuccess = jasmine.createSpy('onSuccess');
profitLoss = Object.create(window.IG.ProfitLoss);
profitLoss.init('data/data.json', {
onSuccess: onSuccess
});
request = jasmine.Ajax.requests.mostRecent();
// Test AJAX
expect(request.url).toBe('data/data.json');
expect(request.method).toBe('GET');
});
describe("on success", function() {
beforeEach(function() {
request.respondWith(TestResponses.profitLossData.success);
});
it("calls onSuccess and returns an array of markets and stock picks", function() {
expect(onSuccess).toHaveBeenCalled();
var successData = profitLoss.data;
expect(successData.markets.length).toEqual(3);
expect(successData.picks.length).toEqual(4);
});
it('should generate a list of stock picks', function(){
var $rows = document.getElementsByClassName('profit-loss--stock_row');
expect($rows.length).toEqual(4);
});
it('should calculate profit / loss per stock', function(){
var stockProfitLosses = [200, 150, 600, -300],
rows = profitLoss.data.picks;
for(var i = 0; i < rows.length; i++){
expect(profitLoss.calcProfitLoss(rows[i].open_level, rows[i].level, rows[i].qty)).toBe(stockProfitLosses[i]);
}
});
it('should calculate a book cost', function(){
var stockBookCosts = [900, 750, 900, 750],
rows = profitLoss.data.picks;
for(var i = 0; i < rows.length; i++){
expect(profitLoss.calcBookCost(rows[i].open_level, rows[i].qty)).toBe(stockBookCosts[i]);
}
});
it('should calculate a total profit / loss', function(){
var total = document.getElementsByClassName('profit-loss--total')[0].innerHTML.substring(1);
expect(parseInt(total, 10)).toBe(650);
});
});
afterEach(function() {
// Remove template
var $profitLossTmpl = document.getElementById('profit-loss');
if($profitLossTmpl){
$profitLossTmpl.parentNode.removeChild($profitLossTmpl);
}
// Uninstall ajax helper
jasmine.Ajax.uninstall();
});
});
|
import './ReactMemo.css';
import photoChuk from './React_chuk.png'
export default function ReactMemo () {
return <>
<h2>React.memo и React Хуки</h2>
<div className="componets-container">
<div>
<p className="reactMemo_text">
Если ваш компонент всегда рендерит одно и то же при неменяющихся пропсах,
вы можете обернуть его в вызов React.memo для повышения производительности
в некоторых случаях, мемоизируя тем самым результат.
Это значит, что React будет использовать результат последнего рендера,
избегая повторного рендеринга.
</p>
<p>Этот метод предназначен только для оптимизации производительности.</p>
<h2>export default React.memo(MyComponent)</h2>
</div>
<div>
<img src={photoChuk} alt="code" width="400" />
</div>
</div>
</>
}
|
;$(function(){
$("#topMenu .sysMenuList").width($(window).width()-410)
var resize = true;
// 显示隐藏的导航菜单
var includeOtherMenuItems = function(){
var hand = $('#showOtherMenuItem');
otherMenuBox = $("#otherMenuItems dl"),
menuBox = $("#topMenu .sysMenuList"),
num;
if( $("#sysMenuList dd").find("a").eq(0).css("font-size")=="16px"){
num = Math.floor( (menuBox.width()-120) / menuBox.find('dd:last').width())
}else if($("#sysMenuList dd").find("a").eq(0).css("font-size")=="14px"){
num = Math.floor( (menuBox.width()-160) / menuBox.find('dd:last').width())
}else if($("#sysMenuList dd").find("a").eq(0).css("font-size")=="12px"){
num = Math.floor( (menuBox.width()-210) / menuBox.find('dd:last').width())
}
if( num < menuBox.find('dd').length ){
otherMenuBox.empty().append(
menuBox.find('dd:gt('+(num-1)+')').clone()
)
hand.removeClass('lockout')
$(".showOtherMenuItem a").removeClass('noback');
return true;
}else{
//$(".showOtherMenuItem a").css("background","none");
$(".showOtherMenuItem a").addClass('noback');
hand.addClass('lockout')
return false;
}
}
// 计算布局高度
// 布局优化方案
function resetLayout(){
includeOtherMenuItems()
var mainPartHeight = document.documentElement.clientHeight-$(".ui-layout-north").outerHeight(true)-$(".ui-layout-south:visible").outerHeight(true);
$('#rdMap').height( mainPartHeight- $('#TaskWrap').height()- 55 );
if( document.documentElement.clientWidth < 1100 ){
$('#newsColumn').appendTo('#mainView .mainViewInner');
$('#newsColumn').css({'overflow':'auto'});
}else{
$('#newsColumn').prependTo('#mainPart');
$('#newsColumn').css({'overflow':'visible'});
}
}
var timer;
if($('#product-menu').is(':visible')){
resetLayout()
}
$(window).resize(function(){
$("#topMenu .sysMenuList").width($(window).width()-410)
resize =true;
clearTimeout(timer);
timer=setTimeout(function(){ resetLayout()},200);
})
function pulldownFun(option){
var dfop={
onHover:"on"
}
var op=this.op=$.extend(dfop,option||{});
var on = $(op.on),
dlg = $(op.dialog),
onHov=op.onHover,
mouseover_tid = [],
i = 0;
on.hover(
function(){
if(op.offset){
var offset=on.offset();
dlg.css({'top':offset.top+(+op.offset),'left':offset.left-(+op.offset-13)})
}
if(resize && op.resize){
// 执行填充方法 如果没有隐藏的项 那么结束
var theFun = includeOtherMenuItems()
if(!theFun){return false;}
}
dlg.slideDown(150)
clearTimeout(mouseover_tid[i]);
$(op.on).addClass(onHov);
}, function(){
mouseover_tid[i] = setTimeout(function(){
dlg.slideUp(150)
},200)
$(op.on).removeClass(onHov);
}
)
dlg.hover(
function(){
clearTimeout(mouseover_tid[i]);
$(op.on).addClass(onHov);
}, function(){
mouseover_tid[i] = setTimeout(function(){
dlg.slideUp(150)
},200)
$(op.on).removeClass(onHov);
}
)
}
new pulldownFun({
resize:true,
on:"#showOtherMenuItem",
dialog:"#otherMenuItems",
onHover:"onHover"
});
//scroll
var itemWidth=$(".scrollpos .normal").width()+10;
var sumWidth=itemWidth*$(".scrollpos .normal").length;
var temp=$(".scrollpos > span").clone();
temp.appendTo(".scrollpos");
$(".scrollpos").width(sumWidth);
var i=0;
setInterval(play,50);
function play(){
$(".scrollpos").css("left",i)
i-=1;
if(Math.abs(parseInt($(".scrollpos").css("left")))>=sumWidth){
i=0;
}
}
})
|
import React, { Component } from 'react';
import './Footer.css';
class Footer extends Component{
render(){
return(
<div>
<div className='thisdiv'>The footer is here</div>
<ul>
<p>thing <a href='#'>a link </a></p><br/>
<p>thing <a href='#'>a link </a></p><br/>
<p>thing <a href='#'>a link </a></p><br/>
<p>thing <a href='#'>a link </a></p><br/>
<p>thing <a href='#'>a link </a></p><br/>
<p>thing <a href='#'>a link </a></p><br/>
</ul>
</div>
)
}
}
export default Footer;
|
'use strict';
window.renderStatistics = function (ctx, names, times) {
var drawBackground = function (x, y, width, height) {
ctx.beginPath();
ctx.moveTo(x, y);
var stepHorizontal = width / 7;
var stepVertical = height / 9;
var x1 = x;
var x2 = x;
for (var i = 0; i < 7; i++) {
x2 += stepHorizontal;
ctx.bezierCurveTo(x1, 0, x2, 0, x2, y);
x1 = x2;
}
var y1 = y;
var y2 = y;
for (i = 0; i < 9; i++) {
y2 += stepVertical;
ctx.bezierCurveTo(x2 + 10, y1, x2 + 10, y2, x2, y2);
y1 = y2;
}
x1 = x2;
for (i = 0; i < 7; i++) {
x2 -= stepHorizontal;
ctx.bezierCurveTo(x1, y2 + 10, x2, y2 + 10, x2, y2);
x1 = x2;
}
y1 = y2;
for (i = 0; i < 9; i++) {
y2 -= stepVertical;
ctx.bezierCurveTo(x2 - 10, y1, x2 - 10, y2, x2, y2);
y1 = y2;
}
ctx.closePath();
ctx.stroke();
ctx.fill();
};
var maxTime = times.reduce(function (max, element) {
return max < element ? element : max;
});
var histogramHeight = 150;
var step = histogramHeight / (maxTime - 0);
var barWidth = 40;
var indent = 50;
var lineHeight = 18;
var initialX = 120;
var initialY = 100;
// var texts = ['Ура вы победили!', 'Список результатов:'];
var writeText = function (x, y, arr) {
for (var i = 0; i < arr.length; i++) {
ctx.fillText(arr[i], x, y);
y += 20;
}
};
var getColor = function () {
var opacity = Math.random() * (1 - 0.1) + 0.1;
return 'rgba(0, 0, 255, ' + opacity.toFixed(1) + ')';
};
var getRectColor = function (name) {
return (name === 'Вы') ? 'rgba(255, 0, 0, 1)' : getColor();
};
var drawColumn = function (x, y, width, height, name, time) {
ctx.fillStyle = getRectColor(name);
ctx.fillRect(x, y, width, height);
ctx.fillStyle = 'black';
ctx.fillText(Math.floor(time), x, y - lineHeight / 2);
ctx.fillText(name, x, y + height + lineHeight);
};
ctx.shadowOffsetX = 10;
ctx.shadowOffsetY = 10;
ctx.shadowColor = 'rgba(0, 0, 0, 0.7)';
ctx.strokeStyle = 'black';
ctx.fillStyle = 'white';
drawBackground(100, 10, 420, 270);
ctx.shadowOffsetX = 0;
ctx.shadowOffsetY = 0;
ctx.shadowColor = 'transparent';
ctx.fillStyle = 'black';
ctx.font = '16px PT Mono';
writeText(120, 40, ['Ура вы победили!', 'Список результатов:']);
for (var i = 0; i < times.length; i++) {
var x = initialX + (barWidth + indent) * i;
var y = initialY + (maxTime - times[i]) * step;
var height = times[i] * step;
drawColumn(x, y, barWidth, height, names[i], times[i]);
}
};
|
function allOpenAllClose()
{
FBTest.progress("All Close");
if (FW.Firebug.PanelActivation)
FW.Firebug.PanelActivation.toggleAll("off");
else
FW.Firebug.Activation.toggleAll("off");
window.allOpenAllCloseURL = FBTest.getHTTPURLBase()+"firebug/OpenFirebugOnThisPage.html";
FBTest.openNewTab(allOpenAllCloseURL, function openFirebug(win)
{
FBTest.progress("opened tab for "+win.location);
var open = FW.Firebug.chrome.isOpen();
FBTest.ok(!open, "Firebug starts closed");
FBTest.progress("All Open");
if (FW.Firebug.PanelActivation)
FW.Firebug.PanelActivation.toggleAll("on");
else
FW.Firebug.Activation.toggleAll("on");
allOpened(); // allow UI to come up then check it
});
}
function allOpened()
{
var placement = FBTest.getFirebugPlacement();
FBTest.compare("inBrowser", placement, "Firebug now open in browser");
if (FBTest.FirebugWindow.Firebug.currentContext)
{
var contextName = FBTest.FirebugWindow.Firebug.currentContext.getName();
/*
var cL = contextName.length;
var aL = allOpenAllCloseURL.length;
FBTest.compare(aL+"", cL+"", "chromeWindow.Firebug.currentContext has same length"+contextName);
for (var i = 0; i < allOpenAllCloseURL.length; i++)
if ( allOpenAllCloseURL[i] != contextName[i] ) FBTest.progress("compare fails at "+i+" "+ allOpenAllCloseURL[i]);
*/
FBTest.compare(allOpenAllCloseURL+"", contextName+"", "Firebug.currentContext set to "+allOpenAllCloseURL);
}
else
FBTest.ok(false, "no Firebug.currentContext");
FBTest.openNewTab(basePath + "firebug/AlsoOpenFirebugOnThisPage.html", alsoOpened);
}
function alsoOpened(win)
{
FBTest.progress("Opened "+win.location);
var placement = FBTest.getFirebugPlacement();
FBTest.compare("inBrowser", placement, "Firebug opened because of all open");
FBTest.pressToggleFirebug(); // toggle to minimize
var placement = FBTest.getFirebugPlacement();
FBTest.compare("minimized", placement, "Firebug minimized");
var statusbarIcon = FW.top.document.getElementById('firebugStatus');
var toolTip = statusbarIcon.getAttribute("tooltiptext");
var number = /^(\d).*Firebugs/.exec(toolTip);
if (number)
FBTest.compare("2", number[1], "Should be 2 Firebugs now");
if (FW.Firebug.PanelActivation)
FW.Firebug.PanelActivation.toggleAll("off");
else
FW.Firebug.Activation.toggleAll("off");
var open = FW.Firebug.chrome.isOpen();
FBTest.ok(!open, "Firebug closed by all off");
var toolTip = statusbarIcon.getAttribute("tooltiptext");
var number = /^(\d).*Firebugs/.exec(toolTip);
FBTest.ok(!number, "Should be no Firebugs now");
if (FW.Firebug.PanelActivation)
FW.Firebug.PanelActivation.toggleAll("none");
else
FW.Firebug.Activation.toggleAll("none");
FBTest.testDone();
}
//------------------------------------------------------------------------
// Auto-run test
function runTest()
{
FBTest.sysout("allOpenAllClose.started");
if (FBTest.FirebugWindow)
FBTest.ok(true, "We have the Firebug Window: "+FBTest.FirebugWindow.location);
else
FBTest.ok(false, "No Firebug Window");
// Auto run sequence
allOpenAllClose();
}
|
"use strict";
/*global alert: true, ODSA, console */
(function ($) {
var av;
var rect;
function runit() {
av = new JSAV($(".avcontainer"));
rect = av.g.rect(0, 120, 245, 10);
av.displayInit();
rect.translate(50,50);
av.step();
rect.translate(-50,-50);
av.g.rect(40, 30, 5, 90);
av.g.rect(120, 30, 5, 90);
av.g.rect(200, 30, 5, 90);
av.g.rect(10, 110, 65, 10).css({"fill": "gray"});
av.g.rect(15, 100, 55, 10).css({"fill": "gray"});
av.g.rect(20, 90, 45, 10).css({"fill": "gray"});
av.g.rect(25, 80, 35, 10).css({"fill": "gray"});
av.g.rect(30, 70, 25, 10).css({"fill": "gray"});
av.g.rect(35, 60, 15, 10).css({"fill": "gray"});
av.g.rect(280, 120, 245, 10);
av.g.rect(320, 30, 5, 90);
av.g.rect(400, 30, 5, 90);
av.g.rect(480, 30, 5, 90);
av.g.rect(290, 110, 65, 10).css({"fill": "gray"});
av.g.rect(375, 110, 55, 10).css({"fill": "gray"});
av.g.rect(380, 100, 45, 10).css({"fill": "gray"});
av.g.rect(385, 90, 35, 10).css({"fill": "gray"});
av.g.rect(390, 80, 25, 10).css({"fill": "gray"});
av.g.rect(395, 70, 15, 10).css({"fill": "gray"});
av.label("1", {"top": "0px", "left": "39px"});
av.label("2", {"top": "0px", "left": "119px"});
av.label("3", {"top": "0px", "left": "199px"});
av.label("1", {"top": "0px", "left": "319px"});
av.label("2", {"top": "0px", "left": "399px"});
av.label("3", {"top": "0px", "left": "479px"});
av.label("(a)", {"top": "140px", "left": "113px"});
av.label("(b)", {"top": "140px", "left": "392px"});
av.recorded();
}
function about() {
var mystring = "Prim's Algorithm Visualization\nWritten by Mohammed Fawzy and Cliff Shaffer\nCreated as part of the OpenDSA hypertextbook project.\nFor more information, see http://opendsa.org.\nWritten during Spring, 2013\nLast update: March, 2013\nJSAV library version " + JSAV.version();
alert(mystring);
}
// Connect action callbacks to the HTML entities
$('#about').click(about);
$('#runit').click(runit);
//$('#help').click(help);
$('#reset').click(ODSA.AV.reset);
}(jQuery));
|
/**
* Created by A NIU on 15-1-4.
*/
//页数
var TOTAL_PAGE = 1,
MAX_PAGE = 0;
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i) ? 'android' : false;
},
iPhone: function() {
return navigator.userAgent.match(/iPhone/i) ? 'iphone' : false;
},
iPad: function() {
return navigator.userAgent.match(/iPad/i) ? 'ipad' : false;
},
any: function() {
return (isMobile.Android() || isMobile.iPad() || isMobile.iPhone());
}
};
$(document).ready(function() {
//ajax 全局
$.ajaxSetup({
timeout: 12000,
error: function(jqXHR, textStatus) {
var html = '';
if (jqXHR.status === 0){
html = 'error: ' + jqXHR.status + ' no connect';
}else if(jqXHR.status == 404) {
html = 'error: Requested page not found. [404]';
}else if (jqXHR.status == 500){
html = 'error: Internal Server Error [500]';
}else if (textStatus == 'timeout'){
html = 'Time out error.';
}else if (textStatus == 'abort'){
html = 'Ajax request aborted.';
}else{
html = 'error: ' + jqXHR.status;
}
$('.error span').html(html);
$('.error').fadeIn().delay(1200).fadeOut();
}
});
//键盘enter
$(document).on('keypress',function(e) {
if(e.keyCode == 13) {
toSearch();
return false;
}
});
//搜索功能
//搜索
$('.ui-search-b').on('click',function() {
window.location.href = 'search_skip.php';
});
$('.ui-search-a').on('click',function() {
window.location.href = 'search_skip.php';
});
//点击关键字搜索
$('.ui-search-recommend').on('click','a',function() {
var value = $(this).text();
if(value == "搜索排行榜"){
return true;
}
var $_searchResult = $('#searchResult');
$('.ui-search').children('input').val(value);
$('.ui-search-recommend').hide();
$('.ui-search-recommend ul').empty();
$('#corrected').find('ul').empty();
$_searchResult.find('ul').empty();
$_searchResult.find('.title').empty();
viewHasResultTitle(isMobile.any());
showSearchResult(value);
$_searchResult.fadeIn();
});
//搜索button
$('.searchDo').on('click',function() {
toSearch();
});
//加载更多
$('#searchResult').on('click','.loadMore',function() {
// console.log('loadmore');
if(TOTAL_PAGE < MAX_PAGE) {
++TOTAL_PAGE;
showSearchResult($('.ui-search').children('input').val(),TOTAL_PAGE);
}else {
$(this).find('a').text("已加载全部结果!");
}
});
});
//前台执行搜索
function toSearch() {
//init 页码
TOTAL_PAGE = 1;
MAX_PAGE = 0;
//判断空搜索 和非法搜索
var $_target = $('.ui-search').children('input'),
$_searchResult = $('#searchResult');
var value = $_target.val();
if(value.length !== 0){
$('.ui-search-recommend').hide();
$_searchResult.find('ul').empty();
$_searchResult.find('.title').empty();
$('#corrected').find('ul').empty();
$('.loadMore').remove();
$_searchResult.fadeIn(function() {
viewHasResultTitle(isMobile.any());
showSearchResult(value);
});
}else {
$_target.attr('placeholder','请输入搜索关键字!')
}
}
//搜索初始化 热门搜索 id值指定推荐或纠错结果位置
function searchInit(id) {
TOTAL_PAGE = 1;
MAX_PAGE = 0;
////判断是否来自 android iphone ipad浏览错误时弹窗 请求 ,url中包含action为是,否则执行正常搜索初始化
var target = window.location.href;
console.log(target);
if(target.match(/action/)) {
console.log(target.match(/action/));
$('.ui-search').children('input').val(decodeURI(target.split('action=')[1]));
toSearch();
}else {
console.log(target.match(/action/));
$('#recommend').fadeToggle(function() {
$.ajax({
type: 'POST',
url: 'search1.php',
data: {'action':'hot', 'project':'aguo', 'app_type':isMobile.any()},
dataType: 'json'
})
.done(function(json) {
// console.log(json);
viewKeyWord(json.info,id);
})
.fail(function() {
console.log('error');
});
});
}
}
//搜索结果显示
function showSearchResult(whatSearch,page) {
defaultLoad();
$("title").html(whatSearch+"_阿果搜索");
$.ajax({
type: 'POST',
url: 'search1.php',
data: {'action':'search','keyword':whatSearch, 'search_ip':"", 'app_type':isMobile.any(),'page':page},
dataType: 'json',
success: function(json){
defaultLoad();
if(json.status == 'false' || json.type == 2) {
//没有纠错词&&没有搜索结果
viewNoResult(whatSearch);
//您可以试试这些
//$('#recommend').fadeToggle();
if(! $.isEmptyObject(json.info)) {
var id = 'recommend';
$('#' + id).fadeIn(function() {
viewCorrectedWord(json.info,id);
});
}
}else if (json.status == true) {
//返回搜索结果 检查翻页
viewHasResult(json.info);
MAX_PAGE = json.total_page;
if($('#searchResult').children('.loadMore').length == 0) {
if(MAX_PAGE > 1) {
viewLoadMore();
}
}
}
}
})
}
//完整搜索结果view
function viewHasResult(json) {
for(var i=0; i < json.length; i++) {
var html = "<li class='ui-listbox'><div class='ui-listbox-up'><a href='" + json[i].titleurl +"' class='ui-listbox-up-img'><img src='" + ""+json[i].titlepic+"" + "'></a><a href='http://count.aguo.com/" + json[i].classid+"/"+ json[i].id+"?listseach' class='ui-listbox-up-a clear'><section><h1>" + json[i].title + "</h1><p>" + json[i].softsay + "</p></section></a></div><ul class='ui-listbox-below'><li class='gameSize'><span>" + ""+json[i].filesize+"" + "</span></li><li class='downNum clear-below-after'><span>" +json[i].totaldown+ "下载</span></li></ul><div class='ui-down ui-down-a'><a href='http://count.aguo.com/" + json[i].classid+"/"+ json[i].id+"?listseach'>下载</a></div></li>";
$('#searchResult').children('ul').append(html);
}
}
//推荐关键词view
function viewKeyWord(json,id) {
$.each(json,function(key,value) {
var html = "<li><a href='javascript:void(0)'>" + key+ "</a></li>";
$('#' + id).children('ul').append(html);
})
$('#' + id).children('ul').append("<li><a href='http://www.aguo.com/search_top.html'>搜索排行榜</a></li>");
}
//纠错词
function viewCorrectedWord(json,id) {
$('#searchResult').find('ul').append("<dd>您还可以试试这些:</dd>");
for(var i=0; i < json.length; i++) {
var html = "<li><a href='javascript:void(0)'>" + json[i].title + "</a></li>";
$('#' + id).children('ul').append(html);
}
}
//没有搜索结果view
function viewNoResult(whatSearch) {
$('#searchResult').find('ul').html("<p class='ui-search-noResult'>找不到和<span>" + whatSearch + "</span>相符的信息!</p>");
}
//显示加载更多view
function viewLoadMore() {
var html = "<div class='ui-listbox ui-listbox-c loadMore'><a class='ui-title-path'>加载更多内容</a></div>";
$('#searchResult').append(html);
}
//搜索结果标题
function viewHasResultTitle(type) {
if(type == false){
type = "网页";
}
var html = "在<span>" + type + "</span>中的搜索结果: ";
$('#searchResult').find('.title').append(html);
}
function defaultLoad() {
$('.loading_icon').toggle();
}
|
define(function (require, exports, module) {
var Global = require("global"),
ChooseUser = require("chooseuser"),
ec = require("echarts/echarts"),
moment = require("moment");
require("echarts/chart/funnel");
require("echarts/chart/line");
require("echarts/chart/bar");
require("daterangepicker");
var Params = {
type: 1,
OrderMapType: 1,
beginTime: new Date().setMonth(new Date().getMonth() - 1).toString().toDate("yyyy-MM-dd"),
endTime: Date.now().toString().toDate("yyyy-MM-dd"),
UserID: "",
TeamID: "",
AgentID: ""
};
var ObjectJS = {};
//初始化
ObjectJS.init = function () {
var _self = this;
_self.teamChart = ec.init(document.getElementById('teamRPT'));
_self.bindEvent();
}
ObjectJS.bindEvent = function () {
var _self = this;
$("#iptCreateTime").daterangepicker({
showDropdowns: true,
empty: true,
opens: "right",
ranges: {
'今天': [moment(), moment()],
'昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
'上周': [moment().subtract(6, 'days'), moment()],
'本月': [moment().startOf('month'), moment().endOf('month')]
}
}, function (start, end, label) {
Params.beginTime = start ? start.format("YYYY-MM-DD") : "";
Params.endTime = end ? end.format("YYYY-MM-DD") : "";
if (Params.type < 2) {
_self.showChart();
} else {
_self.showTeamChart();
}
});
$("#iptCreateTime").val(Params.beginTime + ' 至 ' + Params.endTime);
$(".tab-nav-ul li").click(function () {
var _this = $(this);
if (!_this.hasClass("hover")) {
_this.siblings().removeClass("hover");
_this.addClass("hover");
$(".source-box").hide();
$("#" + _this.data("id")).show();
Params.type = _this.data("type");
if (_this.data("begintime")) {
Params.beginTime= _this.data("begintime");
}
if (_this.data("endtime")) {
Params.endTime = _this.data("endtime");
} else {
Params.endTime = Date.now().toString().toDate("yyyy-MM-dd");
}
$("#iptCreateTime").val(Params.beginTime + ' 至 ' + Params.endTime);
ObjectJS.getRptData();
}
});
require.async("dropdown", function () {
var OrderMapType = [
{ name: "机会金额", value: "1" },
{ name: "机会数量", value: "2" }
];
$("#showType").dropdown({
prevText: "类型-",
defaultText: "机会金额",
defaultValue: "1",
data: OrderMapType,
dataValue: "value",
dataText: "name",
width: "140",
onChange: function (data) {
Params.OrderMapType = data.value;
ObjectJS.getRptData();
}
});
});
require.async("choosebranch", function () {
$("#chooseBranch").chooseBranch({
prevText: "人员-",
defaultText: "全部",
defaultValue: "",
userid: "-1",
isTeam: true,
width: "180",
onChange: function (data) {
Params.UserID = data.userid;
Params.TeamID = data.teamid;
ObjectJS.getRptData();
}
});
});
ObjectJS.getRptData();
}
ObjectJS.getRptData = function () {
var _self = this;
if (Params.type == 1) {
$("#showType").hide();
$("#chooseBranch").show();
_self.showChart();
} else if (Params.type == 2) {
$("#showType").show();
$("#chooseBranch").hide();
_self.showTeamChart();
}
}
ObjectJS.showChart = function () {
var _self = this;
Global.post("/SalesRPT/GetOpportunityStageRate", Params, function (data) {
var colorList = ['#9BA8AD', '#60DCFF', '#D8D6F1', '#FFABAB', '#7FC2EC', '#60DCFF', '#C0BBFB', '#18384C','#C13F3F'];
var innerhtml = '';
var liList = '';
var marginleft = 30;var totalleft = 0;
var totallent = 500;
for (var i = 0, j = data.items.length; i < j; i++) {
var item = data.items[i];
if (i == 0) {
if ((i + 1) < j && item.value > data.items[i + 1]) {
marginleft += 10;
}
} else if (i == (j - 1)) {
if (i > 0 && item.value > data.items[i-1]) {
marginleft += 10;
}
} else {
if (item.value > data.items[i + 1] && item.value > data.items[i - 1]) {
marginleft += 20;
} else if( item.value < data.items[i + 1] && item.value > data.items[i - 1]){
marginleft += 10;
} else if (item.value < data.items[i + 1] && item.value < data.items[i - 1]) {
marginleft -= 5;
}
}
if (i == 0) {
totallent += 2 * marginleft;
}
var headerdiv = '<div class="cont mTop10" style="" title="' + data.items[i].name +' 数量:'+ data.items[i].iValue + '(' + data.items[i].value+ ')">';;
var previousleft = totalleft;
totalleft += marginleft;
if (i < j - 1) {
innerhtml += headerdiv.replace('style="', 'style="margin-left:' + (i > 0 ? previousleft : 0) + 'px;"') + '<div class="taper-left" style="border-top-width:' + marginleft * 2 + 'px;border-left-width:' + marginleft + 'px;border-top-color:' + colorList[i] + ';"></div>' +
'<div class="taper-center" style="background-color:' + colorList[i] + ';width: ' + (i > 0 ? totallent - totalleft * 2 : 500) + 'px;height:' + (marginleft * 2 - 10) + 'px; line-height:' + (marginleft - 5) + 'px;">' + data.items[i].name.replace('(', '<br/>(') + ':' + data.items[i].iValue + '</br>' + data.items[i].desc + ' 占比率: ' + data.items[i].value + '</div>' +
'<div class="taper-right" style="border-top-color:' + colorList[i] + ';border-top-width:' + marginleft * 2 + 'px;border-right-width:' + marginleft + 'px;"></div>' +
'</div>';
}
if (i == j - 1) {
var lastwidth = (i > 0 ? totallent - totalleft * 2 : 500);
var lastheight = marginleft;
innerhtml += headerdiv.replace('style="', 'style="margin-left:' + (i > 0 ? previousleft : 0) + 'px;"') + '<div class="taper-left" style="border-top-width:' + marginleft * 2 + 'px;border-left-width:' + marginleft + 'px;border-top-color:' + colorList[i] + ';"></div>' +
'<div class="taper-center" style="background-color:' + colorList[i] + ';width: ' + lastwidth + 'px;height:' + (marginleft * 2 - 10) + 'px; line-height:' + (marginleft - 5) + 'px;">' + data.items[i].name.replace('(', '<br/>(') + ':' + data.items[i].iValue + '</br>' + data.items[i].desc + ' 占比率: ' + data.items[i].value + '</div>' +
'<div class="taper-right" style="border-top-color:' + colorList[i] + ';border-top-width:' + marginleft * 2 + 'px;border-right-width:' + marginleft + 'px;"></div>' +
'</div>';
innerhtml += headerdiv.replace("cont mTop10", "").replace('style="', 'style="margin-left:' + (i > 0 ? totalleft : 0) + 'px;border-bottom-width: 0px;text-align:center; float:left;border-style: solid;border-color:' + colorList[i] + ' transparent;border-left-width:' + lastwidth / 16 + 'px;border-right-width:' + lastwidth / 16 + 'px;border-top-width:' + lastwidth / 8 + 'px;width:' + lastwidth *7/8+ 'px;') + '</div>';
}
marginleft = 30;
liList += '<li style="list-style-type: none;overflow: auto"><span class="mTop3 left" style="min-width:11px;min-height:14px;background-color:' + colorList[i] + ';"></span><span class="mLeft10 left">' + data.items[i].name + '('+data.items[i].value+')</span> </li>';
}
$('#funnelContent').html(innerhtml);
$('#colorList').html(liList);
});
}
ObjectJS.showTeamChart = function () {
var _self = this;
_self.teamChart.showLoading({
text: "数据正在努力加载...",
x: "center",
y: "center",
textStyle: {
color: "red",
fontSize: 14
},
effect: "spin"
});
Global.post("/SalesRPT/GetUserOpportunitys", Params, function (data) {
var title = [], items = [], datanames = [];
_self.teamChart.clear();
if (Params.OrderMapType == 2) {
for (var i = 0, j = data.items.length; i < j; i++) {
datanames.push(data.items[i].Name);
for (var ii = 0, jj = data.items[i].Stages.length; ii < jj; ii++) {
if (i == 0) {
title.push(data.items[i].Stages[ii].Name);
items.push({
name: data.items[i].Stages[ii].Name,
type: 'line',
stack: '总量',
data: [data.items[i].Stages[ii].Count]
});
} else {
items[ii].data.push(data.items[i].Stages[ii].Count);
}
}
}
} else {
for (var i = 0, j = data.items.length; i < j; i++) {
datanames.push(data.items[i].Name);
for (var ii = 0, jj = data.items[i].Stages.length; ii < jj; ii++) {
if (i == 0) {
title.push(data.items[i].Stages[ii].Name);
items.push({
name: data.items[i].Stages[ii].Name,
type: 'line',
stack: '总量',
data: [data.items[i].Stages[ii].Money]
});
} else {
items[ii].data.push(data.items[i].Stages[ii].Money);
}
}
}
}
option = {
tooltip: {
trigger: 'axis'
},
legend: {
data: title
},
toolbox: {
show: true,
feature: {
magicType: { show: true, type: ['line', 'bar'] },
restore: { show: true },
saveAsImage: { show: true }
}
},
xAxis: [
{
type: 'category',
boundaryGap: false,
data: datanames
}
],
yAxis: [
{
type: 'value'
}
],
noDataLoadingOption: {
text: "",
textStyle: {
color: "red",
fontSize: 14
},
effect: "bubble"
},
series: items
};
_self.teamChart.hideLoading();
_self.teamChart.setOption(option);
});
}
module.exports = ObjectJS;
});
|
angular.module('app.home').controller("homeCtrl", function() {
console.log("Hello World");
})
|
import React from "react"
// Styles
import "../../uikit/sass/header.scss"
import "./header.scss"
// component
const Header = () => (
<header className="uikit-header uikit-header--dark" role="banner">
<div className="container">
<h1 className="uikit-header-heading">Service manual</h1>
</div>
</header>
)
export default Header
|
module.exports = {
Codable: require('./Codable'),
Describable: require('./Describable'),
Identifiable: require('./Identifiable'),
IdentifiableByInteger: require('./IdentifiableByInteger'),
IdentifiableByString: require('./IdentifiableByString'),
Nameable: require('./Nameable'),
Versionable: require('./Versionable'),
Treeness: require('./Treeness'),
HasGps: require('./HasGps'),
HasStreetAddress: require('./HasStreetAddress'),
SemanticallyVersionable: require('./SemanticallyVersionable')
}
|
/*
Hash a password using a given salt.
Also generates a salt to be used in the hash.
*/
var crypto = require('crypto');
var keyLength = 256;
var saltLength = 128;
var iterations = 10000;
exports.hash = function (password, salt, callback) {
crypto.pbkdf2(password, salt, iterations, keyLength, function(err, hash){
callback(err, (new Buffer(hash, 'binary')).toString('base64'));
});
};
exports.getSalt = function(password,callback){
crypto.randomBytes(saltLength, function(err,salt){
if (err) return callback(err);
salt = salt.toString('base64');
exports.hash(password,salt,function(err,hash){
callback(err, salt, hash);
});
});
};
|
import React, { Component } from 'react'
import './style.css'
class Conseils extends Component {
startTest = () => {
this.props.extend()
this.props.setTab('Test')
}
render() {
return (
<div className="Conseils">
<div className="header">Conseils</div>
<div>
<p>
Vous avez <span className="important">45 minutes</span> pour
effectuer le test en ligne. Ne passez pas trop de temps sur une
seule question.
</p>
<p>
Le test ne doit pas <span className="important">s’interrompre</span>.
Si le test est interrompu, vous ne pourrez pas le refaire et votre
candidature ne sera pas retenue.
</p>
<p>
Assurez-vous bien que vous avez une{' '}
<span className="important">bonne connexion</span> internet et que
vous êtes 100% disponible pour faire le test pendant les 45
prochaines minutes.
</p>
</div>
<div className="navigation">
<button className="btn-next" onClick={() => this.startTest()}>
Start !
</button>
</div>
</div>
)
}
}
export default Conseils
|
export default function HeaderComponent() {
return (
<div>
<strong>Welcome to React Session</strong>
<p>Trainer Name: Mayank Gupta</p><hr/>
</div>
)
}
export function HeaderOtherComponent() {
return (
<div>
<strong>Welcome to React Session Other</strong>
<p>Trainer Name: Mayank Gupta</p><hr/>
</div>
)
}
export var userName = "Mayank Gupta";
export var userAge = 10;
|
const $ = jQuery = jquery = require ("jquery")
const switchElement = require ("cloudflare/generic/switch")
$(document).on ( "cloudflare.speed.brotli.initialize", switchElement.initialize )
$(document).on ( "cloudflare.speed.brotli.toggle", switchElement.toggle )
|
import React, { Component, Fragment } from 'react';
import { Col, Button } from 'reactstrap';
import { DataBrasil, MoedaReal } from '../../../utils';
import Evento from '../../../components/EventoHistorico';
import './styles.css';
class HistoricoCliente extends Component {
constructor(props) {
super(props);
this.state = {
isDetalhesOpen: false,
eventoAtual: []
};
}
voltar = () => {
this.props.voltar();
};
fechaDetalhesEvento = () => {
this.setState({
isDetalhesOpen: false
});
};
mostraDetalhesEvento = (id) => {
this.props.mostraItens(id);
const evento = this.props.historico.filter(
(eventoHist) => id === eventoHist.id
);
this.setState({
isDetalhesOpen: true,
eventoAtual: evento
});
};
render() {
const itens = this.props.itensVenda ? (
this.props.itensVenda.map((item) => (
<Fragment key={item.id}>
<tr>
<td>{item.produto}</td>
<td>{item.quant}</td>
<td className='text-right'>
<MoedaReal valor={item.unit} />
</td>
<td className='text-right'>
<MoedaReal valor={item.subTotal} />
</td>
</tr>
</Fragment>
))
) : (
<tr>
<td />
</tr>
);
const historico = this.props.historico.length ? (
<Col md={6} className='cliente-historico'>
<table className='table table-sm table-hover'>
<thead className='thead-dark'>
<tr>
<th>Data</th>
<th>Número da Venda</th>
<th>Operação</th>
<th>Valor</th>
</tr>
</thead>
<tbody>
{this.props.historico
.filter(
(evento) =>
evento.valor !== '0.00' || evento.operacao === 'Pagamento'
)
.map((evento) => (
<Evento
key={evento.id}
dados={evento}
mostraDetalhes={this.mostraDetalhesEvento}
/>
))}
</tbody>
</table>
</Col>
) : (
<Col md={6} className='cliente-historico'>
<h1>Nenhuma operação realizada por este cliente</h1>
</Col>
);
const detalhesEvento = this.state.eventoAtual.length ? (
<Col md={6} className='detalhes-evento'>
<Button
color='danger'
onClick={this.fechaDetalhesEvento}
className='form-control'>
Fecha detalhes
</Button>
<div className='container'>
Venda número: {this.state.eventoAtual[0].id}
<br />
Data: <DataBrasil data={this.state.eventoAtual[0].dataVenda} />
<br />
Total da venda: <MoedaReal valor={this.state.eventoAtual[0].total} />
<br />
Desconto: <MoedaReal valor={this.state.eventoAtual[0].desconto} />
<br />
Total a pagar:{' '}
<MoedaReal valor={this.state.eventoAtual[0].totalAPagar} />
<br />
Valor Pago: <MoedaReal valor={this.state.eventoAtual[0].pago} />
<br />
Forma de pagamento: {this.state.eventoAtual[0].formaPg}
<br />
Crediário: <MoedaReal valor={this.state.eventoAtual[0].resta} />
<br />
<h2>Ítens da venda</h2>
<table className='table table-sm table-hover'>
<tbody>{itens}</tbody>
</table>
</div>
</Col>
) : (
''
);
const mostra = this.state.isDetalhesOpen ? detalhesEvento : historico;
return (
<div className='wrap-historicoCliente'>
<Col md={6} className='cliente-detalhes'>
<Button
color='success'
onClick={this.voltar}
className='form-control'>
Voltar
</Button>
<div className='container'>
Nome: {this.props.cliente.nome}
<br />
Endereço: {this.props.cliente.endereco}
<br />
CPF: {this.props.cliente.cpf}
<br />
RG: {this.props.cliente.rg}
<br />
Telefone: {this.props.cliente.fone}
<br />
Saldo: <MoedaReal valor={this.props.cliente.saldo} />
<br />
Data do Saldo:{' '}
<DataBrasil data={this.props.cliente.dataSaldo || '0/0/0'} />
<br />
Complemento: {this.props.cliente.complemento}
<br />
</div>
</Col>
{mostra}
</div>
);
}
}
export default HistoricoCliente;
|
$(document).ready(function() {
$('.mdb-select').formSelect();
});
|
../../../../../shared/src/App/Favorite/actions.js
|
import React from "react";
import ReactDOM from "react-dom";
import "bootstrap/dist/css/bootstrap.min.css";
import { BrowserRouter as Router } from "react-router-dom";
import { createStore, applyMiddleware, compose, combineReducers } from "redux";
import createSagaMiddleware from "redux-saga";
import { Provider } from "react-redux";
import productReducer from "./store/reducers/product";
import cartReducer from "./store/reducers/cart";
import authReducer from "./store/reducers/auth";
// import productSaga from "./store/sagas/productSaga";
// import authSaga from "./store/sagas/authSaga";
// import cartSaga from "./store/sagas/cartSaga";
import rootSaga from "./store/sagas";
import "./index.css";
import App from "./App";
const composeEnhancers =
process.env.NODE_ENV === "development"
? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
: null || compose;
const sagaMiddleware = createSagaMiddleware();
const rootReducer = combineReducers({
product: productReducer,
cart: cartReducer,
auth: authReducer
});
const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(sagaMiddleware))
);
// sagaMiddleware.run(productSaga);
// sagaMiddleware.run(cartSaga);
// sagaMiddleware.run(authSaga);
sagaMiddleware.run(rootSaga);
const app = (
<Provider store={store}>
<Router>
<App />
</Router>
</Provider>
);
ReactDOM.render(app, document.getElementById("root"));
|
const http = require('http'),
fs = require('fs'),
path = require('path');
const port = process.env.PORT || 3001,
appRoot = __dirname + "/www",
appPath = appRoot + "/index.html"
const app = (request, response) => {
// infer the intended request from request url
let requestUrl = request.url;
// default to index.html for all but resource requests (SPA)
let responseFilePath = appPath;
let contentType = 'text/html';
// remove resources url parameters
const requestUrlExtension = path.extname(requestUrl);
if (!!requestUrlExtension) {
responseFilePath = appRoot + requestUrl;
responseFilePath = responseFilePath.split("?")[0];
}
// find appropriate content type
switch (requestUrlExtension) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
case '.png':
contentType = 'image/png';
break;
case '.jpg':
contentType = 'image/jpg';
break;
case '.svg':
contentType = "image/svg+xml";
break;
case '.otf':
contentType = "font/otf";
break;
case '.ttf':
contentType = "font/ttf";
break;
case '.woff':
contentType = "font/woff";
break;
}
fs.readFile(responseFilePath, (error, content) => {
if (!!error) {
response.writeHead(404, { 'Content-Type': contentType });
response.end("error", 'utf-8');
} else {
response.writeHead(200, { 'Content-Type': contentType });
response.end(content, 'utf-8');
}
});
};
module.exports = app;
if (!module.parent) {
console.log('Initialising server');
http.createServer(app).listen(port, () => {
console.log(`Listening on http://localhost:${port}`);
});
}
|
import React from 'react';
const NotFound = () => {
return (
<>
<div className='pt-5'>
<h2 className='text-danger text-center pt-5'>OOPs!!! Page Not Found <strong>Error 404 </strong> </h2>
</div>
</>
);
};
export default NotFound;
|
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Creates a DomDistiller, applies to to the content of the page, and returns
// a DomDistillerResults as a JavaScript object/dictionary.
(function(options) {
try {
// The generated domdistiller.js accesses the window object only explicitly
// via the window name. This creates a new object with the normal window
// object as its prototype and initialize the domdistiller.js with that new
// context so that it does not change the real window object.
function initialize(window) {
$$DISTILLER_JAVASCRIPT
}
var context = Object.create(window);
context.setTimeout = function() {};
context.clearTimeout = function() {};
initialize(context);
var distiller = context.org.chromium.distiller.DomDistiller;
var res = distiller.applyWithOptions(options);
return res;
} catch (e) {
window.console.error("Error during distillation: " + e);
if (e.stack != undefined) window.console.error(e.stack);
}
return undefined;
// The OPTIONS placeholder will be replaced with the DomDistillerOptions at
// runtime.
})($$OPTIONS)
|
import 'moment/locale/zh-tw';
import {
DatePickerAndroid,
Text,
TouchableOpacity,
} from 'react-native';
import React, {
Component,
} from 'react';
import { dateFieldStyles, formFieldStyles } from '../../styles';
import { datePickerComponentPropTypes } from '../../propTypes/dateField';
import moment from 'moment';
const propTypes = {
...datePickerComponentPropTypes,
};
const defaultProps = {};
export default class AndroidDatePicker extends Component {
showPicker = async () => {
try {
const { action, year, month, day } = await DatePickerAndroid.open({
date: this.props.date,
minDate: this.props.minDate,
maxDate: this.props.maxDate,
});
if (action === DatePickerAndroid.dateSetAction) {
this.props.onDateChange(new Date(year, month, day));
}
} catch ({ code, message }) {
console.warn('Error');
}
}
render() {
const momentDate = moment(this.props.date);
momentDate.locale('zh-tw');
return (
<TouchableOpacity
style={[dateFieldStyles.dateTextContainer]}
onPress={this.showPicker}
>
<Text
style={[formFieldStyles.inputText]}
>
{momentDate.format('Y / M / D (ddd)')}
</Text>
</TouchableOpacity>
);
}
}
AndroidDatePicker.propTypes = propTypes;
AndroidDatePicker.defaultProps = defaultProps;
|
var webpack = require('webpack');
var path = require('path');
var LiveReloadPlugin = require('webpack-livereload-plugin');
var BUILD_DIR = path.resolve(__dirname, './www/js/destination');
var APP_DIR = path.resolve(__dirname, './www/js/src');
var config = {
entry: APP_DIR + '/index.jsx',
output: {
path: BUILD_DIR,
filename: 'bundle.js'
},
plugins: [
new LiveReloadPlugin(/*opts*/)
],
watch: true,
module : {
loaders : [
{
test : /\.jsx?/,
include : APP_DIR,
loader : 'babel'
}
]
}
};
module.exports = config;
|
import ElementUI from 'element-ui'
import Vue from 'vue'
Vue.use(ElementUI)
Vue.prototype.$errors = (message, errors) => {
let html = '<div class="message-errors">' +
'<p>' + message + '</p>' +
'<ul>'
for (let column_key in errors) {
for (let error_msg of errors[column_key]) {
html += '<li>' + error_msg +'</li>'
}
}
html += '</ul></div>'
Vue.prototype.$message({
type: 'error',
dangerouslyUseHTMLString: true,
message: html,
duration: 10000,
showClose: true
})
}
|
module.exports = function(Account) {
Account.disableRemoteMethod('upsert',true);
Account.disableRemoteMethod('findOne',true);
Account.disableRemoteMethod('count',true);
Account.disableRemoteMethod("exists", true);
Account.disableRemoteMethod("updateAll", true);
Account.disableRemoteMethod("deleteById", true);
Account.disableRemoteMethod('__create__accessTokens', false);
Account.disableRemoteMethod('__get__accessTokens', false);
Account.disableRemoteMethod('__count__accessTokens', false);
Account.disableRemoteMethod('__delete__accessTokens', false);
Account.disableRemoteMethod('__destroyById__accessTokens', false);
Account.disableRemoteMethod('__findById__accessTokens', false);
Account.disableRemoteMethod('__updateById__accessTokens', false);
Account.disableRemoteMethod('__exists__accessTokens', false);
Account.disableRemoteMethod('__link__accessTokens', false);
Account.disableRemoteMethod('__unlink__accessTokens', false);
Account.disableRemoteMethod('__findById__tins', false);
Account.disableRemoteMethod('__updateById__tins', false);
Account.disableRemoteMethod('__destroyById__tins', false);
Account.disableRemoteMethod('__count__tins', false);
Account.disableRemoteMethod('__delete__tins', false);
Account.disableRemoteMethod('__exists__tins', false);
Account.disableRemoteMethod('__link__tins', false);
Account.disableRemoteMethod('__unlink__tins', false);
Account.disableRemoteMethod('createChangeStream', true);
};
|
// @flow
import fetch from 'isomorphic-fetch'
import Card from './card'
type Point = {
x: number,
y: number,
}
type CardsArrangement = { [cardId: string]: Point }
type CardsMap = { [cardId: string]: Card }
export type PlainField = {
cardsArrangement?: CardsArrangement,
cardsMap?: CardsMap,
temporaryCardsArrangament?: CardsArrangement,
}
export default class Field {
constructor({
cardsArrangement,
cardsMap,
temporaryCardsArrangament,
}: PlainField = {}) {
this.cardsArrangement = cardsArrangement || {}
this.cardsMap = cardsMap || {}
this.temporaryCardsArrangament = temporaryCardsArrangament || {}
}
cardsArrangement: CardsArrangement
cardsMap: CardsMap
temporaryCardsArrangament: CardsArrangement
getCardByPoint(point: Point): ?Card {
const cardsArrangement = {
...this.cardsArrangement,
...this.temporaryCardsArrangament,
}
const id = Object.keys(cardsArrangement).find(id => {
const cardPoint = cardsArrangement[id]
return cardPoint.x === point.x && cardPoint.y === point.y
})
if (id == null) return null
return this.cardsMap[id]
}
confirmPuttingCard(): Field {
const cardsArrangement = {
...this.temporaryCardsArrangament,
...this.cardsArrangement,
}
return new Field({
...this,
cardsArrangement,
temporaryCardsArrangament: {},
})
}
getTemporaryCards(): Array<Card> {
return Object.keys(this.temporaryCardsArrangament).map(id => this.cardsMap[id])
}
cancelPuttingCard(): Field {
const temporaryCardsArrangament = { ...this.temporaryCardsArrangament }
const cardsMap = { ...this.cardsMap }
Object.keys(this.temporaryCardsArrangament).forEach(id => {
delete cardsMap[id]
})
return new Field({
...this,
temporaryCardsArrangament: {},
cardsMap
})
}
putCard(card: Card, point: Point): Field {
if (!this.isValidPointToPut(point)) return this
const temporaryCardsArrangament = {
...this.temporaryCardsArrangament,
[card.id]: point,
}
const cardsMap = Object.assign({}, this.cardsMap, { [card.id]: card })
return new Field({
...this,
temporaryCardsArrangament,
cardsMap
})
}
putFirstCard(card: Card, point: Point): Field {
const cardsArrangement = Object.assign({}, this.cardsArrangement, { [card.id]: point })
const cardsMap = Object.assign({}, this.cardsMap, { [card.id]: card })
return new Field({
...this,
cardsArrangement,
cardsMap
})
}
isValidPointToPut(point: Point): boolean {
const { x, y } = point
const right = { x: x + 1, y }
const left = { x: x - 1, y }
const up = { x, y: y + 1 }
const down = { x, y: y - 1 }
return [right, left, up, down].some(point => this.getCardByPoint(point) != null)
}
}
|
var CallidForm;
var pageSize = 25;
//活動Model
Ext.define('gigade.VoteEvent', {
extend: 'Ext.data.Model',
fields: [
{ name: "event_id", type: "string" },
{ name: "event_name", type: "string" },
{ name: "event_desc", type: "string" },
{ name: "event_banner", type: "string" },
//{ name: "bannerUrl", type: "string" },
{ name: "event_start", type: "string" },
{ name: "event_end", type: "string" },
{ name: "word_length", type: "string" },
{ name: "vote_everyone_limit", type: "string" },
{ name: "vote_everyday_limit", type: "string" },
{ name: "number_limit", type: "string" },
{ name: "present_event_id", type: "string" },
{ name: "create_user", type: "string" },
{ name: "cuser", type: "string" },
{ name: "create_time", type: "string" },
{ name: "update_user", type: "string" },
{ name: "uuser", type: "string" },
{ name: "update_time", type: "string" },
{ name: "event_status", type: "string" },
{ name: "is_repeat", type: "string" }
]
});
var VoteEventStore = Ext.create('Ext.data.Store', {
autoDestroy: true,
pageSize: pageSize,
model: 'gigade.VoteEvent',
proxy: {
type: 'ajax',
url: '/Vote/GetVoteEventList',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
});
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections)
{
Ext.getCmp("gdVoteEvent").down('#edit').setDisabled(selections.length == 0);
}
}
});
VoteEventStore.on('beforeload', function ()
{
Ext.apply(VoteEventStore.proxy.extraParams, {
search_content: Ext.getCmp('search_content') == null ? "" : Ext.getCmp('search_content').getValue()
});
});
Ext.onReady(function ()
{
var gdVoteEvent = Ext.create('Ext.grid.Panel', {
id: 'gdVoteEvent',
store: VoteEventStore,
width: document.documentElement.clientWidth,
columnLines: true,
frame: true,
columns: [
{ header: "活動編號", dataIndex: 'event_id', width: 80, align: 'center' },
{
header: "活動名稱", dataIndex: 'event_name', width: 150, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store)
{
cellmeta.style = 'overflow:visible;padding:3px 3px 3px 5px;white-space:normal';
return value;
}
},
{
header: "活動描述", dataIndex: 'event_desc', width: 150, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store)
{
cellmeta.style = 'overflow:visible;padding:3px 3px 3px 5px;white-space:normal';
return value;
}
},
{
header: "活動廣告", id: 'imgsmall', colName: 'event_banner',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store)
{
if (value != '')
{
return '<div style="width:50px;height:50px"><a target="_blank", href="' + record.data.event_banner + '"><img width="50px" height="50px" src="' + record.data.event_banner + '" /></a><div>'
} else
{
return null;
}
},
width: 60, align: 'center', sortable: false, menuDisabled: true
},
//{
// header: "問卷廣告鏈接", dataIndex: 'bannerUrl', width: 150, align: 'center',
// renderer: function (value, cellmeta, record, rowIndex, columnIndex, store)
// {
// return Ext.String.format('<a href="{0}" target="bank">{1}</a>', value, value);
// }
//},
{
header: "開始時間", dataIndex: 'event_start', width: 150, align: 'center'
//, renderer: Ext.util.Format.dateRenderer('Y-m-d H:i:s')
},
{
header: "結束時間", dataIndex: 'event_end', width: 150, align: 'center', renderer: function (value, cellmeta, record, rowIndex, columnIndex, store)
{
var event_end = Date.parse(value);
if (event_end < new Date())
{
//return '<p style="color:#F00;">' + Ext.Date.format(new Date(value), 'Y-m-d H:i:s') + '</p>';
return '<p style="color:#FF0000;">' + value + '</p>';
}
else
{
return value;
}
}
},
{ header: "會員投票限制", dataIndex: 'vote_everyone_limit', width: 80, align: 'center' },
{ header: "每日投票限制", dataIndex: 'vote_everyday_limit', width: 80, align: 'center' },
{ header: "會員贈送次數", dataIndex: 'number_limit', width: 100, align: 'center' },
{
header: "促銷編號", dataIndex: 'present_event_id', width: 110, align: 'center'
},
{
header: "是否重複投票", dataIndex: 'is_repeat', width: 110, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store)
{
if (value == "1")
{
return "是"
}
else
{
return "否"
}
}
},
{
header: "創建人", dataIndex: 'cuser', width: 100, align: 'center'
},
{
header: "創建時間", dataIndex: 'create_time', width: 150, align: 'center'
},
{
header: "狀態", dataIndex: 'event_status', width: 100, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store)
{
if (value == "1")
{
return "<a href='javascript:void(0);' onclick='UpdateActive(" + record.data.event_id + ")'><img hidValue='0' id='img" + record.data.event_id + "' src='../../../Content/img/icons/accept.gif'/></a>";
} else
{
return "<a href='javascript:void(0);' onclick='UpdateActive(" + record.data.event_id + ")'><img hidValue='1' id='img" + record.data.event_id + "' src='../../../Content/img/icons/drop-no.gif'/></a>";
}
}
}
],
tbar: [
{ xtype: 'button', text: "新增", id: 'add', hidden: false, iconCls: 'icon-user-add', handler: onAddClick },
{ xtype: 'button', text: "編輯", id: 'edit', hidden: false, iconCls: 'icon-user-edit', disabled: true, handler: onEditClick },
'->',
{
xtype: 'textfield', fieldLabel: "活動編號/名稱/描述", labelWidth: 120, id: 'search_content', listeners: {
specialkey: function (field, e)
{
// e.HOME, e.END, e.PAGE_UP, e.PAGE_DOWN,
// e.TAB, e.ESC, arrow keys: e.LEFT, e.RIGHT, e.UP, e.DOWN
if (e.getKey() == e.ENTER)
{
Query(1);
}
}
}
},
{
text: SEARCH,
iconCls: 'icon-search',
id: 'btnQuery',
handler: Query
}
],
bbar: Ext.create('Ext.PagingToolbar', {
store: VoteEventStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
}),
listeners: {
scrollershow: function (scroller)
{
if (scroller && scroller.scrollEl)
{
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
},
selModel: sm
});
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [gdVoteEvent],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function ()
{
gdVoteEvent.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
ToolAuthority();
//VoteEventStore.load({ params: { start: 0, limit: 25 } });
});
/*************************************************************************************查詢*************************************************************************************************/
function Query(x)
{
if (Ext.getCmp('search_content').getValue().trim() != "") {
VoteEventStore.removeAll();
Ext.getCmp("gdVoteEvent").store.loadPage(1, {
params: {
search_content: Ext.getCmp('search_content') == null ? "" : Ext.getCmp('search_content').getValue()
}
});
}
else {
Ext.Msg.alert(INFORMATION, "请输入搜索条件!");
}
}
/*************************************************************************************新增*************************************************************************************************/
onAddClick = function ()
{
//addWin.show();
editEventFunction(null, VoteEventStore);
}
/*************************************************************************************編輯*************************************************************************************************/
onEditClick = function ()
{
var row = Ext.getCmp("gdVoteEvent").getSelectionModel().getSelection();
//alert(row[0]);
if (row.length == 0)
{
Ext.Msg.alert(INFORMATION, NO_SELECTION);
} else if (row.length > 1)
{
Ext.Msg.alert(INFORMATION, ONE_SELECTION);
} else if (row.length == 1)
{
editEventFunction(row[0], VoteEventStore);
}
}
//更改狀態(啟用或者禁用)
function UpdateActive(id)
{
var activeValue = $("#img" + id).attr("hidValue");
$.ajax({
url: "/Vote/UpdateEventState",
data: {
"id": id,
"active": activeValue
},
type: "POST",
dataType: "json",
success: function (msg)
{
if (activeValue == 1)
{
$("#img" + id).attr("hidValue", 0);
$("#img" + id).attr("src", "../../../Content/img/icons/accept.gif");
VoteEventStore.load();
}
else
{
$("#img" + id).attr("hidValue", 1);
$("#img" + id).attr("src", "../../../Content/img/icons/drop-no.gif");
VoteEventStore.load();
}
},
error: function (msg)
{
Ext.Msg.alert(INFORMATION, FAILURE);
VoteEventStore.load();
}
});
}
|
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const feedSchema = new schema({
feedPicture: { type: String, default: '' },
farmID: { type: String, default: '' }, // ให้ใส่ค่าว่างไว้
name: { type: String, default: '' }, // ถ้าไม่รู้จะใส่อะไรห้ใส่ กรมการข้าว ได้หมดเลย
order: { type: Number, default: 0 }, // เริ่มจาก 1 และ บวกขึ้นไปเรื่อยๆ
activitiesDate: Date,
caption: { type: String, default: '' },
status: { type: String, default: '' }, // ให้ใส่ fales ทั้งไว้เลย
feedType: { type: Number, enum: [0, 1, 2], default: 0 }, // 1(1,2) = farm, 2(3,4,5) = Admin (กรมการข้าว)
activities: [
{
code_type: { type: Number, enum: [0, 3, 4, 5], default: 0 },
array_code: [
{
activityCode: { type: Number, default: 0 },
activity: { type: String, default: '' },
picture: { type: String, default: '' },
activate: { type: Boolean, default: false },
},
],
},
],
activityLenght: { type: Number, default: 0 }, // ใส่ 0
warningLenght: { type: Number, default: 0 }, // ใส่ 0
});
module.exports.feedModel = mongoose.model('feeds', feedSchema);
|
process.env.NODE_ENV = 'test';
var async = require('async');
var db, geomFixture;
before(function () {
lbDs = getDataSource();
geomFixture = getGeomFixture();
});
//expect(polygon01).toBeDefined();
//expect(polygon02).toBeDefined();
//expect(polygon03).toBeDefined();
describe('Mapping models', function () {
it('should honor the postgresql settings for table/column', function (done) {
var schema =
{
"name": "TestInventory",
"options": {
"idInjection": false,
"postgresql": {
"schema": "public", "table": "inventorytest"
}
},
"properties": {
"productId": {
"type": "String", "required": true, "length": 20, "id": 1, "postgresql": {
"columnName": "product_id", "dataType": "VARCHAR", "nullable": "NO"
}
},
"locationId": {
"type": "String", "required": true, "length": 20, "id": 2, "postgresql": {
"columnName": "location_id", "dataType": "VARCHAR", "nullable": "NO"
}
},
"available": {
"type": "Number", "required": false, "postgresql": {
"columnName": "available", "dataType": "INTEGER", "nullable": "YES"
}
},
"total": {
"type": "Number", "required": false, "postgresql": {
"columnName": "total", "dataType": "INTEGER", "nullable": "YES"
}
},
"fooxyz": {
"type": "PointZ", "required": false, "postgresql": {
"columnName": "fooxyz", "dataType": "GEOMETRY(POINTZ,4326)", "nullable": "YES"
}
},
"fooxy": {
"type": "Point", "required": false, "postgresql": {
"columnName": "fooxy", "dataType": "GEOMETRY(POINT,4326)", "nullable": "YES"
}
},
"foopoly": {
"type": "Polygon", "required": false, "postgresql": {
"columnName": "foopolys", "dataType": "GEOMETRY(POLYGON,4326)", "nullable": "YES"
}
}
}
};
var models = lbDs.modelBuilder.buildModels(schema);
console.log(models);
var Model = models['TestInventory'];
Model.attachTo(lbDs);
db.automigrate(function (err, data) {
async.series([
function (callback) {
Model.destroyAll(callback);
},
function (callback) {
Model.create({productId: 'p001', locationId: 'l001', available: 10, total: 50, foopoly: geomFixture.polygon01}, callback);
},
function (callback) {
Model.create({productId: 'p001', locationId: 'l002', available: 30, total: 40, foopoly: geomFixture.polygon02}, callback);
},
function (callback) {
Model.create({productId: 'p002', locationId: 'l001', available: 15, total: 30, foopoly: geomFixture.polygon03}, callback);
},
function forBaselineProps(callback) {
Model.find({fields: ['productId', 'locationId', 'available']}, function (err, results) {
// console.log(results);
results.should.have.lengthOf(3);
results.forEach(function (r) {
r.should.have.property('productId');
r.should.have.property('locationId');
r.should.have.property('available');
r.should.have.property('total', undefined);
r.should.have.property('fooxyz', undefined);
});
callback(null, results);
});
},
function forAnonymous(callback) {
Model.find({fields: {'total': false}}, function (err, results) {
// console.log(results);
results.should.have.lengthOf(3);
results.forEach(function (r) {
r.should.have.property('productId');
r.should.have.property('locationId');
r.should.have.property('available');
r.should.have.property('total', undefined);
r.should.have.property('fooxyz');
});
callback(null, results);
});
},
function forGeoGigTypes (callback) {
Model.find({fields: ['productId', 'locationId','fooxyz', 'foopoly', 'fooxy']}, function (err, results) {
// console.log(results);
results.should.have.lengthOf(3);
results.forEach(function (r) {
r.should.have.property('productId');
r.should.have.property('locationId');
r.should.have.property('available',undefined);
r.should.have.property('total', undefined);
r.should.have.property('foopoly');
r.should.have.property('fooxy');
r.should.have.property('fooxyz');
});
callback(null, results);
});
}
], done);
});
});
});
|
const redis = require('ioredis');
const logger = require('./logger');
module.exports = function(app) {
const client = new redis('6379', process.env.REDIS_URL);
client.on('connect', () => {
logger.log('info', 'Redis Connected');
});
client.on('disconnect', () => {
logger.log('info', 'Redis Disconnected');
});
app.set('redis', client);
return app;
};
|
/**
* Build Title,Description,URL and get best prsm for each proteoform
* @param {String} folderpath - Provides path to the data folder
*/
function protein(folderpath){
// Generate title for the webpage from the data
document.title = "Proteoforms for protein " + prsm_data.protein.sequence_name
+ " "+ prsm_data.protein.sequence_description;
// Generate description of the protein from the data
document.getElementById('sequence_description').innerHTML
= prsm_data.protein.compatible_proteoform_number+" proteoforms for protein "
+ prsm_data.protein.sequence_name + " "+ prsm_data.protein.sequence_description;
// Check if protein has multiple proteoforms
if(Array.isArray(prsm_data.protein.compatible_proteoform)) {
prsm_data.protein.compatible_proteoform.forEach(function(compatible_proteoform,index){
proteoformToHtml(compatible_proteoform,index,folderpath);
})
}
else {
proteoformToHtml(prsm_data.protein.compatible_proteoform,0,folderpath);
}
}
/**
* This function builds a header for a proteoform, gets information of best prsm.
* Forms SVG visualization of the best prsm.
* @param {object} compatible_proteoform - Contains information of a single proteoform
* @param {Int} index - Index of proteoform
* @param {String} folderpath - Provides path to data files
*/
function proteoformToHtml(compatible_proteoform,index,folderpath) {
// Get the div element with class name proteoformcontainer
// All the details of a each proteoform is under the proteoformcontainer div
var div_container = document.getElementsByClassName("proteoformcontainer")[0];
var div = document.createElement('div');
let id = "p"+ compatible_proteoform.proteoform_id;
div.setAttribute("id",id);
var h2 = document.createElement('h3');
let p = document.createElement("p");
let e_value;
let BestPrSM ;
if(compatible_proteoform.prsm.length > 0) {
// Forms header for a proteoform
h2.innerHTML = "Proteoform #" + compatible_proteoform.proteoform_id + " Feature intensity: "
+ compatible_proteoform.prsm[0].ms.ms_header.feature_inte;
let precursor_mass;
let prsm_id ;
// Gets Best prsm with low e value
[e_value,precursor_mass,prsm_id] = getBestPrsm(compatible_proteoform.prsm);
p = Build_BestPrSM(e_value,precursor_mass,prsm_id,compatible_proteoform.proteoform_id,
compatible_proteoform.prsm.length,folderpath);
for(let i = 0; i< compatible_proteoform.prsm.length ; i++)
{
if(prsm_id == compatible_proteoform.prsm[i].prsm_id)
{
prsm = compatible_proteoform.prsm[i] ;
let prot = prsm.annotated_protein;
let [fixedPtms, protVarPtms, variablePtms] = json2Ptms(prsm);
let massShifts = json2MassShifts(prsm);
let sequence = getAminoAcidSequence(0,prot.annotation.residue.length - 1,prot.annotation.residue);
let breakPoints = json2BreakPoints(prsm, parseInt(prot.annotation.first_residue_position));
let proteoformObj = new Proteoform(prot.proteoform_id, prot.sequence_name, sequence,
prot.annotation.first_residue_position, prot.annotation.last_residue_position, prot.proteoform_mass, massShifts, fixedPtms, protVarPtms, variablePtms)
BestPrSM = new Prsm(prsm.prsm_id, proteoformObj, "", "", breakPoints, prsm.matched_peak_number,
prsm.matched_fragment_number, prsm.e_value, prsm.fdr);
break;
}
}
}
else {
// Forms header for a proteoform
h2.innerHTML = "Proteoform #" + compatible_proteoform.proteoform_id + " Feature intensity: "
+ compatible_proteoform.prsm.ms.ms_header.feature_inte;
p.setAttribute("style","font-size:16px;");
let text1 = document.createElement("text");
text1.innerHTML = "There is only ";
p.appendChild(text1);
let a_prsm = document.createElement("a");
a_prsm.href = "prsm.html?folder="+folderpath+"&prsm_id="+compatible_proteoform.prsm.prsm_id;
a_prsm.innerHTML = " 1 PrSM ";
p.appendChild(a_prsm);
let text2 = document.createElement("text");
text2.innerHTML = "with an E-value "+compatible_proteoform.prsm.e_value +" and a precursor mass "+
compatible_proteoform.prsm.ms.ms_header.precursor_mono_mass +".";
p.appendChild(text2);
e_value = compatible_proteoform.prsm.e_value ;
let prsm = compatible_proteoform.prsm ;
let prot = prsm.annotated_protein;
let [fixedPtms, protVarPtms, variablePtms] = json2Ptms(prsm);
let massShifts = json2MassShifts(prsm);
let sequence = getAminoAcidSequence(0,prot.annotation.residue.length - 1,prot.annotation.residue);
let breakPoints = json2BreakPoints(prsm, parseInt(prot.annotation.first_residue_position));
let proteoformObj = new Proteoform(prot.proteoform_id, prot.sequence_name, sequence,
prot.annotation.first_residue_position, prot.annotation.last_residue_position, prot.proteoform_mass, massShifts, fixedPtms, protVarPtms, variablePtms)
BestPrSM = new Prsm(prsm.prsm_id, proteoformObj, "", "", breakPoints, prsm.matched_peak_number,
prsm.matched_fragment_number, prsm.e_value, prsm.fdr);
}
div_container.appendChild(div);
div_container.appendChild(h2);
div_container.appendChild(p);
let containerId = "svg_container" + index;
let svgContainer = document.createElement("div");
svgContainer.setAttribute("id", containerId);
svgContainer.setAttribute("class","svg_container");
div_container.appendChild(svgContainer);
let svgId = "prsm_svg"+ index;
d3.select("#"+containerId).append("svg")
.attr("id",svgId);
//console.log(svgId, BestPrSM);
let graph = new PrsmGraph(svgId, BestPrSM);
graph.redraw();
}
/**
* Get "precursor mass","prsm Id" and least "e value" for each proteoform
* @param {object} prsm - COntains information of the prsms of a proteoform
*/
function getBestPrsm(prsm) {
let e_value = " " ;
let precursor_mass = " " ;
let prsm_id = "";
let temp = parseFloat(prsm[0].e_value);
e_value = prsm[0].e_value;
precursor_mass = prsm[0].ms.ms_header.precursor_mono_mass;
prsm_id = prsm[0].prsm_id;
for(let i = 1 ; i < (prsm.length) ; i++)
{
if(temp >= parseFloat(prsm[i].e_value))
{
temp = parseFloat(prsm[i].e_value)
e_value = prsm[i].e_value;
precursor_mass = prsm[i].ms.ms_header.precursor_mono_mass;
prsm_id = prsm[i].prsm_id;
}
}
return [e_value,precursor_mass,prsm_id];
}
/**
* Create HTML URL link to navigate to best prsm and to navigae to proteoform page
* @param {Float} e_value - Contains e value of the best prsm
* @param {Float} precursor_mass - Contains precursor mass of the best prsm
* @param {Int} prsm_id - Contains the best prsm id
* @param {Int} proteoform_id - Contains the proteoform Id
* @param {Int} PrSM_Count - Contians numbe rof prsms for a proteoform
* @param {String} folderpath - Contains path to the data folder
*/
function Build_BestPrSM(e_value,precursor_mass,prsm_id,proteoform_id, PrSM_Count,folderpath) {
let p = document.createElement("p");
p.setAttribute("style","font-size:16px;");
let text1 = document.createElement("text");
text1.innerHTML = "The ";
p.appendChild(text1);
let a_prsm = document.createElement("a");
a_prsm.href = "prsm.html?folder="+folderpath+"&prsm_id="+prsm_id;
a_prsm.innerHTML = " best PrSM ";
p.appendChild(a_prsm);
let text2 = document.createElement("text");
text2.innerHTML = "has an E-value "+e_value+" and a precursor mass "+precursor_mass+". There are ";
p.appendChild(text2);
let a_proteoform = document.createElement("a");
a_proteoform.href = "proteoform.html?folder="+folderpath+"&proteoform_id=" + proteoform_id;
a_proteoform.innerHTML = PrSM_Count + " PrSMs ";
p.appendChild(a_proteoform);
let text3 = document.createElement("text");
text3.innerHTML = "in total.";
p.appendChild(text3);
return p ;
}
|
/**
* Copyright (c) 2013 Oculus Info Inc.
* http://www.oculusinfo.com/
*
* Released under the MIT License.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
define(['jquery', '../util/ui_util', '../util/rest'], function($, ui_util, rest) {
var baseURL = null;
var updateTagsOnServer = function(updateTagRequest, callback) {
rest.post(baseURL + 'rest/tags/update',updateTagRequest,'UpdateTags', callback, true);
};
var resetAllTags = function(baseUrl, callback) {
var that = this;
var dialogDiv = $('<div title="WARNING">This will remove all tags for every ad. Are you sure you wish to continue?</div>');
$('body').append(dialogDiv);
var onCancel = function(){
$(this).dialog("close");
};
var onOk = function() {
rest.delete(baseUrl + 'rest/tags/resetAllTags', null, 'Reset all tags', callback, true);
$(this).dialog("close");
};
var buttonSet = {
"Ok" : onOk,
"Cancel" : onCancel
};
dialogDiv.dialog({
zIndex:30000000,
width:650,
modal:true,
// These two lines prevent the "x" from appearing in the corner of dialogs. It's annoying to handle closing the dialog
// this way so this is how we can prevent the user from doing this
closeOnEscape: false,
open: function(event, ui) {
$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
},
buttons: buttonSet,
close: function() {
dialogDiv.remove();
},
resizeStop: function(event, ui) {}
});
};
var fetchTags = function(adIds, callback) {
rest.post(baseURL + 'rest/tags/fetch',{list:adIds},'Fetch tags', callback);
};
var modifyTags = function(adIds, tagArray, add, callback) {
if (tagArray && tagArray.length > 0) {
var request = {
tags : tagArray,
adIds : adIds,
add : add
};
updateTagsOnServer(request, callback);
} else {
callback();
}
};
var addTagRow = function(container, tag, bShowRemoveButton, tagsToRemove) {
var tagDivContainer = $('<div/>');
container.append(tagDivContainer);
var tagDiv = $('<div/>').css({display:'inline-block'});
tagDiv.html(tag);
tagDivContainer.append(tagDiv);
if (bShowRemoveButton) {
var removeButton = $('<button/>').button({
text:false,
icons: {
primary: 'ui-icon-close'
}
});
removeButton.click(function() {
tagsToRemove.push(tag);
tagDivContainer.remove();
});
tagDivContainer.append(removeButton);
}
};
var convertAdIdsResponse = function(adIdsToTags) {
var adIdsJSON = {};
if (_.isArray(adIdsToTags.entry) ) {
for (var i = 0; i < adIdsToTags.entry.length; i++) {
var idAndTagList = adIdsToTags.entry[i];
if (idAndTagList.value) {
adIdsJSON[idAndTagList.key] = _.isArray(idAndTagList.value.list) ? idAndTagList.value.list : [idAndTagList.value.list];
}
}
} else {
if (adIdsToTags.entry.value) {
adIdsJSON[adIdsToTags.entry.key] = _.isArray(adIdsToTags.entry.value.list) ? adIdsToTags.entry.value.list : [adIdsToTags.entry.value.list];
}
}
return adIdsJSON;
};
var createWidget = function(container, baseUrl, adIds) {
baseURL = baseUrl;
var adIdsToTags = null;
var tagsToRemove = [];
var tagsToAdd = [];
var allCurrentTags = {};
var tagWidget = {
init: function() {
var existingTagContainer = $('<div/>').html("Existing Tags:");
$(container).append(existingTagContainer);
var tagContainer = $('<div/>').html("Tags:");
$(container).append(tagContainer);
var controlContainer = $('<div/>');
$(container).append(controlContainer);
var tagInput = $('<input/>');
tagInput.attr('type','text');
controlContainer.append(tagInput);
var addTagButton = $('<button/>');
addTagButton.html("Add");
addTagButton.click(function() {
var newTag = tagInput.val();
if (tagsToAdd.indexOf(newTag) == -1) {
addTagRow(tagContainer, tagInput.val());
tagsToAdd.push(newTag);
tagInput.val('');
}
});
controlContainer.append(addTagButton);
var clearAllTagsButton = $('<button/>');
clearAllTagsButton.html("Clear All");
clearAllTagsButton.click(function() {
existingTagContainer.empty();
for (var tag in allCurrentTags) {
if (allCurrentTags.hasOwnProperty(tag)) {
tagsToRemove.push(tag);
}
}
});
controlContainer.append(clearAllTagsButton);
fetchTags(adIds, function(response) {
var i;
var tagCounts = {};
if (response.adIdToTags == null) {
} else {
var adIdToTags = convertAdIdsResponse(response['adIdToTags']);
var adCount = 0;
for (var adId in adIdToTags) {
if (adIdToTags.hasOwnProperty(adId)) {
adCount++;
for (i = 0; i < adIdToTags[adId].length; i++) {
if (tagCounts[adIdToTags[adId][i]]) {
tagCounts[adIdToTags[adId][i]] = tagCounts[adIdToTags[adId][i]] + 1;
} else {
tagCounts[adIdToTags[adId][i]] = 1;
}
}
}
}
var addMultipleTagsText = false;
for (var tag in tagCounts) {
allCurrentTags[tag] = true;
if (tagCounts.hasOwnProperty(tag)) {
if (tagCounts[tag] == adCount) {
addTagRow(existingTagContainer, tag, true, tagsToRemove);
} else {
addMultipleTagsText = true;
}
}
}
if (addMultipleTagsText) {
addTagRow(existingTagContainer, "Multiple Tags", false);
}
}
});
},
updateTags: function(callback) {
modifyTags(adIds, tagsToRemove, false, function() {
modifyTags(adIds, tagsToAdd, true, function() {
callback(tagsToAdd, tagsToRemove);
});
});
}
};
tagWidget.init();
return tagWidget;
};
var showTagDialog = function(baseUrl, adIdsToTagMap, callback) {
var that = this;
var dialogDiv = $('<div/>');
$('body').append(dialogDiv);
var tagWidget = createWidget(dialogDiv[0], baseUrl, adIdsToTagMap);
var onCancel = function(){
$(this).dialog("close");
};
var onOk = function() {
tagWidget.updateTags(callback);
$(this).dialog("close");
};
var clusterButtonSet = {
"Ok" : onOk,
"Cancel" : onCancel
};
dialogDiv.dialog({
zIndex:30000000,
width:650,
modal:true,
// These two lines prevent the "x" from appearing in the corner of dialogs. It's annoying to handle closing the dialog
// this way so this is how we can prevent the user from doing this
closeOnEscape: false,
open: function(event, ui) {
$(this).parent().children().children('.ui-dialog-titlebar-close').hide();
},
buttons: clusterButtonSet,
close: function() {
dialogDiv.remove();
},
resizeStop: function(event, ui) {}
});
};
return {
createWidget:createWidget,
showTagDialog: showTagDialog,
resetAllTags: resetAllTags
};
});
|
const Augur = require("augurbot");
const chess = new (require("chess-web-api"))({queue: true});
const moment = require("moment");
const u = require("../utils/utils");
const Module = new Augur.Module()
.addCommand({name: "chess",
description: "Get your Chess.com games, using the name saved with `!addIGN`",
syntax: "[playerName]",
process: async (msg, suffix) => {
let name;
if (u.userMentions(msg).size > 0) {
try {
let ign = await Module.db.ign.find(u.userMentions(msg).first().id, 'chess');
if (ign) name = ign.ign;
} catch(error) { u.errorHandler(error, msg); }
} else if (suffix) {
name = suffix;
} else {
try {
let ign = await Module.db.ign.find(msg.author.id, 'chess');
if (ign) name = ign.ign;
} catch(error) { u.errorHandler(error, msg); }
}
if (name) {
try {
let result = await chess.getPlayerCurrentDailyChess(encodeURIComponent(name));
let games = result.body.games;
let getPlayer = /https:\/\/api\.chess\.com\/pub\/player\/(.*)$/;
let embed = u.embed().setTitle(`Current Chess.com Games for ${name}`)
.setThumbnail("https://openclipart.org/image/800px/svg_to_png/275248/1_REY_Blanco_Pieza-Mural_.png");
let i = 0;
for (const game of games) {
embed.addField(`♙${getPlayer.exec(game.white)[1]} v ♟${getPlayer.exec(game.black)[1]}`, `Current Turn: ${(game.turn == "white" ? "♙" : "♟")}${getPlayer.exec(game[game.turn])[1]}\nMove By: ${moment(game.move_by).format("ddd h:mmA Z")}\n[[link]](${game.url})`, true);
if (++i == 25) break;
}
if (games.length == 0) embed.setDescription(`No active games found for ${name}.`);
else if (games.length > 25) embed.setDescription(`${name}'s first 25 active games:`);
else embed.setDescription(`${name}'s active games:`);
msg.channel.send({embed});
} catch(error) {
if (error.message == "Not Found" && error.statusCode == 404) {
msg.reply(`I couldn't find a profile for \`${name}\`.`);
} else { u.errorHandler(error, msg); }
}
} else {
if (u.userMentions(msg).size > 0) msg.reply(`${u.userMentions(msg).first().username} hasn't saved a Chess.com IGN!`).then(u.clean);
else msg.reply("you need to tell me who to search for or set an ign with `!addIGN chess name`.").then(u.clean);
}
}
});
module.exports = Module;
|
import React,{Component} from 'react'
import $ from 'jquery'
import promiseXHR from '../../funStore/ServerFun'
import AuthProvider from '../../funStore/AuthProvider'
import SearchBox from './SearchBox'
import MemberList from './MemberList'
import MicroTaskWrapper from './MicroTaskWrapper'
import KnowledgeBase from './KnowledgeBase'
import {API_PATH} from '../../constants/OriginName'
import SearchBoxForCW from './SearchBoxForCW'
import SearchBoxForMT from './SearchBoxForMT'
function FormatDate (strTime) {
var date = new Date(strTime)
var month = ((date.getMonth()+1)<10)? '0'+(date.getMonth()+1) : (date.getMonth()+1)
var day = (date.getDate()<10)? '0'+date.getDate() : date.getDate()
var hours = (date.getHours()<10) ? '0'+date.getHours() : date.getHours()
var minutes = (date.getMinutes()<10) ? '0'+date.getMinutes() : date.getMinutes()
var seconds = (date.getSeconds()%10>=0) ? '0'+date.getSeconds() : date.getSeconds()
return date.getFullYear()+''+month+''+day
}
class MemberListTab extends Component {
constructor(props){
super(props)
}
componentDidMount(){
$('.memberList').get(0).addEventListener('scroll',this.props.removeTagBox)
}
render(){
const {
actions,
keyForMember,
changeKeyForMember,
memberList,
tagEdit,
groupId,
searchKey,
selectRoom,
setIdForLabel,
selectRoomType,
groupCode
} = this.props
return (
<div className='gm-memberWrapper'>
<SearchBox focusColor = '#F8F8F9' blurColor = '#F8F8F9' searchKey = {actions.searchKeyInMember} inputValue={keyForMember} changeKeyForMember={changeKeyForMember}/>
<MemberList memberList = {memberList}
tagEdit = {tagEdit}
groupId = {groupId}
selectMemberId = {actions.selectMemberId}
searchKey = {searchKey}
selectRoom = {selectRoom}
pullSingleMesgById = {actions.pullSingleMesgById}
setIdForLabel = {setIdForLabel}
selectRoomType={selectRoomType}
groupCode={groupCode}
/>
</div>
)
}
}
const HandleInnerBox = ({
currentId,
memberList,
groupId,
actions,
tagEdit,
searchKey,
selectRoom,
setIdForLabel,
microTaskList,
cwList,
keyForMember,
changeKeyForMember,
hotTip,
changeHotTip,
hotTipIcon,
taskTip,
changeTaskTip,
groupList,
userInfo,
removeTagBox,
selectRoomType,
socket
}) => {
const searchKeyForTask = (value) => {
// changeTaskTip();
let url = API_PATH+'/taskadminapi/authsec/v2/group/task'
const params = {
"currentPage": 0,
"groupId": groupId,
"pageSize": 20,
"keySearch":value
}
AuthProvider.getAccessToken()
.then((resolve, reject) => {
promiseXHR(url, {
type: 'Bearer',
value: resolve
}, params, 'POST')
.then((res) => {
const data = JSON.parse(res)
// console.log(data)
actions.pullMicroTask(value,data)
$('.rightBox').scrollTop(0)
changeTaskTip();
})
})
}
const scrollForTask = (callback) => {
if(microTaskList.currentPage == microTaskList.totalPage-1){
setTimeout(()=>{
callback()
},1500)
return
}
let url = API_PATH+'/taskadminapi/authsec/v2/group/task'
const params = {
"currentPage": microTaskList.currentPage+1,
"groupId": groupId,
"pageSize": 20,
"keySearch":microTaskList.searchKey
}
setTimeout(()=>{
AuthProvider.getAccessToken()
.then((resolve, reject) => {
promiseXHR(url, {
type: 'Bearer',
value: resolve
}, params, 'POST')
.then((res) => {
callback&&callback()
const data = JSON.parse(res)
// console.log(data)
actions.addMicroTask(data)
})
})
},1000)
}
const queryNewCwList = (pageInfo,content) => {
if(pageInfo.totalPage!==undefined&&pageInfo.currentPage+1>=pageInfo.totalPage){
return {
pageInfo: pageInfo,
resultContent:[]
}
}
if(pageInfo.totalPage!==undefined&&pageInfo.currentPage+1<pageInfo.totalPage){
// 滚动加载
pageInfo.currentPage +=1
}
const url = API_PATH+"/knowledge-base/authsec/knowledgelistmsg?_currentPage="+pageInfo.currentPage+"&_pageSize="+pageInfo.pageSize
let params = {
content: content
}
return AuthProvider.getAccessToken()
.then((resolve, reject) => {
return promiseXHR(url, {
type: 'Bearer',
value: resolve
}, params, 'POST')
}).then((res) => {
return JSON.parse(res)
})
}
// const queryOldCwList = (page_info,content) => {
// if((page_info.total_page!==undefined&&page_info.current_page+1>=page_info.total_page)||content.trim()==''){
// return {
// page_info: page_info,
// resultContent:[]
// }
// }
// if(content.trim()==''){
// return {
// page_info: page_info,
// resultContent:[]
// }
// }
// if(page_info.total_page!==undefined&&page_info.current_page+1<page_info.total_page){
// // 滚动加载
// page_info.current_page +=1
// }
// const url = API_PATH + "/content-api/noauth/content/knowledge/query/"
// let user_id = groupList.targetGroup.robotGroupMemList==undefined||groupList.targetGroup.robotGroupMemList[0]==undefined
// ?userInfo.info.userinfo.userId
// :groupList.targetGroup.robotGroupMemList[0].imMemId
// const timestamp = parseInt(new Date().getTime()/1000)
// let paramas = {
// "birthday": "",
// "current_page": page_info.current_page,
// "knowledge_type": ["Q&A 问答", "知识卡"],
// "lib_name": ["栗子知识库", "惠氏知识库", "段涛知识库","好奇知识库"],
// "page_size": page_info.page_size,
// "question": content,
// "timestamp": timestamp,
// "user_id": user_id
// }
// return AuthProvider.getAccessToken()
// .then((resolve, reject) => {
// return promiseXHR(url, {
// type: 'Bearer',
// value: resolve
// }, paramas, 'POST')
// }).then((res) => {
// return JSON.parse(res)
// })
// }
const initKW = () =>{
const url = API_PATH+"/knowledge-base/authsec/knowledgelistmsg?_currentPage=0&_pageSize=20"
let paramas = {
content: ''
}
AuthProvider.getAccessToken()
.then((resolve, reject) => {
promiseXHR(url, {
type: 'Bearer',
value: resolve
}, paramas, 'POST')
.then((res) => {
const data = JSON.parse(res)
actions.pullHotCwList(data)
$('.gm-kmBaseWrapper').scrollTop(0)
changeHotTip()
})
})
}
const searchKeyForKW = (value) => {
// 防止出现空搜索
queryNewCwList({currentPage:0,pageSize:20},value).then((oldCwList)=>{
oldCwList.resultContent = oldCwList.resultContent.map(v => ({
...v,
publicFlag: true
}))
let data = {}
// data.pageInfo = newCwList.pageInfo
data.page_info = oldCwList.page_info
data.resultContent = oldCwList.resultContent
actions.pullCwList(value,data)
$('.gm-kmBaseWrapper').scrollTop(0)
changeHotTip();
})
// AuthProvider.getAccessToken()
// .then((resolve, reject) => {
// promiseXHR(url, {
// type: 'Bearer',
// value: resolve
// }, paramas, 'POST')
// .then((res) => {
// const data = JSON.parse(res)
// actions.pullCwList(value,data)
// $('.gm-kmBaseWrapper').scrollTop(0)
// changeHotTip();
// })
// })
}
const scrollForKW = (callback) => {
if(cwList.pageInfo.currentPage == cwList.pageInfo.totalPage-1&&cwList.page_info.currentPage==cwList.page_info.totalPage-1){
setTimeout(()=>{
callback()
},1500)
return
}
// let url = `${API_PATH}/articlemgmt/authsec/knowledgelistmsg?_currentPage=${cwList.pageInfo.currentPage+1}&_pageSize=20`
// let paramas = {
// "content": cwList.searchKey,
// }
setTimeout(()=>{
Promise.all([queryNewCwList(cwList.pageInfo,cwList.searchKey)]).then(([newCwList])=>{
// oldCwList.resultContent = oldCwList.resultContent.map(v => ({
// ...v,
// publicFlag: true
// }))
let data = {}
data.pageInfo = newCwList.pageInfo
// data.page_info = oldCwList.page_info
data.resultContent = newCwList.resultContent
callback&&callback()
actions.addCwList(data)
})
// AuthProvider.getAccessToken()
// .then((resolve, reject) => {
// promiseXHR(url, {
// type: 'Bearer',
// value: resolve
// }, paramas, 'POST')
// .then((res) => {
// callback&&callback()
// const data = JSON.parse(res)
// actions.addCwList(data)
// })
// })
},1000)
}
return (
<div className="gm-memberWrapper-outer">
{
currentId==0?
<MemberListTab
actions={actions}
keyForMember={keyForMember}
changeKeyForMember={changeKeyForMember}
memberList={memberList}
tagEdit={tagEdit}
groupId={groupId}
searchKey={searchKey}
selectRoom={selectRoom}
setIdForLabel={setIdForLabel}
removeTagBox={removeTagBox}
selectRoomType={selectRoomType}
groupCode={groupList.targetGroup.code}
/>
:currentId==1?<div className='gm-memberWrapper'>
<SearchBoxForCW focusColor = '#F8F8F9' blurColor = '#F8F8F9' searchKey = {searchKeyForKW} inputValue={cwList.searchKey}/>
<KnowledgeBase cwList={cwList} scrollEvent={scrollForKW} hotTip={hotTip} changeHotTip={changeHotTip} hotTipIcon={hotTipIcon} groupList={groupList} initKW={initKW} userInfo={userInfo} memberList={memberList} selectRoomType={selectRoomType} socket={socket}/>
</div>
:currentId==2?<div className='gm-memberWrapper'>
<SearchBoxForMT focusColor = '#F8F8F9' blurColor = '#F8F8F9' searchKey = {searchKeyForTask} inputValue={microTaskList.searchKey}/>
<MicroTaskWrapper scrollEvent={scrollForTask} microTaskList={microTaskList} actions={actions} taskTip={taskTip} changeTaskTip={changeTaskTip} groupId={groupId}/>
</div>
:''
}
</div>
)
}
export default HandleInnerBox
|
function num1(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=1;
else
document.design.input.value=document.design.input.value+1;
}
function num2(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=2;
else
document.design.input.value=document.design.input.value+2;
}
function num3(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=3;
else
document.design.input.value=document.design.input.value+3;
}
function num4(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=4;
else
document.design.input.value=document.design.input.value+4;
}
function num5(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=5;
else
document.design.input.value=document.design.input.value+5;
}
function num6(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=6;
else
document.design.input.value=document.design.input.value+6;
}
function num7(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=7;
else
document.design.input.value=document.design.input.value+7;
}
function num8(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=8;
else
document.design.input.value=document.design.input.value+8;
}
function num9(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=9;
else
document.design.input.value=document.design.input.value+9;
}
function num0(){
if(parseInt(document.design.input.value)==0)
document.design.input.value=0;
else
document.design.input.value=document.design.input.value+0;
}
function cancel(){
document.design.input.value = 0;
}
function plusorminus(){
if(document.design.input.value.length==0){
document.design.input.value=0;
}
else{
document.design.input.value= parseFloat(document.design.input.value)*-1;
}
}
function percen(){
const string=document.design.input.value;
const arr1=string.split("");
if(arr1.pop()=="%"){
document.design.input.value=document.design.input.value
}else{
document.design.input.value=document.design.input.value+"%";
}
}
function devide(){
const string=document.design.input.value;
const arr1=string.split("");
if(arr1.pop()=="/"){
document.design.input.value=document.design.input.value
}else{
document.design.input.value=document.design.input.value+"/";
}
}
function multi(){
const string=document.design.input.value;
const arr1=string.split("");
if(arr1.pop()=="*"){
document.design.input.value=document.design.input.value
}else{
document.design.input.value=document.design.input.value+"*";
}
}
function sub(){
const string=document.design.input.value;
const arr1=string.split("");
if(arr1.pop()=="-"){
document.design.input.value=document.design.input.value
}else{
document.design.input.value=document.design.input.value+"-";
}
}
function add(){
const string=document.design.input.value;
const arr1=string.split("");
if(arr1.pop()=="+"){
document.design.input.value=document.design.input.value
}else{
document.design.input.value=document.design.input.value+"+";
}
}
function del(){
const string=document.design.input.value;
const arr1=string.split("");
if(arr1.length==1)
{
document.design.input.value=0;
}else{
delete arr1.pop();
document.design.input.value=arr1.join("");
}
}
function leftb(){
document.design.input.value=document.design.input.value+"(";
}
function rightb(){
document.design.input.value=document.design.input.value+")";
}
function point(){
const string=document.design.input.value;
const arr1=string.split("");
if(arr1.pop()=="."){
document.design.input.value=document.design.input.value
}else{
document.design.input.value=document.design.input.value+".";
}
}
|
export default [
// Welcome.
{
path: '/',
component: require('./pages/welcome').default,
},
// Request.
{
path: '/:id',
name: 'request',
component: require('./pages/request').default,
},
// Response.
{
path: '/eg/:id',
name: 'response',
component: require('./pages/response').default,
},
// Catch all.
{
path: '*',
name: 'catch-all',
component: require('./pages/404').default,
},
];
|
besgamApp
.controller('dataBanner', function( $scope, $http, dataFactory )
{
dataFactory.getDataJson().then( function( json )
{
dataFactory.getDataFeed().then( function( feed )
{
/* Ordenación por orden de importancia de las casas de apuestas */
var feedOrder = [];
for( it in feed.data )
{
if( Number(feed.data[it].id_feed) )
feedOrder[ feed.data[it].n_order ] = Number(feed.data[it].id_feed);
};
function feedOrdered()
{
var orderFeed = function( a, b )
{
return ( feedOrder.indexOf( a ) < feedOrder.indexOf( b ) ) ? -1 :
( feedOrder.indexOf( a ) > feedOrder.indexOf( b ) ) ? 1 : 0;
};
return function( a, b )
{
return ( a['n_odd'] < b['n_odd'] ) ? 1 :
( a['n_odd'] > b['n_odd'] ) ? -1 :
orderFeed( a['id_feed'], b['id_feed'] );
}
}
dataFactory.getDataBanner().then( function( banner )
{
/* Instanciamos variables */
var exit = false,
infoBanner = [],
find = 0,
data = [];
/* Recorremos los id banner */
banner.data.map( function( item )
{
infoBanner.push( item.id_event );
});
for( var nCont = 0, len = json.data.length;
nCont < len && !exit;
nCont++ )
{
if( infoBanner.indexOf(json.data[nCont].id) != -1 )
{
var players = [],
playersName = [],
list_bets = [];
/* Creamos los escudos y nombres */
if( json.data[nCont].shields )
{
playersName = json.data[nCont].event.split(" vs ");
players = [
{name: playersName[0], image: json.data[nCont].shields[0] },
{name: playersName[1], image: json.data[nCont].shields[1] }
];
}
/* Creamos las cuotas */
if( json.data[nCont].markets )
{
var bets = json.data[nCont].markets.str_bet;
for(var index in bets)
{
/* Definimos su posición */
var pos = index == '1' ? 0 : index == 'X' ? 1 : index == '2' && bets.length == 2 ? 1 : 2;
/* Ordenamos las casas */
bets[index].sort( feedOrdered() );
/* Añadimos los datos */
list_bets[ pos ] = {
name: index,
odd: bets[index][0].n_odd,
namefeed: feed.data[bets[index][0].id_feed].str_feed,
feed: bets[index][0].id_feed,
txtimage: feed.data[bets[index][0].id_feed].str_image,
title: index == 'X' ? 'Empate' : playersName[ parseInt(index)-1 ]
};
}
}
/* Creamos el destacado */
data[infoBanner.indexOf(json.data[nCont].id)] = {
idevent: json.data[nCont].id,
id_market_type: banner.data[infoBanner.indexOf(json.data[nCont].id)].id_market_type,
name: json.data[nCont].event,
time: json.data[nCont].time,
idleague: json.data[nCont].leagueID,
league: json.data[nCont].league,
sport: json.data[nCont].sport,
idsport: json.data[nCont].sportID,
players: players,
list_bets: list_bets,
url: json.data[nCont].url
};
/* Si tenemos todos los destacados salimos del loop */
if( ++find == infoBanner.length ) exit = true;
}
}
/* Salida al data binding */
$scope.data = data.filter(Boolean);
});
});
});
});
|
var Hornet = UFX.Thing()
.addcomp(WorldBound)
.addcomp(PortalUser)
.addcomp(HasStates, ["think", "draw"])
var HornetStates = {}
HornetStates.sway = UFX.Thing()
|
history = exports.history = function() {
this.cache = [];
this.push = function (url){
if (this.contains(url))return;
this.cache.push(url);
}
this.contains= function (obj){
for(var i in this.cache){
if(obj===this.cache[i]){
return true;
}
}
return false;
}
this.dump= function(){
for(var i in this.cache){
console.log(this.cache[i]);
}
}
}
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import './TodoItem.css';
const TodoItem = (props) => {
let listClasses = classnames(
'list-group-item -todo-item',
{
'-edit-mode': props.onEditMode === props.details.id
}
);
let textContainerClasses = classnames(
'text-container -todo-item',
{
'-edit-mode': props.onEditMode === props.details.id
}
);
const setInputToFocus = (input) => {
if(input && props.onEditMode === props.details.id) {
console.log(input);
input.focus();
input.setSelectionRange(input.value.length, input.value.length);
}
};
return (
<li className={listClasses}>
<div className="checkbox-container">
<input type="checkbox" className="checkbox" value={props.details.id} onChange={() => props.handleToggleTodo(props.details)} checked={props.todoDone} disabled={props.isUpdating === props.details.id} />
</div>
<div className={textContainerClasses}>
<span className="text" onDoubleClick={()=> props.handleEditMode(props.details)}>{props.details.text}</span>
<input type="text"
ref={setInputToFocus}
className="form-control"
value={props.todoText}
onChange={props.handleInputChange}
onKeyDown={props.handleKeyPress}
onBlur={props.handleEditBlur} disabled={props.isUpdating === props.details.id} />
</div>
<div className="actions -todo-item">
<button className="btn btn-danger" onClick={() => props.onTriggerDelete(props.details)} disabled={props.isUpdating === props.details.id}><i className="fa fa-trash"></i></button>
</div>
</li>
)
};
TodoItem.propTypes = {
status: PropTypes.string,
value: PropTypes.object,
details: PropTypes.object,
handleToggleTodo: PropTypes.func,
handleEditMode: PropTypes.func,
handleDeleteTodo: PropTypes.func,
handleInputChange: PropTypes.func,
handleKeyPress: PropTypes.func,
handleEditBlur: PropTypes.func,
todoText: PropTypes.string
};
export default TodoItem;
|
import * as firebase from 'firebase';
import { firebase as firebaseConfig } from 'config';
const firebaseApp = firebase.initializeApp(firebaseConfig);
const db = firebase.database();
const cachePath = "public-cache/truffle-contracts/"
// TODO: Add Encryption here
// to hide contract data from firebase...
// store encryption key in a contract with owner
// https://github.com/cisco/node-jose
// https://github.com/OR13/JOE
// not sure if i trust this...
const hashCode = (s) => {
return s.split("")
.reduce((a, b) => {
a = ((a << 5) - a) + b.charCodeAt(0);
return a & a;
}, 0);
}
export const resolveKeyType = (key) => {
return (typeof key === 'string') ? key : hashCode(JSON.stringify(key));
}
export const getItem = async (key) => {
let resolvedKey = resolveKeyType(key);
return db.ref(cachePath + resolvedKey)
.once('value')
.then((snapshot) => {
let obj = snapshot.val();
return obj;
});
}
export const setItem = async (key, value) => {
let resolvedKey = resolveKeyType(key);
return db.ref(cachePath + resolvedKey)
.set(value);
}
|
'use strict';
/* @ngInject */
function HomeController($scope, firebaseFactory, $firebaseObject) {
const rootRef = firebaseFactory.database().ref().child('angular');
const ref = rootRef.child('object');
$scope.object = $firebaseObject(ref);
}
module.exports = HomeController;
|
// Copyright IBM Corp. 2015. All Rights Reserved.
// Node module: loopback-getting-started-intermediate
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
/* global angular */
angular
.module('app', [
'ui.router',
'lbServices'
])
.config(['$stateProvider', '$urlRouterProvider', function($stateProvider,
$urlRouterProvider) {
$stateProvider
.state('add-handcraft', {
url: '/add-handcraft',
templateUrl: 'views/handcraft-form.html',
controller: 'AddHandcraftCtrl',
autenticate: true
})
.state('all-handcraft', {
url: '/all-handcraft',
templateUrl: 'views/home.html',
controller: 'AllHandcraftCtrl'
})
.state('view-details', {
url: '/view-details/:id',
templateUrl: 'views/view-details.html',
controller: 'ViewDetailsCtrl'
})
.state('my-handcrafts', {
url: '/my-handcrafts',
templateUrl: 'views/my-handcrafts.html',
controller: 'MyHandcraftsCtrl',
autenticate: true
})
.state('my-favorites', {
url: '/my-favorites',
templateUrl: 'views/my-favorites.html',
controller: 'MyFavoritesCtrl',
authenticate: true
})
.state('delete-handcraft', {
url: '/delete-handcraft/:id',
controller: 'DeleteHandcraftCtrl',
authenticate: true
})
.state('delete-favorite', {
url: '/delete-favorite/:id',
controller: 'DeleteFavoriteCtrl',
authenticate: true
})
.state('edit-handcraft', {
url: '/edit-handcraft/:id',
templateUrl: 'views/handcraft-form.html',
controller: 'EditHandcraftCtrl',
authenticate: true
})
.state('msn-nothing', {
url: '/msn-nothing',
templateUrl: 'views/msn-nothing.html',
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'AuthLoginController'
})
.state('logout', {
url: '/logout',
controller: 'AuthLogoutController'
})
.state('sign-up', {
url: '/sign-up',
templateUrl: 'views/sign-up-form.html',
controller: 'SignUpController'
})
.state('sign-up-success', {
url: '/sign-up/success',
templateUrl: 'views/sign-up-success.html'
});
$urlRouterProvider.otherwise('all-handcraft');
//.............................................................end
/* .state('add-comment', {
url: '/add-comment',
templateUrl: 'views/comment-form.html',
controller: 'AddCommentController',
authenticate: true
})
.state('edit-comment', {
url: '/edit-comment/id',
templateUrl: 'views/comment-form.html',
controller: 'EditCommentController',
authenticate: true
})
.state('delete-comment', {
url: '/delete-comment/:id',
controller: 'DeleteCommentController',
authenticate: true
})
.state('forbidden', {
url: '/forbidden',
templateUrl: 'views/forbidden.html'
})
.state('login', {
url: '/login',
templateUrl: 'views/login.html',
controller: 'AuthLoginController'
})
.state('logout', {
url: '/logout',
controller: 'AuthLogoutController'
})
.state('sign-up', {
url: '/sign-up',
templateUrl: 'views/sign-up-form.html',
controller: 'SignUpController'
})
.state('sign-up-success', {
url: '/sign-up/success',
templateUrl: 'views/sign-up-success.html'
});
$urlRouterProvider.otherwise('all-handcraft');
*/
}])
.run(['$rootScope', '$state', function($rootScope, $state) {
$rootScope.$on('$stateChangeStart', function(event, next) {
//redirect to login page if not logged in
if (next.authenticate && !$rootScope.currentUser) {
event.preventDefault(); //prevent current page from loading
$state.go('forbidden');
}
});
}]);
|
#!/usr/bin/env node
var Express = require('express');
var HTTP = require('http');
var Path = require('path');
require('../lib/config').service('authn').complete();
var app = Express();
var server = HTTP.createServer(app);
// app.set('trust proxy', 'localhost');
app.set('view engine', 'jade');
app.set('views', Path.resolve(__dirname, '../template'));
require('../lib/mw/events').attach(app);
require('../lib/mw/log').attach(app);
require('../lib/mw/favicon').attach(app, Path.resolve(__dirname, '../asset/favicon.ico'));
require('../lib/mw/session').attach(app);
require('../lib/control/authn')
.attach(app)
.providers(app)
.enforce(app);
require('../lib/mw/proxy').attach(app, Config.get('router:service'));
require('../lib/model').sync();
server.listen(Config.get('authn:service:port'),
Config.get('authn:service:hostname'),
function() {
console.log('AuthN: Service listening on ' + server.address().address +
':TCP/' + server.address().port);
});
|
const mongoose = require('mongoose');
const schema = mongoose.Schema;
const userSchema = new schema({
contact:{type:String , required:true},
userName:{type:String , required:true},
imgID:{type:String , default:''},
imgUrl:{type:String , default:''},
Token:{type:Number},
status:{type:Boolean },
publicId:{type:mongoose.SchemaTypes.ObjectId}
})
module.exports = mongoose.model('user', userSchema);
|
const koa = require('koa')
const path = require('path')
const moduleAlias = require('module-alias')
const serve = require('koa-static');
const errorHandle = require('./middleware/errorHandles')
moduleAlias.addAliases({
'@root': __dirname,
'@views': __dirname + '/web/views',
'@config': __dirname + '/config',
'@controllers': __dirname + '/controllers',
'@middleware': __dirname + '/middleware',
'@components': __dirname + '/web/components',
'@assets': __dirname + '/web/assets',
})
const router = require('@controllers/index')
const {
historyApiFallback
} = require('koa2-connect-history-api-fallback');
const {
port
} = require('@config/index')
const co = require('co')
const swig = require('koa-swig')
const app = new koa()
errorHandle.error(app)
let path1 = path.join(__dirname, '../web/assets')
app.use(serve(path1));
app.use(historyApiFallback({
index: '/',
whiteList: ['/books']
}));
let path2 = path.join(__dirname, '../web/views')
console.log(path2, '5555555555', path1);
app.context.render = co.wrap(
swig({
root: path2,
autoescape: true,
cache: 'memory', // disable, set to false
ext: 'html',
})
)
router(app)
app.listen(port)
|
import { Router } from 'express'
import { getTasks, getTasksCount, getTask, saveTask, updateTask, deleteTask } from '../controllers/tasks.controller'
const router = Router();
router.get('/', getTasks);
router.get('/count', getTasksCount);
router.get('/:id', getTask);
router.post('/', saveTask);
router.delete('/:id', updateTask);
router.put('/:id', deleteTask);
export default router;
|
import Vue from 'vue';
import ElementUI from 'element-ui';
import App from './ele.vue';
Vue.use(ElementUI)
new Vue({
el: '#app',
components: {
'app': App
}
})
|
/**
* this file also contains some general use functions
*/
//unloaded bar
/*document.addEventListener('readystatechange', () => {
if(document.readyState == 'complete') {
document.getElementById('progressBar').style.display = 'none';
}
});
window.addEventListener('beforeunload', (event) => {
document.getElementById('progressBar').style.display = 'inline';
});*/
//test if the suer ask the cookie question
/*var cookieasker = document.getElementById('cookie_asked');
if (Cookies.get('robingan.org_isAnswered') == undefined) {
cookieasker.style.display = "block";
}*/
//if the user response the cookie question
function replyCookie(reply) {
var cookieasker = document.getElementById('cookie_asked');
if (reply) {
Cookies.set("robingan.org_isAnswered", "true", { expires: 66 });
} else {
Cookies.set("robingan.org_isAnswered", "false", { expires: 66 });
}
cookieasker.classList.add('gone');
setTimeout(() => {
cookieasker.style.display = "none";
}, 200);
}
function trySub(obj) {
let id_ = obj.id;
let email = document.getElementById(id_ + '_email').value;
addSubscriber(email, id_);
}
function addSubscriber(subEmail, id_input) {
$.ajax({
url: "/php/addSubscriber.php",
method:"POST",
data:{
subEmail: subEmail
},
success: (result) => {
if (result != "short"){
$("#" + id_input).addClass("active");
$("#" + id_input).html(result);
$("#" + id_input + '_email').addClass("active");
}
},
error: (xhr, status, error)=>{
$(id_input).html(error);
}
});
}
function addOneView(name, type) {
return Promise.resolve($.ajax({
url: "/php/addOneView.php",
method: "POST",
data: {
name: name,
type: type
}
}));
}
/** project and media functions */
function setScroll(isScroll) {
if (typeof(Storage) !== "undefined") {
let despage = document.getElementById('projectDesPage');
if(location.hash.length > 0) {
if(isScroll) {
let scrollby = localStorage.getItem(location.hash + "_project");
const int = setInterval(()=> {
despage.scrollTo(0, scrollby);
},10)
setTimeout(()=> {
clearInterval(int);
}, 200);
} else {
despage.scrollTo(0, 0);
}
}
}
}
function onScroll(){
let scrollVal = document.getElementById('projectDesPage').scrollTop;
localStorage.setItem(location.hash+"_project", scrollVal);
//console.log(location.hash+"_project", scrollVal);
/*if (ele.scrollTop > 120){
//document.getElementById('projectDesPage-title').classList.add('h1Fixed');
//document.getElementById('projectDesPage-menu').classList.add('ulFixed');
} else {
//document.getElementById('projectDesPage-menu').classList.remove('ulFixed');
//document.getElementById('projectDesPage-title').classList.remove('h1Fixed');
}*/
}
/**------------------------------ */
function closeNews() {
let btnn = document.getElementById('news_subscribe_button');
btnn.classList.remove('active');
btnn.innerText = "Subscribe";
document.getElementById('news_subscribe_button_email').classList.remove('active');
document.getElementById('modal_cover').style.display = "none";
let move = document.getElementById('lastest_news');
let top = parseInt(move.style.top);
let height = parseInt(move.style.height);
move.style.transform = "translateY(" + -1 * window.innerHeight + "px)";
setTimeout(() => {
document.getElementById('lastest_news').style.display = "none";
}, 200);
var date_ = document.getElementById('news_date').innerText;
Cookies.set("robingan.org_isSeenNews", date_, { expires: 66 });
}
function loadLastestNews(){
fetch('/data/mediaData.xml').then((res) => {
res.text().then((xml) => {
let parser = new DOMParser();
let globalXAM = parser.parseFromString(xml, 'text/xml');
let eleList = globalXAM.getElementsByTagName('table');
let date = eleList[0].getElementsByTagName('date')[0].firstChild.nodeValue;
let title = eleList[0].getElementsByTagName('title')[0].firstChild.nodeValue;
let des = eleList[0].getElementsByTagName('des')[0].firstChild.wholeText;
let link = eleList[0].id;
document.getElementById('news_title-title').innerText = title;
document.getElementById('news_date').innerText = date;
document.getElementById('news_content_text-content').innerHTML = des;
document.getElementById('lastestNewsLink').href = "/media/#" + link;
});
});
}
function openNew() {
removeDoesNotSupport();
let move = document.getElementById('lastest_news');
if (Cookies.get('robingan.org_isSeenNews') == undefined ||
document.getElementById('news_date').innerText != Cookies.get('robingan.org_isSeenNews')) {
move.classList.add('show');
document.getElementById('modal_cover').style.display = "block";
} else {
move.style.display = "none";
}
}
function filterLinks2(link) {
if(link == 'localhost' || link == '') {
return 'robingan.com';
}
if(link.split(':').includes('mailto')) {
return 'email';
}
return link;
}
function filterLinks(llink) {
if(llink.includes('https://')) {
llink = llink.substring(8, llink.length);
return filterLinks2(llink.split('/')[0]);
}
if(llink.includes('http://')) {
llink = llink.substring(7, llink.length);
return filterLinks2(llink.split('/')[0]);
}
return filterLinks2(llink);
}
function links() {
if(!isMobile()) {
let links = document.getElementsByTagName('A');
for(let i=0; i<links.length;i++) {
links[i].addEventListener('mousemove', (e)=> {
let back = hasLink(e.target);
let mit = document.getElementById('mit');
if(back[0]) {
mit.style.top = e.clientY-mit.clientHeight-5 + 'px';
mit.style.left = e.clientX+5 + 'px';
mit.innerText = filterLinks(back[1]);
}
});
}
window.addEventListener('mouseover', (e)=> {
let mit = document.getElementById('mit');
if(e.target.id != 'mit' && hasLink(e.target)[0]) {
mit.style.display = 'inline';
} else {
mit.style.display = 'none';
}
});
}
}
function hasLinkParent(ele) {
if((ele.tagName == 'A') && ele.href != undefined && ele.href != '') {
return [true, ele.href];
}
if(ele.parentNode == undefined) {
return [false, undefined];
}
return hasLink(ele.parentNode);
}
function hasLinkChild(ele) {
if((ele.tagName == 'A') && ele.href != undefined && ele.href != '') {
return [true, ele.href];
}
if(ele.childNode == undefined || ele.childNode.length == 0 || ele.childNode.length > 1 ) {
return [false, undefined];
}
return hasLink(ele.childNode[0]);
}
function hasLink(ele) {
let child = hasLinkChild(ele);
if(child[0]) {
return child;
} else {
let parent = hasLinkParent(ele);
if(parent[0]) {
return parent;
} else {
return [false, undefined];
}
}
}
/**
* check if the user is on mobile or ipad
*/
function isMobile() {
if (/iPhone|iPad|iPodMobi|Android/i.test(navigator.userAgent)) {
return true;
}
return false;
}
function checkBrower(){
if (!isMobile()){
var test = function (reg) {
return reg.test(window.navigator.userAgent);
}
switch (true) {
case test(/edge/i): return false;//misco edge
case test(/Trident/i): return false;//ie
default: return true;
}
}else{
return true;
}
}
function fliterOnlyLetter(s){
let letters = /^[A-Za-z]+$/;
let result = "";
for (var i = 0; i < s.length; i++) {
if(s.charAt(i).match(letters)){
result += s.charAt(i);
}
}
return result;
}
function removeDoesNotSupport(){
document.getElementById('doesNotSupport').classList.remove('show');
document.getElementById('doesNotSupport').style.display = "none";
}
function viewAnyWay(){
removeDoesNotSupport();
document.getElementById('modal_cover').style.display = "none";
openNew();
}
function activeDoesNotSupport(){
document.getElementById('modal_cover').style.display = "block";
document.getElementById('doesNotSupport').classList.add('show');
}
function start(){
if (checkBrower()){
openNew();
addOneView("mainview", "main");
} else{
activeDoesNotSupport();
}
}
/*
loadLastestNews();
setTimeout(()=>{
start();
},2000);*/
|
function tripWeather() {
// event.preventDefault();
var APIKey = "2f34cea018b6436c4b7a13b8a8fe8bf2";
var lat = localStorage.getItem("tripLat");
var lon = localStorage.getItem("tripLng");
console.log("lat:", lat, "lon:", lon);
var queryURL = "https://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&appid=" + APIKey;
$.ajax({
url: queryURL,
method: "GET"
}).done(function(response) {
var tempMin = ((response.main.temp_min-273.15)*1.8)+32;
var tempMax = ((response.main.temp_max-273.15)*1.8)+32;
var tempMinRD = tempMin.toFixed(0);
var tempMaxRD = tempMax.toFixed(0);
$(".cityName").append(response.name);
$(".windSpeed").append("Wind Speed: " + response.wind.speed);
$(".forecast").append("Forecast: " + response.weather[0].main);
$(".minTemp").append("Low Temp (fahrenheit): " + tempMinRD);
$(".maxTemp").append("High Temp (fahrenheit): " + tempMaxRD);
console.log("weather:", response.name, response.wind.speed, response.weather[0].main, tempMinRD, tempMaxRD);
});
};
tripWeather();
|
const cardsData = require('../Data/cards.json');
const problem3 = require('../callback3');
function cb(id) {
return cardsData[id];
}
problem3(cb, "qwsa221").then((res) => {
console.log(res);
});
|
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Defines the PriorityQueueMap and its helper prototypes.
*/
'use strict';
/**
* A map where keys can be bound to multiple values, which are given a priority.
* When you get the value of a key it returns all of the values with the highest
* priority.
*/
export class PriorityQueueMap {
/**
* Constructs the PriorityQueueMap.
*/
constructor() {
/**
* Maps the keys to an array of Bindings.
* @type {!Map<*, !Array<Binding>>}
* @private
*/
this.map_ = new Map();
}
/**
* Returns the highest priority values for the given key. Or undefined if the
* key is not bound.
* @param {*} key The key to find the value of.
* @return {undefined|!Array<*>} The highest priority values for the given
* key. Or undefined if the key is not bound.
*/
getValues(key) {
const bindings = this.getBindings(key);
return bindings && bindings.map((binding) => binding.value);
}
/**
* Returns the highest priority Bindings for the given key. Or undefined if
* the key is not bound.
* @param {*} key The key to find the binding of.
* @return {undefined|!Array<!Binding>} The highest priority Bindings for the
* given key. Or undefined if the key is not bound.
*/
getBindings(key) {
const bindings = this.map_.get(key);
if (!bindings || !bindings.length) {
return undefined;
}
let highestBindings = [bindings[0]];
let highestPriority = bindings[0].priority;
for (let i = 1, binding; (binding = bindings[i]); i++) {
if (binding.priority > highestPriority) {
highestPriority = binding.priority;
highestBindings = [binding];
} else if (binding.priority == highestPriority) {
highestBindings.push(binding);
}
}
return highestBindings;
}
/**
* Adds the given value with the associated priority to the key's priority
* queue of values.
* @param {*} key The key to bind the value to.
* @param {*} value The value to bind to the key.
* @param {number} priority The priority of the binding.
*/
bind(key, value, priority) {
let bindings = this.map_.get(key);
if (!bindings) {
bindings = [];
this.map_.set(key, bindings);
}
bindings.push(new Binding(value, priority));
}
/**
* Removes the given value with the associated priority from the key's
* priority queue of values.
* @param {*} key The key to unbind the value from.
* @param {*} value The value to unbind from the key.
* @param {number} priority The priority of the binding.
*/
unbind(key, value, priority) {
const bindings = this.map_.get(key);
if (!bindings) {
return;
}
const index = bindings.findIndex((binding) =>
binding.value === value && binding.priority === priority);
if (index != -1) {
bindings.splice(index, 1);
}
}
}
/**
* Represents a value with the given priority for use in the PriorityQueueMap.
*/
class Binding {
/**
* Constructs the binding object.
* @param {*} value The value of the binding.
* @param {number} priority The priority of the binding.
*/
constructor(value, priority) {
// We cannot allow stringified numbers because we do comparison tests.
if (isNaN(priority) || typeof priority != 'number') {
throw Error('A binding\'s priority must be a number.');
}
this.value = value;
this.priority = priority;
}
}
|
// JavaScript Document
$(function(){
//二级菜单伸缩
$(".navone").click(function(){
var $navone=$(this).parent("dd").siblings().find(".navone");
$(this).toggleClass("active").next(".navonecon").slideToggle();
$navone.removeClass("active").next(".navonecon").slideUp();
})
//三级菜单伸缩
$(".navtwo").click(function(){
var $navtwo=$(".navtwo").not(this);
$(this).toggleClass("active");
if($(this).next().is(".navtwocon")){
$(this).next(".navtwocon").slideToggle();
}else{
$(this).addClass("active");
}
$navtwo.removeClass("active").next(".navtwocon").slideUp();
})
//三级菜单选中效果
$(".navtwocon li").click(function(){
$(".navtwocon li").not(this).removeClass("active");
$(this).addClass("active");
})
// tab切换
$(".tab_hd h3").click(function(){
var $index=$(this).index();
$(this).addClass("active").siblings().removeClass("active");
$(this).parent().next(".tab_bd").children().eq($index).show().siblings().hide();
})
//菜单伸缩
$("#menuslide").click(function(){
var $logo=$(".header .logo");
var $navbox=$(".navbox");
var $mainbox=$(".main_box");
var $left=$navbox.css("left");
if(parseInt($left)==0){
$logo.stop(true,true).animate({width:"0px"},300);
$navbox.stop(true,true).animate({left:"-216px"},300);
$mainbox.stop(true,true).animate({left:"0px"},300);
}else{
$logo.stop(true,true).animate({width:"216px"},300);
$navbox.stop(true,true).animate({left:"0px"},300);
$mainbox.stop(true,true).animate({left:"216px"},300);
}
})
//省份选择
$(".discountset_operator .province_btn").click(function(event){
event.stopPropagation();
var $top=parseInt($(this).offset().top)+30;
var $left=$(this).offset().left;
$("#province_box").css({position:"fixed",top:$top,left:$left,zIndex:2000}).show();
})
//地区选择
$(".saleset_add").click(function(event){
event.stopPropagation();
var $contentW=$(this).parents(".saleset_con").width();
var $left=$(this).offset().left;
var $top=$(this).offset().top;
$(".saleset_add").siblings("dl").hide();
alert(parseInt($contentW)-parseInt($left));
if(parseInt($contentW)-parseInt($left)<472){
$(this).siblings("dl").css({left:parseInt($contentW)-parseInt($left)-472})
}else{
$(this).siblings("dl").css({left:0})
}
$(this).siblings("dl").show();
})
$(document).click(function(){
$(".saleset_nav").find("dl").hide();
});
$(".saleset_nav dl dd a").click(function(){
var $value=$(this).text();
var $str='<li><span class="saleset_name">'+$value+'</span><input type="text" class="inputtext" /><a href="javascript:" class="saleset_btn">x</a></li>';
$(this).parents("li").before($str);
})
//提醒
$("#tips").click(function(event){
event.stopPropagation();
$(this).children(".tipcon").show();
})
$(document).click(function(){
$("#tips",top.document).children(".tipcon").hide();
});
//更多菜单点击效果
$(".moreperation .moreperationbtn").click(function(){
$(this).siblings(".moreperation_con").show().parents("td").addClass("overflowautoy");
$(this).parents(".moreperation").mouseleave(function(){
$(this).find(".moreperation_con").hide();
$(this).parents("td").removeClass("overflowautoy")
})
})
//省份选择
$(".region_down").click(function(event){
event.stopPropagation();
$(this).next(".region_box").show();
})
$(document).click(function(){
$(".region_box").hide();
})
$(".region_con li").click(function(event){
var $text=$(this).text();
$(this).parents(".region_box").prev(".region_down").find("span").text($text);
})
$(".navbox .home_pannel").click(function(){
$(this).find("a").removeClass("collapsed");
$(".panel_con .panel_tit").find("a").addClass("collapsed");
})
$(".panel_con .panel_tit").click(function(){
$(".home_pannel").find("a").addClass("collapsed");
})
//二级菜单点击
$(".panel_body li").click(function(){
$(".home_pannel").find("a").addClass("collapsed");
$(".panel_body li").removeClass("current");
$(this).addClass("current").parents(".panel_body").siblings(".panel_tit").find("a").removeClass("collapsed");
})
//首页单点击
$(".home_pannel").click(function(){
$(this).find("a").removeClass("collapsed");
$(".panel_tit").find("a").addClass("collapsed");
$(".panel_body li").removeClass("current");
})
//登录输入框获得焦点
$(".logintext .text").focus(function(){
$(this).parents(".logintext").addClass("focus");
})
//登录输入框失去焦点
$(".logintext .text").blur(function(){
$(this).parents(".logintext").removeClass("focus");
})
//多选
$(".checkbox").click(function(){
$(this).toggleClass("checked");
})
//时间控件
$(".start_datetime").datetimepicker({ //开始时间
language: 'zh-TW',
format: "yyyy-mm-dd hh:ii",
autoclose: true
}).on("click",function(ev){
$(".start_datetime").datetimepicker("setEndDate", $(".end_datetime").val());
});
$(".end_datetime").datetimepicker({ //结束时间
language: 'zh-TW',
format: "yyyy-mm-dd hh:ii",
autoclose: true
}).on("click", function (ev) {
$(".end_datetime").datetimepicker("setStartDate", $(".start_datetime").val());
});
// 下拉列表控件触发
$(".select").select2();
tablelistboxHeight();
tableSize();
$(window).resize(function(){
loginHeight();
tablelistboxHeight();
tableSize();
});
$(".tablelist_tbody").scroll(function(){
//$(".tablelist_thead").scrollLeft($(this).scrollLeft());
$(".tablelist_thead").scrollLeft($(this).scrollLeft());
})
//横向滚动条
//$(".mCustomScrollbar_x").mCustomScrollbar({
// axis:"x",
// autoHideScrollbar:true,
// theme:"3d-thick",
// scrollInertia:0,
// });
//纵向滚动条
$(".mCustomScrollbar_y").mCustomScrollbar({
axis:"y", // horizontal scrollbar
scrollbarPosition:"outside",
autoHideScrollbar:true,
scrollInertia:0,
});
//$(".mCustomScrollbar_xy").mCustomScrollbar({
// axis:"yx", // horizontal scrollbar
// scrollbarPosition:"outside",
// autoHideScrollbar:true,
// scrollInertia:0,
// });
//$(".tablelist_con").mCustomScrollbar({
// axis:"yx", // horizontal scrollbar
// scrollInertia:0,
// autoHideScrollbar:true,
// callbacks:{
// whileScrolling: function(){
// if(this.mcs.direction == "y"){
// var $h=-parseInt(this.mcs.top);
// $(".tablelist_thead").css({top:$h})
// }
// } ,
// onUpdate: function(){
// setTimeout(function(){
// var $top=$("#mCSB_1_container").css("top");
// var $headtop =- parseInt($top);
// $(".tablelist_thead").css("top",$headtop);
// },50);
// }
// },
// });
//提示小工具
$('[data-toggle="tooltip"]').tooltip({
trigger:'hover',
});
//首页图表下拉列表点击效果
$(".chart_tit .dropmenu li").click(function(){
var $text = $(this).text();
$(this).addClass("current").siblings().removeClass("current");
$(this).parent(".dropmenu").siblings(".droptit").find(".text").text($text);
})
//文字无间断滚动代码,兼容IE、Firefox、Opera
if(document.getElementById("demo")){
var scrollup = new ScrollText("demo");
scrollup.LineHeight = 34; //单排文字滚动的高度
scrollup.Amount = 1; //注意:子模块(LineHeight)一定要能整除Amount.
scrollup.Delay = 10; //延时
scrollup.Start(); //文字自动滚动
scrollup.Direction = "up"; //默认设置为文字向上滚动
}
});
//alert提示信息
function alertFade(obj){
$("#"+obj).fadeIn(300);
var t=setTimeout("alertHide("+obj+")",2000);
}
//alert信息隐藏
function alertHide(obj){
$(obj).fadeOut(300);
}
//表单区域高度计算函数
function tablelistboxHeight(){
var $searchboxH=$(".search_box").outerHeight();
var $totalH=parseInt($searchboxH)+47+52;
$(".tablelistboxH").css("height","calc(100% - "+$totalH+"px)");
}
// 通用列表宽度计算
//function tableSize()
//{
// var tablelistW=$(".tablelist_tbody table").width();
// var $w=parseInt(tablelistW)-20-2;
// var $totalWidth=0;
// var $changeW=0;
// var $unchangeW=0;
// $(".tablelist_thead th").each(function(i) {
// var $thWidth=parseInt($(this).attr("width"));
// $totalWidth=$totalWidth+$thWidth;
// if($(this).is(".change")){
// $(this).css("width",$thWidth);
// $(".tablelist_tbody tr:first td").eq(i).css("width",$thWidth);
// $changeW=$changeW+$thWidth;
// }
// else{
// $(this).css("width",$thWidth);
// $(".tablelist_tbody tr:first td").eq(i).css("width",$thWidth);
// $unchangeW=$unchangeW+$thWidth;
// }
// });
// if($w>$totalWidth)
// {
// var $surplusW=$w-$unchangeW;
// $(".tablelist_thead th").each(function(i) {
// var $thWidth=parseInt($(this).attr("width"));
// if($(this).is(".change"))
// {
// var $thW=($thWidth/$changeW)*$surplusW;
// $(this).css("width",$thW);
// $(".tablelist_tbody tr:first td").eq(i).css("width",$thW);
// }
// else
// {
// $(this).css("width",$thWidth);
// $(".tablelist_tbody tr:first td").eq(i).css("width",$thW);
// }
// })
// }
//}
// 通用列表宽度计算
function tableSize()
{
var tablelistW=$(".tablelist_tbody table").innerWidth();
var $w=parseInt(tablelistW)-20-2;
var $totalWidth=0;
var $changeW=0;
var $unchangeW=0;
var $theadW=0;
$(".tablelist_thead th").each(function(i) {
var $thWidth=parseInt($(this).attr("width"));
$totalWidth=$totalWidth+$thWidth;
if($(this).is(".change")){
$(this).css("width",$thWidth);
$(".tablelist_tbody tr:first td").eq(i).css("width",$thWidth);
$changeW=$changeW+$thWidth;
}
else{
$(this).css("width",$thWidth);
$(".tablelist_tbody tr:first td").eq(i).css("width",$thWidth);
$unchangeW=$unchangeW+$thWidth;
}
});
if($w>$totalWidth)
{
var $surplusW=$w-$unchangeW;
$(".tablelist_thead th").each(function(i) {
var $thWidth=parseInt($(this).attr("width"));
if($(this).is(".change"))
{
var $thW=($thWidth/$changeW)*$surplusW;
$(this).css("width",$thW);
$(".tablelist_tbody tr:first td").eq(i).css("width",$thW);
}
else
{
$(this).css("width",$thWidth);
$(".tablelist_tbody tr:first td").eq(i).css("width",$thW);
}
})
}
var $tablebodyw=$(".tablelist_tbody").outerWidth();
$theadW=$tablebodyw;
if($(".tablelist_tbody").get(0)){
var $innerW=$(".tablelist_tbody").get(0).clientWidth;
var $outerW=$(".tablelist_tbody").get(0).offsetWidth;
var $sw=parseInt($outerW)-parseInt($innerW);
if($sw>0){
$(".tablelist_thead").width($theadW-$sw);
}else{
$(".tablelist_thead").width("100%");
}
}
}
//弹出框第一个输入框获得焦点
function inputFocus(formname){
$("form[name='"+formname+"']",top.document).find("input[type='text']").first().focus();
}
|
(function(){
var expect = chai.expect;
describe('Schroeder.Utils', function(){
it('should assign a CODECS object to Schroeder.', function(){
expect(Schroeder.CODECS).to.be.an.instanceof(Object);
});
it('should also expose a CODECS.isSupported function, and should return true for mp3 ' +
'(provided that phantom is not running tests.)', function(){
var supported = !isPhantom && Schroeder.CODECS.isSupported('mp3');
var isPhantom = /PhantomJS/.test(window.navigator.userAgent);
expect(Schroeder.CODECS.isSupported).to.be.an.instanceof(Function);
expect(supported).to.be.ok;
});
});
})();
|
import React from "react";
import { text, number } from "@storybook/addon-knobs";
import { Story, Rule, Tagline } from "storybook/assets/styles/common.styles";
import Heading from "@paprika/heading";
import ProgressBar from "../../src";
const progressBarProps = () => ({
a11yText: text("a11yText", ""),
header: text("header", "Preparing your file..."),
bodyText: text("bodyText", ""),
completed: number("completed", "20"),
});
const ExampleStory = props => (
<Story>
<Heading level={1} displayLevel={2} isLight>
ProgressBar Showcase
</Heading>
<Tagline>Use the knobs to tinker with the props.</Tagline>
<Rule />
<ProgressBar {...props} />
</Story>
);
export default () => <ExampleStory {...progressBarProps()} />;
|
import axios from "axios"
import { store } from "../redux/store"
import { verif } from "./cluster"
import { translate } from "./translate"
export const getImageTags = async({
image
})=>{
const lang = store.getState().language
const formData = new FormData()
formData.append("image",image)
const returnal = (await axios.post(
"https://api.imagga.com/v2/tags",
formData,
{
headers:{
Authorization:"Basic YWNjXzBjMjc2MDU2NjBlZGE0NjpiZWVmNjdiZGEzMDYzYzg4MzUxZmNiMTE0N2RmYmM2YQ==",
'Content-Type': 'multipart/form-data'
}
}
)).data.result.tags.filter((a,i)=>i<12).map(a=>({
percentage: a.confidence,
value: a.tag.en
}))
const verified = verif({
array: returnal
})
if(lang.current === "en") return verified
else{
let all = []
for(let val of verified){
const nw = {
...val,
originalValue: val.originalValue || val.value,
value: await translate({
from: lang.previous,
to: lang.current,
input: val.value
})
}
all=[
...all,
nw
]
}
return all
}
}
|
const express = require('express');
const app = express();
const port = 3000;
const config = {
host: 'db',
user: 'root',
password: 'root',
database: 'pfa'
};
const mysql = require('mysql')
const connection = mysql.createConnection(config);
const sql = `INSERT INTO people(name) values('Felipe Cararo')`;
connection.query(sql);
connection.end();
app.get('/', (req,res) => {
var con = mysql.createConnection({
host: 'db',
user: 'root',
password: 'root',
database: 'pfa'
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM people", function (err, result, fields) {
if (err) throw err;
let items = [];
result.forEach(element => {
items.push(element.name);
});
res.send(`<h1>Full Cycle Rocks!</h1> <br>${items.join(', ')}`);
});
});
});
app.listen(port, ()=> {
console.log(`Rodando na porta ${port}`);
})
|
import {
Box,
IconButton,
makeStyles,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Typography,
withStyles,
} from "@material-ui/core";
import { blue, indigo } from "@material-ui/core/colors";
import React, { useEffect, useState } from "react";
import PatientServices from "../Services/PatientServices";
import useFetch from "../Components/useFetch";
import Modal from "../Components/Modal";
import PatientForm from "./PatientForm";
import moment from "moment";
import ButtonControl from "../Components/Controls/ButtonControl";
import { Add, Delete, Edit } from "@material-ui/icons";
import axios from "axios";
import ConfirmDialog from "../Components/ConfirmDialog";
/**
* @author
* @function Patient
**/
const StyledTableCell = withStyles((theme) => ({
head: {
backgroundColor: indigo[800],
color: theme.palette.getContrastText(indigo[800]),
},
body: {
fontSize: 14,
},
}))(TableCell);
const StyledTableRow = withStyles((theme) => ({
root: {
"&:nth-of-type(odd)": {
backgroundColor: theme.palette.action.hover,
},
},
}))(TableRow);
const useStyles = makeStyles({
table: {
minWidth: 700,
},
});
const Patient = (props) => {
const classes = useStyles();
const [rows, setRows] = useState([]);
const [response, error, isLoading] = useFetch(
PatientServices.getAllPatients()
);
const [openModal, setOpenModal] = useState(false)
const [formTitle, setFormTitle] = useState('New Patient')
const [rowForEdit, setRowForEdit] = useState()
const [errMsg, setErrMsg] = useState()
const [confirmDialog, setConfirmDialog] = useState({
isOpen: false,
title: '',
subTitle: '',
})
useEffect(() => {
if (!isLoading) {
setRows(response.map(row=>{return {...row, id: row.patientId}}))
}
}, [isLoading, response]);
const updateRows = (newRow, deleted = false) => {
if (deleted) {
setRows(rows.filter((row) => row.id !== newRow.id))
} else if (rows.filter((item) => item.id === newRow.id).length === 0) {
setRows([...rows, newRow])
} else {
setRows((state) => {
return rows.map((row) => {
if (row.id === newRow.id) {
return { ...newRow }
}
return row
})
})
}
}
const confirmDelete = (item) => {
setConfirmDialog({
isOpen: true,
title: 'Are you sure to delete the patient?',
subTitle: "You can't undo this operation",
onConfirm: () => onDelete(item),
})
}
const onDelete = (item) => {
setConfirmDialog({ ...confirmDialog, isOpen: false })
axios(PatientServices.deletePatient(item.patientId))
.then((res) => {
if (res.status === 200) {
updateRows(item, true)
}
})
.catch((err) => {
console.log(err)
})
}
const addNewRow = () => {
setFormTitle('New Patient')
setRowForEdit(null)
setErrMsg(null)
setOpenModal(true)
}
const openForEdit = (item) => {
setRowForEdit(item)
setFormTitle('Edit Patient')
setErrMsg(null)
setOpenModal(true)
}
const addOrEdit = (row, resetForm) => {
let service = PatientServices.updatePatient(row.patientId, row)
if (row.id === 0) {
service = PatientServices.createPatient(row)
}
axios(service)
.then((res) => {
console.log(res)
if (res.status === 200) {
const newRow = res.data
newRow.id = newRow.patientId
updateRows(newRow)
setRowForEdit(null)
resetForm()
setOpenModal(false)
}
})
.catch((error) => {
const resMessage =
(error.response &&
error.response.data &&
error.response.data.message) ||
error.message ||
error.toString()
setErrMsg(resMessage)
})
}
return (
<>
<Typography variant='h6'>
Patient
</Typography>
<Modal openModal={openModal} setOpenModal={setOpenModal}>
<PatientForm
title={formTitle}
addOrEdit={addOrEdit}
errMsg={errMsg}
rowForEdit={rowForEdit}
/>
</Modal>
<TableContainer component={Paper}>
<Table className={classes.table} aria-label="customized table">
<TableHead>
<TableRow>
<StyledTableCell align="left" />
<StyledTableCell align="left" >Person Code</StyledTableCell>
<StyledTableCell align="left" >Full Name</StyledTableCell>
<StyledTableCell align="left" >Date of Birth</StyledTableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row,i) => (
<StyledTableRow key={i}>
<StyledTableCell align="left" scope="row">
<IconButton
aria-label="edit"
onClick={() =>
openForEdit(row)
}
title="Edit"
>
<Edit htmlColor={blue['A400']} />
</IconButton>
<IconButton
aria-label="delete"
onClick={() =>
confirmDelete(row)
}
title="Delete"
>
<Delete color="secondary" />
</IconButton>
</StyledTableCell>
<StyledTableCell align="left">
{row.patientId}
</StyledTableCell>
<StyledTableCell align="left" >{row.firstName} {row.lastName}</StyledTableCell>
<StyledTableCell align="left" >
{moment(row.dateOfBirth).format('DD MMM, YYYY')}
</StyledTableCell>
</StyledTableRow>
))}
</TableBody>
</Table>
</TableContainer>
<Box m={2} style={{ display: 'flex', justifyContent: 'space-between' }}>
<ButtonControl
text="Create New"
onClick={addNewRow}
startIcon={<Add />}
/>
</Box>
<ConfirmDialog
confirmDialog={confirmDialog}
setConfirmDialog={setConfirmDialog}
/>
</>
);
};
export default Patient;
|
//where all the fun begins
//if it's a KW search result page
$('form[name="searchtool"]').css({'text-align':'center'});
if (
(window.location.search.match(/(searchtype=X|\?\/X)/) && !window.location.search.match(/(frameset)|=%22|%28|%29/)) ||
window.location.href.indexOf('~S') !== -1 ||
window.location.href.indexOf('search/X') !== -1 &&
window.location.href.indexOf('frameset') === -1 &&
window.location.href.indexOf('aexact') === -1 &&
window.location.href.indexOf('indexsort') === -1 ||
window.location.pathname === '/search~S1'
) {
if ($('.reserveBibsArea').length === 0 && window.location.search.indexOf('searchtype=r') === -1 && window.location.search.indexOf('searchtype=p') === -1) {
//hide stuffs
$('form select#searchtype').hide();
//add KW search field facets
$('form[name="searchtool"]').prepend('<div class="col-sm-4 text-center" style="padding:0;"><div id="dnlFieldFacets" class="btn-group"><button type="button" id="dnlAllFacet" class="btn btn-default">All</button><button type="button" id="dnlAuthorFacet" class="btn btn-default">Author</button><button type="button" class="btn btn-default" id="dnlTitleFacet">Title</button><button type="button" id="dnlSubjectFacet" class="btn btn-default">Subject</button></div></div>');
$('#searcharg, #searchscope').css({width:'100%'}).wrap('<div class="col-sm-3">');
$('#searcharg').attr('required', 'required');
$('input[name="SUBMIT"]').wrap('<div class="text-center col-sm-1">').attr('onclick', '');
if ($('.msg:contains(Nearby)').length > 0) {
$('#searcharg').parent().addClass('col-sm-offset-2');
}
//clean up whitespace in form
$('form[name="searchtool"]').addClass('clear-fix').contents().filter(function() { return (this.nodeType == 3 && !/\S/.test(this.nodeValue)); }).remove();
//facet status
var facetUsed;
var letterLookup = {
'a': 'Author',
't': 'Title',
'd': 'Subject'
};
var searcharg = $('#searcharg').val() ? $('#searcharg').val() : '';
if (window.location.search.indexOf('searcharg=a%3A') != -1 || window.location.search.indexOf('?/Xa%3A') != -1 || searcharg.match(/a:\(.*\)/)) { //auth applied
facetUsed = 'Author';
} else if (window.location.search.indexOf('searcharg=d%3A') != -1 || window.location.search.indexOf('?/Xd%3A') != -1 || searcharg.match(/d:\(.*\)/)) { //subj applied
facetUsed = 'Subject';
} else if (window.location.search.indexOf('searcharg=t%3A') != -1 || window.location.search.indexOf('?/Xt%3A') != -1 || searcharg.match(/t:\(.*\)/)) { //title applied
facetUsed = 'Title';
} else if (searcharg.match(/[a-z]:.* [a-z]:/)) { //multiple field searched
var matches = searcharg.match(/([a-z]):\((.+?)\)(.+?)([a-z]):\((.+?)\)((.+?)([a-z]):\((.+?)\))?((.+?)([a-z]):\((.+?)\))?/);
var newhtml = '<div class="query-info">Search Terms: ';
newhtml += '<strong>' + letterLookup[matches[1]] + '</strong> (' + matches[2] + ')';
newhtml += matches[3] + '<strong>' + letterLookup[matches[4]] + '</strong> (' + matches[5] + ')';
if (matches[6]) {
newhtml += matches[7] + '<strong>' + letterLookup[matches[8]] + '</strong> (' + matches[9] + ')';
}
if (matches[10]) {
newhtml += matches[11] + '<strong>' + letterLookup[matches[12]] + '</strong> (' + matches[13] + ')';
}
newhtml += '</div>';
$('.browseSearchtoolMessage').prepend(newhtml);
$('input#searcharg').val('');
$('#dnlAllFacet').addClass('dnlApplied');
} else { //no hacked facet applied
$('#dnlAllFacet').addClass('dnlApplied');
$('td.browseHeaderData').text($('td.browseHeaderData').text().replace('Advanced Keywords','Keywords Search'));
}
if (facetUsed && $('input#searcharg').length > 0) {
$('#dnl' + facetUsed + 'Facet').addClass('dnlApplied');
$('td.browseHeaderData').text($('td.browseHeaderData').text().replace('Advanced Keywords', facetUsed + ' Keywords Search'));
var query = $('input#searcharg').val();
if (query.match(/"(.*?)"~/)) {
$('input#searcharg').val(query.match(/"(.*?)"~/)[1]);
} else if (query.match(/"(.*?)"/)) {
$('input#searcharg').val(query.match(/\((.*?)\)/)[1]);
}
}
//Apply custom keyword search
$('#dnlFieldFacets').on('click', 'button:not(.dnlApplied)', function(e) {
$('#dnlFieldFacets button').removeClass('dnlApplied');
$(this).addClass('dnlApplied');
if ($('#searcharg').val() !== '') {
$('form[name="searchtool"]').submit();
}
});
}
} else if (window.location.search.match(/\/browse|\/2browse/) && !window.location.search.match(/\?\/X/)) {
}
else {//end main if -for kw search
$('select#searchtype').show();
}
|
import { SELECT_CHARACTER_ONE } from "./action/selectCharacterOne.action";
import { SELECT_CHARACTER_ONE_WITH_STYLE_AND_COLOR } from "./action/selectCharacterOneWithSyleAndColor.action";
import { SELECT_CHARACTER_ONE_STYLE } from "./action/selectCharacterOneStyle.action";
import { SELECT_CHARACTER_ONE_COLOR } from "./action/selectCharacterOneColor.action";
import { UNSELECT_CHARACTER_ONE } from "./action/unselectCharacterOne.action";
import { SELECT_CHARACTER_TWO } from "./action/selectCharacterTwo.action";
import { SELECT_CHARACTER_TWO_WITH_STYLE_AND_COLOR } from "./action/selectCharacterTwoWithSyleAndColor.action";
import { SELECT_CHARACTER_TWO_STYLE } from "./action/selectCharacterTwoStyle.action";
import { SELECT_CHARACTER_TWO_COLOR } from "./action/selectCharacterTwoColor.action";
import { SELECT_CHARACTER_TWO_AI_LEVEL } from "./action/selectCharacterTwoAILevel.action";
import { UNSELECT_CHARACTER_TWO } from "./action/unselectCharacterTwo.action";
import { SWITCH_MODE } from "./action/switchMode.action";
import { SELECT_STAGE } from "./action/selectStage.action";
import { END_FIGHT } from "./action/endFight.action";
import selectCharacterOne from "./transition/selectCharacterOne.transition";
import selectCharacterOneWithStyleAndColor from "./transition/selectCharacterOneWithStyleAndColor.transition";
import selectCharacterOneStyle from "./transition/selectCharacterOneStyle.transition";
import selectCharacterOneColor from "./transition/selectCharacterOneColor.transition";
import unselectCharacterOne from "./transition/unselectCharacterOne.transition";
import selectCharacterTwo from "./transition/selectCharacterTwo.transition";
import selectCharacterTwoWithStyleAndColor from "./transition/selectCharacterTwoWithStyleAndColor.transition";
import selectCharacterTwoStyle from "./transition/selectCharacterTwoStyle.transition";
import selectCharacterTwoColor from "./transition/selectCharacterTwoColor.transition";
import selectCharacterTwoAILevel from "./transition/selectCharacterTwoAILevel.transition";
import unselectCharacterTwo from "./transition/unselectCharacterTwo.transition";
import switchMode from "./transition/switchMode.transition";
import selectStage from "./transition/selectStage.transition";
import endFight from "./transition/endFight.transition";
export default function navigationReducer(data, action) {
switch (action.type) {
case SWITCH_MODE:
return switchMode(data);
case SELECT_CHARACTER_ONE:
return selectCharacterOne(data, action);
case SELECT_CHARACTER_ONE_WITH_STYLE_AND_COLOR:
return selectCharacterOneWithStyleAndColor(data, action);
case SELECT_CHARACTER_ONE_STYLE:
return selectCharacterOneStyle(data, action);
case SELECT_CHARACTER_ONE_COLOR:
return selectCharacterOneColor(data, action);
case UNSELECT_CHARACTER_ONE:
return unselectCharacterOne(data);
case SELECT_CHARACTER_TWO:
return selectCharacterTwo(data, action);
case SELECT_CHARACTER_TWO_WITH_STYLE_AND_COLOR:
return selectCharacterTwoWithStyleAndColor(data, action);
case SELECT_CHARACTER_TWO_STYLE:
return selectCharacterTwoStyle(data, action);
case SELECT_CHARACTER_TWO_COLOR:
return selectCharacterTwoColor(data, action);
case SELECT_CHARACTER_TWO_AI_LEVEL:
return selectCharacterTwoAILevel(data, action);
case UNSELECT_CHARACTER_TWO:
return unselectCharacterTwo(data);
case SELECT_STAGE:
return selectStage(data, action);
case END_FIGHT:
return endFight(data);
default:
}
return data;
}
|
function h(d){
/**
* Js_regex_img_url
* coder: xiaohudie
* 2013-05-17
*/
var a=/<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim;
var b = [];
while(c=a.exec(d)){
b.push(c[2]);
}
return b;
}
var d= document.f.g.value;
///alert(e.join('\n'));
|
global.sunCalc = require('suncalc');
var moment = require('moment');
var net = require('net');
global.http = require('http');
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var tlc = require('./tlc');
var mqtt = require('mqtt');
mqttClient = mqtt.connect('mqtt://localhost');
mqttClient.subscribe('/App/Utility/MHRV/Toilet PIR On/#');
mqttClient.subscribe('/App/Utility/MHRV/Utility PIR On/#');
mqttClient.on('message', tlc.decode);
app.set('views', './views');
app.set('view engine', 'jade');
app.use(express.static(__dirname));
app.use('views', express.static(path.join(__dirname, 'views')));
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true })); // support encoded bodies
app.locals.pretty = true;
app.listen(8092);
app.get('/tlc/testPIR', tlc.testPIR);
app.get('/tlc/scenes', tlc.showScenes);
|
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route
} from "react-router-dom";
//style
import "./App.css";
//Components
import Home from "./home";
import Header from "./header";
import MyDogList from "./myDogList";
import Footer from "./footer";
import FourOhFour from "./fourOhFour";
function App() {
return (
<Router>
<Header />
<Switch>
<Route exact path="/">
<Home/>
</Route>
<Route path="/my-list">
<MyDogList/>
</Route>
<Route path="*">
<FourOhFour />
</Route>
</Switch>
<Footer />
</Router>
);
}
export default App;
|
var searchData=
[
['client',['client',['../namespaceclient.html',1,'']]]
];
|
import React from "react"
import { theme } from "../../utilis/theme"
// import post from '../../images/about-ngn.jpg'
import styled from 'styled-components'
import { Link } from "gatsby"
const ArticleContainer = styled.article`
width: 100%;
margin-bottom: 50px;
@media (min-width: 576px){
width: 48%;
}
h3 {
font-size: 1.1em;
a {
color: inherit
}
}
p {
font-size: .95em;
}
img {
width: 100%;
object-fit: cover;
height: 175px;
@media (min-width: 576px){
height: 202px;
}
}
.btn {
padding: .75em 1.5em;
font-size: .75em;
display: block;
margin-top: 20px;
width: fit-content;
}
.blog-list__bar {
display: flex;
align-items: center;
justify-content: space-between;
margin-top: 10px;
.category {
a{
color: ${theme.colors.beige};
font-size: .9em;
font-weight: 600;
margin-right: 5px;
&:after {
content:', '
}
&:last-child:after {
content: ''
}
}
}
.date {
display: flex;
align-items: center;
color: ${theme.colors.grayLight};
font-size: .8em;
/* font-weight: 600; */
svg{
margin-right: 5px;
width: 14px;
height: auto;
fill: ${theme.colors.grayLight}
}
}
}
`
const Article = ({thumbnail, categories, slug, title, date, excerpt, content}) => (
<ArticleContainer className="blog-list__item">
<Link to={`/${slug}`} className="thumbnail" >{thumbnail ? (<img src={thumbnail} alt=""/>) : null}</Link>
<div className="blog-list__bar">
<div className="category">
{categories.nodes ?
(categories.nodes.map((cat,i)=>(
<Link key={i} to={`/${cat.slug}`}>{cat.name}</Link>
))) : null}
</div>
<span className="date">
{date}</span>
</div>
<h3><Link to={`/${slug}`} className="thumbnail" >{title}</Link></h3>
<p dangerouslySetInnerHTML={{__html: excerpt.slice(0,200) + ' ...'}}></p>
<Link to={`/${slug}`} className="btn btn__beige--t">czytaj więcej</Link>
</ArticleContainer>
)
export default Article;
|
'use strict';
/* @flow */
/**
* Our default sum is the [Kahan summation algorithm](https://en.wikipedia.org/wiki/Kahan_summation_algorithm) is
* a method for computing the sum of a list of numbers while correcting
* for floating-point errors. Traditionally, sums are calculated as many
* successive additions, each one with its own floating-point roundoff. These
* losses in precision add up as the number of numbers increases. This alternative
* algorithm is more accurate than the simple way of calculating sums by simple
* addition.
*
* This runs on `O(n)`, linear time in respect to the array
*
* @param {Array<number>} x input
* @return {number} sum of all input numbers
* @example
* console.log(sum([1, 2, 3])); // 6
*/
function sum(x/*: Array<number> */)/*: number */ {
// like the traditional sum algorithm, we keep a running
// count of the current sum.
var sum = 0;
// but we also keep three extra variables as bookkeeping:
// most importantly, an error correction value. This will be a very
// small number that is the opposite of the floating point precision loss.
var errorCompensation = 0;
// this will be each number in the list corrected with the compensation value.
var correctedCurrentValue;
// and this will be the next sum
var nextSum;
for (var i = 0; i < x.length; i++) {
// first correct the value that we're going to add to the sum
correctedCurrentValue = x[i] - errorCompensation;
// compute the next sum. sum is likely a much larger number
// than correctedCurrentValue, so we'll lose precision here,
// and measure how much precision is lost in the next step
nextSum = sum + correctedCurrentValue;
// we intentionally didn't assign sum immediately, but stored
// it for now so we can figure out this: is (sum + nextValue) - nextValue
// not equal to 0? ideally it would be, but in practice it won't:
// it will be some very small number. that's what we record
// as errorCompensation.
errorCompensation = nextSum - sum - correctedCurrentValue;
// now that we've computed how much we'll correct for in the next
// loop, start treating the nextSum as the current sum.
sum = nextSum;
}
return sum;
}
module.exports = sum;
|
import React, { Component } from 'react';
import Snackbar from 'material-ui/Snackbar';
import ContactForm from 'public/components/ContactForm';
import ContactAPI from 'ContactAPI';
export default class ContactPage extends Component {
constructor (props) {
super(props);
this.state = {
errors: {},
user: { person_name: '', email: '', message: '' },
snackbar: { autoHideDuration: 4000, message: 'Message Sent, Thankyou', open: false },
loader: false,
};
}
onSubmit = (e) => {
let { user } = this.state;
e.preventDefault();
this.setState({ loader: true });
ContactAPI(user)
.then((res) =>{
if (!res.success) {
const errors = res.errors ? res.errors : {};
errors.summary = res.message;
this.setState({ errors, loader: false });
} else {
let snackbar = this.state.snackbar;
snackbar.open = true;
this.setState({ errors: {}, snackbar, loader: false });
}
});
}
onChangeFieldValue = (e) => {
const field = e.target.name;
const user = this.state.user;
user[field] = e.target.value;
this.setState({ user });
}
handleActionTouchTap = () => {
let snackbar = this.state.snackbar;
snackbar.open = false;
this.setState({ snackbar });
}
render () {
let { user, errors, loader } = this.state;
let { message, open, autoHideDuration } = this.state.snackbar;
return (
<div className="row">
<div className="col-md-6 col-md-offset-3">
<ContactForm
onSubmit={this.onSubmit}
onChange={this.onChangeFieldValue}
showProgress={loader}
errors={errors}
user={user}
/>
<Snackbar
open={open}
message={message}
action="Okay"
autoHideDuration={autoHideDuration}
onActionTouchTap={this.handleActionTouchTap}
onRequestClose={this.handleActionTouchTap}
/>
</div>
</div>
);
}
};
// export default ContactPage;
|
const { Shop } = require("../src/gilded_rose");
describe("Gilded Rose", () => {
describe("Normal Item", () => {
const name = "normal";
it("before_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 5 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(4);
expect(items[0].sellIn).toBe(9);
});
it("on_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 5 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(3);
expect(items[0].sellIn).toBe(-1);
});
it("after_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: -1, quality: 5 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(3);
expect(items[0].sellIn).toBe(-2);
});
it("of_zero_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 0 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(0);
expect(items[0].sellIn).toBe(9);
});
});
describe("Aged Brie Item", () => {
const name = "Aged Brie";
it("before_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 30 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(31);
expect(items[0].sellIn).toBe(9);
});
it("before_sell_date_with_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 50 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(50);
expect(items[0].sellIn).toBe(9);
});
it("on_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 5 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(7);
expect(items[0].sellIn).toBe(-1);
});
it("on_sell_date_near_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 44 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(46);
expect(items[0].sellIn).toBe(-1);
});
it("on_sell_date_with_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 50 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(50);
expect(items[0].sellIn).toBe(-1);
});
it("after_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: -1, quality: 5 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(7);
expect(items[0].sellIn).toBe(-2);
});
it("after_sell_date_with_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: -1, quality: 50 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(50);
expect(items[0].sellIn).toBe(-2);
});
});
describe("Sulfuras", () => {
const name = "Sulfuras, Hand of Ragnaros";
it("before_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 80 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(80);
expect(items[0].sellIn).toBe(10);
});
it("on_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 80 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(80);
expect(items[0].sellIn).toBe(0);
});
it("after_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: -2, quality: 80 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(80);
expect(items[0].sellIn).toBe(-2);
});
});
describe("Backstage", () => {
const name = "Backstage passes to a TAFKAL80ETC concert";
it("long_before_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 11, quality: 30 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(31);
expect(items[0].sellIn).toBe(10);
});
it("medium_before_sell_date_upper_bound", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 30 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(32);
expect(items[0].sellIn).toBe(9);
});
it("medium_before_sell_date_upper_bound_at_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 50 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(50);
expect(items[0].sellIn).toBe(9);
});
it("medium_before_sell_date_lower_bound", () => {
const gildedRose = new Shop([{ name, sellIn: 6, quality: 30 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(32);
expect(items[0].sellIn).toBe(5);
});
it("medium_before_sell_date_lower_bound_at_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 6, quality: 50 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(50);
expect(items[0].sellIn).toBe(5);
});
it("very_close_to_sell_date_upper_bound", () => {
const gildedRose = new Shop([{ name, sellIn: 5, quality: 30 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(33);
expect(items[0].sellIn).toBe(4);
});
it("very_close_to_sell_date_upper_bound_at_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 5, quality: 50 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(50);
expect(items[0].sellIn).toBe(4);
});
it("very_close_to_sell_date_lower_bound", () => {
const gildedRose = new Shop([{ name, sellIn: 1, quality: 30 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(33);
expect(items[0].sellIn).toBe(0);
});
it("very_close_to_sell_date_lower_bound_at_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 1, quality: 50 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(50);
expect(items[0].sellIn).toBe(0);
});
it("on_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 30 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(0);
expect(items[0].sellIn).toBe(-1);
});
it("on_sell_date_at_max_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 50 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(0);
expect(items[0].sellIn).toBe(-1);
});
it("after_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: -1, quality: 30 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(0);
expect(items[0].sellIn).toBe(-2);
});
});
describe("Conjure Item", () => {
const name = "Conjured";
it("before_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 5 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(3);
expect(items[0].sellIn).toBe(9);
});
it("on_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 5 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(1);
expect(items[0].sellIn).toBe(-1);
});
it("after_sell_date", () => {
const gildedRose = new Shop([{ name, sellIn: -1, quality: 5 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(1);
expect(items[0].sellIn).toBe(-2);
});
it("of_zero_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 10, quality: 0 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(0);
expect(items[0].sellIn).toBe(9);
});
it("of_one_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 1 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(0);
expect(items[0].sellIn).toBe(-1);
});
it("of_two_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 2 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(0);
expect(items[0].sellIn).toBe(-1);
});
it("of_three_quality", () => {
const gildedRose = new Shop([{ name, sellIn: 0, quality: 3 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(0);
expect(items[0].sellIn).toBe(-1);
});
it("of_three_quality_and_one_sellIn", () => {
const gildedRose = new Shop([{ name, sellIn: 1, quality: 3 }]);
const items = gildedRose.update();
expect(items[0].quality).toBe(1);
expect(items[0].sellIn).toBe(0);
});
});
});
|
/*global
alert, confirm, console, prompt, window
*/
var componentMaker;
var entityMaker;
var graphicsComponentMaker;
var graphicsSystemMaker;
var heroMaker;
var locationComponentMaker;
entityMaker = function () {
"use strict";
var components = {};
return Object.freeze({});
};
graphicsComponentMaker = function (spec) {
"use strict";
var entity = spec.entityOfComponent;
var component = {};
var spriteSheet = new Image();
spriteSheet.src = spec.spriteSheet;
component.draw = function (context) {
context.drawImage(spriteSheet, entity.getXLocation(), entity.getYLocation());
};
return Object.freeze(component);
};
locationComponentMaker = function (spec) {
"use strict";
var currentLocation = {
x: spec.initialX,
y: spec.initialY
};
var location = {};
location.getXLocation = function () {
return currentLocation.x;
};
location.getYLocation = function () {
return currentLocation.y;
};
return Object.freeze(location);
};
heroMaker = function () {
"use strict";
var hero = {};
var entity = entityMaker();
var graphics = graphicsComponentMaker({
entityOfComponent: hero,
spriteSheet: "hero.png"
});
var location = locationComponentMaker({
initialX: 0.5,
initialY: 0
});
var components = {
graphics: graphics,
location: location
};
hero.getXLocation = function () {
return components.location.getXLocation();
};
hero.getYLocation = function () {
return components.location.getYLocation();
};
hero.getComponents = function () {
return Object.keys(components);
};
hero.draw = function (context) {
components.graphics.draw(context);
};
return Object.freeze(hero);
};
graphicsSystemMaker = function (initialEntities, gameCanvas) {
"use strict";
var entities = initialEntities;
var graphicsSystem = {};
var canvas = gameCanvas;
var context = canvas.getContext("2d");
graphicsSystem.run = function () {
window.requestAnimationFrame(graphicsSystem.tick);
};
graphicsSystem.tick = function () {
if (canvas.width !== canvas.offsetWidth || canvas.height !== canvas.offsetHeight) {
canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;
}
context.clearRect(0, 0, canvas.width, canvas.height);
context.save();
context.translate(canvas.width / 2, canvas.height / 2);
//context.scale(canvas.height, -canvas.height);
entities.forEach(function (entity) {
if (entity.getComponents().includes("graphics")) {
entity.draw(context);
}
});
context.restore();
window.requestAnimationFrame(graphicsSystem.tick);
};
return Object.freeze(graphicsSystem);
};
document.addEventListener("DOMContentLoaded", function () {
"use strict";
var canvas = document.getElementById("canvas");
var graphics = graphicsSystemMaker([heroMaker()], canvas);
graphics.run();
});
|
'use strict';
describe('Service: Github', function () {
// load the service's module
beforeEach(module('githubExplorerApp'));
// instantiate service
var Github, $httpBackend;
beforeEach(inject(function (_Github_, _$httpBackend_) {
Github = _Github_;
$httpBackend = _$httpBackend_;
}));
it('should do something', function () {
expect(!!Github).toBe(true);
});
describe('Repos', function () {
it('get(): should get owner and repo name', function () {
$httpBackend.expectGET('https://api.github.com/repos/testUser/testRepo')
.respond({
owner: {
login: 'testUser'
},
name: 'testRepo'
});
var result = Github.Repos.get({ owner: 'testUser', repo: 'testRepo'});
$httpBackend.flush();
expect(result.owner.login).toEqual('testUser');
expect(result.name).toEqual('testRepo');
});
});
describe('Contributors', function () {
it('query(): should get an array of contributors', function () {
$httpBackend.expectGET('https://api.github.com/repos/testUser/testRepo/contributors')
.respond([
{
login: 'user1'
},
{
login: 'user2'
}
]);
var result = Github.Contributors.query({ owner: 'testUser', repo: 'testRepo' });
$httpBackend.flush();
expect(result.length).toEqual(2);
});
});
describe('UserRepos', function () {
it('query(): should get an array of repos', function () {
$httpBackend.expectGET('https://api.github.com/users/testUser/repos')
.respond([
{
name: 'repo1'
},
{
name: 'repo2'
}
]);
var result = Github.UserRepos.query({ username: 'testUser'});
$httpBackend.flush();
expect(result.length).toEqual(2);
});
});
describe('Users', function () {
it('get(): should get username and full name', function () {
$httpBackend.expectGET('https://api.github.com/users/kevcenteno')
.respond({
login: 'kevcenteno',
name: 'Kevin Centeno'
});
var result = Github.Users.get({ username: 'kevcenteno' });
$httpBackend.flush();
expect(result.login).toBe('kevcenteno');
expect(result.name).toBe('Kevin Centeno');
});
});
});
|
import React, { Component } from 'react';
import { setUser } from '../../../dux/reducer';
import axios from 'axios';
import './createGroup.scss';
import { connect } from 'react-redux';
class CreateGroup extends Component {
constructor(props){
super(props);
this.state = {
currentRoomName: '',
phone: ''
}
}
handleChange = (e) => {
this.setState({
[e.target.name]: e.target.value
})
}
sendEmail = () => {
let body = {
name: this.props.user.profile_name,
email: this.props.user.email,
group: this.state.currentRoomName
}
axios.post('/api/sendMail', body).then(response => {})
}
sendText = () => {
if (this.state.phone) {
let body = {
to: parseInt(this.state.phone),
body: `ChatNow: You have joined ${this.state.currentRoomName}!`
}
axios.post('/api/messages', body).then(res => {
console.log('text was sent');
})
}
}
joinRoom = (e) => {
let roomName = this.state.currentRoomName;
if(!roomName.length > 0){
return alert('Your group name must be contain some letters...')
}
axios.put('/api/groupCreation', {roomName}).then(res => {
this.props.setUser(res.data.user);
this.sendEmail();
this.sendText();
this.setState({
currentRoomName: '',
phone: ''
})
this.redirect();
})
}
redirect = () => {
this.props.history.goBack();
}
render() {
const { currentRoomName } = this.state;
return (
<div className='roomContainer'>
<label>JOIN OR CREATE YOUR ROOM</label>
<input onChange={this.handleChange} name='currentRoomName' value={currentRoomName}></input>
<label>ADD YOUR NUMBER FOR TEXT CONFIRMATION</label>
<input name='phone' onChange={this.handleChange} placeholder='ENTER YOUR PHONE NUMBER HERE'></input>
<button type='submit' onClick={this.joinRoom}>Join Room</button>
</div>
)
}
}
const mapStateToProps = (state) => {
return {
user: state.user
}
}
const mapDispatchToProps = {
setUser
}
export default connect(mapStateToProps, mapDispatchToProps)(CreateGroup)
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeBlogPost = exports.findBlogPostByCategory = exports.findBlogPostByPubDate = exports.findBlogPostByPath = exports.findBlogPost = exports.addBlogPost = exports.setImage = exports.postRepo = exports.buildBlogPost = exports.categoryRepo = void 0;
const useCases_1 = require("./useCases");
const BlogPostRepository_1 = require("./BlogPostRepository");
const BlogCategoryRepository_1 = require("../blogCategory/BlogCategoryRepository");
const user_1 = require("../user");
const audiosGroup_1 = require("../audiosGroup");
const imagesGroup_1 = require("../imagesGroup");
const imagesGroup_2 = require("../imagesGroup/");
exports.categoryRepo = new BlogCategoryRepository_1.BlogCategoryRepository();
exports.buildBlogPost = new useCases_1.BuildBlogPost(imagesGroup_1.imagesGroupRepository, user_1.userRepo, audiosGroup_1.audioRepo, exports.categoryRepo);
exports.postRepo = new BlogPostRepository_1.BlogPostRepository();
exports.setImage = new useCases_1.SetPostImage(imagesGroup_2.addImagesGroup, exports.postRepo);
exports.addBlogPost = new useCases_1.AddBlogPost(exports.postRepo, user_1.userRepo, exports.categoryRepo, audiosGroup_1.audioRepo);
exports.findBlogPost = new useCases_1.FindBlogPost(exports.postRepo);
exports.findBlogPostByPath = new useCases_1.FindBlogPostByPath(exports.postRepo, exports.buildBlogPost);
exports.findBlogPostByPubDate = new useCases_1.FindBlogPostByPubDate(exports.postRepo, exports.buildBlogPost);
exports.findBlogPostByCategory = new useCases_1.FindBlogPostByCategory(exports.postRepo, exports.categoryRepo);
exports.removeBlogPost = new useCases_1.RemoveBlogPost(exports.postRepo);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/* variable that contains my name */
var myName = 'Hallie';
// console.log(myName);
// constant that contains the number of states in the U.S
var states = 50;
// console.log(states);
// result of adding 5 and 4
var number = 5 + 4;
// console.log(number);
// write a function called sayHello the displays an alert that says Hello World!
function sayHello(num1, num2) {
console.log('Hello World!');
return num1 + num2;
}
sayHello(6, 8);
// fire checkAge function that checks for name and age
function firstCheckAge(name, age) {
if (age <= 20) {
alert("Sorry, " + name + ", you aren't old enough to view this page!");
}
else {
alert("You may enter, " + name);
}
}
firstCheckAge("Charles", 21);
firstCheckAge("Abby", 27);
firstCheckAge("James", 18);
firstCheckAge("John", 17);
// array of my favorite vegetables
var vegetables = ["potato", "broccoli", "edamame", "lettuce"];
for (var _i = 0, vegetables_1 = vegetables; _i < vegetables_1.length; _i++) {
var veggies = vegetables_1[_i];
console.log(veggies);
}
// create a checkage but with a loop
var array = [
{ name: "Hallie", age: 25 },
{ name: "TJ", age: 26 },
{ name: "Wendy", age: 9 },
{ name: "Jack", age: 14 },
{ name: "Mercedes", age: 21 },
];
// function checkAge(name: string, age: number) {
// for (let i = 0; i < array.length; i++) {
// if (array[i].age < 21) {
// console.log("Sorry, " + array[i].name + ", you aren't old enough to view this page!")
// } else {
// console.log("You may enter, " + array[i].name + ".")
// }
// }
// }
// checkAge(array)
// create getLength function
function getLength(str) {
if (str.length % 2 == 0) {
return ('The world is nice and even!');
}
else if (str.length % 2 != 0) {
return ('The World is an odd place!');
}
}
console.log(getLength('hello world!'));
console.log(getLength("Goodbye World!"));
|
import React, {Component} from 'react';
import './App.css';
import Clock from './Clock';
import { Form, FormControl } from 'react-bootstrap';
class App extends Component{
constructor(props){
super(props);
this.state = {
newhours:0,
newminutes:0,
newseconds: 0
}
}
render(){
return(
<div className = "App-area">
<div className = "App-title"> StopWatch Timer for : {this.state.newhours} hours {this.state.newminutes} minutes {this.state.newseconds} seconds</div>
<Clock newhours = {this.state.newhours} newminutes = {this.state.newminutes} newseconds = {this.state.newseconds} />
<Form inline >
Hours <FormControl onChange = {event => this.setState({newhours: event.target.value})} />
{" "}Minutes <FormControl onChange = {event => this.setState({newminutes: event.target.value})} />
{" "}Seconds <FormControl onChange = {event => this.setState({newseconds: event.target.value})} />
</Form>
</div>
)
}
}
export default App;
|
describe('P.views.accounts.Signin', function() {
var View = P.views.accounts.Signin;
PTest.routing(View, 'sign-in', true);
describe('save() valid model', function() {
var view;
beforeEach(function() {
var promise = new Promise(function() {
this.resolve = arguments[0];
this.reject = arguments[1];
}.bind(this));
view = new View();
spyOn(view.model, 'isValid')
.and.returnValue(true);
spyOn(view.model, 'pSave')
.and.returnValue(promise);
spyOn(Sisse, 'execute');
});
it('disables .js-submit button while request is being made', function() {
view.render();
view.submit();
expect(view.$('.js-submit')
.is('.disabled'))
.toBe(true);
});
describe('server success', function() {
var fn,
resp;
beforeEach(function() {
spyOn(Sisse, 'setToken');
fn = view.onSubmit;
spyOn(view, 'onSubmit');
view.render();
P.common.PubSub.off();
resp = {
model: new Backbone.Model({
user_id: 'bar',
access_token: 'blah',
expires_in: 3600
}),
resp: {
responseJSON: {
user_id: 'bar',
access_token: 'blah',
expires_in: 3600
}
}
};
});
it('triggers set_token command with token details', function(done) {
view.onSubmit.and.callFake(function() {
fn.apply(this, arguments);
expect(Sisse.setToken)
.toHaveBeenCalled();
done();
});
view.submit();
this.resolve(resp);
});
it('triggers navigate to plan/day/today after success submit', function(done) {
spyOn(P.common.PubSub, 'navigate');
view.onSubmit.and.callFake(function() {
fn.apply(this, arguments);
expect(P.common.PubSub.navigate)
.toHaveBeenCalledWith('');
done();
});
view.submit();
this.resolve(resp);
});
});
describe('server side error', function() {
var model, asyncTest;
beforeEach(function() {
model = new Backbone.Model();
view.render();
var original = view.onSubmitFail;
spyOn(view, 'onSubmitFail')
.and.callFake(function() {
original.apply(this, arguments);
asyncTest();
});
});
it('falls back to a default error if the code is not found', function(done) {
$el = view.$('.js-err-default');
view.submit();
expect($el.is('.hidden'))
.toBe(true);
this.reject({
model: model,
resp: {
responseJSON: {
code: 'panic'
}
}
});
asyncTest = function() {
expect($el.is('.hidden'))
.toBe(false);
done();
};
});
});
});
});
|
console.log("Bank Account Redo")
var savings = {
balance: 0,
deposit: function(amount) {
savings.balance = savings.balance + amount;
return savings.balance;
},
withdraw: function(amount) {
savings.balance = savings.balance - amount;
return savings.balance;
}
}
var checking = {
balance: 0,
deposit: function(amountChecking) {
checking.balance = checking.balance + amountChecking;
return checking.balance;
},
withdraw: function(amountChecking) {
checking.balance = checking.balance - amountChecking;
return checking.balance;
}
}
// --------
//presentation functions
var balanceDiv = document.querySelector('.balance');
var balanceCheckingDiv = document.querySelector('.balanceChecking')
var amountInput = document.querySelector('.amount');
var depositBtn = document.querySelector('.deposit-btn');
var withdrawBtn = document.querySelector('.withdraw-btn');
var savingsBox = document.querySelector('.savings');
var depositCheckingBtn = document.querySelector('.deposit-checking-btn');
var withdrawCheckingBtn = document.querySelector('.withdraw-checking-btn');
var amountInputChecking = document.querySelector('.amount-checking');
var checkingBox = document.querySelector('.checking');
// SAVINGS ACCOUNT
var renderBalance = function () {
balanceDiv.textContent = '$' + savings.balance.toFixed(2);
return savings.balance;
}
renderBalance();
depositBtn.addEventListener('click', function () {
if (savingsBox.lastElementChild.textContent === "You don't have enough money, mate"){
savingsBox.lastElementChild.textContent = "";
}
var amount = Number(amountInput.value);
savings.deposit(amount);
renderBalance();
amountInput.value = "";
});
withdrawBtn.addEventListener('click', function () {
var amount = Number(amountInput.value);
if (savingsBox.lastElementChild.textContent === "You don't have enough money, mate"){
savingsBox.lastElementChild.textContent = "";
}
if (savings.balance >= amount) {
savings.withdraw(amount);
amountInput.value = "";
renderBalance();
} else {
var noFunds = document.createElement("P");
var alertText = document.createTextNode("You don't have enough money, mate")
noFunds.appendChild(alertText);
savingsBox.appendChild(noFunds);
}
});
// CHECKING ACCOUNT
var renderCheckingBalance = function () {
balanceCheckingDiv.textContent = '$' + checking.balance.toFixed(2);
return checking.balance;
}
renderCheckingBalance();
depositCheckingBtn.addEventListener('click', function () {
if (checkingBox.lastElementChild.textContent === "You don't have enough money, mate"){
checkingBox.lastElementChild.textContent = "";
}
var amountChecking = Number(amountInputChecking.value);
checking.deposit(amountChecking);
renderCheckingBalance();
amountInputChecking.value = "";
});
withdrawCheckingBtn.addEventListener('click', function () {
var amountChecking = Number(amountInputChecking.value);
if (checkingBox.lastElementChild.textContent === "You don't have enough money, mate"){
checkingBox.lastElementChild.textContent = "";
}
if (checking.balance >= amountChecking) {
checking.withdraw(amountChecking);
amountInputChecking.value = "";
renderCheckingBalance();
} else if (checking.balance < amountChecking) {
checking.withdraw(amountChecking);
renderCheckingBalance();
var amountNeeded = checking.balance * -1;//magic
if (savings.balance < amountNeeded){
var noFunds = document.createElement("P");
var alertText = document.createTextNode("You don't have enough money, mate")
noFunds.appendChild(alertText);
checkingBox.appendChild(noFunds);
checking.deposit(amountChecking);
renderCheckingBalance();
} else if (savings.balance >= amountNeeded){
var noFunds = document.createElement("P");
var alertText = document.createTextNode("Now transferring $" + amountNeeded + " to your checking account.")
noFunds.appendChild(alertText);
checkingBox.appendChild(noFunds);
transferFunds(amountNeeded);
renderCheckingBalance();
renderBalance();
}
}
});
// Transferring from Savings to Checking
var transferFunds = function (amountNeeded) {
savings.balance = savings.balance - amountNeeded;
checking.balance = checking.balance + amountNeeded;
}
|
$(document).on("ready",function(){
$(".pagina").click(function(){
paginacion($(this).attr("pagina"));
});
$(".pagina").live("click",function(){
paginacion($(this).attr("pagina"));
});
var paginacion = function(pagina){
var pagina = "pagina=" + pagina;
$.post(_root_ + "post/pruebaAjax",pagina,function(data){
$("#lista_registros").html("");
$("#lista_registros").html(data);
});
}
});
|
import AsyncStorage from "@react-native-community/async-storage";
import Axios from "axios";
import socketIO from "socket.io-client";
export const request = Axios.create({});
request.defaults.baseURL = "http://localhost:8082";
request.defaults.timeout = 1000;
export const getToken = async () => {
try {
const token = await AsyncStorage.getItem("token");
return token;
} catch (error) {
console.error(error);
return error;
}
};
/**
* @description - This function returns data from all post requests that will be made by the client
* @param {Object} data - The payload the clients wants to create
* @param {String} URL - The backend endpoint to access
* @param {Object} config - The configuration object of the request
* @returns {Object} - returns the response data of the request from the server
*/
export const post = async (URL, data) => {
try {
const token = await getToken();
const res = await request.post(URL, data, {
headers: {
Authorization: token,
},
});
return { errorStatus: false, ...res };
} catch (err) {
return err;
}
};
/**
* @description - This function returns data from all get requests that will be made by the client
* @param {String} URL - The backend endpoint to access
* @param {Object} config - The configuration object of the request
* @returns {Object} - returns the response data of the request from the server
*/
export const get = async (URL) => {
try {
const token = await getToken();
const res = await request.get(URL, {
headers: {
Authorization: token,
},
});
return res;
} catch (err) {
return err;
}
};
/**
* @description - This function returns data from all put requests that will be made by the client
* @param {Object} data - The payload the clients wants to update with
* @param {String} URL - The backend endpoint to access
* @param {Object} config - The configuration object of the request
* @returns {Object} - returns the response data of the request from the server
*/
export const put = async (data, URL) => {
try {
const token = await getToken();
const res = await request.put(URL, data, {
headers: {
Authorization: token,
},
});
return res;
} catch (err) {
return err;
}
};
// Initialize Socket IO
const socket = socketIO("http://localhost:8082");
export const startSocketIO = () => {
socket.connect();
socket.on("connecting", (socket) => {
console.log("connected to socket server", socket);
});
socket.on('accepted', (meters) => {
console.log(meters)
});
socket.on('update', (data) => {
console.log(data)
});
};
|
import React from 'react';
import ReactDOM from 'react-dom';
import {
BrowserRouter as Router,
Route,
Link,
Switch
} from 'react-router-dom';
import MainLayout from './layouts/MainLayout/MainLayout';
import NoMatch from './pages/NoMatch/NoMatch'
import Users from './pages/Users/Users';
import Login from './pages/Login/Login';
import Dashboard from './pages/Dashboard/Dashboard';
import './sass/global-styles.scss';
ReactDOM.render(
<Router>
<div>
<Switch>
<Route exact path="/login" component={Login} />
<MainLayout>
<Route exact path="/" component={Dashboard} />
<Route path="/users" component={Users} />
</MainLayout>
<Route component={NoMatch}/>
</Switch>
</div>
</Router>,
document.getElementById('app')
);
|
const showPinyin = () => {
let keys = window.chars.split(' ').join('')
let t = `
<div class="pinyin"> ${keys}</div>
`
e('#simle_input_method').insertAdjacentHTML('beforeend', t)
updateWordCount()
}
const styleBtn = (pages) => {
let up = {
opacity: 1,
offset: -1,
}
let down = {
opacity: 1,
offset: 1,
}
if (window.page == 1) {
up = {
opacity: 0.3,
offset: 0,
}
}
if (pages == window.page && pages !== 0) {
down = {
opacity: 0.3,
offset: 0,
}
}
return {
up,
down,
}
}
/*
找规律:
page = 1
i: 0 - 4
page = 2
i: 5 - 9
考虑最后一页情况
*/
const showFontBox = () => {
let ks = window.chars
let words = window.letterMap[ks] ? window.letterMap[ks].split('') : []
// log('words', words)
// 有多少页
let pages = Math.ceil(words.length / 5)
let {up, down} = styleBtn(pages)
if (words.length > 5) {
let start = 5 * (window.page - 1)
let end = start + 5
// 考虑最后一页情况
if (end > words.length - 1) {
end = words.length - 1
}
words = words.slice(start, end)
}
// log('words', words)
let ws = ''
words.forEach((w, i) => {
let index = 5 * (window.page - 1) + i
ws += `
<li data-number=${index} class="word">${w}</li>
`
})
let t = `
<div class="result">
<ol>
${ws}
</ol>
<div class="page-up-down">
<span class="page-up page-btn" style="opacity: ${up.opacity};" data-offset=${up.offset}>▲</span>
<span class="page-down page-btn" style="opacity: ${down.opacity};" data-offset=${down.offset}>▼</span>
</div>
</div>
`
e('#simle_input_method').insertAdjacentHTML('beforeend', t)
}
const clearBox = () => {
e('#simle_input_method').innerHTML = ''
}
const showBox = () => {
// 清空
clearBox()
// 等输入字符为空的时候,那么不显示
if (window.chars.length === 0) {
return
}
// 当前输入的所有字符
showPinyin()
// 展示文字选项
showFontBox()
}
/**
*
* @param {数字 是那个一个字} number
* @param {是否点击键盘上的 1} isClickKey 【如果是鼠标点击 选择的字那么为 false】
*/
const selectWordBy = (number, isClickKey = true) => {
let n = number
let input = e('.test-input-method')
let v = input.value
let end = isClickKey ? v.length - chars.length - 1 : v.length - chars.length
// 进行数据处理 提取出相应的字
v = v.slice(0, end)
let word = window.letterMap[chars][n]
v += word
input.value = v
window.chars = ''
// 归回首页
window.page = 1
updateWordCount()
}
// 如果全部都为空格 那么返回 false
const inputValueIsEmpty = () => {
let input = e('.test-input-method')
let v = input.value
for (let char of v) {
if (char !== ' ') {
return true
}
}
return false
}
const bindEventKeyupInput = () => {
window.addEventListener('keyup', event => {
log('event', event)
log('event', event.key)
let key = event.key
// 数字
// 目前只有五个选项
if ('12345'.includes(key)) {
let n = Number(key)
log('n', n)
n = 5 * (window.page - 1) + n - 1
log('afer n', n)
// 选择字
selectWordBy(n)
}
// 字母
let lower = 'qwertyyuiopasdfghjklzxcvbnm'
if (lower.includes(key)) {
window.chars += key
}
// 删除
if (key == 'Backspace') {
if (window.chars.length === 0) {
return
}
window.chars = chars.slice(0, chars.length - 1)
}
// 点击空格
if (key === ' ' && inputValueIsEmpty()) {
// 默认选择第一个
let n = 1
n = 5 * (window.page - 1) + n - 1
selectWordBy(n)
}
if (key === 'ArrowUp') {
let ks = window.chars
let words = window.letterMap[ks] ? window.letterMap[ks].split('') : []
// 有多少页
let pages = Math.ceil(words.length / 5)
let p = window.page + 1
if (p <= pages) {
window.page = p
}
}
if (key === 'ArrowDown') {
if (window.page === 1) {
return
}
window.page -= 1
}
// 更新页面
showBox()
})
}
const bindEventClickWord = () => {
e('#simle_input_method').addEventListener('click', event => {
let word = event.target
if (word.classList.contains('word')) {
let n = Number(word.dataset.number)
// 改变值 直接鼠标点击
selectWordBy(n, false)
// 更新页面数据
showBox()
}
updateWordCount()
})
}
const bindEventPageButton = () => {
e('#simle_input_method').addEventListener('click', event => {
let btn = event.target
if (btn.classList.contains('page-btn')) {
let n = Number(btn.dataset.offset)
window.page += n
showBox()
}
})
}
const bindEvents = () => {
bindEventKeyupInput()
bindEventClickWord()
bindEventPageButton()
}
const __main = () => {
window.chars = '' // 当前输入的所有字符
window.page = 1 // 默认当前为第一页
bindEvents()
}
__main()
|
/*
* ProGade API
* Copyright 2012, Hans-Peter Wandura (ProGade)
* Last changes of this file: Aug 21 2012
*/
/*
@start class
@param extends classPG_ClassBasics
*/
function classPG_Objects()
{
// Declarations...
// Construct...
// Methods...
/*
@start method
@return sStructure [type]string[/type]
[en]...[/en]
@param oObject [needed][type]object[/type]
[en]...[/en]
@param bUseHtml [type]bool[/type]
[en]...[/en]
*/
this.getStructureString = function(_bUseHtml, _oObject, _bShowEmpty, _bShowFunctions, _iMaxCount, _iMaxDepth)
{
if (typeof(_oObject) == 'undefined') {var _oObject = null;}
if (typeof(_bShowEmpty) == 'undefined') {var _bShowEmpty = null;}
if (typeof(_bShowFunctions) == 'undefined') {var _bShowFunctions = null;}
if (typeof(_iMaxCount) == 'undefined') {var _iMaxCount = null;}
if (typeof(_iMaxDepth) == 'undefined') {var _iMaxDepth = null;}
_oObject = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'oObject', 'xParameter': _oObject});
_bShowEmpty = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'bShowEmpty', 'xParameter': _bShowEmpty});
_bShowFunctions = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'bShowFunctions', 'xParameter': _bShowFunctions});
_iMaxCount = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'iMaxCount', 'xParameter': _iMaxCount});
_iMaxDepth = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'iMaxDepth', 'xParameter': _iMaxDepth});
_bUseHtml = this.getRealParameter({'oParameters': _bUseHtml, 'sName': 'bUseHtml', 'xParameter': _bUseHtml});
return oPGVars.getStructureString(
{
'xVar': _oObject,
'bUseHtml': _bUseHtml,
'bShowEmpty': _bShowEmpty,
'bShowFunctions': _bShowFunctions,
'iMaxCount': _iMaxCount,
'iMaxDepth': _iMaxDepth
}
);
}
/* @end method */
this.print_r = this.getStructureString;
/*
@start method
@return asInstanceNames [type]string[][/type]
[en]...[/en]
@param oObject [needed][type]object[/type]
[en]...[/en]
*/
this.getInstanceNamesOf = function(_oObject)
{
_oObject = this.getRealParameter({'oParameters': _oObject, 'sName': 'oObject', 'xParameter': _oObject, 'bNotNull': true});
var _asInstanceNames = new Array();
for(var _sObjectName in window)
{
try {if(window[_sObjectName] instanceof _oObject) {_asInstanceNames.push(_sObjectName);}}
catch(_eError) {}
}
return _asInstanceNames;
}
/* @end method */
/*
@start method
@return aoInstances [type]object[][/type]
[en]...[/en]
@param oObject [needed][type]object[/type]
[en]...[/en]
*/
this.getInstancesOf = function(_oObject)
{
_oObject = this.getRealParameter({'oParameters': _oObject, 'sName': 'oObject', 'xParameter': _oObject, 'bNotNull': true});
var _aoInstances = new Array();
for(var _sObjectName in this.oWindow)
{
try {if (this.oWindow[_sObjectName] instanceof _oObject) {_aoInstances.push(this.oWindow[_sObjectName]);}}
catch(_eError) {}
}
return _aoInstances;
}
/* @end method */
/*
@start method
@return sClassName [type]string[/type]
[en]...[/en]
@param oObject [needed][type]object[/type]
[en]...[/en]
*/
this.getTypeOfInstance = function(_oObject)
{
_oObject = this.getRealParameter({'oParameters': _oObject, 'sName': 'oObject', 'xParameter': _oObject, 'bNotNull': true});
for(var _sClassName in this.oWindow)
{
try
{
if ((_oObject instanceof this.oWindow[_sClassName])
&& (_sClassName != 'classPG_ClassBasics')
&& (_sClassName != 'classPG_GameClassBasics'))
{
return _sClassName;
}
}
catch(_eError) {}
}
return false;
}
/* @end method */
this.getClassName = this.getTypeOfInstance;
/*
@start method
@return aoClasses [type]object[][/type]
[en]...[/en]
@param oObject [needed][type]object[/type]
[en]...[/en]
*/
this.getTypesOfInstance = function(_oObject)
{
_oObject = this.getRealParameter({'oParameters': _oObject, 'sName': 'oObject', 'xParameter': _oObject, 'bNotNull': true});
var _aoClasses = new Array();
for(var _sClassName in this.oWindow)
{
try {if(_oObject instanceof this.oWindow[_sClassName]) {_aoClasses.push(_sClassName);}}
catch(_eError) {}
}
return _aoClasses;
}
/* @end method */
this.getClassNames = this.getTypesOfInstance;
/*
@start method
@return oObject [type]object[/type]
[en]...[/en]
@param oObject1 [needed][type]object[/type]
[en]...[/en]
@param oObject2 [needed][type]object[/type]
[en]...[/en]
*/
this.concate = function(_oObject1, _oObject2)
{
_oObject2 = this.getRealParameter({'oParameters': _oObject1, 'sName': 'oObject2', 'xParameter': _oObject2});
_oObject1 = this.getRealParameter({'oParameters': _oObject1, 'sName': 'oObject1', 'xParameter': _oObject1, 'bNotNull': true});
for (_sProperty in _oObject2) {_oObject1[_sProperty] = _oObject2[_sProperty];}
return _oObject1;
}
/* @end method */
}
/* @end class */
classPG_Objects.prototype = new classPG_ClassBasics();
var oPGObjects = new classPG_Objects();
|
import styles from "./secondPanel.module.css"
import BusinessCenterIcon from '@material-ui/icons/BusinessCenter';
import LanguageIcon from '@material-ui/icons/Language';
import MonetizationOnIcon from '@material-ui/icons/MonetizationOn';
import AssessmentIcon from '@material-ui/icons/Assessment';
import ParallaxCustom from "./parallaxCustom";
import { Background, Parallax } from "react-parallax";
import Image from "next/image";
const SecondPanel = () => {
return (
<Parallax className={styles.container}
strength={400}
bgStyle={{background:"center"}}>
<Background bgClassName={styles.background}>
<Image layout="fixed" width={2299} height={1527} alt="building skyline" src="/images/buildingBackground2.jpg" />
</Background>
<div className={styles.textContainer}>
<h1 className={styles.title}>Do you want to bring your business to a new dimension? </h1>
<h2 className={styles.title}>Sophia is the one-stop solution for business owners.</h2>
<p className={styles.text}>
Through our experience and passion for business and technology, we will help you build up your company to its fullest potential. Whether it’s to prepare your business for more growth, to run it more efficiently, or to improve your online presence we can help you.
</p>
<div className={styles.iconContainer}>
<div className={styles.iconSingleContainer}>
<LanguageIcon className={styles.icon} />
<p>Digital Transformation </p>
</div>
<div className={styles.iconSingleContainer}>
<MonetizationOnIcon className={styles.icon} />
<p>Optimize your financial decisions </p>
</div>
<div className={styles.iconSingleContainer}>
<AssessmentIcon className={styles.icon} />
<p>Obtain strategy insights</p>
</div>
<div className={styles.iconSingleContainer}>
<BusinessCenterIcon className={styles.icon}/>
<p>Implement best practices</p>
</div>
</div>
</div>
</Parallax>
)
}
export default SecondPanel
|
module.exports.contato = function(app, req, res){
// render pagina
res.render('contato');
}
|
import React, {Component, Fragment} from "react";
import {connect} from "react-redux";
import ResultsTable from "../../components/ResultsTable/ResultsTable";
import {fetchAllBlock} from "../../store/actions/blocksActions";
import {fetchResults} from "../../store/actions/resultsActions";
import Paper from "../../components/UI/Paper/Paper";
class Results extends Component {
componentDidMount() {
this.props.onFetchResults();
};
render() {
const {classes} = this.props;
console.log(this.props.results);
return (
this.props.results ?
<Fragment>
<Paper>Ваш балл за тестирование: {this.props.overallGrade}</Paper>
{this.props.results.map(result => {
return <ResultsTable blockId={result.id} blockTitle={result.title} blockSections={result.sections} blockGrade={result.blockGrade}/>
})}
</Fragment> : null
)
}
};
const mapStateToProps = state => ({
blocks: state.blocks.blocks,
user: state.users.user,
results: state.results.results,
overallGrade: state.results.overallGrade,
isLoading: state.isLoading.isLoading
});
const mapDispatchToProps = dispatch => ({
onFetchAllBlock: () => dispatch(fetchAllBlock()),
onFetchResults: () => dispatch(fetchResults())
});
export default connect(mapStateToProps, mapDispatchToProps)(Results);
|
import { createStore } from './relook';
import initialState from './state';
import * as actionCreators from './actions';
export const { StoreProvider, StoreConsumer, withStore } = createStore(
initialState,
actionCreators,
[
'selectedTerm',
'selectedCourses',
'scheduleFilters',
'generatedSchedules',
'filteredSchedules',
'coursesByCode',
'sectionsByCode'
]
);
|
define(['apps/system3/production/production.controller',
'apps/system3/production/volume/volume.service'], function (app) {
app.factory("volumePlanScope", function () {
return {
init: function ($scope, $uibModalInstance, volumeService, volPlanParams) {
if (volPlanParams) {
$scope.planVolume = volPlanParams.volumeInfo;
$scope.Process = $scope.ProcessModel_enum[volPlanParams.volumeInfo.Specialty.ProcessModel];
} else {
$scope.$watch("currentVolume", function (newval, oldval) {
if (newval) {
$scope.planVolume = newval;
$scope.Process = $scope.ProcessModel_enum[newval.Specialty.ProcessModel];
$scope.addColDef();
$scope.loadVolumes();
}
})
}
// 加载卷册列表
$scope.loadVolumes = function () {
if ($scope.planVolume == undefined) {
return;
}
volumeService.getSpecVolumes($scope.planVolume.Engineering.ID,
$scope.planVolume.Specialty.SpecialtyID).then(function (result) {
// 获取卷册流程各个节点的信息
angular.forEach(result, function (volume) {
volume.CanDelete = true;
angular.forEach($scope.Process.Tasks, function (task) {
var item = volume.Tasks.get(function (t) { return t.SourceID == task.ID });
volume[task.Owner] = item.UserID;
volume[task.Owner + "_Status"] = item.Status;
if (item.Status == 2) {
volume.CanDelete = false;
}
});
});
$scope.Volumes = result;
});
}
// 卷册表格参数
$scope.volOptions = {
data: "Volumes",
enableCellEditOnFocus: true,
enableRowHeaderSelection: true,
cellEditableCondition: true,
onRegisterApi: function (gridApi) {
//gridApi.cellNav.on.navigate($scope, function (newRowCol, oldRowCol) {
// gridApi.selection.toggleRowSelection(newRowCol.row.entity);
//});
gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
$scope.$safeApply(function () {
rowEntity.IsModified = true;
});
});
$scope.volGridApi = gridApi;
}
}
// 添加卷册表格列
$scope.addColDef = function () {
var index = 0;
$scope.volOptions.columnDefs = [
{ name: 'Number', displayName: $scope.local.volume.number, width: '120', enableColumnMenu: false },
{ name: 'Name', displayName: $scope.local.volume.name, width: '120', enableColumnMenu: false },
{ name: "StartDate", displayName: $scope.local.specil.startDate, width: '120', editableCellTemplate: 'datepicker', cellFilter: 'TDate', enableColumnMenu: false },
{ name: "EndDate", displayName: $scope.local.specil.endDate, width: '120', editableCellTemplate: 'datepicker', cellFilter: 'TDate', enableColumnMenu: false },
{ name: "Note", displayName: $scope.local.specil.note, width: '120', enableColumnMenu: false }
];
angular.forEach($scope.Process.Tasks, function (task) {
var colDef = {
name: task.Owner, displayName: task.Name, width: '120', cellFilter: 'enumMap:"user"', enableColumnMenu: false,
editDropdownValueLabel: 'Name', editDropdownOptionsArray: $scope.user_item,
editableCellTemplate: 'uiSelect',
SpecialtyID: $scope.planVolume.Specialty.SpecialtyID,
ProcessID : $scope.Process.Key,
TaskID: task.ID,
cellClass: function (grid, row, col, rowRenderIndex, colRenderIndex) {
if (row.entity[col.field + "_Status"] == 2) {
return 'bg-blue';
}
},
cellEditableCondition: function ($scope) {
return $scope.row.entity[$scope.col.field + "_Status"] != 2;
},
};
$scope.volOptions.columnDefs.insertAt(2 + index++, colDef);
});
}
// 添加卷册
$scope.addVolume = function (vol) {
var newVol = { Name: '新建卷册' };
var index = $scope.Volumes.length;
if (index == 0) {
angular.forEach($scope.Process.Tasks, function (task) {
newVol[task.Owner] = 1;
newVol[task.Owner + "_Status"] = 0;
});
} else {
var lastVolume = $scope.Volumes[index - 1];
angular.forEach($scope.Process.Tasks, function (task) {
newVol[task.Owner] = lastVolume[task.Owner];
newVol[task.Owner + "_Status"] = 0;
});
}
$scope.Volumes.push(newVol);
}
// 删除卷册
$scope.removeVolume = function () {
var items = $scope.volGridApi.selection.getSelectedRows();
if (items.length > 0) {
bootbox.confirm("共选中" + items.length + "个卷册,确定删除?", function (result) {
if (result) {
for (var i = 0; i < items.length; i++) {
if (items[i].CanDelete != undefined && !items[i].CanDelete) {
bootbox.alert(items[i].Name + '已有完成的任务,无法删除!');
return;
}
}
$scope.$safeApply(function () {
angular.forEach(items, function (item) {
$scope.Volumes.custRemove(function (v) {
return v.$$hashKey == item.$$hashKey
});
});
});
}
});
} else {
bootbox.alert('请选择卷册!');
}
}
// 保存卷册信息
$scope.updateVolumes = function () {
//$scope.thisPanel.block();
angular.forEach($scope.Volumes, function (vol) {
vol.TaskUsers = [];
angular.forEach($scope.Process.Tasks, function (task) {
vol.TaskUsers.push({
ID: task.ID,
Owner: task.Owner,
User: vol[task.Owner]
});
});
})
volumeService.updateVolumes($scope.planVolume.Engineering.ID,
$scope.planVolume.Specialty.SpecialtyID,
$scope.Volumes).then(function (newItems) {
if ($scope.maintainModel == 2) {
$uibModalInstance.close();
} else {
$scope.loadSource();
}
})
}
// 关闭编辑模式
$scope.closeMaintain = function () {
$uibModalInstance.dismiss('cancel');
}
}
}
});
app.controller('production.controller.volume.plan', function ($scope, $uibModalInstance, volumeService, volumePlanScope, volPlanParams) {
volumePlanScope.init($scope, $uibModalInstance, volumeService, volPlanParams);
$scope.addColDef();
$scope.loadVolumes();
});
});
|
$(document).ready(function() {
$('#showGall').click(function() {
$('#gallery').toggle(1000);
if($(this).text() == 'Show the gallery'){
$(this).text('Skip the gallery');
}
else{
$(this).text('Show the gallery');
}
});
$('#small a').click(function(eventObject) {
$('#small a').removeClass('myBorder');
$('#small a').fadeTo(500, 1);
$(this).addClass('myBorder');
$(this).fadeTo(0, 0.5);
if($('#big img').attr('src') != $(this).attr('href')){
$('#big img').hide().attr('src', $(this).attr('href'));
}
$('#big img').load(function() {
$(this).fadeIn(2000);
});
eventObject.preventDefault();
});
}); // End of ready
|
import DataTable from './DataTable';
import Optiopns from './Options'
class CommonChart{
constructor(){
}
toEchartsOption(){
}
toChartjsOption(){
}
}
CommonChart.dataTable = DataTable;
CommonChart.optiopns = Optiopns;
export default CommonChart;
|
import React from 'react'
import { connect } from 'react-redux'
import { hideBuyModal, saveMovie, takeMoney } from '../actions/action-creators'
import store from '../store'
import './styles/modal-buy.css'
function _ModalBuy(props) {
if (props.modalBuy.show){
if (props.modalBuy.price > store.getState().money) {
return (
<div className="modal">
<div className="modal-box">
<div className="header">
Saldo tidak cukup
</div>
<div className="content">
Maaf, saldo anda tidak mencukupi untuk membeli film <strong>{props.modalBuy.title}</strong> seharga <strong>Rp{props.modalBuy.price.toLocaleString('id-ID')}</strong>.
</div>
<div className="actions right">
<div className="button" onClick={props.onClose}>Batal</div>
</div>
</div>
</div>
)
}
else {
return (
<div className="modal">
<div className="modal-box">
<div className="header">
Konfirmasi
</div>
<div className="content">
Beli film <strong>{props.modalBuy.title}</strong> seharga <strong>Rp{props.modalBuy.price.toLocaleString('id-ID')}</strong>?
</div>
<div className="actions right">
<div className="button" onClick={props.onClose}>Batal</div>
<div className="button primary" onClick={(e) => (props.buyMovie(props.modalBuy))}>ya</div>
</div>
</div>
</div>
)
}
}
else return null
}
const mapStateToProps = state => {
return {
modalBuy: state.modalBuy
}
}
const mapDispatchToProps = dispatch => {
return {
onClose: () => {
dispatch(hideBuyModal())
},
buyMovie: (movie) => {
dispatch(saveMovie(movie.id))
dispatch(takeMoney(movie.price))
dispatch(hideBuyModal())
}
}
}
const ModalBuy = connect(mapStateToProps, mapDispatchToProps)(_ModalBuy)
export default ModalBuy
|
import DataType from 'sequelize';
import Model from '../../sequelize';
import { initialize as initializeOrderFillType } from '../utils';
const OrderFillType = Model.define('OrderFillType', {
id: {
type: DataType.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataType.STRING(45),
allowNull: true,
},
});
export const initialize = () => {
const data = [
{
id: 1,
name: 'normal',
},
{
id: 2,
name: 'ioc',
},
{
id: 3,
name: 'aon',
},
];
initializeOrderFillType(OrderFillType, data);
};
export default OrderFillType;
|
const mysql = require('mysql');
let db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'newpass',
port: '3306'
})
//创建数据库
let creteDB = `create database if not exists mynotebook character set utf8 collate utf8_general_ci`;
//使用数据库
let useDB = `use mynotebook`;
//创建用户基本信息
let createUser = `create table if not exists user(
id int unsigned primary key auto_increment comment '用户id',
name varchar(50) not null default '' comment '用户姓名',
age varchar(20) not null default '' comment '年龄',
number varchar(20) not null default '' comment '账号',
password varchar(20) not null default '' comment '密码'
)charset=utf8 engine=myisam comment '用户账号表';`
// //插入管理员用户
// let insertUser = `
// insert into user ( name,age,number,password ) values ('管理员','100','admin','admin');
// `;
let Query = function (db, sql, feedback = '') {
return new Promise((resolve, reject) => {
db.query(sql, (err, data) => {
if (err) {
reject(err);
} else {
resolve(feedback + '成功')
}
})
})
}
async function init() {
let query1 = await Query(db, creteDB, '创建数据库\n');
let query2 = await Query(db, useDB, '使用数据库\n');
let query3 = await Query(db, createUser, '创建用户基本信息\n');
// let query4 = await Query(db, insertUser, '插入管理员用户');
await db.end(err => { err ? console.log(err) : console.log('数据库断开连接\n') });
console.log(query1, query2, query3);
}
module.exports = init;
|
'use strict';
const fs = require('fs');
const buffer = fs.readFileSync('input.txt');
const file = String(buffer);
// Part 1
function assignValue(o, index, value) {
value = parseInt(value, 10);
if (o[index]) o[index].push(value);
else o[index] = [ value ];
return o;
}
function markLine(lines, index) {
lines[index] = true;
return lines;
}
function getObject(bots, output, word) {
let o;
if (word === 'bot') {
o = bots;
} else {
o = output;
}
return o;
}
function part1() {
let lines = file.split('\n'),
totalLines = lines.length,
executedLines = {},
repeat = true,
bots = {},
output = {},
targetBot = '';
while (repeat) {
lines.forEach((line, iteration) => {
if (!executedLines[iteration]) {
let split = line.split(' ');
if (split[2] === 'goes') {
let bot = split[5],
value = split[1];
bots = assignValue(bots, bot, value);
executedLines = markLine(executedLines, iteration);
} else {
let bot = split[1],
low = split[6],
high = split[11],
lowObject = getObject(bots, output, split[5]),
highObject = getObject(bots, output, split[10]),
lowValue, highValue;
if (bots[bot] && bots[bot].length === 2) {
if ((bots[bot][0] === 61 || bots[bot][0] === 17) && (bots[bot][1] === 61 || bots[bot][1] === 17)) {
targetBot = bot;
console.log('Target', bot, bots[bot][0], bots[bot][1]);
}
if (bots[bot][0] > bots[bot][1]) {
lowValue = bots[bot][1];
highValue = bots[bot][0]
} else {
lowValue = bots[bot][0];
highValue = bots[bot][1]
}
highObject = assignValue(highObject, high, highValue);
lowObject = assignValue(lowObject, low, lowValue);
bots[bot] = [];
executedLines = markLine(executedLines, iteration);
}
}
}
});
if (Object.keys(executedLines).length === totalLines) {
repeat = false;
}
}
return targetBot;
}
console.log(part1());
// Part 2
function part2() {
let lines = file.split('\n'),
totalLines = lines.length,
executedLines = {},
repeat = true,
bots = {},
output = {};
while (repeat) {
lines.forEach((line, iteration) => {
if (!executedLines[iteration]) {
let split = line.split(' ');
if (split[2] === 'goes') {
let bot = split[5],
value = split[1];
bots = assignValue(bots, bot, value);
executedLines = markLine(executedLines, iteration);
} else {
let bot = split[1],
low = split[6],
high = split[11],
lowObject = getObject(bots, output, split[5]),
highObject = getObject(bots, output, split[10]),
lowValue, highValue;
if (bots[bot] && bots[bot].length === 2) {
if (bots[bot][0] > bots[bot][1]) {
lowValue = bots[bot][1];
highValue = bots[bot][0]
} else {
lowValue = bots[bot][0];
highValue = bots[bot][1]
}
highObject = assignValue(highObject, high, highValue);
lowObject = assignValue(lowObject, low, lowValue);
bots[bot] = [];
executedLines = markLine(executedLines, iteration);
}
}
}
});
if (Object.keys(executedLines).length === totalLines) {
repeat = false;
}
}
return output[0] * output[1] * output[2];
}
console.log(part2());
|
var Chat = {};
window.onload = function()
{
Chat.data =
{
messages: []
};
Chat.session =
{
username: "Anonymous",
signin: function()
{
var that = this;
var $username = $(".signin-username");
var $password = $(".signin-password")
var username = $username.val();
var password = $password.val();
if (!username) Chat.ui.showAlert("No username provided");
else if (!password) Chat.ui.showAlert("No password provided");
else
{
$username.attr('disable','disable');
$password.attr('disable','disable');
$.post(Chat.config.api + "handler=auth", {username:username,password:password})
.done(function(data)
{
$username.attr('disable',false);
$password.attr('disable',false);
if (!data["auth"] )
{
Chat.ui.showAlert("Invalid username and/or password");
}
else
{
$username.val("");
$password.val("");
that.username = username;
Chat.ui.hideUsernameDialog();
Chat.ui.showAlert("You successfully signed in as <u>" + username + "</u>")
Chat.session.listUsers();
Chat.getMessages(true);
}
})
.fail(function()
{
Chat.ui.showAlert("Something happend. Try again.");
})
}
},
signup: function()
{
var that = this;
var $username = $(".signup-username");
var $password = $(".signup-password")
var $confpassword = $(".signup-confpassword")
var username = $username.val();
var password = $password.val();
var confpassword = $confpassword.val();
if (!username) Chat.ui.showAlert("No username provided");
else if (!password) Chat.ui.showAlert("No password provided");
else if (password != confpassword) Chat.ui.showAlert("Passwords do not match");
else
{
$username.attr('disable','disable');
$password.attr('disable','disable');
$.post(Chat.config.api + "handler=createAccount", {username:username,password:password})
.done(function(data)
{
$username.attr('disable',false);
$password.attr('disable',false);
$confpassword.attr('disable',false);
if (!data["created"] )
{
Chat.ui.showAlert("Something happend during the creation of your account. Try again.");
}
else
{
$username.val("");
$password.val("");
$confpassword.val("");
that.username = username;
Chat.ui.hideUsernameDialog();
Chat.ui.showAlert("You successfully signed in as <u>" + username + "</u>");
Chat.session.listUsers();
Chat.getMessages(true);
}
})
.fail(function()
{
Chat.ui.showAlert("Something happend. Try again.");
})
}
},
listUsers: function()
{
var that = this;
$.get(Chat.config.api + "handler=getUsers")
.done(function(data)
{
var $list = $('#user-sidebar .users').eq(1);
$list.html("");
if (data["users"])
{
for(var index in data["users"])
{
$list.append($('<li data-sidebar-user="'+data["users"][index].username+'" class="user'+(that.username == data["users"][index]["username"] ? " me" : "")+'"><a href="javascript:Chat.ui.filterByUsername(\''+data["users"][index].username+'\')">'+data["users"][index].username+(that.username == data["users"][index]["username"] ? " (Me)" : "")+'</a></li>'));
}
}
})
}
};
Chat.config =
{
api: "it202/assignment4/ddt7.php?",
timeout: 30000,
};
Chat.DOM =
{
usernameDialog: "#username-modal",
usernameSelected: "#username-selected",
sendMessageBtn: "#send-btn",
sendMessageField: "#message-field input",
messagesHolderSelector: "#messages",
messageSelector: "#messages > .message",
getRenderedMessage: function(message)
{
return $("<div data-username='"+message.username+"' class='message"+(Chat.session.username == message.username ? " me" : "")+"'></div>")
.append($("<div>"+(Chat.session.username == message.username ? "Me ("+message.username+")" : message.username)+"</div>"))
.append($("<div><p>"+message.message+"</p></div>"))
.append($("<div>"+message.date_sent+"</div>"))
}
};
Chat.load = function()
{
if (this.isInitialized())
{
$(this.DOM.sendMessageField).on('keyup', function(e)
{
if (e.keyCode == 13)
{
Chat.sendMessage();
}
});
$('div[data-username-view="signin"] input').on('keyup', function(e)
{
if (e.keyCode == 13)
{
Chat.session.signin();
}
});
$('div[data-username-view="signup"] input').on('keyup', function(e)
{
if (e.keyCode == 13)
{
Chat.session.signup();
}
});
}
};
Chat.isInitialized = function()
{
return typeof $ === "function";
};
Chat.sendMessage = function()
{
var that = this;
var message = $(that.DOM.sendMessageField).val()
if (!message)
{
alert("Please provide a message before sending");
}
else if (that.isInitialized())
{
Chat.ui.clearField();
$.post(that.config.api + "handler=sendMessage", {
username: that.session.username,
message: message
})
.done(function(data)
{
if (that.data.messages.length > 0)
{
//Chat.getMessages(true);
Chat.ui.scrollToBottom();
//Chat.getMessagesAfterId(that.data.messages[that.data.messages.length-1].id, true);
}
})
.fail(function()
{
})
}
return that;
};
Chat.getMessages = function(render)
{
var that = this;
if (that.isInitialized())
{
$.get(that.config.api + "handler=getMessages")
.done(function(data)
{
if (data["messages"] instanceof Array)
{
that.data.messages = data["messages"]
if (render) that.renderMessages();
Chat.pollMessages();
Chat.ui.scrollToBottom();
}
})
.fail(function()
{
})
}
return that;
};
Chat.pollMessages = function()
{
$.ajax({
type:"GET",
url:this.config.api + "handler=getMessagesAfterId&id=" + this.data.messages[this.data.messages.length-1].id,
timeout: this.config.timeout
})
.done(function(data)
{
Chat.getMessages(true);
})
.fail(function()
{
Chat.pollMessages();
})
};
Chat.getMessagesAfterId = function(id, render)
{
var that = this;
if (that.isInitialized())
{
$.get(that.config.api + "handler=getMessagesAfterId&id=" + id)
.done(function(data)
{
if (data["messages"] instanceof Array)
{
that.data.messages = that.data.messages.concat(data["messages"])
if (render) that.renderMessages();
Chat.ui.scrollToBottom();
}
})
.fail(function()
{
})
}
return that;
};
Chat.renderMessages = function()
{
var $messages = $(this.DOM.messagesHolderSelector);
if (this.isInitialized() && this.data.messages instanceof Array)
{
$messages.html("");
for(var index in this.data.messages)
{
$messages.append(this.DOM.getRenderedMessage(this.data.messages[index]));
}
}
};
Chat.ui =
{
filterByUsername: function(username)
{
$('li[data-sidebar-user]').removeClass('selected');
$('li[data-sidebar-user="'+username+'"]').addClass('selected');
if (username == "everyone")
{
$('.message').removeClass('hide');
}
else $('.message').not($('.message[data-username="'+username+'"]').removeClass('hide')).addClass('hide');
},
clearField: function()
{
$(Chat.DOM.sendMessageField).val("");
},
scrollToBottom: function()
{
$("html, body").stop().animate({ scrollTop: $(document).height() }, 300);
},
showUsernameDialog: function()
{
if (Chat.isInitialized())
{
$('body').attr('class', 'blur');
$('#username-modal').addClass('show');
}
},
hideUsernameDialog: function()
{
if (Chat.isInitialized())
{
$('#username-modal').removeClass('show');
$('body').attr('class', '');
}
},
changeView: function(view)
{
$('div[data-username-view]').removeClass('show');
$('div[data-username-view="'+view+'"]').addClass('show');
},
showAlert: function(message)
{
$('#alert p').html(message);
$('#alert').addClass('show');
setTimeout(this.hideAlert, 2000);
},
hideAlert: function()
{
$('#alert').removeClass('show');
}
};
Chat.load();
Chat.session.listUsers();
Chat.ui.showUsernameDialog()
};
|
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
/**
* The Date Picker defaults to a portrait dialog. The `mode` property can be set to `landscape`.
* You can also disable the Dialog passing `true` to the `disabled` property.
* To display the year selection first, set the `openToYearSelection` property to `true`.
*/
const DatePickerExampleSimple = () => (
<div>
8. DatePicker
<MuiThemeProvider>
<div>
<DatePicker hintText="Portrait Dialog" />
<DatePicker hintText="Landscape Dialog" mode='landscape' onDismiss={() => {console.log('a')}} />
<DatePicker hintText="Dialog Disabled" disabled={true} />
<DatePicker hintText="Open to Year" openToYearSelection={true} />
</div>
</MuiThemeProvider>
</div>
);
export default DatePickerExampleSimple;
|
import request from '@/utils/request'
// 提交留言
export function add(pojo) {
return request({
url: '/message',
method: 'post',
data: pojo
})
}
|
/**
* 首页管理
*/
function indexPage(){
var self=this;
this.init=function(){
$('.more_blog').bind('click',function(){
$(window.parent.document).find("#m_Iframe").attr("src","view/blogPage.html").attr("name","blogPage");
});
$('.more_q_a').bind('click',function(){
$(window.parent.document).find("#m_Iframe").attr("src","view/questionsAnswersPage.html").attr("name","questionsAnswersPage");
});
$('.more_special').bind('click',function(){
$(window.parent.document).find("#m_Iframe").attr("src","view/specialPage.html").attr("name","specialPage");
});
self.initQuestionAnswersList();
self.initLabelList();
self.initBlogData();
self.initSpeicalList();
}
/**
* 初始化blog
*/
this.initBlogData=function(){
$.post(HOST_URL+"/blog/getAllBlogList",{"page":0,"rows":12,"systemTypeId":0},function(data){
var result = data.data;
var html="";
if(result.length>0){
$.each(result, function(index, itemobj) {
var id=result[index].id;
var browseCount=result[index].browseCount;
var collectCount=result[index].collectCount;
var headImgUrl=result[index].headImgUrl;
var content=result[index].content;
var subtitle=result[index].subtitle;
var title=result[index].title;
var userId=result[index].userId;
var typeId=result[index].typeId;
var typeName=result[index].typeName;
var systemTypeName=result[index].systemTypeName;
var systemTypeId=result[index].systemTypeId;
var userName=result[index].userName;
var labelName=result[index].labelName;
var createTime=result[index].createTime;
var commentCnt=result[index].commentCnt;
createTime = createTime.replace(/ /,"T");
html += "<div class=\"mdui-col mdui-m-t-2\" style=\"cursor: pointer;\" onclick=\"index_config.blogDetailed("+id+")\">";
html += "<div class=\"mdui-card mdui-hoverable\">";
html += "<div class=\"mdui-card-media\">";
html += "<img src=\"http://fakeimg.pl/350x225/?text=geekHome&font=lobster\" />";
html += "<div class=\"mdui-card-media-covered mdui-card-media-covered-top\">";
html += "<div class=\"mdui-card-primary\">";
html += "<div class=\"mdui-card-primary-title\">"+title+"</div>";
html += "<div class=\"mdui-card-primary-subtitle\">"+subtitle+"</div>";
html += "</div>";
html += "</div>";
html += "</div>";
html += "<div class=\"mdui-card-actions mdui-float-right\">";
html += "<i class=\"Hui-iconfont\" style=\"color: #3F3F3F;font-size: 25px;\"></i><span style=\"font-size: 12px;color: grey;\">"+browseCount+"</span> ";
html += "<i class=\"Hui-iconfont\" style=\"color: #3F3F3F;font-size: 25px;\"></i><span style=\"font-size: 12px;color: grey;\">"+collectCount+"</span> ";
html += "<i class=\"Hui-iconfont\" style=\"color: #3F3F3F;font-size: 25px;\"></i><span style=\"font-size: 12px;color: grey;\">"+commentCnt+"</span>";
html += "</div>";
html += "</div>";
html += "</div>";
});
}else{
var html="<button class=\"mdui-btn mdui-btn-block mdui-color-grey-100 mdui-ripple\">暂无数据!</button>";
}
$("#blogList").html(html);
});
}
/**
* 跳转到blog详情页
*/
this.blogDetailed=function(id){
$(window.parent.document).find("#m_Iframe").attr("src","view/blogDetailPage.html?id="+id).attr("name","blogDetailPage");
}
/**
* 初始化标签
*/
this.initLabelList=function(){
var types = new Array();
types.push(1);
types.push(3);
$.post(HOST_URL+"/label/getAllLabel",{"types":types},function(data){
if(data.success){
var result = data.data;
var htmlContent="";
var ulHtml="";
$.each(result, function(index, itemobj) {
var id=result[index].id;
var name=result[index].lableName;
var type=result[index].type;
var createTime=result[index].createTime;
var parentId=result[index].parentId;
var sort=result[index].sort;
if(parentId == 0){
htmlContent += "<a href=\"#\" title="+name+">"+name+"</a>";
var childs=result[index].childs;
$.each(childs, function(index, itemobj) {
var c_id=childs[index].id;
name=childs[index].lableName;
htmlContent += "<a href=\"#\" title="+name+">"+name+"</a>";
});
}
});
$("#tagsList").html(htmlContent);
}
});
}
/**
* 初始化专题
*/
this.initSpeicalList=function(){
var types = new Array();
types.push(1);
types.push(3);
$.post(HOST_URL+"/special/getSpecialList",{"page":0,"rows":12},function(data){
var result = data.data;
var htmlContent="";
$.each(result, function(index, itemobj) {
var id=result[index].id;
var name=result[index].name;
var subtitle=result[index].subtitle;
var imgPath=result[index].imgPath;
htmlContent += "<div class=\"mdui-col mdui-m-t-1 mdui-hoverable\" style=\"cursor: pointer;padding:0px;padding-left: 5px;\">";
htmlContent += "<div class=\"mdui-grid-tile\">";
htmlContent += "<img src=\"http://fakeimg.pl/350x255/?text=geekHome&font=lobster\" />";
htmlContent += "<div class=\"mdui-grid-tile-actions\">";
htmlContent += "<div class=\"mdui-grid-tile-text\">";
htmlContent += "<div class=\"mdui-grid-tile-title\">"+name+"</div>";
htmlContent += "<div class=\"mdui-grid-tile-subtitle\">"+subtitle+"</div>";
htmlContent += "</div></div></div></div>";
});
$("#specialList").html(htmlContent);
});
}
/**
* 初始化问与答列表
*/
this.initQuestionAnswersList=function(){
$.post(HOST_URL+"/questionAnswers/questionAnswersList",{"labelId":0,"page":0,"rows":8},function(data){
var result = data.data;
var tabContent="";
if(result.length>0){
$.each(result, function(index, itemobj) {
var id=result[index].id;
var browseCount=result[index].browseCount;
var collectCount=result[index].collectCount;
var headImgUrl=result[index].headImgUrl;
var labelId=result[index].labelId;
var title=result[index].title;
var userId=result[index].userId;
var userName=result[index].userName;
var labelName=result[index].labelName;
var createTime=result[index].createTime;
var commentCnt=result[index].commentCnt;
createTime = createTime.replace(/ /,"T");
tabContent += "<ul class=\"mdui-list mdui-list-dense\" onclick=\"index_config.questionAnswersDetailed("+id+")\">";
tabContent += "<li class=\"mdui-list-item mdui-ripple\">";
tabContent += "<div class=\"mdui-img-circle\"><img src='"+IMAGE_URL+headImgUrl+"' width=\"50\" height=\"50\"/></div>";
tabContent += "<div class=\"mdui-list-item-content mdui-m-l-2\" style=\"padding-bottom: 20px;padding-top: 15px;\">";
tabContent += "<div class=\"mdui-float-right\"><a href=\"javascript:;\" class=\"mdui-btn mdui-btn-icon\"><i class=\"Hui-iconfont\"></i></a><span style=\"font-size: 12px;\">"+commentCnt+"</span></div>";
tabContent += "<div class=\"mdui-list-item-title questions_title\">"+title+"</div>";
tabContent += "<div class=\"mdui-list-item-text\">";
tabContent += "<div class=\"subtitle mdui-m-t-1\">";
tabContent += "<span class=\"lable\">"+labelName+"</span>";
tabContent += "• <b>"+userName+"</b> • <time class=timeago datetime=\""+createTime+"Z+08:00\"></time>";
tabContent += "</div>";
tabContent += "</div>";
tabContent += "</div>";
tabContent += "</li>";
tabContent += "<div class=\"line\"></div>";
tabContent += "</ul>";
});
}else{
var tabContent="<button class=\"mdui-btn mdui-btn-block mdui-color-grey-100 mdui-ripple\">暂无数据!</button>";
}
$("#questionAnswers_ul").html(tabContent);
$(".timeago").timeago();
});
}
/**
* 跳转到问与答详情页
*/
this.questionAnswersDetailed=function(id){
$(window.parent.document).find("#m_Iframe").attr("src","view/questionsAnswersDetailPage.html?id="+id).attr("name","questionsAnswersDetailPage");
}
self.init();
}
|
'use strict';
app.directive('uniqueName', function($http) {
var toId;
return {
require: 'ngModel',
link: function(scope, elem, attr, ctrl) {
elem.bind('blur', function (e) {
var currentValue = elem.val();
$http.get(NibbleUtils.getServicesUrl() +'/rest/useruq?register_username=' + currentValue).success(function(data) {
if(!data){
NibbleUtils.errorCallback(scope, null, "This email is unavailable, please use another email address", status);
}
ctrl.$setValidity('uniquename', data);
}).error(function(data, status, headers, config) {
console.log("something wrong")
});
});
}
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.