text stringlengths 7 3.69M |
|---|
/**
* Created by I305845 on 21/05/2016.
*/
// load the things we need
var mongoose = require('mongoose');
// define the schema for our matches model
var matchesSchema = mongoose.Schema({
matchID: Number,
team1: String,
team2: String,
kickofftime: Date,
winner: String,
team1score: String,
team2score: String,
goaldiff: String,
firstscore: String
});
module.exports = mongoose.model('Matches', matchesSchema);
|
module.exports = function () {
return function (context) {
console.log('# Search RegEx Hook');
console.log(context.method);
const query = context.params.query;
for (let field in query) {
if(query[field].$search && field.indexOf('$') == -1) {
console.log('## inside $search');
query[field] = { $regex: new RegExp(query[field].$search,'i') }
}
}
console.log(query);
context.params.query = query;
return context;
}
} |
const fetch = require('node-fetch');
const to = require('await-to-js').default;
// make array of numbers since each cafe id is just a sequential number starting at 0
const cafeNumbers = Array.from(Array(25).keys());
const main = async () => {
const cafeData = await Promise.all(cafeNumbers.map(async (v) => {
v = v + 200
const url = new URL('https://legacy.cafebonappetit.com/api/2/menus');
url.search = `cafe=${v}`;
const [err, resRaw] = await to(fetch(url));
if (err) return (err.message);
const [parsingErr, data] = await to(resRaw.json());
if (parsingErr) return (parsingErr.message);
return ({
id: v,
name: data.days[0].cafes[v].name
});
}));
console.log(cafeData);
};
main();
|
import { merge } from "lodash";
import {
RECEIVE_CURRENT_USER,
LOGOUT_CURRENT_USER
} from "./../actions/session_actions";
import { RECEIVE_CHATS, RECEIVE_CHAT } from "./../actions/chat_actions";
import { CLEAR_ORDER } from "./../actions/order_actions";
import {
RECEIVE_MESSAGE,
RECEIVE_MESSAGES
} from "./../actions/message_actions";
const initialState = [];
const sortingOrderReducer = (state = initialState, action) => {
Object.freeze(state);
switch (action.type) {
case RECEIVE_CHATS:
return action.order;
case RECEIVE_CHAT:
let newState = [action.order, ...state];
return newState;
case RECEIVE_MESSAGES:
return action.order;
case RECEIVE_MESSAGE:
let newState2 = [...state, action.message.id];
return newState2;
case LOGOUT_CURRENT_USER:
case CLEAR_ORDER:
return initialState;
default:
return state;
}
};
export default sortingOrderReducer;
|
const TABLE_NAME = 'counter';
exports.seed = function (knex, Promise) {
return knex(TABLE_NAME)
.del()
.then(() => {
return knex(TABLE_NAME).insert({ value: 0 });
});
};
|
var $ = require('fe:widget/js/base/jquery.js');
var cookie = require('fe:widget/js/base/cookie.js');
var events = require('fe:widget/js/lib/events.js');
var config; // login组件的配置项
var userinfo; // 用户信息
var instance; // 登录实例
var isPc = true; // 通过屏幕尺寸判断是否pc,登录框width*1.5为pc
var login;
var loginFlag;
// var passport;
global.isLogin = global.isLogin === undefined ? false : global.isLogin;
function getC() {
var id = (cookie.get('FLASHID') || cookie.get('BAIDUID')).split(':')[0];
return id;
}
// 扩展回调函数
var extendCallbacks = function (options) {
for (var key in options) {
(function (key, options) {
var option = config.options[key];
config.options[key] = function (args) {
option(args);
options[key](args);
};
})(key, options);
}
};
var url = {
wrapperUrl: global.location.protocol + '//passport.baidu.com/passApi/js/uni_login_wrapper.js',
pcLoginUrl: global.location.protocol + '//' + 'www.hao123.com/login.htm',
wapLoginUrl: 'http://wappass.baidu.com/passport/login?authsite=1',
crossdomainUrl: 'http://user.hao123.com/static/crossdomain.php'
};
// passport配置项
var passportOptions = {
apiOpt: {
product: 'hao123', // 产品线标志,原Tpl
staticPage: global.location.protocol + '//' + global.location.host + '/resource/page/v3Jump.html', // 跨域用静态页面
u: global.location.href, // 登陆成功的跳转地址
memberPass: true, // 是否记住登录状态
subpro: global.pageId || 'hao123-erji' // 产品线子页面标志
},
tangram: true,
cache: false, // 可选,是否预先缓存载入登录浮层的CSS,核心js。默认为false,true则点击登录前预先加载资源。
authsite: ['qzone', 'tsina', 'renren'], // 合作网站登录列表
onLoginSuccess: function (args) {
// 同步刷新登录则刷新页面
}, // 若要阻止默认跳转,可设置args.returnValue=false;
onSubmitStart: function (args) {
// todo...
}, // 表单所有输入项校验通过,开始提交时的回调函数,只有唯一的传入参数args是事件对象,若要阻止表单提交可设置args.returnValue=false;
onSubmitedErr: function (args) {
// todo...
}, // 在用户提交(enter键或者点击提交按钮)时,通过了前端校验,不过后端返回错误时回调
onShow: function () {
// todo...
}, // 显示登录浮层之后触发
onHide: function () {
// todo...
}, // 隐藏登录浮层之后触发
onDestroy: function () {
// todo...
} // 销毁登录浮层之后触发
};
login = {
// online: true, // 调用线上or线下接口
env: location.search.split(new RegExp('[\?\&]env=([^\&]+)', 'i'))[1] || 'online',
// 环境: 'online', 'dev':开发环境, 'qa':测试环境
syncLogin: false, // 同步登录,默认false
// userinfoUrl: 'http://www.hao123.com/api/user', // 获取用户信息接口
userinfoUrl: 'http://zhuanla.hao123.com/uc/getuserinfo', // 获取用户信息接口
loginoutUrl: 'http://www.hao123.com/api/logout', // 用户退出登录跳转url
// 获取用户信息
getUserinfo: function () {
// 如果采用同步刷新登录则不发起异步请求
if (config.syncLogin) {
return;
}
var callbackName = 's_' + (new Date().getTime());
window[callbackName] = function (data) {
if (data.errno === 0) {
loginSuccess(data);
} else {
loginFail(data);
}
window[callbackName] = null;
};
var url = config.userinfoUrl + '?callback=' + callbackName + '&c=' + getC();
$.getScript(url);
return userinfo;
},
// 登录状态初始化及登录事件绑定
init: function (options) {
// 登录状态校验
login.getUserinfo();
// passport配置拓展
config.options = $.extend(true, {}, passportOptions, options);
extendCallbacks({
onLoginSuccess: function (args) {
if (!login.syncLogin) {
args.returnValue = false;
login.getUserinfo();
instance.hide();
}
loginFlag = true;
login.onceLoginSuccess && login.onceLoginSuccess();
login.onceLoginSuccess = null;
},
onSubmitStart: function (args) {
loginFlag = false;
},
onSubmitedErr: function (args) {
loginFlag = true;
},
onShow: function (args) {
loginFlag = true;
},
onHide: function (args) {
loginFlag && (login.onceLoginSuccess = null);
},
onDestroy: function (args) {
}
});
config.options.onHide();
var doms = $('[data-hook=login]:not([has-bind-login])');
// 事件绑定
doms.on('click', function (e) {
if ($(global).width() > 393 * 1.1) {
// 显示弹层
e.preventDefault();
if (global.isLogin) {
return false;
}
login.show();
return false;
} else {
var wapLoginUrl = url.wapLoginUrl
+ '&u=' + encodeURIComponent(url.crossdomainUrl
+ '?j=' + encodeURIComponent(global.location.href))
+ '&tpl=' + config.options.apiOpt['product'];
$('[data-hook=login]').attr('href', wapLoginUrl);
}
});
// 避免重复绑定事件
doms.attr('has-bind-login', 1);
// 登出按钮url初始化
$('[data-hook=logout]').attr('href', login.getLogoutUrl());
},
// 显示登录弹层
show: function (options) {
login.onceLoginSuccess = options ? options.onceLoginSuccess : null;
if (!instance) {
// var passDomain = !config.online
// ? global.location.protocol
// + '//passport.rdtest.baidu.com/passApi/js/uni_login_wrapper.js'
// : url.wrapperUrl;
var baseUrl = url.wrapperUrl;
if (config.env === 'dev') {
baseUrl = global.location.protocol + '//passport.rdtest.baidu.com/passApi/js/uni_login_wrapper.js';
} else if (config.env === 'qa') {
baseUrl = global.location.protocol + '//passport.qatest.baidu.com/passApi/js/uni_login_wrapper.js';
}
var wrapperUrl = baseUrl + '?cdnversion' + new Date().getTime();
$.getScript(wrapperUrl, function () {
var passport = window.passport || null;
instance = passport.pop.init(config.options);
instance.show();
});
} else {
instance.show();
}
},
// 获取passport登录实例句柄
getInstance: function () {
return instance;
},
// 获取退出登录url
getLogoutUrl: function () {
var url = config.loginoutUrl + '?gotourl=' + encodeURIComponent(global.location.href) + '&c=' + getC();
return url;
},
onceLoginSuccess: null
};
config = login;
// 登录成功回调函数
function loginSuccess(data) {
userinfo = {
userName: data.data.user_name,
userAvatar: data.data.user_avatar,
coinNum: data.data.coin_num
};
global.isLogin = true;
// 派发登录成功事件
events.emit('loginSuccess', userinfo);
}
// 登录失败回调函数
function loginFail(data) {
events.emit('loginFail', data);
}
module.exports = login;
|
require("dotenv").config();
//required to import the keys.js file
var keys = require("../keys");
//get the key data from keys
var spoonacularId = keys.AppKeys.SpoonId;
//const path = require("path");
const axios = require("axios");
//const router = require("express").Router();
//const bookController = require("../controllers/bookController");
//api routes
module.exports =function(app){
// Matches with "/api/googlebooks"
app.get("/recipesCallBulk/:query", function(req, res){
var query = req.params.query;
var url="https://api.spoonacular.com/recipes/informationBulk?apiKey="+ spoonacularId +"&ids=" + query;
axios.get(url)
.then (({data}) => {res.json(data); console.log(query)})
.catch(err => {console.log(err);res.status(422).json(err)});
});
app.get("/recipesCall/:query", function(req, res){
var query = req.params.query
var url="https://api.spoonacular.com/recipes/search?number=6&apiKey="+spoonacularId+"&query=" + query;
axios.get(url)
.then (({data}) => {res.json(data); console.log(url)})
.catch(err => {console.log(err);res.status(422).json(err)});
});
} |
let txtExample = document.getElementById("txtExample");
let dvFound = document.getElementById("dvFound");
let objects = [
{ color: "#FF0000", height: 100, width: 300 },
{ color: "#FFFF00", height: 200, width: 200 },
{ color: "#ff0000", height: 300, width: 100 },
];
function makeDivs() {
for (var count = 0; count < objects.length; count++) {
let newEL = document.createElement("div");
newEL.innerHTML = objects[count].color + ": " + objects[count].height + ": " + objects[count].width;
dvFound.appendChild(newEL);
}
} |
import ContentSubmission from "./ContentSubmission";
export default ContentSubmission;
|
jQuery(document).ready(function() {
/** Function select2 */
if (document.getElementById('searchProductSelect2')) {
$('#searchProductSelect2').select2({
ajax: {
url: queryVariantProduct,
dataType: 'json',
method: 'POST',
delay: 250,
data: function(params) {
return {
q: params.term, // search term
};
},
processResults: function(data) {
return {
results: jQuery.map(data, function(obj) {
return { id: obj.id, text: obj.name, ref: obj.ref, image: obj.image };
})
};
}
// Additional AJAX parameters go here; see the end of this chapter for the full code of this example
},
placeholder: 'Select spare parts of nevel 3',
minimumInputLength: 1,
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
jQuery('#searchProductSelect2').on("select2:select", function(e) {
//console.log(e.params.data);
jQuery('#box-termin').append('<div id="box_piece_' + e.params.data.id +
'" class="mt-4 d-flex flex-wrap position-relative box-piece"><div class="box-img-span"><img src="' + e.params.data.image +
'" ></div><div class="data-ref"><span class = "d-none id-piece" data-id = "' + e.params.data.id +
'" > </span><span class="text-inp d-block">' + e.params.data.text +
'</span ><span class="ref-inp d-block">Ref: ' + e.params.data.ref +
'</span ></div><button type="button" data-id="' + e.params.data.id + '" data-box="box_piece_' + e.params.data.id + '" onclick="eraseProductSpareparts(this, this.dataset.id, this.dataset.box)" class="close" aria-label="Close"><span aria-hidden="true">×</span></button></div>');
});
function formatRepo(repo) {
console.log(repo);
if (repo.loading) {
return repo.text;
}
var $container = jQuery(
"<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__avatar img__avatar__piece'><img src='" + repo.image + "' /></div>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title img__avatar__text'>" + repo.text + "</div>" +
"<div class='select2-result-repository__description img__avatar__ref'>" + repo.ref + "</div>" +
"</div>" +
"</div>"
);
$container.find(".select2-result-repository__title").text(repo.text);
$container.find(".select2-result-repository__description").text(repo.ref);
return $container;
}
function formatRepoSelection(repo) {
return repo.text;
}
}
jQuery("#save-spareparts").click(function() {
var itemPiece = document.querySelectorAll('#box-termin .box-piece .data-ref .id-piece');
var idPieceLevelTwo = document.getElementById('id_product_spareparts_level_two').value;
var namePieceLevelTwo = document.getElementById('name_product_spareparts_level_two').value;
var id_product_spareparts = document.getElementById('id_product_spareparts').value;
var piece = [];
for (var i = 0; i < itemPiece.length; i++) {
piece.push(itemPiece[i].dataset.id);
}
var jsonString = JSON.stringify(piece);
jQuery.ajax({
type: "POST",
url: ajax_spareparts,
data: { data: jsonString, idProduct: id_product_spareparts, namePieceLevelTwo: namePieceLevelTwo, idPieceLevelTwo: idPieceLevelTwo},
cache: false,
success: function(entry) {
var ans = JSON.parse(entry);
console.log(ans);
if(ans){
if( document.getElementById('id_product_spareparts_level_two') && document.getElementById('id_product_spareparts'))
{
idProductLevelOne = document.getElementById('id_product_spareparts').value;
idProductLevelTwo = document.getElementById('id_product_spareparts_level_two').value;
jQuery.ajax({
type: "POST",
url: ajax_spareparts_list,
data: { idProductLevelOne: idProductLevelOne, idProductLevelTwo: idProductLevelTwo},
cache: false,
success: function(entryDev) {
carga_panel_2(entryDev);
}
});
}
}
else{
}
}
});
});
}); |
const db = require('./../models');
const queries = require('../queries');
db.query(queries.airport.dropTable).then((data) => {
});
db.query(queries.airlines.dropTable).then((data) => {
});
|
import React from 'react';
import ReactDOM from 'react-dom';
import { CookiesProvider } from 'react-cookie';
import './google-fonts.css';
import './reset.css';
import './index.css';
import registerServiceWorker from './registerServiceWorker';
import Header from './Modules/Main/Header'
import Body from './Modules/Main/Body'
import Footer from './Modules/Main/Footer'
ReactDOM.render(
<CookiesProvider>
<Header />
<Body />
<Footer />
</CookiesProvider>, document.getElementById('root'));
registerServiceWorker(); |
/*global beforeEach, describe, it, assert, expect */
'use strict';
describe('ProfileInfo Collection', function () {
beforeEach(function () {
this.ProfileInfoCollection = new PipedriveTest.Collections.ProfileInfo();
});
});
|
import { React } from 'react';
import { injectGlobal } from 'styled-components';
import { Grid, Row, Column } from './Grid';
import { Form, TextInput, TextInputArea, RadioBox, CheckBox, Label, Fieldset, Select, Legend } from './Forms';
import { Anchor, H1, H2, H3, H4, H5, H6, Strong } from './Typography';
import { Ruler } from './Ruler';
import { ListItem, OrderedList, UnOrderedList } from './Lists';
import { Table, Th, Td } from './Tables';
import { Button, Submit } from './Buttons';
import { Code } from './Code';
import { HtmlTag, SmallText, Tag } from './Helpers';
injectGlobal`
html {
font-size: 62.5%;
}
body {
font-size: 1.4em; /* currently ems cause chrome bug misinterpreting rems on body element */
line-height: 1.6;
font-weight: 400;
font-family: "Raleway", "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #222;
}
p {
margin-top: 0;
}
/* raleway-100 - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 100;
src: url('fonts/raleway-v12-latin-100.eot'); /* IE9 Compat Modes */
src: local('Raleway Thin'), local('Raleway-Thin'),
url('fonts/raleway-v12-latin-100.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-100.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-100.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-100.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-100.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-100italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 100;
src: url('fonts/raleway-v12-latin-100italic.eot'); /* IE9 Compat Modes */
src: local('Raleway Thin Italic'), local('Raleway-ThinItalic'),
url('fonts/raleway-v12-latin-100italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-100italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-100italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-100italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-100italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-200 - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 200;
src: url('fonts/raleway-v12-latin-200.eot'); /* IE9 Compat Modes */
src: local('Raleway ExtraLight'), local('Raleway-ExtraLight'),
url('fonts/raleway-v12-latin-200.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-200.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-200.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-200.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-200.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-200italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 200;
src: url('fonts/raleway-v12-latin-200italic.eot'); /* IE9 Compat Modes */
src: local('Raleway ExtraLight Italic'), local('Raleway-ExtraLightItalic'),
url('fonts/raleway-v12-latin-200italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-200italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-200italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-200italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-200italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-300 - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 300;
src: url('fonts/raleway-v12-latin-300.eot'); /* IE9 Compat Modes */
src: local('Raleway Light'), local('Raleway-Light'),
url('fonts/raleway-v12-latin-300.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-300.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-300.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-300.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-300.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-300italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 300;
src: url('fonts/raleway-v12-latin-300italic.eot'); /* IE9 Compat Modes */
src: local('Raleway Light Italic'), local('Raleway-LightItalic'),
url('fonts/raleway-v12-latin-300italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-300italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-300italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-300italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-300italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-regular - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 400;
src: url('fonts/raleway-v12-latin-regular.eot'); /* IE9 Compat Modes */
src: local('Raleway'), local('Raleway-Regular'),
url('fonts/raleway-v12-latin-regular.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-regular.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-regular.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-regular.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-regular.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 400;
src: url('fonts/raleway-v12-latin-italic.eot'); /* IE9 Compat Modes */
src: local('Raleway Italic'), local('Raleway-Italic'),
url('fonts/raleway-v12-latin-italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-500 - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 500;
src: url('fonts/raleway-v12-latin-500.eot'); /* IE9 Compat Modes */
src: local('Raleway Medium'), local('Raleway-Medium'),
url('fonts/raleway-v12-latin-500.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-500.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-500.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-500.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-500.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-500italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 500;
src: url('fonts/raleway-v12-latin-500italic.eot'); /* IE9 Compat Modes */
src: local('Raleway Medium Italic'), local('Raleway-MediumItalic'),
url('fonts/raleway-v12-latin-500italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-500italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-500italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-500italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-500italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-600 - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 600;
src: url('fonts/raleway-v12-latin-600.eot'); /* IE9 Compat Modes */
src: local('Raleway SemiBold'), local('Raleway-SemiBold'),
url('fonts/raleway-v12-latin-600.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-600.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-600.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-600.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-600.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-600italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 600;
src: url('fonts/raleway-v12-latin-600italic.eot'); /* IE9 Compat Modes */
src: local('Raleway SemiBold Italic'), local('Raleway-SemiBoldItalic'),
url('fonts/raleway-v12-latin-600italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-600italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-600italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-600italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-600italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-700 - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 700;
src: url('fonts/raleway-v12-latin-700.eot'); /* IE9 Compat Modes */
src: local('Raleway Bold'), local('Raleway-Bold'),
url('fonts/raleway-v12-latin-700.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-700.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-700.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-700.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-700.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-700italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 700;
src: url('fonts/raleway-v12-latin-700italic.eot'); /* IE9 Compat Modes */
src: local('Raleway Bold Italic'), local('Raleway-BoldItalic'),
url('fonts/raleway-v12-latin-700italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-700italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-700italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-700italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-700italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-800 - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 800;
src: url('fonts/raleway-v12-latin-800.eot'); /* IE9 Compat Modes */
src: local('Raleway ExtraBold'), local('Raleway-ExtraBold'),
url('fonts/raleway-v12-latin-800.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-800.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-800.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-800.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-800.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-800italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 800;
src: url('fonts/raleway-v12-latin-800italic.eot'); /* IE9 Compat Modes */
src: local('Raleway ExtraBold Italic'), local('Raleway-ExtraBoldItalic'),
url('fonts/raleway-v12-latin-800italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-800italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-800italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-800italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-800italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-900 - latin */
@font-face {
font-family: 'Raleway';
font-style: normal;
font-weight: 900;
src: url('fonts/raleway-v12-latin-900.eot'); /* IE9 Compat Modes */
src: local('Raleway Black'), local('Raleway-Black'),
url('fonts/raleway-v12-latin-900.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-900.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-900.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-900.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-900.svg#Raleway') format('svg'); /* Legacy iOS */
}
/* raleway-900italic - latin */
@font-face {
font-family: 'Raleway';
font-style: italic;
font-weight: 900;
src: url('fonts/raleway-v12-latin-900italic.eot'); /* IE9 Compat Modes */
src: local('Raleway Black Italic'), local('Raleway-BlackItalic'),
url('fonts/raleway-v12-latin-900italic.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
url('fonts/raleway-v12-latin-900italic.woff2') format('woff2'), /* Super Modern Browsers */
url('fonts/raleway-v12-latin-900italic.woff') format('woff'), /* Modern Browsers */
url('fonts/raleway-v12-latin-900italic.ttf') format('truetype'), /* Safari, Android, iOS */
url('fonts/raleway-v12-latin-900italic.svg#Raleway') format('svg'); /* Legacy iOS */
}
`;
export {
/* Grid components */
Grid, Row, Column,
/* Form components */
Form, TextInput, TextInputArea, RadioBox, CheckBox, Label, Fieldset, Select, Legend,
/* Typography components */
Anchor, H1, H2, H3, H4, H5, H6, Strong,
/* Ruler component */
Ruler,
/* List components */
ListItem, OrderedList, UnOrderedList,
/* Table components */
Table, Th, Td,
/* Button components */
Button, Submit,
/* Code component */
Code,
/* Helper components */
HtmlTag, SmallText, Tag
}; |
var ga = ga || function(){};
|
const asar = require('asar');
const npm = require("npm")
const { join } = require('path');
const diff = require('diff');
const fs = require('fs');
const { app } = require('electron');
const hashfile = require("sha256-file")
const MergeTrees = require("merge-trees")
const Module = require("module");
const appInjectedPath = join(__dirname,"app-injected");
const patchesPath = join(__dirname,"patches");
var patchesToApply = fs.existsSync(patchesPath) ? fs.readdirSync(patchesPath) : false
var appliedPatches = fs.existsSync(join(__dirname, "applied-patches.json")) ? require(join(__dirname, "applied-patches.json")) : {}
var patchesNeedApplying = false;
app.setPath('userData', join(app.getPath('userData'), "..", "tetrio-desktop")) // Otherwise the game will not load existing user data
//unpack the client
function unpackClient(refresh = false) {
if (refresh) {
if (fs.existsSync(appInjectedPath))
fs.rmdirSync(appInjectedPath, { recursive: true })
if (fs.existsSync(join(__dirname, "index.html")))
fs.unlinkSync(join(__dirname, "index.html"))
if (fs.existsSync(join(__dirname, "assets")))
fs.unlinkSync(join(__dirname, "assets"))
}
if (refresh || !fs.existsSync(appInjectedPath)) {
asar.extractAll(join(__dirname, "..", "app.asar"), appInjectedPath)
}
//symlink to avoid having to patch the game for our own installation
if (!fs.existsSync(join(__dirname, "index.html")))
fs.linkSync(join(appInjectedPath, "index.html"), join(__dirname, "index.html"), "file")
if (!fs.existsSync(join(__dirname, "assets")))
fs.symlinkSync(join(appInjectedPath, "assets"), join(__dirname, "assets"), "junction")
}
// create the patches dir if it doesnt exist
if (!patchesToApply) {
fs.mkdirSync(patchesPath)
patchesToApply = [];
}
//check if patches need applying
for (var i of patchesToApply) {
if (!i.endsWith(".patch")) continue // not a patch file
var patchHash = hashfile(join(patchesPath, i))
var file = i.replace(/.patch$/, "")
if (!appliedPatches[file] || appliedPatches[file] != patchHash) {
patchesNeedApplying = true;
unpackClient(true)
break;
}
}
if (!patchesNeedApplying) unpackClient();
// apply patches
if (patchesNeedApplying) {
fs.renameSync(join(appInjectedPath,"package.json"),join(appInjectedPath,"package.json.original"))
fs.linkSync(join(patchesPath,"package.json"),join(appInjectedPath,"package.json"))
var originalDir = process.cwd();
process.chdir(appInjectedPath);
npm.load({"package-lock":false}, () => {
npm.commands.install([appInjectedPath], (er, data) => {
process.chdir(originalDir)
fs.unlinkSync(join(appInjectedPath,"package.json"))
fs.renameSync(join(appInjectedPath,"package.json.original"),join(appInjectedPath,"package.json"))
if (!er) {
for (var i of patchesToApply) {
if (!i.endsWith(".patch")) continue; //not a patch file
var file = i.replace(/.patch$/, "")
var patchHash = hashfile(join(patchesPath, i))
if (appliedPatches[file] && appliedPatches[file] == patchHash) continue //patch already applied?
appliedPatches[file] = patchHash;
var source = fs.readFileSync(join(appInjectedPath, file), { encoding: "utf-8" })
var patch = fs.readFileSync(join(patchesPath, i), { encoding: "utf-8" })
var patched = diff.applyPatch(source, patch)
fs.writeFileSync(join(appInjectedPath, file), patched)
}
finalizeLaunch();
} else {
throw er
}
})
})
} else {
finalizeLaunch();
}
function finalizeLaunch() {
// save applied patches
fs.writeFileSync(join(__dirname, "applied-patches.json"), JSON.stringify(appliedPatches))
Module._load(join(appInjectedPath, "main.js"), null, true) // load the game :)
} |
'use strict';
const fs = require('fs');
const meow = require('meow');
const request = require('request');
const SmallRepoSize = 150;
const cli = meow(`
Usage
$ scour-github <search-term>
Options
--html Output results in HTML
--ignore-small Ignore "small" repositories
--min-size={value} Minimum repository size
`);
var searchTerm = cli.input[0];
if(!searchTerm)
{
console.error("No search term provided");
return;
}
searchRepositories(searchTerm);
var repos = [];
var pageCount = 1;
function searchRepositories(term)
{
let options = {
url: 'https://api.github.com/search/repositories?q=',
headers: {
'User-Agent': 'github-search'
}
};
options.url += (term + '&page=' + pageCount);
request(options, (error, response, body) => {
let results = JSON.parse(body);
// If we hit the GitHub rate limit, wait a minute and try again
if(results.message && results.message.startsWith('API rate limit'))
{
setTimeout(() => { searchRepositories(term); }, 60000);
return;
}
if(!results.items || results.items.length === 0) {
onSearchComplete();
return;
}
results.items.forEach(result => {
repos.push(result);
});
pageCount++;
searchRepositories(term);
});
}
function onSearchComplete(output)
{
let orgs = {};
let projects = [];
// Split organizations/projects
repos.forEach(repo => {
var minSize = 0;
if(cli.flags.minSize)
{
minSize = cli.flags.minSize;
}
if(cli.flags.ignoreSmall && SmallRepoSize > minSize)
{
minSize = SmallRepoSize;
}
if(minSize && repo.size < minSize)
{
return;
}
// Organizations
if(repo.owner.type === 'Organization')
{
// We use an object (rather than array) to store the organizations
// since we want a *distinct* list (no duplicates)
orgs[repo.owner.login] = {
name: repo.owner.login, url:
repo.owner.html_url
};
}
// Projects
else
{
projects.push({ url: repo.html_url });
}
});
// Copy our key-value object into an array
let orgsList = [];
for(let org in orgs) {
orgsList.push(orgs[org]);
}
// Sort
orgsList.sort((o1, o2) => {
return o1.name.toLowerCase().localeCompare(o2.name.toLowerCase());
});
projects.sort((p1, p2) => {
return p1.url.toLowerCase().localeCompare(p2.url.toLowerCase());
});
// Output
if(cli.flags.html)
{
outputHtml(orgsList, projects);
}
else
{
outputConsole(orgsList, projects);
}
}
function outputHtml(orgs, projects)
{
// Header
console.log(`<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>GitHub Search Results</title>
</head>
<body>
<h1>GitHub Search Results</h1>`);
// Organizations
console.log(`<h2>Total Organizations: ${orgs.length}</h2>`);
console.log('<ul>');
orgs.forEach(org => {
console.log(`<li><a href="${org.url}" target="_blank">${org.name}</a></li>`);
});
console.log('</ul>');
// Projects
console.log(`<h2>Total Projects: ${projects.length}</h2>`);
console.log('<ul>');
projects.forEach(project => {
console.log(`<li><a href="${project.url}" target="_blank">${project.url}</a></li>`);
});
console.log('</ul>');
// Footer
console.log('</body></html>');
};
function outputConsole(orgs, projects) {
// Header
console.log('GitHub Search Results');
console.log('\n')
// Organizations
console.log(`Total Organizations: ${orgs.length}`);
orgs.forEach(org => {
console.log(org.url);
});
console.log('\n');
// Projects
console.log(`Total Projects: ${projects.length}`);
projects.forEach(project => {
console.log(project.url);
});
};
|
import Model, { attr, hasMany } from '@ember-data/model';
export default class PanelModel extends Model {
@attr layoutRowClass;
@attr layoutColumnClass;
@attr otherClasses;
@hasMany('illustration', { async: false }) illustrations;
}
|
const { app, BrowserWindow, remote } = require( 'electron' )
const https = require( 'https' )
let win;
var createWindow = function createWindow () {
// Create the browser window.
win = new BrowserWindow( { width: 800, height: 600 } );
global.getAddress = getAddress;
// and load the index.html of the app.
win.loadURL( `file://${__dirname}/views/index.html` );
// Open the DevTools.
// win.webContents.openDevTools();
// Emitted when the window is closed.
win.on( 'closed', () => {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
win = null
});
};
var getAddress = function ( cep, callback ) {
var url = `https://maps.googleapis.com/maps/api/geocode/json?address=${cep}`;
https.get( url, function ( res ) {
var body = '';
res.on( 'data', function ( chunk ) {
body += chunk;
});
res.on( 'end', function () {
callback( JSON.parse( body ) );
});
});
};
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on( 'ready', createWindow );
// Quit when all windows are closed.
app.on( 'window-all-closed', () => {
// On macOS it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if ( process.platform !== 'darwin' ) {
app.quit();
}
});
app.on( 'activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if ( win === null ) {
createWindow();
}
});
// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.
|
require('dotenv').config()
const mongoose = require("mongoose");
class DB {
constructor() {
const app = express();
const dbURI = process.env.MONGODB_URI
mongoose.connect(this.dbURI)
then((result) => app.listen(3000))
}
}
|
function playSound(e) {
const audio = document.querySelector(`audio[data-beat="${e.keyCode}"]`);
if (!audio) return;
audio.currentTime = 0;
audio.play();
hideAllDots(e);
const dot = document.querySelector(`.dot[data-beat="${e.keyCode}"]`);
dot.style.display = 'block';
setTimeout(hideAllDots, 300);
}
function hideAllDots(e) {
const dots = document.querySelectorAll('.dot');
dots.forEach(dot => {
dot.style.display = 'none';
});
}
function endTransition(e) {
console.log(e);
}
window.addEventListener('keydown', playSound)
window.addEventListener('load', hideAllDots) |
//add search fields
$(document).ready(function () {
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.add-group'); //Input field wrapper
var x = 1; //Initial field counter is 1
var fieldHTML =
'<div class=" sidebar-list" >' +
'<div class="row justify-content-between " id="ingrMeasure" style="margin: 0px">' +
'<div class=" md-3 col-5 ">' +
'<input type="text" required maxlength="20" minlength="2" name="drinkIngredients[0][ingredient[name]]" value="" placeholder="Ingredient..." class="form-control"/>'+
'<div class="invalid-feedback alert alert-danger">Input ingredient</div>\n' +
'</div>' +
'<div class=" md-3 col-5 ">' +
'<input type="text" required maxlength="20" minlength="2" name="drinkIngredients[0][measure[quantity]]" value="" placeholder="Quantity..." class="form-control"/>'+
'<div class="invalid-feedback alert alert-danger">Input measure</div>\n' +
'</div>' +
'<a id="remove_blue" href="javascript:void(0);"' +
' class="remove_button col-1">' +
'<svg class="bi bi-trash" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">\n' +
'<path d="M5.5 5.5A.5.5 0 0 1 6 6v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm2.5 0a.5.5 0 0 1 .5.5v6a.5.5 0 0 1-1 0V6a.5.5 0 0 1 .5-.5zm3 .5a.5.5 0 0 0-1 0v6a.5.5 0 0 0 1 0V6z"/>\n' +
'<path fill-rule="evenodd" d="M14.5 3a1 1 0 0 1-1 1H13v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V4h-.5a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1H6a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1h3.5a1 1 0 0 1 1 1v1zM4.118 4L4 4.059V13a1 1 0 0 0 1 1h6a1 1 0 0 0 1-1V4.059L11.882 4H4.118zM2.5 3V2h11v1h-11z"/>\n' +
'</svg><br></a></div>'; //New input field html
//Once add button is clicked
$(addButton).click(function () {
//Check maximum number of input fields
if (x < maxField) {
x++; //Increment field counter
$(wrapper).append(fieldHTML); //Add field html
}
});
//Once remove button is clicked
$(wrapper).on('click', '.remove_button', function (e) {
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
|
export default {
theme: 'modern',
skin_url: '/tinymce/skins/lightgray',
codesample_content_css: '/prism/prism.css',
statusbar: false,
autoresize_min_height: 500,
language_url: '/tinymce/langs/zh_CN.js',
plugins: `print preview searchreplace autolink directionality visualblocks visualchars help
fullscreen image link media template codesample table charmap hr pagebreak nonbreaking textpattern
anchor toc insertdatetime advlist lists textcolor imagetools colorpicker autoresize`,
toolbar: `formatselect | bold italic strikethrough forecolor backcolor | link image |
alignleft aligncenter alignright alignjustify | numlist bullist outdent indent | removeformat`,
image_uploadtab: true,
images_upload_url: '/resource',
// images_upload_base_path: '',
codesample_languages: [
{text: 'JavaScript', value: 'javascript'},
{text: 'Java', value: 'java'},
{text: 'JSON', value: 'json'},
{text: 'Sass', value: 'sass'}
]
};
|
/*global Backbone */
var App = App || {};
(function () {
// Create Foods Collection View
App.Views.Foods = Backbone.View.extend({
tagName: 'ul',
className: 'selected-result',
// listen to collection add event. Then call a method to create an element and append to the DOM.
initialize: function(){
this.collection.on('add', this.addOne, this);
},
// Method for render unordered list of selected food. Use for initiating the app with data from localstorage
render: function(){
this.collection.each(this.addOne, this);
return this;
},
// Method for add new model and append to the DOM.
addOne: function(food){
$('#resultAlert').hide();
var foodView = new App.Views.Food ({model: food});
this.$el.append(foodView.render().el);
}
});
// Create Add food View
App.Views.AddFood = Backbone.View.extend({
el: '#addFood',
// Fire event when clicked on element with id foodSubmit
events: {
'click #foodSubmit' : 'submit'
},
submit: function(e) {
e.preventDefault();
// Get value from selected food
var newFoodName = $('#FoodName').text().toString();
var newFoodCal = parseInt($('#FoodCal').text());
// Check if food Calorie is really a number. If it isn't then return
if (isNaN(newFoodCal)) {
return;
}
// Add food model with data above to the collection.
var food = new App.Models.Food({title: newFoodName, calorie: newFoodCal}, {validate: true});
this.collection.add(food);
// Add to localstorage
food.save();
}
});
// Create Sum total Calorie View
App.Views.Total = Backbone.View.extend({
el: '#total',
initialize: function(){
this.render();
// listen to update event on collection. If there's an update then re-render this view
this.collection.on('update', this.render, this);
},
render: function(){
var total = 0;
// Loop through collection item and add it's calorie to total calorie
this.collection.each(function(elem){
total += parseInt(elem.get('calorie'));
}, this);
// Show total number
this.$el.text(total);
return this;
}
});
})();
|
import React from 'react';
import Search from '../Images/iconsearch2.png';
import Plus from '../Images/plus.svg';
import SettingIcon from '../Images/settings.svg';
import Pencil from '../Images/pencil.svg';
import { Link } from "react-router-dom";
//Compontente stateless com interface principal da tela administrativa
const AdminInterface = () =>{
return(
<div className='itens-container'>
<Link to="/admin7tons/consulta"><div className='admin-item'>
<img src={Search} width='40' height='40' alt='seach icon' />
<span> CONSULTAR COMPRAS</span>
</div></Link>
<Link to="/admin7tons/novoproduto"><div className='admin-item'>
<img src={Plus} width='40' height='40' alt='seach icon' />
<span> ADICIONAR NOVO PRODUTO </span>
</div></Link>
<Link to="/admin7tons/editarprodutos"> <div className='admin-item'>
<img src={SettingIcon} width='40' height='40' alt='seach icon' />
<span> EDITAR PRODUTOS </span>
</div></Link>
<Link to="/admin7tons/blog"><div className='admin-item'>
<img src={Pencil} width='40' height='40' alt='seach icon' />
<span> BLOG </span>
</div> </Link>
</div>
)
}
export default AdminInterface |
const navbar = document.querySelector('.fixed-top');
window.onscroll = () => {
if (window.scrollY > 300) {
navbar.classList.add('nav-active');
} else {
navbar.classList.remove('nav-active');
}
}; |
import styled from 'styled-components';
const BookingSummaryListWrapper = styled.div`
display: block;
margin-bottom: 8px;
`;
export default BookingSummaryListWrapper |
import React, { Component } from 'react';
import {TodoForm, TodoList} from './components/todo';
import {addTodo, generateId, findById, toogleTodo, updateTodo} from './lib/todoHelpers'
import './App.css';
class App extends Component {
state = {
todos: [
{id: 1, name: 'Item for todo 1', isComplete: false },
{id: 2, name: 'Item for todo 2', isComplete: true },
{id: 3, name: 'Item for todo 3', isComplete: false }
],
currentItem: '',
errorMessage: ''
}
handleToogle = (id) => {
const todo = findById(id, this.state.todos)
const toogled = toogleTodo(todo)
const updatedTodos = updateTodo(this.state.todos, toogled)
this.setState({
todos: updatedTodos
})
}
handleSubmit = (event) => {
event.preventDefault()
const newId = generateId()
const newItem = {id: newId, name: this.state.currentItem, isComplete: false};
const updatedTodos = addTodo(this.state.todos, newItem)
this.setState({
todos: updatedTodos,
currentItem: '',
errorMessage: ''
})
}
handleEmptySubmit = (event) => {
event.preventDefault()
this.setState({
errorMessage: 'Please provide some todo'
})
}
handleCurrentItem = (event) => {
this.setState({
currentItem: event.target.value
})
}
render() {
const submitHandler = (this.state.currentItem) ? this.handleSubmit : this.handleEmptySubmit
return (
<div className="App">
<div className="App-header">
<h2>To Do</h2>
</div>
<div className="Todo-App">
{this.state.errorMessage && <span className="errorMessage">{this.state.errorMessage}</span>}
<TodoForm
handleCurrentItem={this.handleCurrentItem}
currentItem={this.state.currentItem}
handleSubmit={submitHandler}
/>
<TodoList handleToogle={this.handleToogle} todos={this.state.todos} />
</div>
</div>
);
}
}
export default App;
|
var app = window.angular.module('app', []);
app.controller('mainCtrl', mainCtrl);
var api_root = "/message";
function mainCtrl($scope, $http) {
$scope.name = "";
$scope.sendingMessage = "";
$scope.pin = "";
$scope.retrievePin = "";
$scope.retrieveName = "";
$scope.retrievedMessage = "Secret Message";
$scope.postMessage = function () {
console.log("In post message function");
$http.post(api_root, { name: $scope.name, message: $scope.sendingMessage })
.then(function (resp) {
if (resp) {
$scope.pin = resp.data.data;
}
else {
console.log("Some error occured");
}
})
}
$scope.getMessage = function () {
console.log("In get message function");
$scope.retrievedMessage = "";
$http.get(api_root + '/' + $scope.retrieveName + '/' + $scope.retrievePin)
.then(function (resp) {
if (!resp) {
$scope.retrievedMessage = "No Message Found"
}
else {
$scope.retrievedMessage = resp.data;
}
})
}
}
|
$('.menu-title').click(function(){
$('.menu-title').removeClass('active');
$(this).addClass('active');
});
$('.sub-menu li').click(function(){
$('.sub-menu li').removeClass('active');
$('.sub-menu li .fa-star').removeClass('fa-star').addClass('fa-star-o');
$(this).addClass('active');
$(this).find('i').removeClass('fa-star-o').addClass('fa-star');
}) |
app.factory("User", function($http, $cookies) {
var url = "/api/usuario/"
return {
login: function(rfc, pass) {
return $http.post(url + 'entrar/', {
rfc: rfc,
pass: pass
});
},
signup: function(razon, email, rfc, pass) {
return $http.post(url + 'registrar/', {
razon: razon,
email: email,
rfc: rfc,
pass: pass
});
},
update: function(razon, rfc, value, type) {
return $http.post(url + 'editar/', {
razon: razon,
rfc: rfc,
value: value,
type: type
});
},
logout: function() {
return $http.post(url + 'salir/');
},
me: function() {
return $http.get(url + 'me/');
},
reactivate: function(rfc) {
return $http.post(url + 'reactivate/', {
rfc: rfc
});
},
saveToken: function(token) {
$cookies.put('andrade-token-provider', token);
},
getToken: function() {
return $cookies.get('andrade-token-provider')
},
validate: function(rfc, token, op) {
return $http.post(url + 'validar/', {
rfc: rfc,
token: token,
option: op
});
},
activate: function(rfc, token, op) {
return $http.post(url + 'activar/', {
rfc: rfc,
token: token,
option: op
});
}
}
});
|
const MyPureComponent = () => {
return (
<h1>MyPureComponentTest</h1>
)
}
ReactDOM.render(
<MyPureComponent />,
document.getElementById('myPureComponent')
)
|
import React, { Component } from 'react';
import Panel from 'react-bootstrap/lib/Panel';
import './Post.css';
class Post extends Component {
render() {
return (
<Panel>
<Panel.Heading> {this.props.title} </Panel.Heading>
<Panel.Body> {this.props.content} </Panel.Body>
</Panel>
);
}
}
export default Post;
|
import React, { Component } from "react";
import {
View, Text, StyleSheet
} from "react-native";
export default class HinhChuNhatComponent extends Component {
render() {
return (
<View style={ao.ti}>
<Text>{this.props.textComponent} - {this.props.text2}</Text>
</View>
);
}
}
HinhChuNhatComponent.propType = {
textComponent: React.PropTypes.string,
text2: React.PropTypes.string
}
var ao = StyleSheet.create({
ti: {
backgroundColor: 'green',
height: 100,
width: 300
}
});
|
const { Client, Message, MessageEmbed } = require("discord.js");
const BoltyUtil = require("../../classes/BoltyUtil");
/**
*
* @param {Client} client
* @param {Message} message
* @param {String[]} args
*/
module.exports.run = async (client, message, args) => {
if (!message.member.permissions.has("ADMINISTRATOR")) return;
let guild = message.guild;
let msg = await message.channel.send({
embeds: [
BoltyUtil.BoltyEmbed(client).setDescription(`Starting the setup...`),
],
});
guild.roles
.create({
data: {
name: "Muted (Bolty)",
color: "GREY",
permissions: ["VIEW_CHANNEL"],
},
reason: "Bolty Bot Setup",
})
.catch((e) => {
message.channel.send({
embeds: [
BoltyUtil.BoltyEmbed(client).setDescription(
`${BoltyUtil.BoltyEmotes.wrong_error} There was an error, please check that the bot have the proper permissions.\n${e}`
),
],
});
});
msg.edit({
embeds: [
BoltyUtil.BoltyEmbed(client).setDescription(`Created The Muted Role`),
],
});
msg.delete({ timeout: 3000 });
message.channel.send({
embeds: [
BoltyUtil.BoltyEmbed(client).setDescription(
`${BoltyUtil.BoltyEmotes.success} The Setup was successful!\nI have created the muted role, so you can mute people.`
),
],
});
};
module.exports.help = {
name: "setup",
description: "Will do basic setup so Bolty can work correctly!",
aliases: ["stup", "st", "sp"],
usage: "",
category: "Setup",
};
|
requirejs.config({
baseUrl: "js"
});
requirejs(["./a"], function(a) {
// a.js和b.js文件在baseUrl目录下可以正常进行,但如果在其他路径,报错
a.method();
console.log("Success!");
}); |
import React, { Component } from "react";
import { Container } from "./styles";
//conectar nosso componente com o redux
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { Creators as RepositoriesActions } from "../../store/ducks/repositories";
import { ActivityIndicator, Text } from "react-native";
class Repositories extends Component {
//chamar reducer 'LOADING_REPOSITORIES_REQUEST'
componentDidMount() {
const { loadRepositoriesRequest } = this.props;
loadRepositoriesRequest();
}
render() {
//buscando os estados dos repositorios
const { repositories } = this.props;
return (
<Container>
{repositories.loading ? (
<ActivityIndicator size="small" color="#999" />
) : (
repositories.data.map(repositories => (
<Text key={repositories.id}>{repositories.name}</Text>
))
)}
</Container>
);
}
}
const mapStateToProps = state => ({
//acesso a todos os estados do reducer repositories
repositories: state.repositories
});
const mapDispatchToProps = dispatch =>
bindActionCreators(RepositoriesActions, dispatch);
export default connect(
mapStateToProps,
mapDispatchToProps
)(Repositories);
|
const text = {
fontFamily: 'Acme'
};
const label = Object.assign({}, text, {
color: '#fff',
fontSize: '32px',
});
const title = Object.assign({}, label, {
align: 'center',
backgroundColor: '#2DAA58',
fontSize: '64px'
});
const button = Object.assign({}, label, {
fontSize: '64px',
align: 'center',
});
const primaryButton = Object.assign({}, button, {
backgroundColor: '#2B67AB'
});
const secondaryButton = Object.assign({}, button, {
backgroundColor: '#444'
});
const negativeButton = Object.assign({}, button, {
backgroundColor: '#E95C3B'
});
const explanation = Object.assign({}, label, {
backgroundColor: '#333333',
wordWrap: { width: 1160 }
});
const monospaceLabel = Object.assign({}, label, {
fontFamily: 'Courier',
fontSize: '22px',
backgroundColor: '#333333',
wordWrap: { width: 1200 }
});
const styles = {
text,
label,
title,
button,
primaryButton,
secondaryButton,
negativeButton,
explanation,
monospaceLabel
};
export default styles;
|
import React from 'react';
import {NavLink} from "react-router-dom";
const NavigationItem = (props) => {
return <NavLink style={{
textDecoration: "none",
fontWeight: "bold",
textTransform: "capitalize",
color: "black",
margin: '5px'
}}
to={props.to}
exact={props.exact}
>
{props.children}
</NavLink>
};
export default NavigationItem; |
export const FETCH_SUMMONER = 'FETCH_SUMMONER';
export const RECEIVE_SUMMONER = 'RECEIVE_SUMMONER';
export const fetchSummoner = (summoner) => ({
type: FETCH_SUMMONER,
summoner
});
export const receiveSummoner = (summoner) => ({
type: RECEIVE_SUMMONER,
summoner
});
|
$(function () {
/*相应变色*/
$('.column-header ul li').on('mouseover', function () {
$(this).addClass('active').siblings().removeClass('active');
/*相应变色*/
var index = $.inArray(this, $(this).parent().children().toArray());
var $div = $(this)
.parent().parent()
.siblings('.column-body')
.children(':nth-child(' + (index) + ')');
console.info(typeof $div);
$div.show().siblings().hide();
});
$('.column-header ul li:first-child').trigger('mouseover');
});
/*方式二*/
// $(document).ready(function () {
//
// }); |
// AppRoot.jsx
import React from 'react';
import ListStore from '../stores/ListStore';
import AppDispatcher from '../dispatcher/AppDispatcher';
// Sub components
import NewItemForm from './NewItemForm';
// Method to retrieve state from Stores
let getListState = () => {
return {
items: ListStore.getItems()
};
}
class AppRoot extends React.Component {
// Method to setState based upon Store changes
_onChange() {
this.setState(getListState());
}
constructor() {
super();
this.state = getListState();
}
// Add change listeners to stores
componentDidMount() {
ListStore.addChangeListener(this._onChange.bind(this));
}
// Remove change listeners from stores
componentWillUnmount() {
ListStore.removeChangeListener(this._onChange.bind(this));
}
removeItem(e){
let id = e.target.dataset.id;
AppDispatcher.dispatch({
action: 'remove-item',
id: id
});
}
render(){
let _this = this;
let items = ListStore.getItems();
let itemHtml = items.map(( listItem ) => {
return <li key={ listItem.id }>
{ listItem.name } <button onClick={ _this.removeItem } data-id={ listItem.id }>×</button>
</li>;
});
return (
<div>
<ul>
{ itemHtml }
</ul>
<NewItemForm />
</div>
);
}
}
export default AppRoot;
|
if ('workbox' in self) {
workbox.precaching.precacheAndRoute(self.__precacheManifest || []);
}
self.addEventListener('push', event => {
const message = JSON.parse(event.data.text())
const { title } = message
const { url } = message
const options = {
body: message.body,
icon: message.icon,
badge: message.badge,
data: url
}
event.waitUntil(self.registration.showNotification(title, options))
})
self.addEventListener('notificationclick', event => {
event.notification.close()
event.waitUntil(clients.openWindow(event.notification.data))
}) |
export const convert = (totalMinutes) => {
const minToHour = (totalMinutes / 60);
const hours = Math.floor(minToHour);
const minuteResult = (minToHour - hours) * 60;
const minutes = Math.round(minuteResult);
return {
toHours: hours,
toMins: minutes
}
}
export const twoDigitsFormat = (time) => {
return ('0' + time).slice(-2);
} |
import styles from '../../styles/components/slider.module.css'
import { files } from './files'
export default function Slider() {
return (
<div className={styles.caroussel}>
<div className={styles.gallery}>
<img src={files[0].src} alt="" />
<div className={styles.texts}>
<h1>{files[0].text}</h1>
<h2>{files[0].subtitle}</h2>
</div>
</div>
<div className={styles.options}>
<span className={styles.buttonActive} />
<span className={styles.button} />
<span className={styles.button} />
</div>
</div>
)
} |
/**
* Created by sanya on 20.04.2016.
*/
'use strict';
angular.module('app')
.controller('RootController', ['$scope', '$uibModal', function ($scope, $uibModal) {
$scope.showWorkoutHistory = function () {
var dialog = $uibModal.open({
templateUrl: 'partials/workout-history.html',
controller: WorkoutHistoryController,
size: 'lg'
});
};
var WorkoutHistoryController = function ($scope, $uibModalInstance, workoutHistoryTracker) {
$scope.search = {};
$scope.search.completed = '';
$scope.history = workoutHistoryTracker.getHistory();
$scope.ok = function () {
$uibModalInstance.close();
}
};
WorkoutHistoryController['$inject'] = ['$scope', '$uibModalInstance', 'workoutHistoryTracker'];
}]); |
DefaultScript.global.expect = remember(null, '@expect', function $logic$(scopes, step, stepName, actualValue, onException) {
var label = '@expect(actual: ' + DefaultScript.global.type(actualValue) + ')';
return remember(null, label, function $trap$(scopes, step, stepName, expectedValue, onException) {
if (actualValue !== expectedValue) {
return onException(new Error('Woah'));
}
DefaultScript.global.log('QSNMQSKQNMSQS');
});
});
|
// 2 below will be add in the future development
// for future require bootstrap-datetimepicker
// for future require bootstrap_datetimepicker/dates
//= require jquery3
//= require jquery_ujs
//= require rails-ujs
//= require bootstrap-sprockets
//= require sweetalert2
//= require sweet-alert2-rails
//= require bootstrap_notify
//= require paper-kit/application
//= require activestorage
//= require gdpr/cookie_consent
//= require turbolinks
|
import React, {useState} from 'react';
import './search-bar.css'
import Autosuggest from 'react-autosuggest';
const SearchBar = ({searchKeyword, onQuerySelected}) => {
const [suggestions, setSuggestions] = useState([]);
const [value, setValue] = useState("");
const handleSearch = async (keyword) => {
const results = await searchKeyword(keyword);
setSuggestions(results);
}
const onSuggestionsFetchRequested = ({value, reason}) => handleSearch(value)
const onSuggestionsClearRequested = () => setSuggestions([])
const getSuggestionValue = item => `${item.Title} (${item.Year})`
const renderSuggestion = item => <span>{`${item.Title} (${item.Year})`}</span>
const inputProps = {
value, // usually comes from the application state
onChange: (e, {newValue}) => setValue(newValue), // called every time the input value changes
placeholder: "Search A Movie"
};
const onSuggestionSelected = (event, { suggestion }) => onQuerySelected(suggestion)
return (
<div className="d-flex flex-column align-items-center mt-2">
<Autosuggest
suggestions={suggestions}
onSuggestionsFetchRequested={onSuggestionsFetchRequested}
onSuggestionsClearRequested={onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
inputProps={inputProps}
onSuggestionSelected={onSuggestionSelected}
/>
</div>
);
};
SearchBar.propTypes = {};
export default SearchBar;
|
import axios from "axios";
export const FETCH_SMURFS = "FETCH_SMURFS";
export const FETCHED_SMURFS = "FETCHED_SMURFS";
export const ADDING_SMURF = "ADDING_SMURF";
export const ADDED_SMURF = "ADD_SMURF";
export const DELETING_USER = "DELETING_SMURF";
export const DELETED_USER = "DELETED_SMURF";
export const UPDATING_SMURF = "UPDATING_SMURF";
export const UPDATED_SMURF = "UPDATED_SMURF";
export const ERROR = "ERROR";
export const getSmurfs = () => {
return dispatch => {
dispatch({ type: FETCH_SMURFS });
axios
.get(`http://localhost:3333/smurfs`)
.then(res => {
dispatch({ type: FETCHED_SMURFS, payload: res.data });
})
.catch(err => dispatch({ type: ERROR, error: err }));
};
};
export const addSmurf = smurf => {
return dispatch => {
dispatch({ type: ADDING_SMURF });
axios
.post(`http://localhost:3333/smurfs`, {
name: smurf.name,
age: smurf.age,
height: smurf.height
})
.then(res => {
console.log(res);
dispatch({ type: ADDED_SMURF, payload: res.data });
})
.catch(err => dispatch({ type: ERROR, error: err }));
};
};
export const deleteSmurf = smurfID => {
return dispatch => {
console.log(`~~~~~~~~~~DELETE~~~~~~~~~~~~`);
console.log(smurfID);
dispatch({ type: DELETING_USER });
axios
.delete(`http://localhost:3333/smurfs/${smurfID}`)
.then(res => {
dispatch({ type: DELETED_USER, payload: res.data });
})
.catch(err => dispatch({ type: ERROR, payload: err }));
};
};
export const updateSmurf = smurf => {
return dispatch => {
console.log(`^^^^^^^^UPDATE^^^^^^^^`);
console.log(smurf);
dispatch({ type: UPDATING_SMURF });
axios
.put(`http://localhost:3333/smurfs/${smurf.id}`, {
name: smurf.name,
age: smurf.age,
height: smurf.height,
id: smurf.id
})
.then(res => {
dispatch({ type: UPDATED_SMURF, payload: res.data });
})
.catch(err => dispatch({ type: ERROR, payload: err }));
};
};
|
const ACTIONS = {
JOIN_SERVER: 'JOIN_SERVER',
SET_WINNER: 'SET_WINNER',
SET_GAME_DATA: 'SET_GAME_DATA',
SET_PLAYER_NUMBER: 'SET_PLAYER_NUMBER',
SET_ROOM: 'SET_ROOM',
SET_TURN: 'SET_TURN',
SET_ERRORS: 'SET_ERRORS',
SET_ERROR_EXIST: 'SET_ERROR_EXIST',
CLEAR_ERRORS: 'CLEAR_ERRORS',
};
export default ACTIONS;
|
// Register Card template
Vue.component('card', {
template: '#cardTpl',
data: {
ticks: [],
skipped: false,
flipped: false
},
computed: {
completed: function() {
if (this.skipped) return true;
else return (this.done >= this.repeat);
}
},
ready: cardReady,
methods: {
complete: complete,
skip: skip,
flip: flip,
testFunc: test
}
});
// Register completion message
Vue.component('congrats', {
template: '#congratsTpl',
data: {
choices: ['Nice One!', 'Good Job!', 'Feeling Good!']
},
computed: {
skipped: function() {
return this.$parent.skipped; // Get the skipped boolean
},
msg: function(){
if (this.skipped) return 'Skipped';
else { // Return random congrats message
var l = this.choices.length;
var i = Math.floor(Math.random()*l);
return this.choices[i];
}
},
icon: function () { // Return icon
if (this.skipped) return 'T';
else return 'T';
}
},
ready: function() {
var e = this.$el;
setTimeout(function(){
$(e)
.children('div.subject')
.animate({opacity: 1, marginTop: '0px'}, 200, 'easeOutQuint'); // Fade in Message
}, 500);
this.$on('congratsFade', function(index, callback){
if (index == this.index) {
$(this.$el)
.children('div.subject')
.animate({marginTop: '50px', opacity: 0}, 200, 'easeInQuint') // Fade out Message
.promise().done(function(){
setTimeout(callback, 200); // Insert new goal
});
}
});
}
});
// Init cards
function cardReady() {
// Create tick lists
var r = this.repeat;
var d = this.done;
var t = this;
setTimeout(function() {
t.$el.classList.remove('slideeClosed');
}, 200);
this.ticks = [];
for (var j= 0; j < r; j++) {
var b = (j < d) ? true : false;
this.ticks.push(b);
}
}
// Complete a task
function complete() {
this.done++;
this.ticks.$set(this.done-1, true);
if (this.done == this.repeat) {
this.$dispatch('replaceCard', this.$index);
}
}
// Flip a card
function flip() {
this.flipped = !this.flipped;
}
// Skip a task
function skip() {
//Reset tab button
// var skipTab = app.$.View.$.tabSkip;
// skipTab.change(skipTab, 's', 'skip');
this.skipped = true;
this.$dispatch('replaceCard', this.$index);
} |
/**
* Route Mappings
* (sails.config.routes)
*
* Your routes map URLs to views and controllers.
*
* If Sails receives a URL that doesn't match any of the routes below,
* it will check for matching files (images, scripts, stylesheets, etc.)
* in your assets directory. e.g. `http://localhost:1337/images/foo.jpg`
* might match an image file: `/assets/images/foo.jpg`
*
* Finally, if those don't match either, the default 404 handler is triggered.
* See `api/responses/notFound.js` to adjust your app's 404 logic.
*
* Note: Sails doesn't ACTUALLY serve stuff from `assets`-- the default Gruntfile in Sails copies
* flat files from `assets` to `.tmp/public`. This allows you to do things like compile LESS or
* CoffeeScript for the front-end.
*
* For more information on configuring custom routes, check out:
* http://sailsjs.org/#!/documentation/concepts/Routes/RouteTargetSyntax.html
*/
module.exports.routes = {
/***************************************************************************
* *
* Make the view located at `views/homepage.ejs` (or `views/homepage.jade`, *
* etc. depending on your default view engine) your home page. *
* *
* (Alternatively, remove this and add an `index.html` file in your *
* `assets` directory) *
* *
***************************************************************************/
'GET /': {
controller : 'games',
action : "gamePopular",
},
'GET /login':{
controller: 'session',
action: "login",
},
'GET /user/profile/:id': {
controller: 'user',
action: "userProfile",
},
'GET /user/edit-profile/:id': {
controller: 'user',
action: "editProfile",
},
'GET /games/detailGame/:id':{
controller:'games',
action:"detailGame",
} ,
'GET /games/add': {
view:'admin/addGame',
},
'GET /games/popular/:page' : {
controller : 'games',
action : "populargame",
},
'GET /games/newgame/:page' : {
controller : 'games',
action : "newgame",
},
'GET /genrelist/add' : {
view:'admin/addGenreList'
},
'GET /ram/add' : {
view:'admin/addRam'
},
'POST /search/:page':{
controller:"games",
action:"search"
} ,
'GET /processor/add' : {
view:'admin/addProcessor'
},
'GET /vga/add' : {
view:'admin/addVga'
},
'GET /register':{
controller: 'session',
action: "register",
},
'GET/games/addspesifikasi' : {
view : 'admin/addSpesifikasi'
},
'GET /games/updatespesifikasi' : {
view : 'admin/updatespek'
},
'GET /spesifikasi/add' : {
view : 'admin/addSpesifikasi'
},
'GET /rekomendasi/rekomendasi' : {
controller : 'rekomendasi',
action : "matriks",
},
'GET /cart/checkcart' : {
controller : 'cart',
action : "checkcart",
},
'GET /user/uploadPhotoProfil' : {
controller : 'user',
action : "uploadPhotoProfil",
},
'GET /vga/updatescore' : {
view : 'admin/updateVga'
},
'GET /user/updateSpek' : {
controller : 'user',
action : "updateSpek",
},
'GET /cart/checkout' : {
controller : 'cart',
action : "checkout",
},
'GET /games/populargameMobile' : {
controller : 'games',
action : "populargameMobile",
},
'GET /games/populargameMobile' : {
controller : 'games',
action : "populargameMobile",
},
'POST /masuk' : {
controller : 'UserMobile',
action : "mobilelogin",
},
'POST /games/populargameMobile' : {
controller : 'games',
action : "populargameMobile",
},
'POST /games/newgameMobile' : {
controller : 'games',
action : "newgameMobile",
},
'POST /rating/addreview' : {
controller : 'rating',
action : "addreview",
},
'POST /games/detailGameMobile/:id' : {
controller : 'games',
action : "detailGameMobile",
},
'GET /admin/adminpanel' : {
controller : 'admin',
action : "userdata",
},
'GET /admin/gamepanel' : {
controller : 'admin',
action : "gamedata",
},
'POST /cart/getCartmobile' : {
controller : 'cart',
action : "getCartmobile",
},
'GET /admin/korelasipanel' : {
controller : 'admin',
action : "matriks",
},
'GET /admin/salespanel' : {
controller : 'admin',
action : "listowngameweb",
},
'GET /admin/frekuensipanel' : {
controller : 'admin',
action : "frekuensigenre",
},
'GET /admin/adminrekomendasi' : {
controller : 'admin',
action : "rekomendasi",
},
'POST /admin/gameedit' : {
controller : 'admin',
action : "editgame",
}
/***************************************************************************
* *
* Custom routes here... *
* *
* If a request to a URL doesn't match any of the custom routes above, it *
* is matched against Sails route blueprints. See `config/blueprints.js` *
* for configuration options and examples. *
* *
***************************************************************************/
};
|
var _viewer = this;
var height = jQuery(window).height() - 50;
var width = jQuery(window).width() - 200;
//取消行点击事件
$(".rhGrid").find("tr").unbind("dblclick");
//每一行添加编辑和删除
$("#TS_BM_GROUP_USER .rhGrid").find("tr").each(function (index, item) {
if (index != 0) {
var dataId = item.id;
$(item).find("td[icode='BUTTONS']").append(
'<a class="rhGrid-td-rowBtnObj rh-icon" id="TS_BM_GROUP_USER_look" operCode="optLookBtn" rowpk="' + dataId + '"><span class="rh-icon-inner">查看</span><span class="rh-icon-img btn-edit"></span></a>' +
'<a class="rhGrid-td-rowBtnObj rh-icon" id="TS_BM_GROUP_USER_delete" actcode="delete" rowpk="' + dataId + '"><span class="rh-icon-inner-notext">删除</span><span class="rh-icon-img btn-delete"></span></a>'
);
// 为每个按钮绑定卡片
bindCard();
}
});
/*
* 删除前方法执行
*/
_viewer.beforeDelete = function (pkArray) {
showVerify(pkArray, _viewer);
}
//绑定的事件
function bindCard() {
//当行删除事件
jQuery("td [id='TS_BM_GROUP_USER_delete']").unbind("click").bind("click", function () {
var pkCode = jQuery(this).attr("rowpk");
rowDelete(pkCode, _viewer);
});
//查看
jQuery("td [id='TS_BM_GROUP_USER_look']").unbind("click").bind("click", function () {
var pkCode = jQuery(this).attr("rowpk");
//$(".hoverDiv").css('display','none');
openMyCard(pkCode, true);
});
/* //当行编辑事件
jQuery("td [id='TS_BM_GROUP_USER-upd']").unbind("click").bind("click", function() {
var pkCode = jQuery(this).attr("rowpk");
var height = jQuery(window).height()-200;
var width = jQuery(window).width()-200;
rowEdit(pkCode,_viewer,[width,height],[100,100]);
});*/
}
//列表操作按钮 弹dialog
function openMyCard(dataId, readOnly, showTab) {
var temp = {
"act": UIConst.ACT_CARD_MODIFY,
"sId": _viewer.servId,
"parHandler": _viewer,
"widHeiArray": [width, height],
"xyArray": [50, 50]
};
temp[UIConst.PK_KEY] = dataId;
if (readOnly != "") {
temp["readOnly"] = readOnly;
}
if (showTab != "") {
temp["showTab"] = showTab;
}
var cardView = new rh.vi.cardView(temp);
cardView.show();
}
_viewer.getBtn("impUser").unbind("click").bind("click", function (event) {
var configStr = "TS_ORG_USER_ALL,{'TARGET':'USER_CODE~USER_NAME~USER_LOGIN_NAME','SOURCE':'USER_CODE~USER_NAME~USER_LOGIN_NAME'," +
"'HIDE':'','TYPE':'multi','HTMLITEM':''}";
var options = {
"config": configStr,
// "params" : {"_TABLE_":"SY_ORG_USER"},
"parHandler": _viewer,
"formHandler": _viewer.form,
"replaceCallBack": function (idArray) {//回调,idArray为选中记录的相应字段的数组集合
var codes = idArray.USER_CODE.split(",");
var names = idArray.USER_NAME.split(",");
var paramArray = [];
for (var i = 0; i < codes.length; i++) {
var param = {};
//群组ID
param.G_ID = _viewer.getParHandler()._pkCode;
//用户编码
param.USER_DEPT_CODE = codes[i];
//用户名称
param.USER_DEPT_NAME = names[i];
//选取类型 1人员
param.G_TYPE = 1;
//岗位类别 序列
var result = FireFly.byId("SY_HRM_ZDSTAFFPOSITION", codes[i]);
if (result != null) {
param.GW_LB = result.STATION_TYPE;
param.GW_XL = result.STATION_NO;
}
// 一二机构
var paramstr = {};
paramstr["user_code"] = codes[i];
var resultstr = FireFly.doAct("TS_BMSH_PASS", "getDept", paramstr);
param.FIR_LEVEL = resultstr.LEVEL0;
param.SEN_LEVEL = resultstr.LEVEL1;
param.ODEPT_CODE= resultstr.dept_code;
paramArray.push(param);
}
var batchData = {};
batchData.BATCHDATAS = paramArray;
//批量保存
var rtn = FireFly.batchSave(_viewer.servId, batchData, null, true, false);
_viewer.refresh();
}
};
//2.用系统的查询选择组件 rh.vi.rhSelectListView()
var queryView = new rh.vi.rhSelectListView(options);
queryView.show(event, [], [0, 495]);
});
_viewer.getBtn("impDept").unbind("click").bind("click", function (event) {
// var configStr = "TS_ORG_DEPT,{'TARGET':'DEPT_CODE~DEPT_NAME','SOURCE':'DEPT_CODE~DEPT_NAME'," +
// "'HIDE':'DEPT_CODE','TYPE':'multi','HTMLITEM':''}";
var configStr = "TS_ORG_DEPT_ALL,{'TYPE':'multi'}";
var options = {
"config": configStr,
// "params" : {"_TABLE_":"SY_ORG_USER"},
"params": {"USE_SERV_ID": "TS_ORG_DEPT"},
"parHandler": _viewer,
"formHandler": _viewer.form,
"replaceCallBack": function (idArray, nameArray) {//回调,idArray为选中记录的相应字段的数组集合
var codes = idArray;
var names = nameArray;
var paramArray = [];
for (var i = 0; i < codes.length; i++) {
var param = {};
//群组ID
param.G_ID = _viewer.getParHandler()._pkCode;
//用户编码
param.USER_DEPT_CODE = codes[i];
//用户名称
param.USER_DEPT_NAME = names[i];
//选取类型 1人员
param.G_TYPE = 2;
paramArray.push(param);
}
var batchData = {};
batchData.BATCHDATAS = paramArray;
//批量保存
var rtn = FireFly.batchSave(_viewer.servId, batchData, null, 2, false);
_viewer.refresh();
}
};
//2.用系统的查询选择组件 rh.vi.rhSelectListView()
// var queryView = new rh.vi.rhSelectListView(options);
var queryView = new rh.vi.rhDictTreeView(options);
queryView.show(event, [], [0, 495]);
});
//从excel中导入人员
const IMPORT_FILE_ID = _viewer.servId + "-impUserByExcel";
var $importUser = $('#' + IMPORT_FILE_ID);
var $impFile = jQuery('#' + _viewer.servId + '-impFile');
//避免刷新数据重复添加
if ($importUser.length === 0) {
var config = {
"SERV_ID": _viewer.servId,
"TEXT": "导入用户",
"FILE_CAT": "",
"FILENUMBER": 1,
"BTN_IMAGE": "btn-imp",
// "VALUE": 15,
"TYPES": "*.xls;*.xlsx;",
"DESC": ""
};
var file = new rh.ui.File({
"id": IMPORT_FILE_ID,
"config": config
});
file._obj.insertBefore($impFile);
$("#" + file.time + "-upload span:first").css('padding', '0 7px 2px 20px');
jQuery('<span class="rh-icon-img btn-imp"></span>').appendTo($("#" + file.time + "-upload"));
file.initUpload();
file.afterQueueComplete = function (fileData) {// 这个上传队列完成之后
console.log("这个上传队列完成之后" + fileData);
for (var propertyName in fileData) {
var filesize = fileData[propertyName].FILE_SIZE;
if(filesize>1024*1024*20){
alert("文件超过20M");
file.clear();
return false;
}
var fileId = fileData[propertyName].FILE_ID;
if (fileId) {
var data = {};
// data.XM_SZ_ID = xmSzId;
data.G_ID = _viewer.getParHandler()._pkCode;
data.FILE_ID = fileId;
FireFly.doAct(_viewer.servId, "saveFromExcel", data, false, false, function (data) {
rh.ui.File.prototype.downloadFile(data.FILE_ID, "test");
_viewer.refresh();
alert(data._MSG_);
});
}
}
file.clear();
};
}
$importUser.find('object').css('cursor', 'pointer');
$importUser.find('object').css('z-index', '999999999');
$importUser.find('object').css('width', '100%');
$importUser.attr('title', '导入文件为excel格式文件,内容为无标题的单列数据,一行数据为一个用户,数据为人力资源编码、统一认证号、身份证号');
//导入模板下载
$impFile.unbind('click').bind('click', function () {
window.open(FireFly.getContextPath() + '/ts/imp_template/项目可见报名人员导入模板.xls');
}); |
import React from 'react';
import gql from 'graphql-tag';
import { useRouter } from 'next/router';
import { useMutation } from '@apollo/react-hooks';
import Form from './styles/Form';
import formatMoney from '../lib/formatMoney';
import Error from './ErrorMessage';
import { useForm } from '../hooks/useForm';
export const CREATE_ITEM_MUTATION = gql`
mutation CREATE_ITEM_MUTATION(
$title: String!
$description: String!
$price: Int!
$image: String
$largeImage: String
) {
createItem(title: $title, description: $description, price: $price, image: $image, largeImage: $largeImage) {
id
}
}
`;
export default function CreateItem() {
const initialValues = {
title: '',
description: '',
image: '',
largeImage: '',
price: 0,
};
const [values, handleChange] = useForm(initialValues);
const [createItem] = useMutation(CREATE_ITEM_MUTATION);
const router = useRouter();
const uploadFile = async e => {
const { files } = e.target;
const data = new FormData();
data.append('file', files[0]);
data.append('upload_preset', 'ddl35kq6');
const res = await fetch('https://api.cloudinary.com/v1_1/du3mknohf/image/upload', {
method: 'POST',
body: data,
});
const file = await res.json();
handleChange({
target: { name: 'image', value: file.secure_url },
});
handleChange({
target: { name: 'largeImage', value: file.eager[0].secure_url },
});
};
return (
<Form
onSubmit={async e => {
e.preventDefault();
const res = await createItem({
variables: values,
});
router.push({
pathname: '/item',
query: { id: res.data.createItem.id },
});
}}
>
<fieldset>
<label htmlFor="file">
Image
<input type="file" id="file" name="file" placeholder="Upload an image" required onChange={uploadFile} />
{values.image && <img width="200" src={values.image} alt="Upload Preview" />}
</label>
</fieldset>
<fieldset>
<label htmlFor="title">
Title
<input
type="text"
id="title"
name="title"
placeholder="Title"
required
value={values.title}
onChange={handleChange}
/>
</label>
<label htmlFor="price">
Price
<input
type="number"
id="price"
name="price"
placeholder="Price"
required
value={values.price}
onChange={handleChange}
/>
</label>
<label htmlFor="description">
Description
<textarea
id="description"
name="description"
placeholder="Enter A Description"
required
value={values.description}
onChange={handleChange}
/>
</label>
<button type="submit">Submit</button>
</fieldset>
</Form>
);
}
|
//==================================
// NEWS READER
//==================================
/*
Composite pattern is used for this solution
To extend the code with new type like hastag,
we will have to create a method name called
hashtagFormatter that will consume the factory
function 'formatterInterface' using function composition.
Then we will have to add the mapping type in the constant
formatterMapping
Output formats considered:
Module 1:
=========
Module one output is considered to be in the string format
Module 2:
=========
Module two output is in the format of array of objects.
Object's format will be as follows
{
startIndex,
endIndex,
type
}
*/
/**
*
* @param {object} props
* Mimicing interface implementation in JS to make sure that all the types(like entity, link, twitterUsername) has the format method.
*/
const formatterInterface = (props) => ({
type: 'formatInterface',
format: () => props.format(props)
});
/**
*
* @param {object} props
* This method is used to generate the composite object.
*/
const getCompositeObj = (props) => {
const interfaceObj = formatterInterface(props);
return Object.create(interfaceObj);
};
/**
*
* @param {string} entity
* This method is used to format the entity type.
*/
const entityFormatter = (entity) => {
const props = {
entity,
format: (props) => `<strong>${props.entity}</strong>`
};
return Object.assign(getCompositeObj(props), {
entity
})
}
/**
*
* @param {string} link
* This method is used to format the link type.
*/
const linkFormatter = (link) => {
const props = {
link,
format: (props) => `<a href="${props.link}">${props.link}</a>`
};
return Object.assign(getCompositeObj(props), {
link
})
}
/**
*
* @param {string} userName
* This method is used to format the twitter username type.
*/
const twitterUsernameFormatter = (userName) => {
const props = {
userName,
format: (props) => {
const {
userName
} = props;
return `${userName[0]}<a href="https://twitter.com/${userName.substring(1)}">${userName.substring(1)}</a>`
}
};
return Object.assign(getCompositeObj(props), {
userName
})
}
/**
*
* @param {string} hashTag
* This method is used to format the twitter hashtag type.
*/
const twitterHashtagFormatter = (hashTag) => {
const props = {
hashTag,
format: (props) => {
const {
hashTag
} = props;
return `${hashTag[0]}<a href="https://twitter.com/hashtag/${hashTag.substring(1)}">${hashTag.substring(1)}</a>`
}
};
return Object.assign(getCompositeObj(props), {
hashTag
})
}
/**
* This variable stores the mapping between types and formatters.
*/
const formatterMapping = {
entity: entityFormatter,
twitterUsername: twitterUsernameFormatter,
link: linkFormatter,
twitterHashtag: twitterHashtagFormatter,
};
/**
*
* @param {string} crawledString | crawledString is the output of module one
* @param {array} parsedObj | paresedObj is the output of module two. parsedObj is array of objects.
* This is the main method used to generate the module three output.
*/
const newsReader = (crawledString, parsedObj) => {
let processedString = crawledString;
parsedObj.forEach(obj => {
const {
startIndex,
endIndex,
type
} = obj;
const stringToBeParsed = crawledString.substring(startIndex, endIndex);
//Checking if the formatter mapping exists and if the mapping is of type function to avoid errors
if (formatterMapping[type] && typeof formatterMapping[type] === 'function') {
const formattedString = formatterMapping[type](stringToBeParsed);
//Checking if the formatter mapping is actually a formatInterface
if (Object.getPrototypeOf(formattedString).type === "formatInterface") {
processedString = processedString.replace(stringToBeParsed, formatterMapping[type](stringToBeParsed).format());
}
}
})
return processedString;
}
//Output one : output for the example given in technical challenge
const output1 = newsReader("Obama visited Facebook headquarters: http://bit.ly/xyz @elversatile", [{
startIndex: 14,
endIndex: 22,
type: 'entity'
}, {
startIndex: 0,
endIndex: 5,
type: 'entity'
}, {
startIndex: 55,
endIndex: 67,
type: 'twitterUsername'
}, {
startIndex: 37,
endIndex: 54,
type: 'link'
}]);
//Output two: output for the example that contains hashtag type
const output2 = newsReader("Obama visited Facebook headquarters: http://bit.ly/xyz @elversatile #usPrez", [{
startIndex: 14,
endIndex: 22,
type: 'entity'
}, {
startIndex: 0,
endIndex: 5,
type: 'entity'
}, {
startIndex: 55,
endIndex: 67,
type: 'twitterUsername'
}, {
startIndex: 37,
endIndex: 54,
type: 'link'
}, {
startIndex: 68,
endIndex: 76,
type: 'twitterHashtag'
}]);
//Output three: output for the example that contains invalid type that are not there in the mapped object
const output3 = newsReader("Obama visited Facebook headquarters: http://bit.ly/xyz @elversatile #usPrez", [{
startIndex: 14,
endIndex: 22,
type: 'entityInvalid'
}, {
startIndex: 0,
endIndex: 5,
type: 'entity'
}, {
startIndex: 55,
endIndex: 67,
type: 'twitterUsernameInvalid'
}, {
startIndex: 37,
endIndex: 54,
type: 'link'
}, {
startIndex: 68,
endIndex: 76,
type: 'twitterHashtag'
}]);
console.log(output1);
console.log(output2);
console.log(output3); |
import React, { Component } from "react";
import NavBar from "./components/NavBar/NavBar";
import TopDestinations from "./components/TopDestinations/TopDestinations";
import Products from "./components/Products/Products";
import MainContent from "./components/MainContent/MainContent";
import Form from "./components/Form/Form";
import Footer from "./components/Footer/Footer";
import { Link } from "react-scroll";
function App() {
return (
// All this is my Landing page
<div className="Landing" id="Landing">
<div class="hero-image">
<NavBar />
<h1>Stay & Vacay</h1>
<div className="explore-button">
{/* Smoothe Scroll */}
<Link
activeClass="active"
to="TopDestinations"
spy={true}
smooth={true}
offset={-70}
duration={1000}
type="button"
>
Explore
</Link>
</div>
</div>
<TopDestinations />
<MainContent />
<Products />
<Form />
<Footer />
</div>
);
}
export default App;
|
const state = [{
href: "flexBoxGallery/",
text: "Simple Flexbox Gallery"
},
{
href: "intervalTimer/",
text: 'Interval Timer'
},
{
href: "calculator/",
text: 'Calculator'
},
{
href: "taskList/",
text: 'Task List'
},
{
href: "randomPonyName/",
text: 'MLP Name Generator'
},
{
href: "secretSanta/",
text: 'Secret Santa Generator'
}
]
const render = () => state.reduce((str, project) => (str + `
<li>
<a href="${ project.href }">
<span class="icon">
<i class="fas fa-lg fa-folder"></i>
</span>${ project.text }</a>
</li>
`), '')
module.exports = {render} |
const {
AkairoClient,
CommandHandler,
ListenerHandler,
} = require("discord-akairo");
const { Intents } = require("discord.js");
const { join } = require("path");
const { CreatePrompt } = require("../Utility/CreatePrompt");
const config = require("../config");
const { CreateEmbed } = require("../Utility/CreateEmbed");
const { logger } = require("../Utility/Logger");
module.exports = class PythagorasClient extends AkairoClient {
constructor() {
super(
{
ownerID: config.owners,
},
{
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_BANS,
Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
Intents.FLAGS.GUILD_MEMBERS,
],
}
);
this.logger = logger;
this.config = config;
this.CommandHandler = new CommandHandler(this, {
allowMention: true,
directory: join(__dirname, "..", "Commands"),
prefix: config.prefix,
defaultCooldown: 3000,
argumentDefaults: {
prompt: {
modifyStart: (message, text) => ({
embeds: [CreateEmbed("info", CreatePrompt(text))],
}),
modifyRetry: (message, text) => ({
embeds: [CreateEmbed("info", CreatePrompt(text))],
}),
modifyTimeout: () => ({
embeds: [CreateEmbed("warn", "⛔ | command timeout.")],
}),
modifyEnded: () => ({
embeds: [CreateEmbed("warn", "⛔ | command ended.")],
}),
modifyCancel: () => ({
embeds: [
CreateEmbed(
"info",
"⛔ | invalid arguments, command session has ended."
),
],
}),
retries: 3,
time: 30000,
},
},
})
.on("commandFinished", (msg, command) => {
this.logger.info(
`[${msg.author.tag}] USING [${command.id.toUpperCase()}] COMMANDS`
);
})
.on("cooldown", async (msg, command, remaining) => {
const awaitMsg = await msg.channel.send(
CreateEmbed(
"warn",
`Chill.. wait ${(remaining / 1000).toFixed(
2
)} second(s) to use command again`
)
);
setTimeout(() => awaitMsg.delete(), remaining);
this.logger.warn(
`[${
msg.author.tag
}] GETTING RATE LIMIT ON [${command.id.toUpperCase()}] COMMANDS`
);
});
this.ListenerHandler = new ListenerHandler(this, {
directory: join(__dirname, "..", "Listeners"),
});
}
initialize() {
this.CommandHandler.loadAll();
this.ListenerHandler.loadAll();
// console.log(process.env.DISCORD_TOKEN)
//this.login(process.env.DISCORD_TOKEN);
}
};
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import DragContainer from '../components/DragContainer.js'
storiesOf('DragContainer', module)
.add('testing', () => {
class Foo extends React.Component {
render () {
return (
<div
ref={this.props.dragContainerRef}
style={{
border: 'thin solid green',
padding: 100,
...(this.props.style || {})
}}
>
<span ref={this.props.dragHandleRef}>Foo</span>
</div>
)
}
}
return (
<div>
yo
<DragContainer
style={{position: 'relative'}}
>
{
[1,2,3].map((i) => {
return (
<Foo
key={i}
pos={{x : i * 50, y: i * 50}}
>
{i}
</Foo>
)
})
}
</DragContainer>
</div>
)
})
|
import React from 'react'
import { connect } from 'react-redux'
class Layers extends React.PureComponent {
render() {
const { layers, layer, opacity, setOpacity } = this.props
if (!layers || !layers.length) return null
return (
<div>
<input type="range"
min={0}
max={100}
value={opacity > -1 ? opacity : 100}
onChange={(e) => setOpacity(e.target.value)} />
<select className="form-control" value={layer?.id} onChange={this.handleChange.bind(this)}>
<option value={null}>No historic map</option>
{layers.map(l => <option key={l.id} value={l.id}>{l.name}</option>)}
</select>
</div>
)
}
handleChange(event) {
const value = parseInt(event.currentTarget.value)
const layer = this.props.layers.find(l => l.id === value)
this.props.toggle(layer?.id)
}
}
const mapStateToProps = state => {
return { ...state.layers }
}
const actions = {
toggle: (id) => ({ type: 'LAYER_TOGGLE', id }),
setOpacity: (opacity) => ({ type: 'LAYER_OPACITY', opacity })
}
const Component = connect(mapStateToProps, actions)(Layers)
export default Component
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Breed = new Schema(
{ title: String },
{ collection: 'breeds' }
);
const toResponse = (breed) => {
const { id, title } = breed;
return { id, title };
};
module.exports = {
Breed: mongoose.model('breeds', Breed),
toResponse,
};
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, {Component} from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator, //存放界面你的栈的容器
} from 'react-native';
//引入主界面
var Home = require('./js/TabBottom');
//相当于application,Navigatory一定要在应用启动的时候初始化
class RnProject extends Component {
constructor(props) {
super(props)
}
render() {
return (
<Navigator style={styles.container}
initialRoute={{
component: Home //将根界面压栈
}}
renderScene={(route, navigator) => { // 用来渲染navigator栈顶的route里的component页面
return <route.component navigator={navigator} {...route} {...route.passProps}/>// {...route.passProps}即就是把passProps里的键值对全部以给属性赋值的方式展开 如:test={10}
}}/>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1
}
});
AppRegistry.registerComponent('RnProject', () => RnProject);
|
/**
* Created by liu 2018/6/5
**/
import React, {Component} from 'react';
import {Form, Select, Input, Radio, Button, DatePicker, message} from 'antd';
import moment from 'moment'
const RadioGroup = Radio.Group;
const Option = Select.Option;
const FormItem = Form.Item;
function hasErrors(fieldsError) {
return Object.keys(fieldsError).some(field => fieldsError[field]);
}
class EditAPI extends Component {
componentDidMount() {
if (this.itemData) {
this.props.form.setFieldsValue({
apiKey: this.itemData.apiKey,
apiSecretKey: this.itemData.apiSecretKey,
id: this.itemData.apiSecretKey,
ip: this.itemData.ip,
status: this.itemData.status,
userId: this.itemData.userId,
})
}
}
componentWillMount() {
this.itemData = this.props.itemData || null
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
if (this.itemData) {
values.id = this.itemData.id
}
this.props.postData(values)
}
});
}
render() {
const {getFieldDecorator, getFieldsError, getFieldError, isFieldTouched} = this.props.form;
const formItemLayout = {
labelCol: {span: 6},
wrapperCol: {span: 14},
};
return (
<Form onSubmit={this.handleSubmit}>
<FormItem label={`用户id`} {...formItemLayout} >
{getFieldDecorator('userId', {
rules: [{required: true, message: '不能为空'}],
})(
<Input className={'edit-input-view'} placeholder=""/>
)}
</FormItem>
<FormItem
{...formItemLayout} label={`KEY`}>
{getFieldDecorator('apiKey', {
rules: [{required: true, message: '不能为空'}],
})(
<Input className={'edit-input-view'}/>
)}
</FormItem>
<FormItem
{...formItemLayout} label={`密钥`}>
{getFieldDecorator('apiSecretKey', {
rules: [{required: true, message: '不能为空'}],
})(
<Input className={'edit-input-view'}/>
)}
</FormItem>
<FormItem
{...formItemLayout} label={`IP`}>
{getFieldDecorator('ip', {
rules: [{message: '不能为空'}],
})(
<Input className={'edit-input-view'} placeholder="多个ip使用英文;分隔"/>
)}
</FormItem>
<FormItem {...formItemLayout} label={`状态`}>
{getFieldDecorator('status', {
rules: [], initialValue: 0
})(
<Select
style={{width: '200px'}}
placeholder="状态"
>
<Option key='android' value={0}>启动</Option>
<Option key='ios' value={1}>禁用</Option>
</Select>
)}
</FormItem>
<div style={{display: 'flex', flex: 1, justifyContent: 'center'}}>
<Button
onClick={this.handleSubmit}
type="primary"
style={{marginRight: '20px'}}
disabled={hasErrors(getFieldsError())}
>
提交
</Button>
<Button onClick={this.props.onCancel}>返回 </Button>
</div>
</Form>
)
}
}
const NewEditAPI = Form.create()(EditAPI);
export default NewEditAPI
|
import { Text, View, Image, ScrollView, StyleSheet, Alert, TouchableOpacity, AppState, StatusBar } from 'react-native'
import React from 'react';
import expect from 'expect';
import Enzyme, { shallow } from 'enzyme';
import { Provider } from "react-redux";
import Adapter from 'enzyme-adapter-react-16';
import store from '../../store/store';
import Dashboard from '../../screens/Dashboard';
import NewMonitor from '../../components/NewMonitor';
Enzyme.configure({ adapter: new Adapter() });
describe('dashboard component testing', () => {
it("should render without throwing an error", () => {
expect(
shallow(
<Provider store={store}>
<Dashboard />
</Provider>
).exists(
<View>
<NewMonitor text={'Door'} />
<NewMonitor text={'Gas'} />
<NewMonitor text={'Garage'} />
</View>
)
).toBe(true);
});
}); |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = function (Vue) {
Vue.directive('touch', {
bind: function bind(el, binding, vnode) {
var type = binding.arg; // 传入点击的类型
var coordinate = {}; // 记录坐标点的对象
var timeOutTap = void 0;
var timeOutLong = void 0;
var scaleSize = void 0; // 缩放尺寸
var displacement = {}; //移动的位移
// 勾股定理计算距离
function getDistance(bg, end) {
return Math.sqrt(Math.pow(end.x - bg.x, 2) + Math.pow(end.y - bg.y, 2));
}
// 点击开始的时候
el.addEventListener('touchstart', function (e) {
// 获取第一个手指点击的坐标
var x = e.touches[0].pageX;
var y = e.touches[0].pageY;
// 如果点击的时间很长,那么点击的类型就是长按 --- longTouch
timeOutLong = setTimeout(function () {
timeOutLong = 0;
if (type === 'longTouch') {
binding.value.func(binding.value.param);
}
}, 2000);
timeOutTap = setTimeout(function () {
timeOutTap = 0;
if (type === 'tap' && e.touches.length === 1) {
binding.value.func(binding.value.param);
}
}, 200);
// 如果是两个手指,而且类型是缩放 --- scaleTocuh
if (e.touches.length > 1 && type === 'scaleTouch') {
// 记录双指的间距长度
coordinate.start = getDistance({
x: e.touches[0].pageX,
y: e.touches[0].pageY
}, {
x: e.touches[1].pageX,
y: e.touches[1].pageY
});
}
// 如果是移动的话,还要记录下来最开始的位置,只能一个手指位移
if (type === 'slideTouch' && e.touches.length == 1) {
// debugger
displacement.start = {
x: e.touches[0].pageX,
y: e.touches[0].pageY
};
}
}, false);
el.addEventListener('touchmove', function (e) {
clearTimeout(timeOutTap);
clearTimeout(timeOutLong);
timeOutTap = 0;timeOutLong = 0;
// 如果是缩放类型
if (type == 'scaleTouch' && e.touches.length === 2) {
// 计算移动过程中的两个手指的距离
coordinate.stop = getDistance({
x: e.touches[0].pageX,
y: e.touches[0].pageY
}, {
x: e.touches[1].pageX,
y: e.touches[1].pageY
});
// 设置缩放尺寸
scaleSize = coordinate.stop / coordinate.start - 1;
// 这里设置图片不能无限放大与缩小
// 这里设置放大缩小速度慢一点,所以 /4一下
binding.value.func(scaleSize / 2, false);
}
// 如果是移动类型
if (type == 'slideTouch' && e.touches.length === 1) {
displacement.end = {
x: e.changedTouches[0].pageX,
y: e.changedTouches[0].pageY
};
binding.value.func({ x: displacement.end.x - displacement.start.x, y: displacement.end.y - displacement.start.y, is_endMove: false });
}
}, false);
el.addEventListener('touchend', function (e) {
if (type === 'scaleTouch') {
binding.value.func(0, true);
}
if (type === 'slideTouch') {
binding.value.func({ x: 0, y: 0, is_endMove: true });
}
}, false);
}
});
}; |
/**
* @param {number[]} numbers
* @param {number} target
* @return {number[]}
*/
//same solution as twosum
var twoSum = function (numbers, target) {
const N = new Map();
for (let i = 0; i < numbers.length; i++) {
N.set(numbers[i], i);
// stills work the arr is non-descreasing,
//if at least two n equal, and n + n = target, the save index will be the last one.
// while loop through the arr, we will access the first n with different index. => the condition satified => return result.
}
for (let i = 0; i < numbers.length; i++) {
const findIndex = N.get(target - numbers[i]);
if (findIndex && findIndex !== i) return [i + 1, findIndex + 1];
}
};
//optimize space
var betterTwoSum = function (numbers, target) {
let l = 0,
r = numbers.length - 1;
while (l !== r && target !== numbers[l] + numbers[r]) {
if (numbers[r] + numbers[l] > target) {
r--;
}
if (numbers[r] + numbers[l] < target) {
l++;
}
}
return [l + 1, r + 1];
};
|
import React from 'react';
import { shallow } from 'enzyme';
import Stars from '../client/src/components/Stars.jsx';
import { stars } from './testDummyData.js' ;
describe('Stars', () => {
it('should be defined', () => {
expect(Stars).toBeDefined();
});
it('should render correctly', () => {
const tree = shallow(
<Stars name="Star test" stars={stars} />
);
expect(tree).toMatchSnapshot();
})
})
|
let btnNav = document.querySelector('.mobile');
let links = document.querySelector('.links');
let btnClose = document.querySelector('.close');
let btnLinks = document.querySelectorAll('li');
let titleCapa = document.querySelector('.titulo__capa');
let target = document.querySelectorAll('.animate');
let animateClass = 'animate__animated animate__fadeInLeft animate__delay-.8s';
let v1 = 'animate__animated'
let v2 ='animate__fadeInLeft'
let v3 ='animate__delay-.8s'
const debounce = (func, wait, immediate) =>{
let timeout;
return function(...args){
const context = this;
const later = () =>{
timeout = null;
if(!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args)
}
}
const animeScroll = () =>{
const windowTop = window.pageYOffset + ((window.innerHeight * 3) / 4);
target.forEach(val =>{
if(windowTop > val.offsetTop){
val.classList.add(v1, v2, v3);
}else{
val.classList.remove(v1, v2, v3);
}
})
}
animeScroll();
if(target.length)
{
window.addEventListener('scroll', debounce(() =>{
animeScroll();
}, 100))
}
const fecharLinks = () =>{
fecharNav();
}
const abrirNav = () =>{
links.style.left = 0;
}
const fecharNav = () =>{
links.style.left = '-100%';
}
const removeClasseCapa = () =>{
setTimeout(()=>{
titleCapa.classList.remove('animate__fadeInLeft');
}, 1300)
}
const scrollTop = () => {
window.scrollTo(0, 0)
}
removeClasseCapa();
btnNav.addEventListener('click', abrirNav)
btnClose.addEventListener('click', fecharNav);
|
function reverseWords(string){
var stringArr = string.split(' '),
newArr =[];
stringArr.forEach(element => {
newWord = ""
for (i = element.length; i > 0; i--){
newWord += element[i - 1]
console.log(element, i)
}
newArr.push(newWord)
});
return newArr.join(' ')
}
console.log(reverseWords("This is a string")); |
class Card {
// getTemplate - возвращает только шаблон, на вход получает данные любой карточки,
// на выходе только разметка, для единственной любой карточки
constructor(api) {
this.api = api;
}
getTemplate(cardName, cardLink, cardLikes, cardOwnerID, cardID) {
return `<div class="place-card" id="${this.getIconUserCard(cardOwnerID, cardID)}">
<div class="place-card__image" style="background-image: url(${this.sanitizeHTMLUpdate(cardLink)}">
<button class="place-card__delete-icon${this.addIcon(cardOwnerID)}"></button>
</div>
<div class="place-card__description">
<h3 class="place-card__name">${this.sanitizeHTMLUpdate(cardName)}</h3>
<div class="counter">
<button class="place-card__like-icon"></button>
<p class="place-card__number-like">${this.getSumLike(cardLikes)}</p>
</div>
</div>
</div>`
;
}
sanitizeHTMLUpdate(str) {
let temp = str.replace(/[.*+?^${}()<>|[\]\\]/g, '\\$&');
return temp;
}
getSumLike(cardLike) {
return cardLike.length;
}
getIconUserCard(cardOwnerID, cardID){
// Сделать проверку ИД карточки админа с другими пользователями
if (cardOwnerID === 'aae80730aff6f85bc5513f38'){
return cardID;
} else {
return cardID;
}
}
addIcon(cardOwnerID){
if ( cardOwnerID === 'aae80730aff6f85bc5513f38'){
return ' place-card__delete-icon_user';
}
else {
return ''
}
}
// Лайки
likeHandler = event => {
if (event.target.classList.contains('place-card__like-icon')) {
this.api.getLikes(event.target.closest(".place-card").id)
.then(res => {
event.target.nextElementSibling.textContent = res.likes.length;
event.target.classList.add("place-card__like-icon_liked");
})
.catch((err) => {
{} // выведем ошибку в консоль
});
}
if (event.target.classList.contains("place-card__like-icon_liked")){
this.api.removeLikes(event.target.closest(".place-card").id)
.then(res =>{
event.target.nextElementSibling.textContent = res.likes.length;
event.target.classList.remove("place-card__like-icon_liked");
})
.catch((error)=>{})
}
};
// Удаление карты
removeCard = event => {
if (event.target.classList.contains('place-card__delete-icon')) {
if (confirm("Вы уверены, что хотите удалить карточку?")) {
this.api.removeCardsAPI(event.target.closest(".place-card").id)
.catch((err) => {
});
const card = event.target.closest(".place-card");
card.remove();
}
}
}
}
export {Card};
|
var mongoose = require('mongoose'),
encryption = require('../utilities/encryption'),
userSchema = mongoose.Schema({
username: {
type: String,
require: '{PATH} is required',
unique: true
},
firstName: {
type: String,
require: '{PATH} is required'
},
lastName: {
type: String,
require: '{PATH} is required'
},
email: {
type: String,
require: '{PATH} is required'
},
phone: String,
points: {
type: Number,
default: 0
},
initiative: {
type: String,
require: '{PATH} is required'
},
season: {
type: String,
require: '{PATH} is required'
},
image: {
type: String,
default: ''
},
facebook: String,
twitter: String,
linkedin: String,
google: String,
salt: String,
hashPass: String
}),
User = mongoose.model('User', userSchema);
userSchema.method({
authenticate: function authenticate(password) {
if (encryption.generateHashedPassword(this.salt, password) === this.hashPass) {
return true;
} else {
return false;
}
}
});
module.exports.seedInitialUsers = function seedInitialUsers() {
User
.find({})
.exec(function(err, collection) {
if (err) {
console.log('Cannot find users: ' + err);
return;
}
if (collection.length === 0) {
var salt;
var hashedPwd;
salt = encryption.generateSalt();
hashedPwd = encryption.generateHashedPassword(salt, '123456');
User.create({
username: 'pesho',
firstName: 'Pesho',
lastName: 'Peshov',
email: 'pesho@abv.bg',
initiative:'Software Academy',
season: ['Started 2010', 'Started 2011', 'Started 2012', 'Started 2013'],
salt: salt,
hashPass: hashedPwd
});
salt = encryption.generateSalt();
hashedPwd = encryption.generateHashedPassword(salt, '123456');
User.create({
username: 'gosho',
firstName: 'Gosho',
lastName: 'Goshov',
email: 'gosho@abv.bg',
initiative:'Software Academy',
season: 'Started 2010',
salt: salt,
hashPass: hashedPwd
});
console.log("Starting users created");
}
});
};
|
var DaylightMap, updateDateTime;
var eu = ["EL", "ES", "FR", "HR", "IT",
"CY", "LV", "BE", "BG", "CZ", "DK", "DE",
"EE", "IE", "LT", "LU", "HU", "MT", "NL",
"AT", "PL", "PT", "RO", "SI", "SK", "FI",
"SE"];
function randomChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
DaylightMap = function() {
class DaylightMap {
constructor(svg, date, options = {}) {
if (
!(
typeof SunCalc !== "undefined" &&
SunCalc !== null &&
(typeof $ !== "undefined" && $ !== null) &&
(typeof d3 !== "undefined" && d3 !== null)
)
) {
throw new Error("Unmet dependency (requires d3.js, jQuery, SunCalc)");
}
if (!svg) {
throw new TypeError(
"DaylightMap must be instantiated with a valid SVG"
);
}
this.options = {
tickDur: options.tickDur || 400,
shadowOpacity: options.shadowOpacity || 0.16,
bgColorLeft: options.bgColorLeft || "#eee",
bgColorRight: options.bgColorRight || "#eee",
lightsColor: options.lightsColor || "#FFBEA0",
lightsOpacity: options.lightsOpacity || 1,
sunOpacity: options.sunOpacity || 0.11
};
this.PRECISION_LAT = 1; // How many latitudinal degrees per point when checking solar position.
this.PRECISION_LNG = 10; // How may longitudial degrees per sunrise / sunset path point.
this.MAP_WIDTH = options.width || 1100;
this.MAP_HEIGHT = this.MAP_WIDTH / 2;
this.SCALAR_X = this.MAP_WIDTH / 360;
this.SCALAR_Y = this.MAP_HEIGHT / 180;
this.PROJECTION_SCALE = this.MAP_WIDTH / 6.25;
this.WORLD_PATHS_URL = "world-110m.json";
this.CITIES_DATA_URL = "cities-200000.json";
this.MESSAGES_DATA_URL = "messages-cc.json";
this.svg = svg;
this.isAnimating = false;
this.cities = [];
this.messages = [];
this.animInterval = null;
this.currDate = date || new Date();
}
colorLuminance(hex, lum = 0) {
var c, i, rgb;
c = null;
i = 0;
rgb = "#";
hex = String(hex).replace(/[^0-9a-f]/gi, "");
if (hex.length < 6) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
while (i < 3) {
c = parseInt(hex.substr(i * 2, 2), 16);
c = Math.round(Math.min(Math.max(0, c + c * lum), 255)).toString(16);
rgb += ("00" + c).substr(c.length);
i++;
}
return rgb;
}
isDaylight(obj) {
return obj.altitude > 0;
}
isNorthSun() {
return this.isDaylight(SunCalc.getPosition(this.currDate, 90, 0));
}
getSunriseSunsetLatitude(lng, northSun) {
var delta, endLat, lat, startLat;
if (northSun) {
startLat = -90;
endLat = 90;
delta = this.PRECISION_LAT;
} else {
startLat = 90;
endLat = -90;
delta = -this.PRECISION_LAT;
}
lat = startLat;
while (lat !== endLat) {
if (this.isDaylight(SunCalc.getPosition(this.currDate, lat, lng))) {
return lat;
}
lat += delta;
}
return lat;
}
getAllSunPositionsAtLng(lng) {
var alt, lat, peak, result;
lat = -90;
peak = 0;
result = [];
while (lat < 90) {
alt = SunCalc.getPosition(this.currDate, lat, lng).altitude;
if (alt > peak) {
peak = alt;
result = [peak, lat];
}
lat += this.PRECISION_LNG;
}
return result;
}
getSunPosition() {
var alt, coords, lng, peak, result;
lng = -180;
coords = [];
peak = 0;
while (lng < 180) {
alt = this.getAllSunPositionsAtLng(lng);
if (alt[0] > peak) {
peak = alt[0];
result = [alt[1], lng];
}
lng += this.PRECISION_LAT;
}
return this.coordToXY(result);
}
getAllSunriseSunsetCoords(northSun) {
var coords, lng;
lng = -180;
coords = [];
while (lng < 180) {
coords.push([this.getSunriseSunsetLatitude(lng, northSun), lng]);
lng += this.PRECISION_LNG;
}
// Add the last point to the map.
coords.push([this.getSunriseSunsetLatitude(180, northSun), 180]);
return coords;
}
coordToXY(coord) {
var x, y;
x = (coord[1] + 180) * this.SCALAR_X;
y = this.MAP_HEIGHT - (coord[0] + 90) * this.SCALAR_Y;
return {
x: x,
y: y
};
}
getCityOpacity(coord) {
if (SunCalc.getPosition(this.currDate, coord[0], coord[1]).altitude > 0) {
return 0;
}
return 1;
}
getCityRadius(population) {
if (population < 200000) {
return 0.3;
} else if (population < 500000) {
return 0.4;
} else if (population < 100000) {
return 0.5;
} else if (population < 2000000) {
return 0.6;
} else if (population < 4000000) {
return 0.8;
} else {
return 1;
}
}
getPath(northSun) {
var coords, path;
path = [];
coords = this.getAllSunriseSunsetCoords(northSun);
coords.forEach(val => {
return path.push(this.coordToXY(val));
});
return path;
}
getPathString(northSun) {
var path, pathStr, yStart;
if (!northSun) {
yStart = 0;
} else {
yStart = this.MAP_HEIGHT;
}
pathStr = `M 0 ${yStart}`;
path = this.getPath(northSun);
pathStr += this.lineFunction(path);
// Close the path back to the origin.
pathStr += ` L ${this.MAP_WIDTH}, ${yStart} `;
pathStr += ` L 0, ${yStart} `;
return pathStr;
}
createDefs() {
d3.select(this.svg)
.append("defs")
.append("linearGradient")
.attr("id", "gradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "0%");
d3.select("#gradient")
.append("stop")
.attr("offset", "0%")
.attr("stop-color", this.options.bgColorLeft);
d3.select("#gradient")
.append("stop")
.attr("offset", "100%")
.attr("stop-color", this.options.bgColorRight);
d3.select(this.svg)
.select("defs")
.append("linearGradient")
.attr("id", "landGradient")
.attr("x1", "0%")
.attr("y1", "0%")
.attr("x2", "100%")
.attr("y2", "0%");
d3.select("#landGradient")
.append("stop")
.attr("offset", "0%")
.attr(
"stop-color",
this.colorLuminance(this.options.bgColorLeft, -0.2)
);
d3.select("#landGradient")
.append("stop")
.attr("offset", "100%")
.attr(
"stop-color",
this.colorLuminance(this.options.bgColorRight, -0.2)
);
d3.select(this.svg)
.select("defs")
.append("radialGradient")
.attr("id", "radialGradient");
d3.select("#radialGradient")
.append("stop")
.attr("offset", "0%")
.attr("stop-opacity", this.options.sunOpacity)
.attr("stop-color", "rgb(255, 255, 255)");
return d3
.select("#radialGradient")
.append("stop")
.attr("offset", "100%")
.attr("stop-opacity", 0)
.attr("stop-color", "rgb(255, 255, 255)");
}
drawSVG() {
return d3
.select(this.svg)
.attr("width", this.MAP_WIDTH)
.attr("height", this.MAP_HEIGHT)
.attr("viewBox", `0 0 ${this.MAP_WIDTH} ${this.MAP_HEIGHT}`)
.append("rect")
.attr("width", this.MAP_WIDTH)
.attr("height", this.MAP_HEIGHT)
.attr("fill", "url(#gradient)");
}
drawSun() {
var xy;
xy = this.getSunPosition();
return d3
.select(this.svg)
.append("circle")
.attr("cx", xy.x)
.attr("cy", xy.y)
.attr("id", "sun")
.attr("r", 150)
.attr("opacity", 1)
.attr("fill", "url(#radialGradient)");
}
drawPath() {
var path;
path = this.getPathString(this.isNorthSun());
return d3
.select(this.svg)
.append("path")
.attr("id", "nightPath")
.attr("fill", "rgb(0,0,0)")
.attr("fill-opacity", this.options.shadowOpacity)
.attr("d", path);
}
drawLand() {
return $.get(this.WORLD_PATHS_URL, data => {
var projection, worldPath;
projection = d3.geo
.equirectangular()
.scale(this.PROJECTION_SCALE)
.translate([this.MAP_WIDTH / 2, this.MAP_HEIGHT / 2])
.precision(0.1);
worldPath = d3.geo.path().projection(projection);
d3.select(this.svg)
.append("path")
.attr("id", "land")
.attr("fill", "url(#landGradient)")
.datum(topojson.feature(data, data.objects.land))
.attr("d", worldPath);
// Asynchronous so re-order the elements here.
return this.shuffleElements();
});
}
weighted_random(options) {
var i;
var weights = [];
for (i = 0; i < options.length; i++) {
weights[i] = parseInt(options[i][2]) + (weights[i - 1] || 0);
}
var random = Math.random() * weights[weights.length - 1];
for (i = 0; i < weights.length; i++) {
if (weights[i] > random) {
break;
}
}
return [parseFloat(options[i][0]), parseFloat(options[i][1])];
}
drawMessages() {
return $.get(this.CITIES_DATA_URL, city => {
var cityMap = {};
city
.map(x => {
return [x[5], x[2], x[3], x[0]];
})
.forEach(y => {
if (cityMap[y[0]] === undefined) {
cityMap[y[0]] = [];
}
cityMap[y[0]].push([y[1], y[2], y[3]]);
});
return fetch(this.MESSAGES_DATA_URL)
.then(response => response.json())
.then(msg => {
var tmp = msg.map(x => {
var ts = x[0],
cc = x[1];
if (cc == "NL"){
cc = randomChoice(eu);
if(cityMap[cc] === undefined){
cc = "NL";
}
console.log("NL", cc);
}
var z = this.weighted_random(cityMap[cc]);
return [ts, z, cc]
}).forEach((val, i) => {
var coords = [parseFloat(val[1][0]), parseFloat(val[1][1])],
xy = this.coordToXY(coords),
id = `msg-${val[0]}-${val[1]}`.replaceAll(',', '').replaceAll('.', '');
d3.select(this.svg)
.append("circle")
.attr("cx", xy.x)
.attr("cy", xy.y)
.attr("id", id)
.attr("r", 3)
.attr("opacity", 0)
.attr("fill", `hsl(${Math.random() * 256}, 80%, 50%)`);
return this.messages.push({
title: id,
country: val[2],
latlng: coords,
date: moment(parseFloat(val[0]) * 1000),
xy: xy,
id: id,
opacity: 0
});
})
});
});
}
drawCities() {
return $.get(this.CITIES_DATA_URL, data => {
return data.forEach((val, i) => {
var coords, id, opacity, radius, xy;
coords = [parseFloat(val[2]), parseFloat(val[3])];
xy = this.coordToXY(coords);
id = `city${i}`;
opacity = this.getCityOpacity(coords);
radius = this.getCityRadius(val[0]) * 2;
d3.select(this.svg)
.append("circle")
.attr("cx", xy.x)
.attr("cy", xy.y)
.attr("id", id)
.attr("r", radius)
.attr("opacity", opacity * this.options.lightsOpacity)
.attr("fill", this.options.lightsColor);
return this.cities.push({
title: val[1],
country: val[5],
latlng: coords,
xy: xy,
population: parseInt(val[0]),
id: id,
opacity: opacity
});
});
});
}
searchCities(str) {
var cities;
cities = _.filter(this.cities, function(val) {
return val.title.toLowerCase().indexOf(str) === 0;
});
cities = _.sortBy(cities, function(val) {
return val.population;
});
return cities.reverse();
}
redrawSun(animate) {
var curX, xy;
xy = this.getSunPosition();
curX = parseInt(d3.select("#sun").attr("cx"));
if (animate && Math.abs(xy.x - curX) < this.MAP_WIDTH * 0.8) {
return d3
.select("#sun")
.transition()
.duration(this.options.tickDur)
.ease("linear")
.attr("cx", xy.x)
.attr("cy", xy.y);
} else {
return d3
.select("#sun")
.attr("cx", xy.x)
.attr("cy", xy.y);
}
}
redrawCities() {
var k;
k = 0;
return this.cities.forEach((val, i) => {
var opacity;
opacity = this.getCityOpacity(val.latlng);
if (val.opacity !== opacity) {
this.cities[i].opacity = opacity;
k++;
return d3
.select(`#${val.id}`)
.transition()
.duration(this.options.tickDur * 2)
.attr("opacity", this.options.lightsOpacity * opacity);
}
});
}
redrawMessages() {
var k;
k = 0;
var z0 = 5000000, z1 = 10000000;
console.log(this.messages.filter(x => { (moment(this.currDate) - x.date) > 0 }).length)
return this.messages.forEach((val, i) => {
var opacity = 0;
var diff = moment(this.currDate) - val.date
if (diff > 0 && diff < z0) {
opacity = 0.5;
} else if (diff > z0 && diff < z1) {
opacity = 0.5 - ((diff - (z0)) / (z1 - z0))/2;
}
if (val.opacity !== opacity) {
this.messages[i].opacity = opacity;
k++;
return d3
.select(`#${val.id}`)
.transition()
.duration(this.options.tickDur * 2)
.attr("opacity", this.options.lightsOpacity * opacity);
}
});
}
redrawPath(animate) {
var nightPath, path;
path = this.getPathString(this.isNorthSun(this.currDate));
nightPath = d3.select("#nightPath");
if (animate) {
return nightPath
.transition()
.duration(this.options.tickDur)
.ease("linear")
.attr("d", path);
} else {
return nightPath.attr("d", path);
}
}
redrawAll(increment = 15, animate = true) {
this.currDate.setMinutes(this.currDate.getMinutes() + increment);
this.redrawPath(animate);
this.redrawSun(animate);
this.redrawMessages();
return this.redrawCities();
}
drawAll() {
this.drawSVG();
this.createDefs();
this.drawLand();
this.drawPath();
this.drawSun();
this.drawMessages();
return this.drawCities();
}
shuffleElements() {
$("#land").insertBefore("#nightPath");
return $("#sun").insertBefore("#land");
}
animate(increment = 0) {
if (!this.isAnimating) {
this.isAnimating = true;
return (this.animInterval = setInterval(() => {
this.redrawAll(increment);
return $(document).trigger("update-date-time", this.currDate);
}, this.options.tickDur));
}
}
stop() {
this.isAnimating = false;
return clearInterval(this.animInterval);
}
init() {
this.drawAll();
return setInterval(() => {
if (this.isAnimating) {
return;
}
this.redrawAll(1, false);
return $(document).trigger("update-date-time", this.currDate);
}, 60000);
}
}
DaylightMap.prototype.lineFunction = d3.svg
.line()
.x(function(d) {
return d.x;
})
.y(function(d) {
return d.y;
})
.interpolate("basis");
return DaylightMap;
}.call(this);
updateDateTime = function(date) {
// tz = date.toString().match(/\(([A-Za-z\s].*)\)/)[1]
$(".curr-time")
.find("span")
.html(moment(date).format("HH:mm"));
return $(".curr-date")
.find("span")
.text(moment(date).format("DD MMM"));
};
$(document).ready(function() {
var map, svg;
svg = document.getElementById("daylight-map");
map = new DaylightMap(svg, new Date("2021-02-15"));
map.init();
updateDateTime(map.currDate);
$(document).on("update-date-time", function(date) {
return updateDateTime(map.currDate);
});
$(".toggle-btn").on("click", function(e) {
var $el;
e.preventDefault();
$el = $(this);
return $el.toggleClass("active");
});
map.animate(20);
});
|
import React from 'react'
const HomeScreen = () => {
return (
<div>
<h1>Welcome<br></br></h1>
</div>
)
}
export default HomeScreen
|
import React, { useContext } from 'react';
import { Link } from 'react-router-dom'
import { SetlistContext } from '../../contexts/SetlistContext'
import './styles.css'
import NavBar from '../../components/NavBar'
export default function ShowAllSetlists({ match }) {
const { setlists, loading, handleDelete } = useContext(SetlistContext)
if (loading) return "Loading"
return (
<div>
<NavBar title="SETLISTS" leftItem="logo" />
<div className="setlists">
<ul>
{setlists.map(setlist => (
<li key={setlist.name} className="setlist-item">
<Link to={`${match.path}/${setlist._id}`}>{setlist.name}</Link>
<Link to={`${match.path}/edit/${setlist._id}`}>
<i className="fas fa-pen" />
</Link>
<i
className="fas fa-trash"
onClick={() => handleDelete(setlist)}
/>
</li>
))}
</ul>
<Link to="/new_setlist">NEW SETLIST</Link>
</div>
</div>
);
}
|
const multer = require("multer");
const multerS3 = require("multer-s3");
const aws = require("aws-sdk");
const { secretAccessKey, accessKeyId, region } = require("../config/keys");
aws.config.update({
secretAccessKey: secretAccessKey,
accessKeyId: accessKeyId,
region: region // region of your bucket
});
const s3 = new aws.S3();
var maxSize = 5 * 1024 * 1024; //5mb
const upload = multer({
storage: multerS3({
s3: s3,
bucket: "suitsavatar",
contentType: multerS3.AUTO_CONTENT_TYPE,
metadata: function(req, file, cb) {
console.log(file);
cb(null, { fieldName: file.fieldname });
},
key: function(req, file, cb) {
cb(null, Date.now().toString() + file.originalname);
}
}),
limits: { fileSize: maxSize }
});
module.exports = upload;
|
$(document).ready(function() {
faq.forEach(function(entry, index) {
generateEntry(entry, index);
});
var followScroll = true;
$(".toc-entry").click(function() {
var index = this.id.match(/toc-entry-(.*)/);
if (index) {
$('html, body').animate({
scrollTop: $("#entry-" + index[1]).offset().top - 20
}, 500);
} else if (this.id == "top") {
$('html, body').animate({
scrollTop: $("html").offset().top
}, 500);
}
$(".toc-entry.selected").removeClass("selected");
$(this).addClass("selected");
});
$(document).scroll(function() {
if (followScroll) {
for (var i = 0; i < faq.length; i++) {
if ($(this).scrollTop() >= $("#entry-" + i).position().top + $("#entry-" + i - 1 + " .question").height() - 70) {
$(".toc-entry.selected").removeClass("selected");
$("#toc-entry-" + i).addClass("selected");
}
}
}
if ($(this).scrollTop() < $(".header").height()) {
$(".table-of-contents").css("top", $(".header").height() - $(this).scrollTop() + 20 + "px");
}
else if ($(".table-of-contents").css("top") !== "20px") {
$(".table-of-contents").css("top", "20px");
}
})
$(".created-by").click(function() {
window.open("https://github.com/jacobnisnevich/i-like-bernie-but", "_blank");
});
$(".convinced-button").click(function() {
window.open("http://berniesanders.com", "_blank");
});
});
var generateEntry = function(entry, index) {
$(".faq").append("<div class='entry clearfix' id='entry-" + index + "'>\
<div class='question-container'>\
<div class='question'>" + entry.question + "</div>\
</div>\
<div class='answer-container'>\
<div class='answer'>" + entry.answer + "</div>\
</div>\
</div>");
if (entry.question.indexOf("learn more") < 0) {
$(".table-of-contents .questions").append("<div class='toc-entry' id='toc-entry-" + index + "'>" + entry.question + "</div>");
}
}
|
// import React from "react";
// import PropTypes from "prop-types";
// import { withStyles } from "@material-ui/core/styles";
// import CircularProgress from "@material-ui/core/CircularProgress";
// const styles = theme => ({
// progress: {
// margin: theme.spacing.unit * 0,
// }
// });
// function CircularIndeterminate(props) {
// const { classes } = props;
// return (
// <div>
// <CircularProgress className={classes.progress} size={100} thickness={2}/>
// </div>
// );
// }
// CircularIndeterminate.propTypes = {
// classes: PropTypes.object.isRequired
// };
// export default withStyles(styles)(CircularIndeterminate);
import React from 'react'
import { Dimmer, Loader } from 'semantic-ui-react'
const LoaderExampleSizesInverted = (props) => (
<div>
<Dimmer active inverted>
<Loader size='massive'>{props.Loading}</Loader>
</Dimmer>
</div>
)
export default LoaderExampleSizesInverted
|
const express = require('express');
const auth = require('../middleware/auth');
const photoController = require('../controllers/photo-controller');
const multer = require('multer');
const storage = require("../middleware/multerStorage");
const upload = multer({storage:storage.storageConfig, fileFilter: storage.fileFilter});
const photo_controller = new photoController();
const router = new express.Router();
router.get('/all/:id', auth, photo_controller.getAllPhotos);
router.get('/:id', auth, photo_controller.getPhoto);
router.post('/wall', auth, upload.array(`uploadedImages`, 10), photo_controller.addWallPhoto);
router.post('/:id', auth, upload.array(`uploadedImages`, 10), photo_controller.add);
router.delete('/:id', auth, photo_controller.delete);
router.put('/upd', auth, photo_controller.update);
router.put('/avatar', auth, upload.single('avatar'), photo_controller.setAvatar);
router.put('/change', auth, photo_controller.changeAvatar);
module.exports = router;
|
'use strict';
/**
* @ngdoc overview
* @name appApp
* @description
* # appApp
*
* Main module of the application.
*/
angular
.module('meanDemoApp', [
'ngResource',
'ngSanitize'
]);
|
let deadpoll = {
nombre: 'Juan',
apellido: 'OC',
poder: 'Endeudarse',
getNombre: function () {
return `${this.nombre} ${this.apellido} - poder: ${this.poder}`
}
}
console.log(deadpoll);
let { nombre: primerNombre, apellido, poder } = deadpoll
console.log(primerNombre, apellido, poder); |
const express = require("express");
const dotenv = require("dotenv");
const cors = require("cors");
const router = require("./api/routes");
const fileUpload = require("express-fileupload");
const app = express();
dotenv.config();
app.use(express.json());
app.use(cors());
app.use(
fileUpload({
createParentPath: true,
})
);
app.use((req, _, next) => {
req.requestTime = new Date().toISOString();
next();
});
app.use(express.static("./public"));
app.post("/upload/image", (req, res) => {
if (req.files) {
const file = req.files.image;
const fileName = file.name;
file.mv("./public/imgs/" + fileName, (err) => {
if (err) {
res.status(404).json({
status: "error",
data: err,
});
} else {
res.status(200).json({
status: "success",
data: "Imagen Subida",
});
}
});
} else {
res.status(404).json({
status: "error",
data: "Necesitas subir un archivo",
});
}
});
app.use("/", router);
// *** Start Server
const port = process.env.PORT;
app.listen(port, () => {
console.log(`App en puerto:_${port}...`);
});
|
const fileContents = (
software,
artist,
imageDescription,
userComment,
copyright,
pixels
) =>
JSON.stringify({
exif: {
software,
artist,
imageDescription,
userComment,
copyright,
dateTime: new Date()
},
pxif: {
pixels
}
});
export default fileContents;
|
export default function test(input) {
return (/^[A-Z]/i.test(input));
} |
import React, { useState } from "react";
import Logo from "./Logo";
import { Button, Grid } from "@material-ui/core";
//import {AppDecorator} from '@your-scope/storybook'
//dummy, aslong as not imported from storybook by previous line
import { AppDecorator } from "./AppDecorator";
import A from "./A";
export default function App() {
return AppDecorator({})(function _App() {
const [count, setCount] = useState(0);
return (
<React.StrictMode>
<Grid
style={{ height: 600 }}
container
direction="column"
alignItems="center"
justify="space-around"
>
<Logo />
<div>
Hello Vite <A href="https://reactjs.org">React</A> +
<A href="">Material-Ui</A> +
<A href="https://styled-components.com">styled-components</A>!
</div>
<Button onClick={() => setCount((count) => count + 1)}>
count is: {count}
</Button>
<div>
Edit <code>App.jsx</code> and save to test HMR updates.
</div>
<div>
Build with <A href="https://vitejs.dev">Vite</A>
</div>
</Grid>
</React.StrictMode>
);
});
}
|
let listState = {
url: '',
template: require('./list.html'),
controller: 'list.controller as list'
}
export default listState
|
var template = require('./template.marko')
var data = {
msg:"Hello Marko!"
}
template.render(data,function (err,output) {
console.log(output);
})
|
var annotated =
[
[ "fsml", null, [
[ "Action", "classfsml_1_1Action.html", "classfsml_1_1Action" ],
[ "AstStep", "structfsml_1_1AstStep.html", "structfsml_1_1AstStep" ],
[ "AstState", "structfsml_1_1AstState.html", "structfsml_1_1AstState" ],
[ "AstMachine", "structfsml_1_1AstMachine.html", "structfsml_1_1AstMachine" ],
[ "DeterministicException", "structfsml_1_1DeterministicException.html", "structfsml_1_1DeterministicException" ],
[ "FileReadException", "structfsml_1_1FileReadException.html", "structfsml_1_1FileReadException" ],
[ "FileWriteException", "structfsml_1_1FileWriteException.html", "structfsml_1_1FileWriteException" ],
[ "InitialStateException", "structfsml_1_1InitialStateException.html", "structfsml_1_1InitialStateException" ],
[ "InvalidInputException", "structfsml_1_1InvalidInputException.html", "structfsml_1_1InvalidInputException" ],
[ "ParserException", "structfsml_1_1ParserException.html", "structfsml_1_1ParserException" ],
[ "ReachableException", "structfsml_1_1ReachableException.html", "structfsml_1_1ReachableException" ],
[ "ResolvableException", "structfsml_1_1ResolvableException.html", "structfsml_1_1ResolvableException" ],
[ "UniqueException", "structfsml_1_1UniqueException.html", "structfsml_1_1UniqueException" ],
[ "FlatMachine", "structfsml_1_1FlatMachine.html", "structfsml_1_1FlatMachine" ],
[ "FlatStep", "structfsml_1_1FlatStep.html", "structfsml_1_1FlatStep" ],
[ "Machine", "classfsml_1_1Machine.html", "classfsml_1_1Machine" ],
[ "State", "classfsml_1_1State.html", "classfsml_1_1State" ],
[ "Step", "classfsml_1_1Step.html", "classfsml_1_1Step" ]
] ]
]; |
import React, { useEffect } from "react";
import styled from "styled-components";
import { useSelector, useDispatch } from "react-redux";
import { color } from "../../styles/global";
import { Paperclip, Smile, SendArrow } from "../../components/Icons";
import { fetchMessages } from "../../actions";
import Message from "../../components/Message/";
const ChatStyled = styled.div`
display: flex;
flex-direction: column;
width: 100%;
.header {
padding: 0.75rem;
border-bottom: 1px solid ${color.medium};
}
.title {
font-weight: 500;
font-size: 0.75rem;
letter-spacing: 1px;
}
.conversation {
flex-grow: 1;
padding: 0.75rem;
background: #f7fafc;
overflow-y: scroll;
}
.textarea {
display: flex;
padding: 0.5rem;
border-top: 1px solid ${color.medium};
input {
width: 100%;
padding-left: 0.5rem;
border: none;
background: transparent;
outline: none;
color: inherit;
}
}
`;
const Chat = () => {
const state = useSelector(state => state.messages);
const selectedRoomId = useSelector(state => state.rooms.selectedRoom);
const user = useSelector(state => state.user);
const dispatch = useDispatch();
useEffect(() => {
fetch("http://localhost:3000/messages")
.then(response => response.json())
.then(messages => {
const filtred = messages.filter(
message => message.room_id === selectedRoomId
);
dispatch(fetchMessages(filtred));
});
}, [dispatch, selectedRoomId]);
return (
<ChatStyled>
<div className="header">
<span className="title">Regina Fisher</span>
</div>
<div className="conversation">
{state.messages.length &&
state.messages.map(message => (
<Message
key={message.id}
src={message.user.src}
username={message.user.name}
timestamp={message.created_at}
text={message.text}
media={{
images: []
}}
isMe={message.author_id === user.currentUserId ? true : false}
/>
))}
</div>
<div className="textarea">
<button className="buttonWithIcon">
<Paperclip />
</button>
<input type="text" placeholder="Write a message..." />
<button className="buttonWithIcon">
<Smile />
</button>
<button className="buttonWithIcon">
<SendArrow />
</button>
</div>
</ChatStyled>
);
};
export default Chat;
|
import styled from 'styled-components';
const PassWordInput = styled.input.attrs({
type: 'password',
padding: props=> props.size || '0.5em',
})`
border: 1px solid dodgerblue;
border-radius: 5px;
color: green;
margin: ${props=> props.margin};
`;
export default PassWordInput; |
import React from 'react';
import { shallow } from 'enzyme';
import NumberOfEvents from '../NumberOfEvents';
describe('<NumberOfEvents />, component', () => {
let NumberWrapper;
beforeAll(() => {
NumberWrapper = shallow(<NumberOfEvents />)
})
test('textbox renders', () => {
expect(NumberWrapper.find('.numberOfEventsClass')).toHaveLength(1);
})
test('number of requests is generated', () => {
expect(NumberWrapper.find('.numberOfEvents_entered')).toHaveLength(1);
})
test('render input to state', () => {
const inputNumber = NumberWrapper.state('numberOfEvents');
expect(NumberWrapper.find('.numberOfEvents_entered').prop('value')).toBe(inputNumber)
})
}) |
// @flow
import { type Middleware } from 'redux'
import { showError } from '../../components/services/AirshipInstance.js'
import { type Action, type RootState } from '../../types/reduxTypes.js'
export const errorAlert: Middleware<RootState, Action> = store => next => action => {
try {
const out: any = next(action)
if (out != null && typeof out.then === 'function') {
out.catch(showError)
}
return out
} catch (error) {
showError(error)
}
return action
}
|
import "./css/style.scss";
import "./css/media.scss";
import "./js/scripts";
|
import React from "react";
<section className="section-packages">
<div className="u-center-text u-margin-bottom-huge">
<h2 className="heading-packages">Elite Training Packages</h2>
</div>
<div className="row">
<div className="col-1-of-3">
<div className="cardP">
<div className="cardP_side cardP_side--front">
<div className="cardP_picture cardP_picture-1"> </div>
<h4 className="cardP_heading">
<span className="cardP_heading-span cardP_heading-span--1">
Elite Personal Training
</span>
</h4>
<div className="cardP_details">
<ul>
<li>Food</li>
<li>Water</li>
<li>Protien</li>
<li>Carbs</li>
<li>Vegetables</li>
</ul>
</div>
</div>
<div className="cardP_side cardP_side--back cardP_side--back-1">
<div className="cardP_cta">
<div className="card_price-box">
<p className="class cardP_price-only">Only</p>
<p className="class cardP_price-value">$1000</p>
</div>
<a href="#" className="btn btn-white">
Book Now!
</a>
</div>
</div>
</div>
</div>
<div clasName="col-1-of-3">
<div className="cardP">
<div className="cardP_side cardP_side--front">
<div className="cardP_picture cardP_picture-2"> </div>
<h4 className="cardP_heading">
<span className="cardP_heading-span cardP_heading-span--2">
Star Citizen
</span>
</h4>
<div className="cardP_details">
<ul>
<li>Food</li>
<li>Water</li>
<li>Protien</li>
<li>Carbs</li>
<li>Vegetables</li>
</ul>
</div>
</div>
<div className="cardP_side cardP_side--back cardP_side--back-2">
<div className="cardP_cta">
<div className="card_price-box">
<p className="class cardP_price-only">Only</p>
<p className="class cardP_price-value">$1000</p>
</div>
<a href="#" className="btn btn-white">
Book Now!
</a>
</div>
</div>
</div>
</div>
<div className="col-1-of-3">
<div className="cardP">
<div className="cardP_side cardP_side--front">
<div className="cardP_picture cardP_picture-3"> </div>
<h4 className="cardP_heading">
<span className="cardP_heading-span cardP_heading-span--3">
Swizzle TV
</span>
</h4>
<div className="cardP_details">
<ul>
<li>Food</li>
<li>Water</li>
<li>Protien</li>
<li>Carbs</li>
<li>Vegetables</li>
</ul>
</div>
</div>
<div className="cardP_side cardP_side--back cardP_side--back-3">
<div className="cardP_cta">
<div className="card_price-box">
<p className="class cardP_price-only">Only</p>
<p className="class cardP_price-value">$1000</p>
</div>
<a href="#" className="btn btn-white">
Book Now!
</a>
</div>
</div>
</div>
</div>
</div>
<div className="row">
<div class="col-1-of-3">
<div className="cardP">
<div className="cardP_side cardP_side--front">
<div className="cardP_picture cardP_picture-1"> </div>
<h4 className="cardP_heading">
<span className="cardP_heading-span cardP_heading-span--1">
Elite Personal Training
</span>
</h4>
<div className="cardP_details">
<ul>
<li>Food</li>
<li>Water</li>
<li>Protien</li>
<li>Carbs</li>
<li>Vegetables</li>
</ul>
</div>
</div>
<div className="cardP_side cardP_side--back cardP_side--back-1">
<div className="cardP_cta">
<div className="card_price-box">
<p className="class cardP_price-only">Only</p>
<p className="class cardP_price-value">$1000</p>
</div>
<a href="#" className="btn btn-white">
Book Now!
</a>
</div>
</div>
</div>
</div>
<div className="col-1-of-3">
<div className="cardP">
<div className="cardP_side cardP_side--front">
<div className="cardP_picture cardP_picture-2"> </div>
<h4 className="cardP_heading">
<span className="cardP_heading-span cardP_heading-span--2">
Star Citizen
</span>
</h4>
<div className="cardP_details">
<ul>
<li>Food</li>
<li>Water</li>
<li>Protien</li>
<li>Carbs</li>
<li>Vegetables</li>
</ul>
</div>
</div>
<div className="cardP_side cardP_side--back cardP_side--back-2">
<div className="cardP_cta">
<div className="card_price-box">
<p className="class cardP_price-only">Only</p>
<p className="class cardP_price-value">$1000</p>
</div>
<a href="#" className="btn btn-white">
Book Now!
</a>
</div>
</div>
</div>
</div>
<div className="col-1-of-3">
<div className="cardP">
<div className="cardP_side cardP_side--front">
<div className="cardP_picture cardP_picture-3"> </div>
<h4 className="cardP_heading">
<span className="cardP_heading-span cardP_heading-span--3">
Swizzle TV
</span>
</h4>
<div className="cardP_details">
<ul>
<li>Food</li>
<li>Water</li>
<li>Protien</li>
<li>Carbs</li>
<li>Vegetables</li>
</ul>
</div>
</div>
<div className="cardP_side cardP_side--back cardP_side--back-3">
<div className="cardP_cta">
<div className="card_price-box">
<p className="class cardP_price-only">Only</p>
<p className="class cardP_price-value">$1000</p>
</div>
<a href="#" className="btn btn-white">
Book Now!
</a>
</div>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-1-of-3">
<div className="cardP">
<div className="cardP_side cardP_side--front">
<div className="cardP_picture cardP_picture-1"> </div>
<h4 className="cardP_heading">
<span className="cardP_heading-span cardP_heading-span--1">
Elite Personal Training
</span>
</h4>
<div className="cardP_details">
<ul>
<li>Food</li>
<li>Water</li>
<li>Protien</li>
<li>Carbs</li>
<li>Vegetables</li>
</ul>
</div>
</div>
<div className="cardP_side cardP_side--back cardP_side--back-1">
<div className="cardP_cta">
<div className="card_price-box">
<p className="class cardP_price-only">Only</p>
<p className="class cardP_price-value">$1000</p>
</div>
<a href="#" className="btn btn-white">
Book Now!
</a>
</div>
</div>
</div>
</div>
</div>
</section>;
|
'use strict';
/**
* @ngdoc function
* @name quiverCmsApp.controller:UsersCtrl
* @description
* # UsersCtrl
* Controller of the quiverCmsApp
*/
angular.module('quiverCmsApp')
.controller('UsersCtrl', function ($scope) {
});
|
const authCtrl = {};
const express = require("express");
const bcrypt = require("bcrypt");
const User = require("../models/User.Model");
const jwt = require("jsonwebtoken");
const checkAuth = require('../middleware/check-auth');
authCtrl.login = (req,res,next) => {
let FindedUser;
User.findOne({username: req.body.username})
.then(user => {
if(!user) {
return res.status(401).json({
message: "there is not a user with the username " + req.body.username
});
}
console.log("usuario encontrado")
FindedUser = user;
return bcrypt.compare(req.body.password, user.password);
})
.then(result => {
if(!result) {
return res.status(401).json({
message: "Password does not match"
});
}
console.log("contraseña coincide")
const token = jwt.sign({username: FindedUser.username, password: FindedUser.password}, "palabra_secreta_que_deberia_guardar_y_hashear_en_la_db",
{expiresIn: "1h"}
);
res.status(200).json({
message: "Usuario logeado exitosamente",
token:token
});
})
.catch(err => {
message: "Error en la authentificacion."
});
};
authCtrl.signup = async (req,res,next) => {
try {
let {username, password} = req.body;
let hashed;
let user;
let foundUsers = await User.findOne({username:username});
if(foundUsers) {
return res.status(400).json({
success: false,
message:'el usuario ya existe'
})
}
console.log(bcrypt.hashSync(req.body.password, 10))
user = new User({
username: username,
password: bcrypt.hashSync(req.body.password, 10)
});
await user.save();
res.status(200).json({
success: true,
message:'usuario guardado con exito'
})
} catch(error) {
console.log(`Ha ocurrido un error ${error}`);
return res.status(500).json({
success: false,
message: `Ha ocurrido un error, por favor intente más tarde`
})
}
};
module.exports = authCtrl; |
import React from 'react';
import _ from 'lodash';
import {
Button,
DatePicker,
Select,
Input,
Row,
Col,
Table,
Modal,
Tooltip,
Form,
Icon,
Spin,
InputNumber,
Card,
Popconfirm,
message,
Tabs,
Divider,
} from 'antd';
import ReportTable from '@/components/ReportTable/index'; // 报表组件
import NewBreadcrumb from '@/components/Breadcrumb'; //面包屑组件
import CustomerHeader from '@/components/CustomerHeader'; //头部组件
import DetailPage from '@/components/DetailPage/Index'; // 主表详情组件
// import ChildTable from '@/components/HY/DeliveryChildTable/Index'; //子表组件
import ChildTable from '@/components/HY/ChildTable/Index'; //子表组件
import Detailbuttons from '@/components/HY/DeliveryDetailButtons'; // 详情页头部的按钮栏
import SkeletonCom from '@/components/Skeleton';
import { connect } from 'dva';
import styles from './Index.less';
let child = {};
@Form.create()
@connect(({ tableTemplate, loading }) => ({
tableTemplate,
loadingG:
loading.effects['tableTemplate/getDetailPageConfig'] ||
loading.effects['tableTemplate/save'] ||
loading.effects['tableTemplate/getDetailSave'] ||
loading.effects['tableTemplate/getTransactionProcess'] ||
loading.effects['tableTemplate/getSummaryPageConfig'] ||
loading.effects['tableTemplate/getDetailPage'],
}))
//详情页模块
export default class DetailsPageModule extends React.Component {
state = {
isSkeleton: true,
};
componentWillReceiveProps = newProps => {
if (newProps.loadingGG != this.state.isSkeleton) {
this.setState({
isSkeleton: newProps.loadingGG,
});
}
};
getMasterTable = () => {
let MasterTable = this.DetailPage.getFieldsValue();
return MasterTable;
};
onRef = ref => {
this.child = ref;
};
//保存重新渲染新的数据
renderDataWhenSave = data => {
this.props.dispatch({
type: 'tableTemplate/save',
payload: {
isEditSave: false,
isEdit: true,
buttonType: true,
isNewSave: false,
disEditStyle: true,
},
});
this.child.onRenderData(data, this.forceUpdate());
};
render() {
let { isSkeleton } = this.state;
return (
<div>
{/* 报表部分 */}
{this.props.tableTemplate.reportFormURL && <ReportTable />}
{/* 详情页部分 */}
{!this.props.tableTemplate.reportFormURL && (
<div
style={{ display: this.props.tableTemplate.isEdit ? 'block' : 'none' }}
className={styles.SingleTableDetail}
>
<SkeletonCom type="detailPage" loading={this.props.loadingGG || false} />
<div style={{ display: isSkeleton ? 'none' : 'block' }}>
{/* 头部title/面包屑 */}
<CustomerHeader />
<div>
<Detailbuttons
renderDataWhenSave={e => this.renderDataWhenSave(e)}
detailForm={this.DetailPage}
/>
</div>
<hr
style={{
backgroundColor: '#d3d3d3',
margin: '0',
height: '1px',
border: 'none',
marginBottom: '5px',
marginTop: 0,
}}
/>
{/* <Spin spinning={this.props.loadingButton || false} tip="Loading..."> */}
<div className="BasicEditSearch">
<span style={{ fontSize: '1.2rem' }}>{this.props.subtitle}</span>
{/* 主表内容 */}
<DetailPage
onRef={this.onRef}
ref={dom => (this.DetailPage = dom)}
disabled={this.props.tableTemplate.disEditStyle}
/>
</div>
{/* 子表表格 */}
<Card
style={{ width: '100%', marginTop: '1.2rem' }}
bodyStyle={{
paddingTop: 0,
paddingLeft: '16px',
paddingRight: '16px',
paddingBottom: '16px',
display: this.props.tableTemplate.detailColumns.child ? 'block' : 'none',
}}
>
<div style={{ marginTop: '5px' }}>
<ChildTable getMasterTable={value => this.getMasterTable(value)} detailForm={this.DetailPage} />
</div>
</Card>
{/* </Spin> */}
</div>
</div>
)}
</div>
);
}
}
|
import { Route, Redirect, Switch } from "react-router-dom";
import BookContainer from "../BookContainer/BookContainer";
import BookDetails from "../BookDetails/BookDetails";
import Error from "../Error/Error";
import Header from "../Header/Header";
import React, { Component } from "react";
import styled from "styled-components";
import Welcome from "../Welcome/Welcome";
const Wrapper = styled.div`
height: 100%;
width: 100%;
`;
class App extends Component {
constructor(props) {
super(props);
this.state = {
books: [],
error: null,
isLoaded: false,
selectedBook: {},
};
}
componentDidMount = () => {
fetch("https://black-stories-matter-api.herokuapp.com/api/v1/books", {
//request headers
headers: {
"Access-Control-Allow-Origin": "*",
},
})
.then((response) => response.json())
.then(
(data) => {
this.setState({ books: data.data, isLoaded: true });
},
(error) => {
this.setState({ error, isLoaded: true });
}
);
};
setSelectedBook = (book) => {
this.setState({ selectedBook: book });
};
render() {
return (
<Wrapper>
<Header />
<Switch>
<Route path="/" exact component={Welcome} />
<Route
path="/books"
exact
render={() => {
return (
<BookContainer
books={this.state.books}
setSelectedBook={this.setSelectedBook}
/>
);
}}
/>
<Route
path="/books/:id"
exact
render={() => {
return <BookDetails selectedBook={this.state.selectedBook} />;
}}
/>
<Route path="/error" component={Error} />
<Redirect to="/error" />
</Switch>
</Wrapper>
);
}
}
export default App;
|
const { response } = require('express');
const { mongo } = require('mongoose');
const fetch = require('node-fetch');
const Empresa = require('../models/empresa');
const crearAgencia = async (req, res = response) => {
const empresa = req.empresa;
const idAgencia = mongo.ObjectId();
if (empresa.agenciaDefault == '000000000000000000000000') {
empresa.agenciaDefault = idAgencia;
}
try {
const agencias = empresa.agencias;
const numeroAgencia = agencias.length + 1;
req.body.numeroAgencia = ('000' + numeroAgencia).slice(-3);
req.body.usuarioRegistro = req.user_id;
req.body.monedaFacturacion = empresa.monedaDefault;
req.body._id = idAgencia;
req.body.consecutivos = {
facturaElectronica: 0,
notaCreditoElectronica: 0,
notaDebitoElectronica: 0,
facturaCompraElectronica: 0,
facturaExportacionElectronica: 0,
tiqueteElectronico: 0,
aceptacionDocumentoElectrinico: 0,
proforma: 0,
reciboCuentaCobrar: 0,
ncCuentaCobrar: 0,
ndCuentaCobrar: 0,
asientos: 0,
movimientoInventario: 0,
};
//genera id de bodega
const idBodega = mongo.ObjectId()
req.body.bodegaDefault = idBodega;
req.body.bodegas = [{
_id: idBodega,
nombre: "Bodega default",
usuarioRegistro: req.user_id
}],
empresa.agencias.push(req.body);
await empresa.save();
res.status(201).json({
ok: true,
msg: 'Agencia creada correctamente'
});
} catch (error) {
console.log('Error al crear agencia ' + error)
res.status(500).json({
ok: false,
msg: 'Por favor hable con el administrador ' + error
});
}
}
const actualizarAgencia = async (req, res = response) => {
const empresa = req.empresa;
const agencia = req.agencia;
const id = req.params.id;
try {
//obtener el indice de la agencia actualizar
const indexAgencia = (element) => element._id == id;
const index = empresa.agencias.findIndex(indexAgencia);
let _empresa = new Empresa();
_empresa = empresa;
_empresa.agencias[index].nombre = req.body.nombre;
_empresa.agencias[index].numeroAgencia = req.body.numeroAgencia;
_empresa.agencias[index].encargado = req.body.encargado;
_empresa.agencias[index].telefono = req.body.telefono;
_empresa.agencias[index].movil = req.body.movil;
_empresa.agencias[index].email = req.body.email;
_empresa.agencias[index].direccion = req.body.direccion;
_empresa.agencias[index].monedaFacturacion = req.body.monedaFacturacion;
_empresa.agencias[index].tiket = req.body.tiket;
_empresa.agencias[index].bodegaDefault = req.body.bodegaDefault;
console.log('empresa actualizada', _empresa);
const empresaActualizada = await _empresa.save();
res.status(201).json({
ok: true,
agencia: empresaActualizada.agencias[index]
});
} catch (error) {
console.log('Error al actualizar agencia ' + error)
res.status(500).json({
ok: false,
msg: 'Por favor hable con el administrador ' + error
});
}
}
const eliminarAgencia = async (req, res = response) => {
const empresaActual = req.empresa;
const agencia = req.agencia;
const id = req.params.id;
try {
let empresa = new Empresa(empresaActual);
//obtener el indice de la agencia actualizar
const indexAgencia = (element) => element._id == id;
const index = empresa.agencias.findIndex(indexAgencia);
empresa.agencias[index].activa = false;
const empresaActualizada = await empresa.save();
res.status(201).json({
ok: true,
agencia: empresaActualizada.agencias[index]
});
} catch (error) {
console.log('Error al eliminar agencia ' + error)
res.status(500).json({
ok: false,
msg: 'Por favor hable con el administrador ' + error
});
}
}
module.exports = {
crearAgencia,
actualizarAgencia,
eliminarAgencia
} |
$("#loginform").submit(function(e){
e.preventDefault();
var username = $("#username").val();
var password = $("#password").val();
$("#flash_message").empty();
if(username == "" && password == ""){
$("#flash_message").append("<div class='alert alert-danger'>" +
"Both fields are required" +
"</div>");
}
if(username =="admin" && password =="admin"){
window.location.href="Admin/index.php";
}else{
$("#flash_message").append("<div class='alert alert-danger'>" +
"Incorrect Username and Password" +
"</div>");
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.