text
stringlengths 7
3.69M
|
|---|
var _nexus = function( scene, nexus, mob, id ) {
this.self = new _baseEnt( BABYLON.Mesh.CreateSphere("nexus_"+id, 10.0, 3.0, scene), scene );
var material = new BABYLON.StandardMaterial("material01", scene);
material.diffuseColor = new BABYLON.Color3(((id==0)?0:1), ((id==0)?1:0), 0);
this.self.self.material = material;
this.self.setScale(10,10,10);
this.id = id;
this.mobCount = 0;
this.Cap = 25;
this.size = 1;
this.mob = mob;
this.nexus = nexus;
this.scene = scene;
this.maxincome = 100;
this.income = this.maxincome;
this.maxhp = 1000;
this.hp = this.maxhp;
this.incomecur = 0
this.spawncur = 0
this.AI_update = 0;
this.hitoffset = 1;
this.spawntime = 15;
}
_nexus.prototype.effect = function() {
this.scene.loadEffect.effect("energy", { "pos": this.self.getPos(), "color": { 'r': ((this.id == 0) ? 0 : 1), 'g': ((this.id == 0) ? 1 : 0), 'b': 0 } });
}
_nexus.prototype.SpawnMob = function( i, type, pos ) {
this.mob[i] = new mob[type](this.scene, this.nexus, this.mob, this.id, i);
this.mob[i].self.setPos( this.nexus[this.id].self.getPos() );
this.mob[i].self.setPos( pos.x, pos.y, pos.z );
this.mobCount += 1;
return (this.mob[i]);
}
_nexus.prototype.Spawn = function( ) {
var list = this._AI();
var num = 1, size = 10;
for (var x in list) {
if ( !mob[ list[x].c.mobtype ].prototype.notmob) {
num += list[x].c.count;
}
}
num = Math.min( this.Cap-this.mobCount, num );
var row = Math.floor( Math.sqrt(num/2) );
for (var x in list) {
var type = list[x].c.mobtype;
var count = list[x].c.count;
for (var v = 0; v < count; v++) {
if (mob[type].prototype.notmob) {
if ( (this.income-mob[type].prototype.cost) >= 0 ) {
var ent = new mob[type](this.scene, this.nexus, this.mob, this.id, i);
if (!ent.return) {
this.income += ent.cost * -1;
}
}
} else {
if (this.mobCount < this.Cap && (this.income-mob[type].prototype.cost) >= 0) {
var i = 0; while (typeof(this.mob[(i = i + 1)]) != "undefined");
var ent = this.SpawnMob( i, type, this.nexus[this.id].self.getPos() );
ent.self.setPos(
( (v%2==0)? '+' : '-' )+( 50+((v/2)*size)-(Math.floor((v/2)/row)*(row*size)) ),
"+"+mob[type].prototype.heightoffset,
( (this.id==1)? '+' : '-' )+( Math.floor((v/2)/row)*size )
);
this.income += ent.cost * -1;
this.effect();
}
}
}
}
}
_nexus.prototype.def_think = function( a ) {
this.hitoffset = Math.max( 0.1, this.hitoffset-=0.1 );
this.hp = Math.max( 0, this.hp-(a*2) );
if (this.hp <= 0) {
this.scene.pause = true;
scene._runwin( this.id );
}
}
_nexus.prototype.Think = function( ) {
var gamespeed = this.scene._gamepref.gamespeed;
this.maxincomecur = ( ((1000*this.spawntime)/this.scene.game_tickrate)/gamespeed )
if ( this.scene.globaltime > this.incomecur+this.maxincomecur ) {
this.incomecur = this.scene.globaltime;
this.income = this.maxincome;
this.spawntime = 15;
}
this.maxspawncur = ( ((1000*10)/this.scene.game_tickrate)/gamespeed )
if ( this.scene.globaltime > this.spawncur+this.maxspawncur ) {
this.spawncur = this.scene.globaltime;
if (this.income == this.maxincome && !this.AI) {
this.scene.sound.play( "spawn.mp3", "fx", 0.5 );
}
this.Spawn( );
}
this.hitoffset = Math.min( 1, this.hitoffset+=0.01 );
var sesc = 10*this.hitoffset;
this.self.setScale(sesc, sesc, sesc);
}
_nexus.prototype._AI = function( ) {
if (this.AI) {
var gamespeed = this.scene._gamepref.gamespeed;
if ( this.scene.globaltime > this.AI_update+((this.scene.Ai_difficulty/this.scene.game_tickrate)/gamespeed) || !isset(this.AI_list) ) {
this.AI_update = this.scene.globaltime;
var dif = (this.nexus[( (this.id == 1)? 0 : 1 )].mobCount-this.mobCount);
var counter = {
'smallbox':{
"count":( (dif > 10)? 0.2 : 0.5 ),
"mobtype":( (dif > 10)? "bomber" : "box" )
},
'box':{
"count":( (dif > 10)? 0.5 : 1 ),
"mobtype":( (dif > 10)? "bomber" : "bigbox" )
},
'bigbox':{
"count":( (dif > 10)? 1 : 2 ),
"mobtype":( (dif > 10)? "priest" : "smallbox" )
},
'smallrangebox':{
"count":1,
"mobtype":"rangebox"
},
'rangebox':{
"count":1,
"mobtype":"bigrangebox"
},
'bigrangebox':{
"count":( (dif > 10)? 1 : 5 ),
"mobtype":( (dif > 10)? "smallrangebox" : "smallbox" )
},
'bomber':{
"count":1,
"mobtype":"smallrangebox"
},
}
var tier_func = function( a, b ) {
return ( (a>=b)? tier_func(a, b*2)+1 : 1 );
}
var tier = Math.min( 3, tier_func( this.maxincome/this.Cap, 50 ) );
var a = this.scene._rungetmob(), b = {}, prix = 0, mobcount = 0, listcount = 0;
for (var i in a) {
var fcounter = (a[i].c.mobtype).split('_')[0];
if ( isset(counter[fcounter]) ) {
b[i] = {'c':{
"count":Math.ceil( counter[fcounter].count * a[i].c.count ),
"mobtype":counter[fcounter].mobtype+( (tier == 1)? '' : '_'+tier )
}}
prix += mob[b[i].c.mobtype].prototype.cost;
mobcount += b[i].c.count;
listcount += 1;
}
}
prix = this.maxincome-prix;
var left = this.mobCount+mobcount;
if ( prix >= 20 && left < this.Cap ) {
var best = 'healer', addincome = -1
for (var v in mob) {
if ( !mob[v].prototype.notmob ) {
var canget = Math.min( Math.floor(prix/mob[v].prototype.cost), (this.Cap-left) );
if ( addincome == -1 || addincome < (mob[v].prototype.income*canget) ) {
best = v;
addincome = mob[v].prototype.income*(this.Cap-left);
}
}
}
b[listcount] = {'c':{
"count":Math.min( Math.floor(prix/mob[best].prototype.cost), (this.Cap-left) ),
"mobtype":best
}}
listcount += 1;
prix += (Math.min( Math.floor(prix/mob[best].prototype.cost), (this.Cap-left) )*mob[best].prototype.cost)*-1;
}
if ( prix >= 100 ) {
var upgrade = {
"addhpcap":function( him, income ) {
return ( ( income >= 500 )? 1 : 0 );
},
"healnexus":function( him, income ) {
return ( ( income >= 100 )? Math.floor( (him.maxhp-him.hp)/100 ) : 0 );
},
"addcap":function( him, income ) {
return ( ( income >= 100 )? 1 : 0 );
}
}
for (var i in upgrade) {
b[listcount] = {'c':{
"count":upgrade[i]( this, prix ),
"mobtype":i
}}
}
}
for(var i in b) {
for(var v in b) {
if ( mob[ b[i].c.mobtype ].prototype.cost < mob[ b[v].c.mobtype ].prototype.cost ) {
var tmp = b[i];
b[i] = b[v];
b[v] = tmp;
}
}
}
this.AI_list = b;
}
return ( this.AI_list );
} else {
return (this.scene._rungetmob());
}
}
|
const express = require('express');
const Budget = require('./Budget.js');
const router = express.Router();
router
.route('/')
.get((req, res) => {
Budget
.find({})
.then(ans => {
res.status(200).json(ans);
})
.catch(err => {
res.status(500).json(err);
})
})
.post((req, res) => {
const newBudget = new Budget(req.body)
newBudget
.save()
.then(ans => {
res.status(200).json({status: "Added successfully!"})
})
.catch(err => {
res.status(500).json(err)
})
})
module.exports = router;
|
import { GraphQLObjectType, GraphQLID, GraphQLList } from 'graphql'
import organizationType from '../types/organization'
import { FilterInput } from '../types/inputs'
import resolve from '../resolvers/organizations'
const organizations = {
name: 'organizations',
type: new GraphQLList(organizationType),
args: {
filter: {
type: FilterInput
}
},
resolve
}
export default organizations
|
/* eslint-disable valid-jsdoc */
'use strict';
/**
* @author Dave Grix
* @param data string
* @return array
*/
const validateInventoryTransactions = async(data) => {
const supplierData = JSON.parse(data);
let result = {};
let finalObject = [];
const dateRegex = '/^\d{4}-\d{2}-\d{2}$/';
let request = supplierData.map((row) => {
return new Promise((resolve, reject) => {
/**
* @param row object
* @param row.organisation_id string required
* @param row.movement_date string required (yyyy-mm-dd)
* @param row.product_id string required
* @param row.quantity number required
* @param row.movement_type string (purchase/waste)
* @param row.unit_purchase_price_wo_vat number
* @param row.currency string
* @param row.source_system string
*/
if (!row.organisation_id) {
result.errorID = row.organisation_id;
result.errorField = 'organisation_id';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (typeof row.organisation_id !== 'string') {
result.errorID = row.organisation_id;
result.errorField = 'organisation_id';
result.errorReason = 'Not a String';
reject(result);
}
}
if (!row.movement_date) {
result.errorID = row.organisation_id;
result.errorField = 'movement_date';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (typeof row.movement_date !== 'string') {
result.errorID = row.organisation_id;
result.errorField = 'movement_date';
result.errorReason = 'Not a String';
reject(result);
} else if (!row.movement_date.match(dateRegex)) {
result.errorID = row.organisation_id;
result.errorField = 'movement_date';
result.errorReason = 'Not in correct format of yyyy-mm-dd';
reject(result);
}
}
if (!row.product_id) {
result.errorID = row.organisation_id;
result.errorField = 'product_id';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (typeof row.product_id !== 'string') {
result.errorID = row.organisation_id;
result.errorField = 'product_id';
result.errorReason = 'Not a String';
reject(result);
}
}
if (!row.quantity) {
result.errorID = row.organisation_id;
result.errorField = 'quantity';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (isNaN(row.quantity)) {
result.errorID = row.organisation_id;
result.errorField = 'quantity';
result.errorReason = 'Not a Number!';
reject(result);
}
}
if (!row.movement_type) {
result.errorID = row.organisation_id;
result.errorField = 'movement_type';
result.errorReason = 'Missing Required Property';
reject(result);
} else {
if (row.movement_type !== 'waste' || row.movement_type !== 'purchase') {
result.errorID = row.organisation_id;
result.errorField = 'movement_type';
result.errorReason = 'Only accepts waste or purchase';
reject(result);
}
}
if (row.unit_purchase_price) {
if (isNaN(row.unit_purchase_price)) {
result.errorID = row.organisation_id;
result.errorField = 'unit_purchase_price';
result.errorReason = 'Not a Number!';
reject(result);
}
} else {
row.unit_purchase_price = 0;
}
if (row.unit_purchase_price_wo_vat) {
if (isNaN(row.unit_purchase_price_wo_vat)) {
result.errorID = row.organisation_id;
result.errorField = 'unit_purchase_price_wo_vat';
result.errorReason = 'Not a Number!';
reject(result);
}
} else {
row.unit_purchase_price_wo_vat = 0;
}
if (row.currency) {
if (typeof row.currency !== 'string') {
result.errorID = row.organisation_id;
result.errorField = 'currency';
result.errorReason = 'Not a String';
reject(result);
}
} else {
row.currency = '';
}
if (row.source_system) {
if (typeof row.source_system !== 'string') {
result.errorID = row.organisation_id;
result.errorField = 'source_system';
result.errorReason = 'Not a String';
reject(result);
}
} else {
row.source_system = '';
}
finalObject.push(row);
resolve(row);
});
});
return await Promise.all(request);
};
module.exports = {
validateInventoryTransactions
};
|
var vm = new Vue({
el: '#box',
data: {
editing: '',
newBookMessage: {
name: '',
author: '',
price: ''
},
bookMessage: {
name: '',
author: '',
price: ''
},
bookData: [
{
id: 1,
bookName: '红楼梦',
bookAuthor: '曹雪芹',
bookPrice: 30
},
{
id: 2,
bookName: '西游记',
bookAuthor: '吴承恩',
bookPrice: 35
},
{
id: 3,
bookName: '水浒传',
bookAuthor: '施耐庵',
bookPrice: 33
},
{
id: 4,
bookName: '三国',
bookAuthor: '罗贯中',
bookPrice: 38
}
]
},
methods: {
// 获取ID
getID: function () {
// 要获取一个唯一的ID 通过随机数获取
var id = Math.random() * 10;
for (var i = 0; i < this.bookData.length; i++) {
if (id === this.bookData[i].id) {
id = this.getID();
}
}
console.log(id)
return id;
},
//添加书籍
addBook: function (e) {
// if (e.keyCode == 13) {
// e.preventDefault();
// }
e.keyCode == 13 ? e.preventDefault():'';
if (this.bookMessage.name == '' || this.bookMessage.author == '' || this.bookMessage.price == '') {
alert('请输入完整内容')
return;
}
this.bookData.push({
id: this.getID(),
bookName: this.bookMessage.name,
bookAuthor: this.bookMessage.author,
bookPrice: this.bookMessage.price,
})
this.bookMessage.name = '',
this.bookMessage.author = '',
this.bookMessage.price = ''
console.log(this.bookData)
},
// 删除
delBook: function (id) {
for (var i = 0; i < this.bookData.length; i++) {
if (id === this.bookData[i].id) {
this.bookData.splice(i, 1);
}
}
},
//计算总价格
totalPrice: function () {
var price = 0;
for (var i = 0; i < this.bookData.length; i++) {
price += this.bookData[i].bookPrice - 0;
}
return price;
},
// 模态框获取信息
getBookMessage: function (id) {
for (var i = 0; i < this.bookData.length; i++) {
if (id === this.bookData[i].id) {
this.newBookMessage.name = this.bookData[i].bookName;
this.newBookMessage.author = this.bookData[i].bookAuthor;
this.newBookMessage.price = this.bookData[i].bookPrice;
this.editing = i;
console.log(i)
}
}
},
//保存修改编辑内容
saveEditing: function () {
this.bookData[this.editing].bookName = this.newBookMessage.name;
this.bookData[this.editing].bookAuthor = this.newBookMessage.author;
this.bookData[this.editing].bookPrice = this.newBookMessage.price;
}
},
})
//虽然有很多个删除和编辑,但每一个删除和编辑都有唯一的ID来区分!!!!
|
module.exports.Calling = {
"base_path": process.env.VUE_APP_API,
"proxy_get": process.env.VUE_APP_PROXY_GET,
"proxy_test" : process.env.VUE_APP_PROXY_TEST,
"proxy_reassign": process.env.VUE_APP_PROXY_REASSIGN,
"proxy_update": process.env.VUE_APP_PROXY_UPDATE,
"account_login": process.env.VUE_APP_ACCOUNT_LOGIN,
"account_register": process.env.VUE_APP_ACCOUNT_REGISTER,
"account_confirm": process.env.VUE_APP_ACCOUNT_CONFIRM,
"account_refresh" : process.env.VUE_APP_ACCOUNT_REFRESH,
"account_confirmation": process.env.VUE_APP_ACCOUNT_CONFIRMATION,
"account_changepp": process.env.VUE_APP_ACCOUNT_CHANGEPP,
"account_changebio": process.env.VUE_APP_ACCOUNT_CHANGEBIO,
"account_get_instagrams_account": process.env.VUE_APP_ACCOUNT_GET_INSTAGRAMS_ACCOUNT,
"account_get_user_instagram_account": process.env.VUE_APP_ACCOUNT_GET_USER_INSTAGRAM_ACCOUNT_STATE,
"account_update_agent_state": process.env.VUE_APP_ACCOUNT_UPDATE_AGENT_STATE,
"account_add_instagram": process.env.VUE_APP_ACCOUNT_ADD_INSTAGRAM,
"account_delete_instagram": process.env.VUE_APP_ACCOUNT_DELETE_INSTAGRAM,
"account_instagram_challenge": process.env.VUE_APP_ACCOUNT_INSTAGRAM_CHALLENGE,
"account_instagram_challenge_phone":process.env.VUE_APP_ACCOUNT_INSTAGRAM_PHONE_CHALLENGE,
"account_instagram_refresh": process.env.VUE_APP_ACCOUNT_INSTAGRAM_REFRESH,
"account_get_profiles": process.env.VUE_APP_ACCOUNT_GET_PROFILES,
"account_update_profile": process.env.VUE_APP_ACCOUNT_UPDATE_PROFILE,
"account_add_profile_topics": process.env.VUE_APP_PROFILE_ADD_TOPICS,
"account_upload": process.env.VUE_APP_ACCOUNT_UPLOAD,
"account_session": process.env.VUE_APP_ACCOUNT_SESSION,
"account_detail": process.env.VUE_APP_ACCOUNT_DETAILS,
"query_config": process.env.VUE_APP_QUERY_CONFIG,
"query_related_by_parent": process.env.VUE_APP_QUERY_RELATED_TOPIC,
"query_place_search": process.env.VUE_APP_QUERY_PLACE_SEARCH,
"query_place_autocomplete": process.env.VUE_APP_QUERY_PLACE_AUTOCOMPLETE,
"query_similar_image_search": process.env.VUE_APP_QUERY_SIMILAR_IMAGE_SEARCH,
"query_related_topics": process.env.VUE_APP_QUERY_RELATED_TOPICS,
"query_buildtags": process.env.VUE_APP_QUERY_BUILDTAGS,
"query_searchTopic": process.env.VUE_APP_QUERY_SEARCHTOPIC,
"query_searchLocation": process.env.VUE_APP_QUERY_SEARCHLOCATION,
"query_userMedia": process.env.VUE_APP_QUERY_USERMEDIA,
"query_userInbox": process.env.VUE_APP_QUERY_USERINBOX,
"query_userFeed": process.env.VUE_APP_QUERY_USERFEED,
"query_recentComments": process.env.VUE_APP_QUERY_RECENTCOMMENTS,
"query_userFollowerList" : process.env.VUE_APP_QUERY_USERFOLLOWERLIST,
"query_userFollowingList" : process.env.VUE_APP_QUERY_USERFOLLOWINGLIST,
"query_userTargetLocation" : process.env.VUE_APP_QUERY_USERTARGETLOCATION,
"query_userTargetList" : process.env.VUE_APP_QUERY_USERTARGETLIST,
"query_userFollowingSuggestions" : process.env.VUE_APP_QUERY_USERFOLLOWINGSUGGESTIONS,
"query_mediaByLocation" : process.env.VUE_APP_QUERY_MEDIABYLOCATION,
"messaging_thread": process.env.VUE_APP_MESSAGING_THREAD,
"messaging_post_text": process.env.VUE_APP_MESSAGING_POST_TEXT,
"messaging_delete_comment": process.env.VUE_APP_MESSAGING_DELETE_COMMENT,
"messaging_like_comment": process.env.VUE_APP_MESSAGING_LIKE_COMMENT,
"messaging_unlike_comment": process.env.VUE_APP_MESSAGING_UNLIKE_COMMENT,
"messaging_reply_comment": process.env.VUE_APP_MESSAGING_REPLY_COMMENT,
"messaging_create_comment": process.env.VUE_APP_MESSAGING_CREATE_COMMENT,
"timeline_get_user_timeline": process.env.VUE_APP_TIMELINE_GET_USER_TIMELINE,
"timeline_delete_event": process.env.VUE_APP_TIMELINE_DELETE_EVENT,
"timeline_enqueue_event": process.env.VUE_APP_TIMELINE_ENQUEUE_EVENT,
"timeline_update_event": process.env.VUE_APP_TIMELINE_UPDATE_EVENT,
"timeline_create_post": process.env.VUE_APP_TIMELINE_CREATE_POST,
"timeline_create_message" : process.env.VUE_APP_TIMELINE_CREATE_MESSAGE,
"notifications_get_events": process.env.VUE_APP_NOTIFICATION_GET_EVENTS,
"notifications_get_event_for_user": process.env.VUE_APP_NOTIFICATION_GET_EVENTS_FOR_USER,
"library_get_captions": process.env.VUE_APP_LIBRARY_GET_CAPTIONS,
"library_get_medias": process.env.VUE_APP_LIBRARY_GET_MEDIAS,
"library_get_hashtags": process.env.VUE_APP_LIBRARY_GET_HASHTAGS,
"library_get_messages": process.env.VUE_APP_LIBRARY_GET_MESSAGES,
"library_get_captions_for_user": process.env.VUE_APP_LIBRARY_GET_CAPTIONS_FOR_USER,
"library_get_medias_for_user": process.env.VUE_APP_LIBRARY_GET_MEDIAS_FOR_USER,
"library_get_hashtags_for_user": process.env.VUE_APP_LIBRARY_GET_HASHTAGS_FOR_USER,
"library_get_messages_for_user": process.env.VUE_APP_LIBRARY_GET_MESSAGES_FOR_USER,
"library_set_captions": process.env.VUE_APP_LIBRARY_SET_CAPTIONS,
"library_set_medias": process.env.VUE_APP_LIBRARY_SET_MEDIAS,
"library_set_hashtags": process.env.VUE_APP_LIBRARY_SET_HASHTAGS,
"library_set_messages": process.env.VUE_APP_LIBRARY_SET_MESSAGES,
"library_update_captions": process.env.VUE_APP_LIBRARY_UPDATE_CAPTIONS,
"library_update_hashtags": process.env.VUE_APP_LIBRARY_UPDATE_HASHTAGS,
"library_update_messages": process.env.VUE_APP_LIBRARY_UPDATE_MESSAGES,
"library_delete_captions": process.env.VUE_APP_LIBRARY_DELETE_CAPTIONS,
"library_delete_medias": process.env.VUE_APP_LIBRARY_DELETE_MEDIAS,
"library_delete_hashtags": process.env.VUE_APP_LIBRARY_DELETE_HASHTAGS,
"library_delete_messages": process.env.VUE_APP_LIBRARY_DELETE_MESSAGES,
}
|
var requestsUtile = require('../utile/requests.server.utile.js');
var config = require('../../config/config.js');
var validate = require("validate.js");
var SEO = require('../../config/seo/seo.js');
var constraints = {
query: {
format: {
pattern: "[a-z0-9ãáàâíôóõúçéê_ ]+",
flags: "i",
message: "can only contain a-z ,0-9 and ã,á,à,â,í,ô,ó,õ,ú,ç,é,ê"
}
}
};
exports.render = function(req,res){
res.render('offers',{
title:'Before Deciding - reviews antes de comprar',
//user: JSON.stringify(req.user)
});
};
/**
* [checkCookie set cookie to mark user visit in the landing page ]
* @param {http} req
* @param {http} res
* @param {callback} next
* @return {resp,flagFirstVisit}
*/
exports.checkCookie = function (req,res){
console.log("check cookie >>");
var cookie = req.cookies.bd_lp;
var flagFirstVisit;
if(cookie === undefined){
console.log("cookie doesn't exist >>");
res.cookie('bd_lp','1',{expires: new Date(Date.now() + (2000*24*60*60*1000)),encode: String});
// res.redirect('/static/lp/welcome');
getOffersHome(req,res);
}else{
console.log("cookie exists");
getOffersHome(req,res);
}
// next(res,flagFirstVisit);
};
var getErrorMessage = function(err){
if(err.errors){
for (var errName in err.errors){
if(err.errors[errName].message){
return err.errors[errName].message;
}
}
}else{
return 'Unknown server error';
}
};
exports.list = function(req,res){
Article.find().sort('-created').populate('creator','firstName last name fullName').exec(function(err,articles){
if(err){
return res.status(400).send({
message: getErrorMessage(err)
});
}else{
res.json(articles);
}
});
};
/**
* @description list offers by ean
* @param {req}
* @param {res}
* @param {next}
* @return {list of offers of ean requested}
*/
exports.getOffersByEan = function(req,res,next){
var ean = req.params.reviews;
var url = config.service_host + '/api/offers/bd/ean/' + ean + '/page/1/limit/100/';
var call = new requestsUtile();
call.getJson(url,function(data,response,error){
if(error){
console.log(error);
return next(err);
}else{
req.offers = data;
next();
}
});
};
function validateSearch(req,res,next){
console.log("validate Search >> ");
var page = req.query.page;
if ((page === undefined ) || (page < 0)){
page = 1;
};
var query = req.query.query;
if ((validate.isEmpty(query)) || (query === undefined)){
query = "smartphones";
return next(query,page);
}else if(validate({query: query}, constraints)){
res.render('partials/error',{
title: config.title,
message: config.message_search_validate,
env: process.env.NODE_ENV,
slogan: config.slogan,
});
}else{
return next(query,page);
};
};
/**
* @description return pagination of offers page
* @param {data} return of bd services api
* @param {page} current page
* @param {callback}
* @return {from,to,previous,next}
*/
function pagination(data,page,callback){
if(Number(page) <= data.limit){
var to = data.limit;
var from = 1;
var previous = 0;
var next = to + 1;
}else{
var decimal = Math.floor((Number(page) / data.limit));
var to = (decimal + 1) * data.limit;
var from = (to - data.limit) + 1;
var previous = from - data.limit;
var next = to + 1;
};
if(to > data.pages){
to = data.pages;
next = 0;
};
console.log("from >> ",from);
console.log("to >>",to);
console.log("next >> ",next);
console.log("previous >>",previous);
return callback(from,to,previous,next);
}
function getOffersHome(req,res){
console.log("getOffersByQuery controller >> ");
validateSearch(req,res,function(query,page){
var order = req.query.order;
console.log("order by >>",order);
if ((order === undefined ) || (order < 0)){
order = 1;
}
console.log("query",query);
var url = config.service_host + "/api/offers/bd/query/" + query + "/page/" + page + "/limit/" + config.limit + "/order/" + order;
console.log(url);
var call = new requestsUtile();
call.getJson(url,function(data,response,error){
if(data.total == 0){
var message = "produto não encontrado";
res.render('partials/error',{
title: config.title,
message: config.message_search_error,
slogan: config.slogan,
env: process.env.NODE_ENV
});
}
else if(data.code == 500) {
console.log("error >>", data.message);
var message = "ops! ocorreu algum problema técnico. Fique tranquilo, o nosso time já está trabalhando na resolução. = )";
res.render('partials/error',{
title: config.title,
message: message,
slogan: config.slogan,
env: process.env.NODE_ENV
});
}
else if(error){
console.log("error",error);
return res.status(400).send({
message: getErrorMessage(error)
});
}else{
console.log(data.docs[0]);
pagination(data,page,function(from,to,previous,next){
res.render('home/home',{
title: SEO.title,
slogan: SEO.slogan,
pagination: {
page: page,
from:from,
to:to,
next:next,
previous:previous,
pages:data.pages,
},
offers: data,
query: query,
total: data.total,
env: process.env.NODE_ENV,
order: order,
featureToogle: config.offers_toogle
});
});
};
});
});
}
// exports.read = function(req,res){
// console.log("testes server");
// res.json(req.article);
// };
|
// todo remove suppression on multiple exports
export const CoordState = {
typedWords: null,
foundWord: false,
usecase: null,
isTriSymOfAFound: false,
isTriSymOfCFound: false,
isSqSymOfAFound: false,
isSqSymOfBFound: false,
isSqSymOfCFound: false,
isSqSymOfDFound: false,
isPolySymOfAFound: false,
isPolySymOfBFound: false,
isPolySymOfCFound: false,
isPolySymOfDFound: false,
isPolySymOfEFound: false,
isWordFound: false,
symOfAFound: false,
symOfBFound: false,
symOfCFound: false,
symOfDFound: false,
sqSymOfAFound: false,
sqSymOfBFound: false,
sqSymOfDFound: false,
polySymOfAFound: false,
polySymOfBFound: false,
polySymOfCFound: false,
polySymOfDFound: false,
polySymOfEFound: false,
obserViewActive: true,
triCoordA: [{ x: 0, y: 13 }],
triCoordB: [{ x: 5, y: 0 }],
triCoordC: [{ x: 3, y: 5 }],
triCoordA_PRIM: [{ x: 3, y: 5 }],
triCoordB_PRIM: [{ x: 7, y: 4 }],
triCoordC_PRIM: [{ x: 3, y: 5 }],
sqCoordA: [{ x: 1, y: 5 }],
sqCoordB: [{ x: 2, y: 8 }],
sqCoordC: [{ x: 5, y: 4 }],
sqCoordD: [{ x: 7, y: 12 }],
sqCoordA_PRIM: [{ x: 2, y: 12 }],
sqCoordB_PRIM: [{ x: 11, y: 3 }],
sqCoordC_PRIM: [{ x: 4, y: 8 }],
sqCoordD_PRIM: [{ x: 45, y: 12 }],
polyCoordA: [{ x: 9, y: 54 }],
polyCoordB: [{ x: 42, y: 11 }],
polyCoordC: [{ x: 11, y: 34 }],
polyCoordD: [{ x: 45, y: 7.5 }],
polyCoordE: [{ x: 66, y: 11 }],
};
export default CoordState;
|
$(function(){
var clenWidth = function(){
var bodyWidth = $(window).width();
var newHhtmlFontSzie = 100 * (bodyWidth/750) + 'px';
$('html').css({
'font-size' : newHhtmlFontSzie
})
}
clenWidth();
window.onresize = function(){
clenWidth();
}
})
|
const path = require('path'); //path 模块提供了一些工具函数,用于处理文件与目录的路径。
const merge = require('webpack-merge');
const common = require('./webpack.config.js');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const ip = require('ip').address();
const port = 9000
const resolve = function (pathNmae) {
return path.resolve(__dirname, pathNmae)
}
module.exports = merge(common,{
mode: "development",
devtool: 'cheap-module-eval-source-map', //生曾map 映射对应代码 方便错误查询
devServer:{
hot:true, //hot模式开启
port: port,
contentBase: resolve('dist'),
historyApiFallback: true,
clientLogLevel: "none",
host: '0.0.0.0',
overlay:true,
quiet: true,
publicPath:"/"
},
module:{ //处理项目中的不同类型的模块。
rules:[ // rules 各种规则(数组类型) 每个规则可以分为三部分 - 条件(condition),结果(result)和嵌套规则(nested rule)
{
test:/\.(sa|sc|c)ss$/i,
use: [
'style-loader',
'css-loader',
'sass-loader',
'postcss-loader'
], // style-loader 和css-loader 编译css处理
}]
},
plugins:[
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: ['App running at:',`- Local: http://localhost:${port}`,`- Network: http://${ip}:${port}`],
},
onErrors:function (severity, errors) {
console.log("severity",severity,errors);
// You can listen to errors transformed and prioritized by the plugin
// severity can be 'error' or 'warning'
},
clearConsole: true,
}),
]
});
|
var App = angular.module('App', ['ui.router', 'remoteValidation', 'permission', 'ODataResources','ui.grid']);
App.config(function ($stateProvider, $urlRouterProvider, $locationProvider, $provide) {
$provide.decorator("$exceptionHandler", function ($delegate, $injector) {
return function (exception, cause) {
var $rootScope = $injector.get("$rootScope");
//send to server the error i guess.
$delegate(exception, cause);
};
});
$urlRouterProvider.otherwise(function ($injector, $location) { // nasty bug.
var $state = $injector.get("$state");
$state.go("home");
});
$stateProvider
.state('home', {
url: '/home',
templateUrl: '/App/Areas/Home/home.html',
controller: 'HomeCtrl'
});
$stateProvider
.state('loginPage', {
url: '/login/:redirectUrl',
templateUrl: '/App/common/Login/Login.html',
controller: 'LoginPageCtrl'
});
$stateProvider
.state('admin', {
url: '/admin/:adminid',
templateUrl: '/App/Areas/Admin/admin.html',
controller: 'AdminCtrl',
data: {
permissions: {
only: ['Admin']
}
}
});
$stateProvider
.state('admin.companies', {
url: '/companies/:companyId',
templateUrl: '/App/Areas/Admin/Companies/Companies.html',
controller: 'CompaniesCtrl',
data: {
permissions: {
only: ['Admin']
}
}
});
});
App.run(function ($rootScope, currentUser, $state, $location, Permission, ModalService) {
Permission.defineRole('Admin', function () {
return currentUser.isInRole('Admin');
});
if (localStorage.getItem("Token")) {
$rootScope.LoggedIn = true;
}
else {
$rootScope.LoggedIn = false;
}
$rootScope.$on('$stateChangeStart',
function (event, toState, toParams, fromState, fromParams) {
if (localStorage.getItem("Token") == null && toState.name != "loginPage") {
event.preventDefault();
$state.go('loginPage', { redirectUrl: toState.name });
return;
}
});
$rootScope.$on('$stateChangePermissionDenied',
function (toState, toParams, fromParams) {
ModalService.showModal({
templateUrl: '/App/common/Login/Login.html',
controller: 'LoginCtrl',
title: 'Access denied.Login with another account to continue.'
}).then(function (modal) {
modal.element.modal({
backdrop: 'static',
keyboard: false
});
modal.close.then(function (result) {
if (result == "1") // user has successfully authenticated.
{
$state.go(toParams.name, fromParams);
}
else {
// do nothing hm?h
}
});
});
});
});
App.constant('BaseUrl', 'http://localhost:8337/');
|
import React from 'react';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
TouchableOpacity,
useColorScheme,
View,
} from 'react-native';
import {
Colors,
DebugInstructions,
Header,
LearnMoreLinks,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
import ImagePicker from 'react-native-image-crop-picker';
export default function Imagecrop() {
const takePhotoFromCamera = () => {
ImagePicker.openCamera({
width: 300,
height: 400,
cropping: true,
}).then(image => {
console.log(image);
});
}
const takePhotoFromGallary = () => {
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true
}).then(image => {
console.log(image);
});
}
return (
<ScrollView>
<View style={styles.inputButton}>
<TouchableOpacity
style={styles.roundButton1}
onPress={takePhotoFromCamera}>
<Text style={styles.buttonText}>Click to open camera</Text>
</TouchableOpacity>
</View>
<View style={styles.inputButton}>
<TouchableOpacity
style={styles.roundButton1}
onPress={takePhotoFromGallary}>
<Text style={styles.buttonText}>Choose from gallary</Text>
</TouchableOpacity>
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
inputButton: {
marginTop: 40,
margin: 10,
alignItems: 'center',
},
buttonText: {
color: 'white',
fontWeight: 'bold',
},
roundButton1: {
width: 290,
height: 50,
justifyContent: 'center',
alignItems: 'center',
padding: 10,
borderRadius: 60,
backgroundColor: '#3154A5',
},
});
|
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import categoryFragment from '../fragments/category'
export const CategoryQuery = gql`
query CategoryQuery($categoryId: ID!) {
category(id: $categoryId) {
...CategoryFragment
}
}
${categoryFragment}
`
const queryConfig = {
options: ({ categoryId }) => ({
variables: {
categoryId
}
}),
props: ({ ownProps, data }) => ({
...ownProps,
...data
})
}
export default graphql(CategoryQuery, queryConfig)
|
var tasks = [
{name: 'Recoger setas en el campo', completed: false},
{name: 'Comprar pilas', completed: true},
{name: 'Poner una lavadora de blancos', completed: true},
{name: 'Aprender cómo se realizan las peticiones al servidor en JavaScript', completed: false}
];
function pintarListaTares () {
var html_task = "", cont_completa = 0, cont_por_realizar = 0;
tasks.forEach( (task, index) =>{
task.completed?cont_completa++:cont_por_realizar++;
html_task += `<li class = "${task.completed?"completa":""}">${task.name}</li>
<input class = "tarea" type = "checkbox" ${task.completed?"checked":""} index = ${index}> `;
});
$("#completadas span").html(cont_completa);
$("#por_realizar span").html(cont_por_realizar)
$("#lista_tares").html(html_task);
}
$(document).ready( (e) => {
$(document).on('click', '.tarea', (e) => {
tasks[e.target.getAttribute('index')].completed = e.target.checked?true:false;
pintarListaTares();
})
$('#hola').click((e) => {
alert("Diste click");
});
pintarListaTares ();
});
|
/**
* Created by alucas on 14/1/17.
*/
import React, { Component, PropTypes } from 'react';
import Cell from './Cell';
export default class SudokuBoard extends Component {
static propTypes = {
height: React.PropTypes.number,
width: React.PropTypes.number,
};
getStyles() {
return {
root: {
height: this.props.height,
width: this.props.width,
},
rect: {
height: this.props.height,
width: this.props.width,
fill: 'rgb(33,33,33)'
}
}
}
componentDidMount() {
}
constructor(props) {
super(props);
}
render() {
let styles = this.getStyles();
let RowGridLine = (i, n) => <line data-n={i} key={i} x1={0} y1={(this.props.height*i)/n} x2={this.props.width} y2={(this.props.height*i)/n} style={{strokeWidth:1, stroke:'red'}}/>;
var Rows = [];
let RowGridLines = (n = 9) => {
for(let i = 0; i < n; i++) {
Rows.push(RowGridLine(i, n));
}
};
RowGridLines(9);
let ColGridLine = (i, n) => <line data-n={i} key={i} y1={0} x1={(this.props.width*i)/n} y2={this.props.height} x2={(this.props.width*i)/n} style={{strokeWidth:1, stroke:'red'}}/>;
var Cols = [];
let ColGridLines = (n = 9) => {
for(let i = 0; i < n; i++) {
Cols.push(ColGridLine(i, n));
}
};
ColGridLines(9);
let SqrGridLine = (i, n) => (
<rect
x={(Math.trunc(i%Math.sqrt(n))) * this.props.width / Math.sqrt(n)}
y={(Math.trunc(i/Math.sqrt(n))) * this.props.height / Math.sqrt(n)}
width={this.props.width/Math.sqrt(n)}
height={this.props.height/Math.sqrt(n)}
style={{
fill: 'none',
stroke: 'red',
strokeWidth: 5
}}
data-n={i}
key={i}
/>
);
var Sqrs = [];
let SqrGridLines = (n = 9) => {
for(let i = 0; i < n; i++) {
Sqrs.push(SqrGridLine(i, n));
}
};
SqrGridLines(9);
const getCells = (() => {
console.log('getCells');
const r = [];
for(let y = 0; y<9; y++) {
for (let x = 0; x < 9; x++) {
// console.log(x,y, '--->', x * this.props.width / Math.sqrt(9), y * this.props.height / Math.sqrt(9), this.props.width/9, this.props.height/9);
r.push(
<Cell
id={`cell-x${x}y${y}`}
key={`cell-x${x}y${y}`}
x={(x * this.props.width / 9) + 4}
y={(y * this.props.height / 9) + 4}
width={(this.props.width/9) - 8}
height={(this.props.height/9) -8}
/>
)
}
}
return r;
});
return (
<svg style={styles.root}>
<rect
style={styles.rect}
/>
<g id="rows">{Rows}</g>
<g id="cols">{Cols}</g>
<g id="sqrs">{Sqrs}</g>
<g id="cells">{getCells()}</g>
</svg>
);
}
}
|
const firebaseConfig = {
apiKey: "AIzaSyCe7qa6pcT1Nir5h9V5ldFCN46nf4Ln5xs",
authDomain: "hot-onion-restaurant-b3126.firebaseapp.com",
databaseURL: "https://hot-onion-restaurant-b3126.firebaseio.com",
projectId: "hot-onion-restaurant-b3126",
storageBucket: "hot-onion-restaurant-b3126.appspot.com",
messagingSenderId: "557079488183",
appId: "1:557079488183:web:4ed6d12b954f15bb158f32"
};
export default firebaseConfig;
|
const Books = require('../models').Book;
const Authors = require('../models').Author;
const paginate = require('./paginate').paginate;
const returnObject = require('./paginate').returnObject;
module.exports = {
// add book to library
create(req, res) {
return Books
.create({
title: req.body.title,
genre_id: req.body.genre_id,
description: req.body.description,
ISBN: req.body.ISBN,
quantity: req.body.quantity,
available: req.body.quantity,
documentURL: req.body.documentURL || null,
coverPhotoURL: req.body.coverPhotoURL || null
})
.then(book => res.status(201).send({
message: `${book.title} have been added to library`,
book
}))
.catch(() => res.status(500).send({ message: 'Internal Server Error' }));
},
//allow users to modify book information
update(req, res) {
try {
return Books
.find({
where: {
id: req.params.bookId
}
})
.then(books => {
if (!books) {
res.status(404).send({
message: 'Book Not Found'
});
}
return books.update({
title: req.body.title || books.title,
genre_id: req.body.genre_id || books.genre_id,
description: req.body.description || books.description,
ISBN: req.body.ISBN || books.ISBN,
quantity: req.body.quantity || books.quantity,
available: req.body.available || books.quantity,
documentURL: req.body.documentURL || books.documentURL,
coverPhotoURL: req.body.coverPhotoURL || books.coverPhotoURL
})
.then(updatedBook => res.status(200).send({
message: `${updatedBook.title} record have been updated`,
updatedBook
}));
});
} catch (e) {
res.status(500).send({ message: 'Internal Server Error' });
}
},
getBooks(req, res) {
const { count, page } = req.query;
const { bookId } = req.params;
let { limit, offset } = paginate(page, count)
return Books.findAll({
where: (
bookId ? { id: bookId } : {}
),
limit: limit,
offset: offset,
order: [
['id', 'ASC']
],
include: [{
model: Authors,
through: {
attributes: ['id', 'fullName', 'dateOfBirth', 'dateOfDeath', 'lifeSpan']
}
}]
}).then((books) => {
if (!books || books.length === 0) {
return res.status(200).send({
message: 'Oops! No books exists in this section'
});
}
return res.status(200).send(returnObject(books, 'books'))
}).catch(() => {
return res.status(500).send({
message: 'Internal Server Error'
});
});
},
delete(req, res) {
return Books
.destroy({
where: { id: req.params.bookId }
}).then(books => {
if (!books) {
return res.status(404).send({
message: 'Book not found'
});
}
if (books) {
return res.status(200).send({
message: 'Book have been successfully deleted'
});
}
})
.catch(() => res.status(500).send({
message: 'Internal Server Error'
}));
}
};
|
/* eslint-disable no-undef,prefer-reflect */
const path = require('path');
const fs = require('fs')
// const sharp = require('sharp')
const mediaTags = require("jsmediatags")
// const BaseRest = require('./_rest')
module.exports = class extends think.Controller {
async postAction () {
const postModel = this.model('posts')
const optionsModel = this.model('options')
// 获取 当前用户配置
const option = await optionsModel.get(true)
let config = option.upload
// Basil @170831 获取 用户自定义上传服务(现仅支持七牛)
if (!Object.is(option.upload, undefined)) {
config = option.upload
}
const httpx = config.option.ssl ? 'https' : 'http'
// 获取 文件信息
const file = think.extend({}, this.file('file'))
const filePath = file.path
const extname = path.extname(file.name)
const basename = path.basename(filePath) + extname;
// if (oneOf(file.type, ['audio/mpeg', 'audio/mp3'])) {
// return this.success(file.originalFilename)
// }
// 执行文件上传逻辑
if (config.type === 'qiniu') {
const service = this.service('qiniu')
const upload = await service.upload(filePath, basename, config.option)
// console.log(this.ctx.state)
if (!think.isEmpty(upload)) {
const data = {
// 验证权限 后获取
author: this.ctx.state.user.userInfo.id,
title: file.name.split('.')[0],
name: upload.hash,
// path: '/upload/picture/' + dateformat(new Date().getTime(), "Y-m-d") + '/' + basename,
type: 'attachment',
mime_type: file.type,
guid: `${httpx}://${config.option.domain}/${upload.key}`,
create_time: new Date().getTime(),
status: 'publish',
}
const fileUrl = `${httpx}://${config.option.domain}/${upload.key}`
const _post_id = await postModel.add(data);
const retData = {
id: _post_id,
url: fileUrl,
title: data.title
}
if (oneOf(file.type, ['image/jpg', 'image/jpeg', 'image/png'])) {
try {
// await this.sharpMetadata(file.path)
await postModel.addMeta(_post_id, '_attachment_file', fileUrl)
return this.success(retData)
} catch (e) {
console.error(e)
return this.fail()
// eslint-disable-next-line no-unreachable
}
}
}
return this.success(retData)
}
}
/**
* 文件上传
* @returns {Promise.<*>}
*/
async uploadAction () {
const _postModel = this.model('posts', {orgId: this.orgId})
const file = think.extend({}, this.file('file'));
// console.log(JSON.stringify(file))
// console.log(this.options)
const filepath = file.path;
const basename = path.basename(filepath);
const ret = {'status': 1, 'info': '上传成功', 'data': ""}
let res;
// 加入七牛接口
if (this.options.upload.type === "qiniu") {
const qiniu = think.service("qiniu");
// eslint-disable-next-line new-cap
const instance = new qiniu();
const uppic = await instance.upload(filepath, basename, this.aid);
if (!think.isEmpty(uppic)) {
const data = {
author: this.ctx.state.user.id,
title: file.originalFilename,
name: uppic.hash,
// path: '/upload/picture/' + dateformat(new Date().getTime(), "Y-m-d") + '/' + basename,
type: 'attachment',
mime_type: file.headers['content-type'],
guid: "http://" + this.options.upload.option.domain + "/" + uppic.key,
create_time: new Date().getTime(),
status: 1,
};
// const _attachment_metadata = '';
// const _attachment_metadata = await this.sharpMetadata(file.path)
const _post_id = await _postModel.add(data);
if (!think.isEmpty(_post_id)) {
// await _postModel.addPostMeta(_post_id, "_attachment_metadata", _attachment_metadata);
await _postModel.addPostMeta(_post_id, "_attachment_file", uppic.key);
}
ret.data = data;
}
} else {
const uploadPath = think.RESOURCE_PATH + '/upload/picture/' + dateformat(new Date().getTime(), "Y-m-d");
think.mkdir(uploadPath);
if (think.isFile(filepath)) {
fs.renameSync(filepath, uploadPath + '/' + basename);
} else {
console.log("文件不存在!")
}
file.path = uploadPath + '/' + basename;
if (think.isFile(file.path)) {
const _path = '/upload/picture/' + dateformat(new Date().getTime(), "Y-m-d") + '/' + basename;
const data = {
author: this.userInfo.id,
title: file.originalFilename,
name: basename,
// path: '/upload/picture/' + dateformat(new Date().getTime(), "Y-m-d") + '/' + basename,
type: 'attachment',
mime_type: file.headers['content-type'],
guid: this.options.site_url + _path,
create_time: new Date().getTime(),
status: 1,
}
// const _attachment_metadata = await sharp(file.path).metadata();
// delete _attachment_metadata.exif;
const _post_id = await _dao.add(data);
// this.dao.addPostMeta(_post_id, "_attachment_metadata", _attachment_metadata);
await _dao.addPostMeta(_post_id, "_attachment_file", _path);
ret.data = data;
} else {
console.log('not exist')
}
}
return this.json(ret);
}
// 用 sharp 处理图片信息
async sharpMetadata (filepath) {
// const metadata = await sharp(filepath).metadata();
// Reflect.deleteProperty(metadata, 'exif')
// delete metadata.exif;
// return metadata
}
}
|
import { shallowMount } from '@vue/test-utils';
import Vue from 'vue';
import Vuetify from 'vuetify';
import VueRouter from 'vue-router';
import AuthorProfile from '../../src/components/AuthorProfile.vue';
import Snackbar from '../../src/components/Snackbar.vue';
// Store.
import store from '../Store.js';
Vue.use(VueRouter);
Vue.use(Vuetify);
describe('AuthorProfile', () => {
it('is a Vue instance', () => {
const wrapper = shallowMount(AuthorProfile, {
mocks: {
$store: store
}
});
expect(wrapper.isVueInstance()).toBeTruthy();
});
it('is data a function', () => {
expect(typeof AuthorProfile.data).toBe('function');
});
it('has data correct data types', () => {
expect(AuthorProfile.data()).toEqual({
showChangePasswordDialog: expect.any(Boolean),
showProfileUpdatedSnackbar: expect.any(Boolean),
loading: expect.any(Boolean),
isFormValid: expect.any(Boolean),
name: expect.any(String),
nameRules: expect.any(Array),
lastname: expect.any(String),
lastnameRules: expect.any(Array),
email: expect.any(String),
emailRules: expect.any(Array),
showPassword: expect.any(Boolean),
showPasswordConfirmation: expect.any(Boolean),
password: expect.any(String),
passwordConfirmation: expect.any(String),
passwordRules: expect.any(Object),
gender: expect.any(String),
genderSelectorRules: expect.any(Object),
profileImageSrc: expect.any(String)
});
});
it('is mounted a function', () => {
expect(typeof AuthorProfile.mounted).toBe('function');
});
it('is methods an Object', () => {
expect(typeof AuthorProfile.methods).toBe('object');
});
it('has required methods', () => {
expect(AuthorProfile.methods).toEqual({
blurInput: expect.any(Function),
doPasswordsMatch: expect.any(Function),
changePassword: expect.any(Function),
checkPasswordChange: expect.any(Function),
updateAuthorsProfile: expect.any(Function)
});
});
it('is watch an Object', () => {
expect(typeof AuthorProfile.watch).toBe('object');
});
it('has watch required functions', () => {
expect(AuthorProfile.watch).toEqual({
loader: expect.any(Function)
});
});
it('is components an Object', () => {
expect(typeof AuthorProfile.components).toBe('object');
});
it('has correct components', () => {
expect(AuthorProfile.components).toEqual({
Snackbar
});
});
it('are all components a Vue component', () => {
const wrapper = shallowMount(Snackbar, {
propsData: {
show: true,
snackbarColor: 'grey',
snackbarText: 'Test',
snackbarCloseTime: 6000,
snackbarCloseText: 'Close'
}
});
expect(wrapper.isVueInstance()).toBeTruthy();
});
});
|
var request = require('request');
//request list of subscribers CHANNEL IDs for given user
function getSubscriberChannelsIdApi (user, callback) {
//return ALL user subscriptions as an array of SUBSCRIBER IDs
getUserSubscriptions(user, function(err, subscriptions) {
if(err) return err;
getChannelsForSubscriptions(user, subscriptions, function(err, channels) {
if(err) return callback(err);
callback(null, channels);
})
});
}
//return the array of ALL channels subscribed (multiple pages)
function getChannelsForSubscriptions (user, subscriptionsIds, callback) {
var userSubscribedChannelIds = [];
var allSubscriptionIds = subscriptionsIds; // assume this has 100 or more email addresses in it
var splicedSubscriptionIds = [];
var responses = [];
var count = 0;
while(allSubscriptionIds.length > 0) {
splicedSubscriptionIds.push(allSubscriptionIds.splice(0,10));
}
splicedSubscriptionIds.forEach(function(subscriptionIdsRequest, index) {
runChannelsForSubscriptionsApi(user, subscriptionIdsRequest, function(err, response){
if(err) return err;
responses[index] = response;
count++
if (count == splicedSubscriptionIds.length) {
channelApiFinished();
}
});
})
function channelApiFinished() {
responses.forEach(function(response) {
response.items.forEach(function(channel){
console.log(channel);
userSubscribedChannelIds.push(channel.snippet.resourceId.channelId);
})
})
callback(null, userSubscribedChannelIds);
}
}
//runs requested api and returns parsed JSON data (single page);
function runChannelsForSubscriptionsApi (user, subscriptionIds, callback) {
//create api request
var options = { method: 'GET',
url: 'https://www.googleapis.com/youtube/v3/subscriptions',
qs:
{
part: 'snippet, contentDetails',
id: subscriptionIds.join(','),
access_token: user.google.accessToken,
maxResults : 50
},
headers:
{
'postman-token': 'f40b852d-3d9d-d6af-611e-443709e965d1',
'cache-control': 'no-cache'
}
};
//response from api
request(options, function (err, response, body) {
if (err) return callback(err);
//convert body to JSON and parse out subscriptions into array
var obj = JSON.parse(body);
callback(null, obj);
});
}
//return the array of ALL subscriptions (multiple pages)
function getUserSubscriptions (user, callback) {
var subscriptionIds = [];
var pageToken = null;
var morePages = true;
runAPI();
function runAPI() {
if (morePages == true) {
runUserSubscriptionsApi(user, pageToken, function(err, subscriptionData) {
if(err) return err;
subscriptionData.items.forEach(function(subscription) {
subscriptionIds.push(subscription.id);
})
if(subscriptionData.hasOwnProperty('nextPageToken')) {
pageToken = subscriptionData.nextPageToken;
} else {
morePages = false;
}
runAPI();
});
} else {
callback(null, subscriptionIds);
}
}
}
//runs requested api and returns parsed JSON data (single page);
function runUserSubscriptionsApi(user, pageToken, callback) {
//get user subscriptions
var options = { method: 'GET',
url: 'https://www.googleapis.com/youtube/v3/subscriptions',
qs:
{ part: 'id',
mine: 'true',
access_token: user.google.accessToken,
pageToken: pageToken,
maxResults: 50
},
headers:
{ 'postman-token': '74246038-0e5e-07ae-8b7f-c242b67d9309',
'cache-control': 'no-cache' } };
//response from api
request(options, function (err, response, body) {
if (err) return callback(err);
//convert body to JSON and parse out subscriptions into array
var obj = JSON.parse(body);
callback(null, obj);
});
}
module.exports = getSubscriberChannelsIdApi;
|
const { GraphQLID } = require("graphql");
const { getPost } = require("../../../services/post.service");
const postType = require("../../types/post");
module.exports = {
type: postType,
description: "Get a post",
args: {
postId: { type: GraphQLID }
},
resolve: async (root, { postId }) => {
return await getPost({ postId });
}
};
|
let studentScores = {
student1: {
id: 123456789,
scores: {
exams: [90, 95, 100, 80],
exercises: [20, 15, 10, 19, 15],
},
},
student2: {
id: 123456799,
scores: {
exams: [50, 70, 90, 100],
exercises: [0, 15, 20, 15, 15],
},
},
student3: {
id: 123457789,
scores: {
exams: [88, 87, 88, 89],
exercises: [10, 20, 10, 19, 18],
},
},
student4: {
id: 112233445,
scores: {
exams: [100, 100, 100, 100],
exercises: [10, 15, 10, 10, 15],
},
},
student5: {
id: 112233446,
scores: {
exams: [50, 80, 60, 90],
exercises: [10, 0, 10, 10, 0],
},
},
};
function sum(array) {
return array.reduce((memo, elem) => memo + elem);
}
function arrayAverage(array) {
return sum(array) / array.length;
}
function getNumberGrade(scores) {
let examAverage = arrayAverage(scores.exams);
let exerciseTotal = sum(scores.exercises);
return Math.round((examAverage * .65) + (exerciseTotal * .35));
}
function getLetterGrade(numberGrade) {
if (numberGrade >= 93) {
return 'A';
} else if (numberGrade >= 85) {
return 'B';
} else if (numberGrade >= 77) {
return 'C';
} else if (numberGrade >= 69) {
return 'D';
} else if (numberGrade >= 60) {
return 'E';
} else {
return 'F';
}
}
function grade(student) {
let numberGrade = getNumberGrade(student.scores);
let letterGrade = getLetterGrade(numberGrade);
return `${numberGrade} (${letterGrade})`;
}
function min(array) {
return array.reduce((memo, elem) => {
return memo < elem ? memo : elem;
});
}
function max(array) {
return array.reduce((memo, elem) => {
return memo > elem ? memo : elem;
});
}
function getExamStats(exams) {
let average = Math.round(arrayAverage(exams) * 10) / 10;
let minimum = min(exams);
let maximum = max(exams);
return { average, minimum, maximum };
}
function generateClassRecordSummary(scores) {
let studentGrades = [];
let exams = [];
Object.keys(scores).forEach(student => {
studentGrades.push(grade(scores[student]));
exams.push(getExamStats(scores[student].scores.exams));
});
return { studentGrades, exams };
}
console.log(generateClassRecordSummary(studentScores));
// returns:
/*{
studentGrades: [ '87 (B)', '73 (D)', '84 (C)', '86 (B)', '56 (F)' ],
exams: [
{ average: 75.6, minimum: 50, maximum: 100 },
{ average: 86.4, minimum: 70, maximum: 100 },
{ average: 87.6, minimum: 60, maximum: 100 },
{ average: 91.8, minimum: 80, maximum: 100 },
],
}*/
|
define(['zepto', 'underscore', 'backbone',
'echo', 'app/api', 'app/refreshtoken',
'app/utils',
'text!templates/bindPhoneStep2.html'
],
function($, _, Backbone, echo, Api, Token, utils, bindPhoneStep2Template) {
var $page = $("#bind-phone-step2");
var $phoneNumber ;
var $btn;
var $verificationCode;
var telephoneMobile;
var bindPhoneStep2View = Backbone.View.extend({
el: $page,
render: function(mobile) {
console.log("mobile: " + mobile);
telephoneMobile = mobile;
utils.showPage($page, function() {
$page.empty().append(bindPhoneStep2Template);
$phoneNumber = $page.find(".phone_number");
$btn = $page.find(".btn_countdown");
$verificationCode = $page.find(".verification_code");
setMobilePhone();
//验证码按钮倒计时
countDown();
});
},
events: {
//
"tap .btn_next":"next",
},
next: function(){
//判断验证码是否为空
var code = $verificationCode.val();
if (code == "") {
$.Dialog.info("请输入验证码")
return false;
}
bindStep2(code);
},
});
var bindStep2 = function(code){
var fromData = "captcha=" + code;
var param = {fromData:fromData};
Api.bindStep2(param, function(successsData){
window.location.hash = "bindPhone";
}, function(errorData){
//token过期 刷新token
if( errorData.err_code == 20002 ){
Token.getRefeshToken(type,function(data){
bindStep2(code);
},function(data){
window.location.href = window.LOGIN_REDIRECT_URL;
});
}
});
};
var setMobilePhone = function(){
var mumber = telephoneMobile.substring(0, 3) + "********";
$phoneNumber.html(mumber);
};
var countDown = function(){
var timeout = 60;
$btn.off('tap');
var handler = window.setInterval(function () {
--timeout;
if (timeout <= 0) {
//$btn.text("获取验证码").removeClass("disabled").on("tap", RegisterModel.sendCode);
$btn.text("获取验证码");
sendCode();
return window.clearInterval(handler);
}
$btn.text(timeout + "秒后重新获取");
}, 1000)
};
//得到验证码
var sendCode = function(){
//验证手机号码
if (!verifyMobile(telephoneMobile))
return;
//用户协议
//TODO
var fromData = "mobile=" + telephoneMobile;
var param = {fromData:fromData};
Api.getBindPhoneVerCode(param, function(successsData){
countDown();
utils.storage.set( "bindCode", successsData.result);
}, function(errorData){
//token过期 刷新token
if( errorData.err_code == 20002 ){
Token.getRefeshToken(type,function(data){
sendCode();
},function(data){
window.location.href = window.LOGIN_REDIRECT_URL;
});
}
});
};
// 验证手机号码
var verifyMobile = function(mobile) {
if (mobile == "") {
$.Dialog.info("请输入手机号码")
return false;
}
if (!$.isPhone(mobile)) {
$.Dialog.info("您输入的手机号码格式不正确")
return false;
}
return true;
};
return bindPhoneStep2View;
});
|
import transformForTokens from './transformForTokens';
import forEachTheme from '../../test/utils/forEachTheme';
describe('transformForTokens', () => {
forEachTheme(({ theme }) => {
test('Rules', () => {
expect(
transformForTokens({
tokens: theme.tokens
})
).toMatchSnapshot();
});
});
});
|
const INITIAL_STATE = {
activeTasks: [],
historyTasks: [],
tasks: [],
profiles: []
}
export default function (state = INITIAL_STATE, action) {
switch (action.type) {
// [GN] action used to get the profile names' for each task
case 'GET_PROFILES':
return { ...state, profiles: action.payload.data }
case 'GET_ACTIVE_TASKS':
return { ...state, activeTasks: action.payload.data }
case 'GET_TASKS':
return { ...state, tasks: action.payload }
case 'GET_HISTORY_TASKS':
return { ...state, historyTasks: action.payload.data }
case 'DATA_TASK_UNAUTHORIZED':
return { ...state, tasks: null }
case 'ADD_TASK':
let _tasks = state.tasks
_tasks.push(action.payload.data)
return { ...state, tasks: _tasks }
default:
return state
}
}
|
var request = require("../manager/request");
var config = require("../common/config");
var Time = {
serviceTime: null,
offset: 0,
update: function (dt) {
if (dt < 0.5) {
this.offset += dt
}
},
//同步服务器时间
sync: function (func) {
var param = {
GetCurrentTime: ""
}
request.post(config.configUrl.url, param, function (data) {
console.log(data)
this.serviceTime = parseInt(data.CurrentTime)
this.offset = 0
if (func)
func()
}.bind(this))
},
//初始化
init: function (func) {
if (!WECHATGAME) {
this.serviceTime = parseInt(new Date().getTime() / 1000)
this.offset = 0
}
else
this.sync(func)
},
//获取现在的时间
now: function () {
var timeNow = this.serviceTime + this.offset
return parseInt(timeNow)
},
}
module.exports = {
sync: Time.sync,
init: Time.init,
now: Time.now,
update: Time.update,
};
|
var $ = require('./jquery-1.10.1.min.js');
require('./swiper-3.3.1.min.js');
var p = require('./swiper.animate1.0.2.min.js');
mainSwiper = new Swiper('.swiper-container',{
resistanceRatio:0, //边缘抵抗为0
pagination:'.swiper-pagination', //定义分页器
onInit:function(swiper){ //swiper 初始化完成以后
p.swiperAnimateCache(); //隐藏动画元素
p.swiperAnimate(); //初始化完成开始动画
},
//滑动结束的时候触发的回调函数
onSlideChangeEnd:function(swiper){
//previousIndex 表示滑动前一页
p.swiperAnimate(); //每个slide切换结束时也运行当前slide动画
}
})
|
import React from "react";
import {Link} from "react-router-dom";
import styled from "styled-components";
const StyledLink = styled(Link)`
text-decoration: none;
color: inherit;
font-weight: 500;
padding: 0 1rem;
&:focus, &:hover, &:visited, &:link, &:active {
text-decoration: none;
}
&:focus {
color: #21a9b2;
}
&:active {
color: #21a9b2;
}
`;
const LinkStyled = (props) => (
<StyledLink {...props}>
{props.children}
</StyledLink>
);
export default LinkStyled;
|
import Promise from 'bluebird'
import _ from 'lodash'
import moment from 'moment'
let fs = Promise.promisifyAll(require('fs'))
let EventEmitter = require("events").EventEmitter
function year(item){
return moment(new Date(item.date)).year()
}
function computeHistogram(items, filterFunc){
let matches = _.filter(items, filterFunc)
let gs = _.groupBy(matches, year)
let hist = _.mapValues(gs, (v,k) => {
return v.length
})
return hist
}
function computeHistogram1(items, filterFunc){
// let matches = _.filter(items, filterFunc)
let matches = _.flatten(_.pluck(items, 'file_callsites'))
let gs = _.groupBy(matches)
let hist = _.mapValues(gs, (v,k) => {
return v.length
})
hist = _.pick(hist, v => {
return v > 200
})
return hist
}
class IncremenalHistogram {
constructor() {
this.hist = {}
this.total = 0
}
add(items, filterFunc) {
let hist = computeHistogram(items, filterFunc)
this.total += items.length
_.forIn(hist, (v,k) => {
this.hist[k] = _.get(this.hist, k, 0) + v
})
console.log(this.total, this.hist)
}
}
import glob from 'glob'
let files = glob.sync('/Users/tomyeh/data/slices/*')
// _.map(['a','b','c','d','e','f'], c => {
// return `/Users/tomyeh/data/slices/xa${c}`
// })
export default class Timeline {
constructor(options){
this.ee = new EventEmitter()
//this.filterFunc = item => {return _.includes(item[options.field], options.pattern)}
this.filterFunc = item => {return _.some(item[options.field], v => {
if (v.match(options.pattern)){
return true
}
})}
}
onData(callback){
this.ee.on('data', items => {
if (!this.stopped){
this.H.add(items, this.filterFunc)
callback(this.H)
}
})
}
stop(){
this.stopped = true
}
start(){
this.H = new IncremenalHistogram()
Promise.each(files, (file,i) => {
if (!this.stopped){
return fs.readFileAsync(file, 'utf8')
.then((contents) => {
// console.log('file',i)
let items = _.map(contents.trim().split('\n'), JSON.parse)
// console.log('items ', items.length)
this.ee.emit('data', items)
})
}
})
}
}
|
var Launcher = window.Launcher || {};
Launcher.init = function() {
function wait( delay ) {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve();
}, delay);
return deferred.promise();
}
function gapiCall(method, data) {
var deferred = $.Deferred();
gapi.client.gezzoo[method](
data
).execute(function(resp) {
if (resp.error) {
} else {
deferred.resolve(resp);
}
});
return deferred.promise();
}
function getGames(token) {
var deferred = $.Deferred();
gapi.client.gezzoo.getGames({
token:token
}).execute(function(resp) {
if (resp.error) {
} else {
deferred.resolve(resp.items);
}
});
return deferred.promise();
}
App = Ember.Application.create({
LOG_TRANSITIONS: true,
});
App.FOR_NAVIKA = false;
// 'http://placehold.it/214x317';
App.USER_AVATAR = 'http://placehold.it/64x64';
App.OPPONENT_AVATAR = 'http://placehold.it/64x64';
App.en = {
'index': {
title: "Guess Who? for you ... Navika Dutta <3",
instructions: "Happy Birthday my love! So all these weeks, and you've been wondering what I've been working on. Well here it is! It's Guess Who? Except I'm not sure if I'm allowed to call it Guess Who, so I called it Gezzoo.. get it?? lol! Anyways, I wrote this game for you as a birthday present. It's a little rough, but I hope you like :) If nothing else, it'll just be a fun game for us to play when we're bored. I just want to tell you what you mean to me, without you, my world would be incomplete. I love you very much, you are my inspiration, my heart and my everything. I wish you the happiest of birthdays!",
button: "So Whenever you're ready to play, press here!",
},
'user.view': {
instructions: "Start a new game by pressing the + button, or press any of the games in progress.",
your_turn: "It's your turn",
their_turn: "It's their turn",
game_over: 'Game over :('
},
'game.select': {
instructions: Handlebars.compile("Select your character from the choices below! {{opponent}} will have to guess who you chose.")
},
'game.board': {
instructions1: Handlebars.compile("Try to guess who you think {{opponent}} has. You can press any of the faces below and flip them over if you think {{opponent}} hasnt chosen them. Or hit the 'Questions' tab, and ask them a question!"),
instructions2: Handlebars.compile("Its not your turn right now, maybe taking a look at the past questions might help you figure out who {{opponent}} might have!")
},
'game.reply': {
instructions: Handlebars.compile("Below is a list of questions that {{opponent}} has asked you. You have to reply to their question before you have a chance to guess theirs.")
},
'new.game.modal': {
title: 'Creating...',
loading: 'Hang in there... we just gotta find you someone to play with. Then youll get to pick your character.',
success: 'Done!',
fail: "D'oh! Failed to create a new game for you :( ... Maybe you can try again a little later?",
fail_button: "Fineahh!"
},
'select.modal': {
title: 'Saving...',
loading: 'Ok, just saving your selection to the cloud! After this, you will have to wait for your friend to play',
success: 'Done!',
fail: "ARGGHHH! I failed to save your choice. Wanna go back home and try another game?",
fail_button: "Whatever.."
},
'guess.modal': {
title: 'Checking...',
loading: 'Verifying if your guess is the right one... Just gimme a sec',
success: 'Done!',
fail: "Hmmm, looks like something isn't right. I can't save your guess. Mind trying again later?",
fail_button: "OK?",
guess_right_title: "NICE!",
guess_right_text: Handlebars.compile("You're right! {{opponent}} had {{character}}! I'll let {{opponent}} know."),
guess_right_button: "Yay!",
guess_wrong_title: "Nope",
guess_wrong_text: Handlebars.compile("{{opponent}} didn't have {{character}}. Good guess though. You'll have to let {{opponent}} go next before you can go again."),
guess_wrong_button: "Ugh...:(",
},
'ask.modal': {
title: 'Asking...',
loading: "Alright, I'll ask your friend your question. Hopefully they give you an answer that will help.",
success: 'Done!',
fail: "Ooops! There's a bit of a problem. Go out, have a coffee, come back in a bit and hopefully I'll have fixed things.",
fail_button: "Boo-urns"
},
'reply.modal': {
title: 'Replying...',
loading: "Gimme a sec, need to talk to the internet server thingy, just sending your reply out.",
success: 'Done!',
fail: "Dammit! There was some kinda problem. I couldn't save your reply. You can try again, or maybe you can come back and try again later.",
fail_button: "Sure..."
},
};
App.lang = function( category, key, value ) {
var l = App.en[category][key];
if ( _.isFunction(l) ) {
return l(value);
} else if ( _.isString(l) ) {
return l;
}
return "null";
};
App.Router.map(function() {
this.route('/');
this.resource('user', { path: ':user' }, function() {
this.route('view');
this.resource('game', { path:':game' }, function() {
this.route('select');
this.route('board');
this.route('reply');
});
});
});
////////////////
// MODAL DIALOG
////////////////
App.ModalController = Ember.ObjectController.extend({
actions: {
confirm: function() {
var confirm = this.get('model.confirm');
if ( confirm && confirm.callback ) {
confirm.callback();
} else {
this.send('hideModalDialog');
}
}
}
});
App.AbstractCharacterItemController = Ember.Controller.extend({
img: function() {
var character = this.get('model');
return character.img;
}.property('model.img'),
name: function() {
var character = this.get('model');
return character.name;
}.property('model.name'),
isUserSelection: function() {
var state = this.get('controllers.game.model.state');
return state === 'user-select-character';
}.property('controllers.game.model.state'),
isUserAction: function() {
var state = this.get('controllers.game.model.state');
return state === 'user-action';
}.property('controllers.game.model.state'),
up: function(key, value) {
if (value === undefined) {
var e = this.get('model.up');
if (( typeof e ) === "boolean" ) {
return e;
} else {
return e === "true" ? true:false;
}
} else {
this.set('model.up', value);
return value;
}
}.property('model.up')
});
////////////////
// APPLICATION
////////////////
App.ApplicationRoute = Ember.Route.extend({
actions: {
showModalDialog: function(id, data) {
this.controllerFor(id).set('model', data);
return this.render(id, {
into: 'application',
outlet: 'modal'
});
},
updateDialog: function(id, data) {
this.controllerFor(id).set('model', data);
},
hideModalDialog: function() {
return this.disconnectOutlet({
outlet: 'modal',
parentView: 'application'
});
}
}
// , goBack: function() {
// Ember.AnimatedContainerView.enqueueAnimations({main: 'slideRight'});
// history.go(-1);
// }
});
App.ApplicationController = Ember.Controller.extend({
user: null,
token: localStorage.token,
tokenChanged: function() {
console.log('token changed: ' + this.get('token'));
localStorage.token = this.get('token');
this.set('user', null);
this.transitionToRoute('index');
}.observes('token'),
login: function() {
var token = this.get('token');
console.log('login: ' + token);
var self = this;
var data = token ? {token:token} : {};
function success(response) {
self.set('user', {
id: response.id,
name: response.name,
token: response.token
});
self.set('token', response.token);
}
function failed(err) {
console.log('login fail:');
console.log(JSON.stringify(err));
}
if ( token ) {
return gapiCall('login', data).then(success, failed);
} else {
return gapiCall('createProfile', data).then(success, failed);
}
},
doDialog: function(method, data, category, success, responseHandler) {
var self = this;
self.send('showModalDialog', 'modal', {
title: App.lang(category, 'title'),
text: App.lang(category, 'loading')
});
var post = gapiCall(method, data);
$.when( post, wait( 2000 ) ).then(function(resp) {
var response = resp;
var content = responseHandler ? responseHandler(response) : null;
if ( content ) {
self.send('updateDialog', 'modal', {
title: content.title, //App.lang(category, 'title'),
text: content.text, //App.lang(category, 'fail'),
confirm: {
text: content.button_text, //App.lang(category, 'success_button')
callback: function() {
self.send('hideModalDialog');
if (success) success(response);
}
}
});
} else {
self.send('updateDialog', 'modal', {
title: App.lang(category, 'title'),
text: App.lang(category, 'success'),
});
$.when( wait( 500 ) ).then(function() {
self.send('hideModalDialog');
if (success) success(response);
});
}
}, function(err) {
self.send('updateDialog', 'modal', {
title: App.lang(category, 'title'),
text: App.lang(category, 'fail'),
confirm: {
text: App.lang(category, 'fail_button'),
callback: function() {
self.send('hideModalDialog');
}
}
});
});
},
newgame: function(opponentid) {
var self = this;
if ( opponentid ) {
var data = {
token: this.get('token'),
opponent: opponentid
};
this.doDialog( 'newGameWith', data, 'new.game.modal', function( response ) {
var token = self.get('token');
var gameid = response._id;
self.transitionToRouteAnimated('game.select', {main: 'slideLeft'}, token, gameid);
});
} else {
var data = { token: this.get('token') };
this.doDialog( 'newGame', data, 'new.game.modal', function( response ) {
var token = self.get('token');
var gameid = response._id;
self.transitionToRouteAnimated('game.select', {main: 'slideLeft'}, token, gameid);
});
}
},
select: function( gameid, characterid, me ) {
var data = {
token: this.get('token'),
character: characterid,
gameId: gameid
};
var self = this;
this.doDialog( 'setCharacter', data, 'select.modal', function( response ) {
console.log('me: ' + me);
console.log('turn: ' + response.turn);
if ( me === response.turn ) {
self.transitionToRouteAnimated('game.board', {main: 'slideLeft'}, self.get('token'), gameid);
} else {
self.transitionToRouteAnimated('index', {main: 'slideRight'});
}
});
},
ask: function( gameid, question, board ) {
var data = {
token: this.get('token'),
gameId: gameid,
question: question,
board: board
};
var self = this;
this.doDialog('askQuestion', data, 'ask.modal', function() {
self.transitionToRouteAnimated('index', {main: 'slideRight'});
});
},
guess: function( gameid, character, board, opponent ) {
console.log(character);
var data = {
token: this.get('token'),
gameId: gameid,
characterId: character._id,
board: board
};
var self = this;
this.doDialog('guess', data, 'guess.modal', function() {
self.transitionToRouteAnimated('index', {main: 'slideRight'});
}, function( response ) {
var text = {
opponent: opponent,
character: character.name
};
var result = response.ended ? 'right' : 'wrong';
return {
title: App.lang('guess.modal', 'guess_' + result + '_title'),
text: App.lang('guess.modal', 'guess_' + result + '_text', text),
button_text: App.lang('guess.modal', 'guess_' + result + '_button')
};
});
},
reply: function( gameid, questionid, reply ) {
var data = {
token: this.get('token'),
gameId: gameid,
questionId: questionid,
reply: reply
};
var self = this;
this.doDialog('postReply', data, 'reply.modal', function() {
self.transitionToRouteAnimated('game.board', {main: 'slideLeft'}, self.get('token'), gameid);
});
}
});
App.ApplicationView = Ember.View.extend({
classNames: ["l-fill-parent"]
});
App.AuthenticatedRoute = Ember.Route.extend({
beforeModel: function() {
var app = this.controllerFor('application');
if ( ! app.get('user') ) {
return app.login();
}
},
});
App.IndexRoute = App.AuthenticatedRoute.extend({
afterModel: function() {
if ( ! App.FOR_NAVIKA ) {
var app = this.controllerFor('application');
var token = app.get('token');
this.transitionTo('user.view', token);
}
}
});
App.IndexController = Ember.Controller.extend({
needs: ['application'],
actions: {
go: function() {
var app = this.get('controllers.application');
var token = app.get('token');
this.transitionToRouteAnimated('user.view', {main: 'slideLeft'}, token);
}
},
forNavika: App.FOR_NAVIKA,
title: App.lang('index', 'title'),
instructions: App.lang('index', 'instructions'),
button: App.lang('index', 'button')
});
/////////////
// GAME LIST
/////////////
App.UserRoute = App.AuthenticatedRoute.extend({
model: function() {
var user = this.controllerFor('application').get('user');
return getGames(user.token);
}
});
App.UserViewRoute = Ember.Route.extend({
model: function() {
return this.modelFor('user');
}
});
App.UserViewController = Ember.ArrayController.extend({
needs: ['application'],
actions: {
newgame: function() {
var controller = this.get('controllers.application');
controller.newgame();
}
},
instructions: App.lang('user.view', 'instructions')
});
App.GameItemController = Ember.Controller.extend({
needs: ['application'],
actions: {
select: function() {
var token = this.get('controllers.application.token');
var gameid = this.get('model._id');
var state = this.get('model.state');
var ended = this.get('model.ended');
var transition = {main: 'slideLeft'};
if ( ended === true ) {
var id = this.get('model.me._id');
var winner = this.get('model.winner.by');
if ( id === winner ) {
this.transitionToRouteAnimated('game.board', transition, token, gameid);
} else {
this.transitionToRouteAnimated('game.reply', transition, token, gameid);
}
} else if ( 'user-action' === state ) {
this.transitionToRouteAnimated('game.board', transition, token, gameid);
} else if ( 'user-reply' === state ) {
this.transitionToRouteAnimated('game.reply', transition, token, gameid);
} else if ( 'user-select-character' === state ) {
this.transitionToRouteAnimated('game.select', transition, token, gameid);
} else if ( 'read-only' === state ) {
this.transitionToRouteAnimated('game.board', transition, token, gameid);
}
}
},
date: function(key, value) {
var game = this.get('model');
return moment(game.modified).fromNow();
}.property('model.modified'),
turn: function(key, value) {
var game = this.get('model');
if ( game.ended ) {
return App.lang('user.view', 'game_over');
} else {
var turn = game.turn === game.me._id;
return turn ? App.lang('user.view', 'your_turn') : App.lang('user.view', 'their_turn');
}
}.property('model.turn'),
username: function(key, value) {
var game = this.get('model');
return game.opponent.username;
}.property('model.opponent.username'),
useravatar: function() {
return App.USER_AVATAR;
}.property('model.opponent.username')
});
App.GameRoute = App.AuthenticatedRoute.extend({
model: function( params ) {
var user = this.controllerFor('application').get('user');
return gapiCall('getGame', {
gameId: params.game,
token: user.token
});
}
});
///////////////////
// OPPONENT REPLY
///////////////////
App.GameReplyRoute = Ember.Route.extend({
model: function() {
return this.modelFor('game');
}
});
App.GameReplyView = Ember.View.extend({
classNames: ["l-fill-parent", "l-container", 't-background']
});
App.GameReplyController = Ember.Controller.extend({
findCharacterById: function( id ) {
var characters = this.get('model.board.characters');
return _.find( characters, function( character ) {
return id === character._id;
});
},
convert: function( action ) {
var data = {};
if ( action ) {
if ( action.action === 'question' ) {
data.opponent = {
id: action._id,
name: this.get('model.opponent.username'),
avatar: App.OPPONENT_AVATAR,
value: action.value,
type: action.action
};
data.me = {
avatar: App.USER_AVATAR,
};
if ( action.reply ) {
data.me.value = action.reply.value;
}
} else if ( action.action === 'guess' ) {
var isWinner = false;
var winner = this.get('model.winner');
if ( winner ) {
isWinner = winner.by === this.get('model.opponent._id') &&
winner.actionid === action._id;
}
var character = this.findCharacterById( action.value );
data.opponent = {
name: this.get('model.opponent.username'),
avatar: App.OPPONENT_AVATAR,
type: action.action,
character: character,
right: isWinner ? "right!" : "wrong."
}
}
}
return data;
},
allactions: function() {
var results = [];
var actions = this.get('model.opponent.actions');
for ( var i = 0; i < actions.length; i++ ) {
var action = actions[i];
results.push(this.convert(action));
}
return results;
}.property('model.opponent.actions'),
opponent: function() {
return this.get('model.opponent.username');
}.property('model.opponent.username')
});
App.ReplyItemController = Ember.Controller.extend({
needs: ['gameReply', 'application'],
actions: {
reply: function() {
var value = $.trim(this.get('userreply'));
if ( value && value.length !== 0 ) {
this.postReply( value );
}
},
replay: function() {
var opponentid = this.get('controllers.gameReply.model.opponent._id');
var controller = this.get('controllers.application');
controller.newgame(opponentid);
}
},
postReply: function( reply ) {
var gameid = this.get('controllers.gameReply.model._id');
var application = this.get('controllers.application');
var questionid = this.get('model.opponent.id');
application.reply( gameid, questionid, reply );
},
isAction: function() {
return (this.get('model.opponent.type') === 'question');
}.property('model.opponent.type'),
me: function() {
return this.get('model.me');
}.property('model.me'),
opponent: function() {
return this.get('model.opponent');
}.property('model.opponent'),
isUserReply: function() {
return this.get('controllers.gameReply.model.state') === 'user-reply';
}.property('controllers.gameReply.model.state'),
selectedCharacter: function() {
var controller = this.get('controllers.gameReply');
var mycharacter = this.get('controllers.gameReply.model.me.character');
return controller.findCharacterById( mycharacter );
}.property('controllers.gameReply.model.me.character'),
lost: function() {
var ended = this.get('controllers.gameReply.model.ended');
var winner = this.get('controllers.gameReply.model.winner');
var userid = this.get('controllers.gameReply.model.opponent._id');
if ( ended === true && winner ) {
return winner.by === userid;
} else {
return false;
}
return true;
}.property('controllers.gameReply.model.ended')
});
////////////////
// PLAYER BOARD
////////////////
App.GameBoardRoute = Ember.Route.extend({
model: function() {
return this.modelFor('game');
}
});
App.GameBoardView = Ember.View.extend({
classNames: ["l-fill-parent", "l-container", 't-background']
});
App.GameBoardController = Ember.Controller.extend({
needs: ['application'],
actions: {
board: function() {
this.set('viewBoard', true);
},
question: function() {
this.set('viewBoard', false);
},
ask: function() {
var value = $.trim(this.get('userquestion'));
if ( value && value.length !== 0 ) {
this.postQuestion( value );
}
}
},
current_selection: '',
instructions: function() {
var opponent = {
opponent: this.get('model.opponent.username')
};
if ( this.get('model.state') === 'user-action' ) {
return App.lang('game.board','instructions1', opponent);
} else {
return App.lang('game.board','instructions2', opponent);
}
}.property('model.opponent.username'),
selection: function(key, value) {
if (value === undefined) {
return this.get('current_selection');
} else {
this.set('current_selection', value);
return value;
}
}.property('current_selection'),
init: function() {
this._super();
this.set('viewBoard', true);
},
// TODO: This method needs to look at the modified
// time to know which is the most recent
getLastAction: function() {
var actions = this.get('model.me.actions');
if ( actions && actions.length > 0 ) {
return actions[actions.length-1];
}
return null;
},
// TODO: What if the last action was a guess?
lastaction: function() {
var action = this.getLastAction();
var data = {};
if ( action && action.action === 'question' ) {
data.me = {
avatar: App.USER_AVATAR,
value: action.value
};
if ( action.reply ) {
data.opponent = {
name: this.get('model.opponent.username'),
avatar: App.OPPONENT_AVATAR,
value: action.reply.value
};
}
}
return data;
}.property('model.me.actions'),
board: function() {
var board = this.get('model.me.board');
var characters = this.get('model.board.characters');
var a = board.concat( characters );
var b = _.reduce(a, function(m, item) {
m[item._id] = ( m[item._id] ? _.extend(m[item._id], item) : item );
return m;
}, {});
return _.values(b);
}.property('model.me.board'),
findCharacterById: function( id ) {
var characters = this.get('model.board.characters');
return _.find( characters, function( character ) {
return id === character._id;
});
},
convert: function( action ) {
var data = {};
if ( action ) {
if ( action.action === 'question' ) {
data.me = {
avatar: App.USER_AVATAR,
value: action.value,
type: action.action
};
if ( action.reply ) {
data.opponent = {
name: this.get('model.opponent.username'),
avatar: App.OPPONENT_AVATAR,
value: action.reply.value
};
}
} else if ( action.action === 'guess' ) {
var isWinner = false;
var winner = this.get('model.winner');
if ( winner ) {
isWinner = winner.by === this.get('model.me._id') &&
winner.actionid === action._id;
}
var character = this.findCharacterById( action.value );
data.me = {
character: character,
type: action.action,
avatar: App.USER_AVATAR,
right: isWinner ? "right!" : "wrong."
}
}
}
return data;
},
allactions: function() {
var results = [];
var actions = this.get('model.me.actions');
if ( actions ) {
for ( var i = 0; i < actions.length; i++ ) {
var action = actions[i];
results.push(this.convert(action));
}
}
return results;
}.property('model.me.actions'),
isUserAction: function() {
return this.get('model.state') === 'user-action';
}.property('model.state'),
avatar: function() {
return App.USER_AVATAR;
}.property('model.me'),
opponent: function() {
return this.get('model.opponent.username');
}.property('model.opponent.username'),
getUserBoard: function() {
var board = [];
_.each(this.get('model.me.board'), function(item) {
board.push(_.pick(item, '_id', 'up'));
});
return board;
},
guess: function( character ) {
var gameid = this.get('model._id');
var board = this.getUserBoard();
var application = this.get('controllers.application');
var opponent = this.get('model.opponent.username');
application.guess( gameid, character, board, opponent );
},
postQuestion: function( question ) {
var gameid = this.get('model._id');
var board = this.getUserBoard();
var application = this.get('controllers.application');
this.set('current_selection', '');
this.set('userquestion', '');
application.ask( gameid, question, board );
}
});
App.GameBoardCharacterItemController = App.AbstractCharacterItemController.extend({
needs: ['gameBoard', 'game'],
actions: {
guess: function() {
var up = this.get('model.up');
this.set('model.up', !up);
this.get('controllers.gameBoard').set('selection', '');
var controller = this.get('controllers.gameBoard');
controller.guess(this.get('model'));
},
flip: function() {
var up = this.get('model.up');
this.set('model.up', !up);
},
clicked: function() {
var controller = this.get('controllers.gameBoard');
if ( controller ) {
controller.set('selection', this.get('model._id'));
}
}
},
isselected: function() {
var selected = this.get('controllers.gameBoard.selection');
return selected === this.get('model._id');
}.property('controllers.gameBoard.selection'),
});
App.ActionItemController = Ember.Controller.extend({
isAction: function() {
return (this.get('model.me.type') === 'question');
}.property('model.me.type'),
me: function() {
return this.get('model.me');
}.property('model.me'),
opponent: function() {
return this.get('model.opponent');
}.property('model.opponent'),
avatar: function() {
return this.get('model.me.avatar');
}.property('model.me.avatar')
});
/////////////////////
// CHARACTER SELECT
/////////////////////
App.GameSelectRoute = Ember.Route.extend({
model: function( params, transition ) {
return this.modelFor('game');
}
});
App.GameSelectView = Ember.View.extend({
classNames: ["l-fill-parent", "l-container", 't-background']
});
App.GameSelectController = Ember.Controller.extend({
needs: ['application'],
current_selection: '',
instructions: function() {
return App.lang('game.select', 'instructions', {
opponent: this.get('model.opponent.username')
});
}.property('model.opponent.username'),
opponent: function() {
return this.get('model.opponent.username');
}.property('model.opponent.username'),
selection: function(key, value) {
if (value === undefined) {
return this.get('current_selection');
} else {
this.set('current_selection', value);
return value;
}
}.property('current_selection'),
characters: function() {
return this.get('model.board.characters');
}.property('model.board.characters'),
selectCharacter: function(characterid) {
var application = this.get('controllers.application');
var gameid = this.get('model._id');
var me = this.get('model.me._id');
this.set('current_selection', '');
application.select( gameid, characterid, me );
}
});
App.GameSelectCharacterItemController = App.AbstractCharacterItemController.extend({
needs: ['gameSelect', 'game'],
actions: {
select: function() {
this.get('controllers.gameSelect').set('selection', '');
var controller = this.get('controllers.gameSelect');
controller.selectCharacter(this.get('model._id'));
},
clicked: function() {
var controller = this.get('controllers.gameSelect');
if ( controller ) {
controller.set('selection', this.get('model._id'));
}
}
},
isselected: function() {
var selected = this.get('controllers.gameSelect.selection');
return selected === this.get('model._id');
}.property('controllers.gameSelect.selection'),
});
};
window.Launcher = Launcher;
|
import React from 'react'
import { View, StyleSheet, Text, Animated, Easing } from 'react-native'
class ProgressBar extends React.Component {
constructor(props) {
super(props)
this.width = new Animated.Value(0)
}
componentDidUpdate(prevProps) {
if (prevProps.value !== this.props.value) {
Animated.timing(
this.width,
{
toValue: parseInt(this.props.value),
duration: this.props.test ? 100 : 1000,
easing: Easing.easeInCirc
}
).start()
}
}
render() {
const w = this.width.interpolate({
inputRange: [0, 100],
outputRange: ['0%', '100%']
})
return (
<Animated.View style={[styles.content, { width: w }]}></Animated.View>
)
}
}
const styles = StyleSheet.create({
content: {
backgroundColor: '#FFF',
height: 3,
width: '100%',
alignSelf: 'stretch',
}
})
export default ProgressBar
|
import { catarse } from '../api';
import h from '../h';
import m from 'mithril';
import prop from 'mithril/stream';
import moment from 'moment';
import _ from 'underscore';
import models from '../models';
const currentContribution = prop({});
const getUserProjectContributions = (userId, projectId, states) => {
const vm = catarse.filtersVM({
user_id: 'eq',
project_id: 'eq',
state: 'in',
});
vm.user_id(userId);
vm.project_id(projectId);
vm.state(states);
const lProjectContributions = catarse.loaderWithToken(models.userContribution.getPageOptions(vm.parameters()));
return lProjectContributions.load();
};
const getCurrentContribution = () => {
const root = document.getElementById('application'),
data = root && root.getAttribute('data-contribution');
if (data) {
currentContribution(JSON.parse(data));
m.redraw(true);
return currentContribution;
}
return false;
};
const wasConfirmed = contribution => _.contains(['paid', 'pending_refund', 'refunded'], contribution.state);
const canShowReceipt = contribution => wasConfirmed(contribution);
const canShowSlip = contribution =>
contribution.payment_method === 'BoletoBancario' &&
moment(contribution.gateway_data.boleto_expiration_date)
.endOf('day')
.isAfter(moment()) &&
contribution.state === 'pending';
const canGenerateSlip = contribution =>
contribution.payment_method === 'BoletoBancario' &&
(contribution.state === 'pending' || contribution.state === 'refused') &&
contribution.project_state === 'online' &&
!contribution.reward_sold_out &&
!moment(contribution.gateway_data.boleto_expiration_date)
.endOf('day')
.isAfter(moment());
const canBeDelivered = contribution => contribution.state === 'paid' && contribution.reward_id && contribution.project_state !== 'failed';
const getUserContributionsListWithFilter = () => {
const contributions = catarse.paginationVM(models.userContribution, 'created_at.desc', { Prefer: 'count=exact' });
return {
firstPage: params => contributions.firstPage(params).then(() => h.redraw()),
isLoading: contributions.isLoading,
collection: contributions.collection,
isLastPage: contributions.isLastPage,
nextPage: () => contributions.nextPage().then(() => h.redraw()),
};
};
const getUserContributedProjectsWithFilter = () => {
const contributions = catarse.paginationVM(models.project, 'created_at.desc', { Prefer: 'count=exact' });
return {
firstPage: params => contributions.firstPage(params).then(() => h.redraw()),
isLoading: contributions.isLoading,
collection: contributions.collection,
isLastPage: contributions.isLastPage,
nextPage: () => contributions.nextPage().then(() => h.redraw()),
};
};
const contributionVM = {
getUserContributedProjectsWithFilter,
getCurrentContribution,
canShowReceipt,
canGenerateSlip,
canShowSlip,
getUserProjectContributions,
canBeDelivered,
getUserContributionsListWithFilter,
};
export default contributionVM;
|
// NOTES
// - new Date().toISOString()
//Firebase
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
const firebase = require("firebase");
firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
})
//UTIL
const bodyParser = require("body-parser");
const cors = require("cors");
//Express
const express = require("express");
const app = express();
app.use(bodyParser.json());
app.use(cors());
//AUTH MIDDLEWARE
const authMid = (req, res, next) => {
// make sure a token is recieved
let idToken;
if (
req.headers.authorization &&
req.headers.authorization.startsWith("Bearer ")
) {
idToken = req.headers.authorization.split("Bearer ")[1];
} else {
console.error("no token");
return res.status(403).json({ error: "unauthorized" });
}
// authorize token
admin
.auth()
.verifyIdToken(idToken)
.then((decodedToken) => {
req.user = decodedToken;
})
.catch((err) => {
console.error("Error while varifying token", err);
return res.status(403).json(err);
});
};
// ----- UNAUTHED -----
// SIGN UP
app.post("/signup", (req, res) => {
// vars
let password = req.body.password;
let email = req.body.email;
let admin = req.body.admin;
let userID;
let JWT;
// - check if passwords match
if (req.password != req.passwordConfirm) {
console.log(req.password);
return res.status(422).send("passwords don't match");
}
// - check if email exists
// - sign up and return token
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((data) => {
console.log(`SIGNED UP ${data.user.uid}`);
userID = data.user.uid;
return data.user.getIdToken();
})
.then((token) => {
JWT = token;
// return res.status(201).send(token);
console.log(userID);
const newUser = new UsersModel({
email: email,
name: req.body.name,
userID: userID,
admin: admin
});
// save user to db and return token
newUser
.save()
.then((result) => {
console.log(result);
res.status(200).json({JWT});
})
.catch((err) => {
console.log(err);
return res.status(400).send(err);
});
})
.catch((err) => {
console.error(err);
return res.status(500).send(err);
});
});
// SIGN IN
app.post("/signin", (req, res) => {
const user = {
email: req.body.email,
password: req.body.password,
};
firebase
.auth()
.signInWithEmailAndPassword(user.email, user.password)
.then((data) => {
return data.user.getIdToken();
})
.then((token) => {
return res.json({ token });
})
.catch((err) => {
console.error(err);
return res.status(403).send(err);
});
});
exports.api = functions.https.onRequest(app);
|
//
module.exports = function (config) {
config.set({
autoWatch: true,
basePath: '../..',
browsers: [ 'Chrome' ],
frameworks: [ 'mocha', 'chai' ],
colors: true,
exclude: [],
files: [
'vendor/bower_components/angular/angular.js',
'vendor/bower_components/angular-mocks/angular-mocks.js',
'app/**/*.js',
'tests/unit/**/*.spec.js'
]
});
};
|
// import helpers function to assert for equality
let assertEqual = require('./assertEqual');
const head = function(item) {
let length = item.length;
if (length > 0) {
return item[0];
} else {
return 'underfined';
}
};
module.exports = head;
|
/**
* Contrôleur de la page logout.
*/
var LogoutController = function($scope, $location, $cookies) {
/**
* Méthode de déconnexion.
*/
$scope.logout = function() {
// On supprime le cookie
$cookies.remove("access_token");
// On redirige vers la page de connexion
$location.path('/signin').replace();
};
};
// On injecte les dépendences dans le contrôleur
LogoutController.$inject = ["$scope", "$location", "$cookies"];
// On enregistre le contrôleur auprès du module de l'application
angular.module("application").controller("LogoutController", LogoutController);
|
//Project : DoDo
module.exports =
{
db : 'mongodb://127.0.0.1/resterdb',
sessionSecret : "rester",
}
|
import React from "react"
import {
View,
Image,
ImageBackground,
TouchableOpacity,
Text,
Button,
Switch,
TextInput,
StyleSheet,
ScrollView
} from "react-native"
import Icon from "react-native-vector-icons/FontAwesome"
import { CheckBox } from "react-native-elements"
import { connect } from "react-redux"
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp
} from "react-native-responsive-screen"
import { getNavigationScreen } from "@screens"
export class Blank extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
render = () => (
<ScrollView
contentContainerStyle={{ flexGrow: 1 }}
style={styles.ScrollView_1}
>
<View style={styles.View_2} />
<View style={styles.View_1242_6347} />
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/9d50/5d95/f7580b552ff47c48d47f6d481e2db1e4"
}}
style={styles.ImageBackground_1242_6348}
/>
<View style={styles.View_1242_6353}>
<Text style={styles.Text_1242_6353}>This Month</Text>
</View>
<View style={styles.View_1242_6354}>
<Text style={styles.Text_1242_6354}>
2 of 12 Budget is exceeds the limit
</Text>
</View>
<View style={styles.View_1242_6386}>
<View style={styles.View_1242_6387}>
<View style={styles.View_1242_6388}>
<View style={styles.View_1242_6389}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/068b/dcbb/73d4f5fea782acb7ed7e34720cddc40e"
}}
style={styles.ImageBackground_I1242_6389_280_5910}
/>
</View>
</View>
<View style={styles.View_1242_6390}>
<View style={styles.View_1242_6391}>
<Text style={styles.Text_1242_6391}>Shopping</Text>
</View>
</View>
</View>
</View>
<View style={styles.View_1242_6399}>
<View style={styles.View_1242_6400}>
<View style={styles.View_1242_6401}>
<View style={styles.View_1242_6402}>
<View style={styles.View_I1242_6402_280_7557}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/a472/34b8/2ac66f2d2a9124e56be2280804d44558"
}}
style={styles.ImageBackground_I1242_6402_280_7558}
/>
</View>
</View>
</View>
<View style={styles.View_1242_6403}>
<View style={styles.View_1242_6404}>
<Text style={styles.Text_1242_6404}>Food</Text>
</View>
</View>
</View>
</View>
<View style={styles.View_1242_6363}>
<View style={styles.View_I1242_6363_217_6979}>
<View style={styles.View_I1242_6363_217_6979_108_2809} />
</View>
</View>
<View style={styles.View_1242_6364}>
<View style={styles.View_I1242_6364_816_117}>
<View style={styles.View_I1242_6364_816_118}>
<Text style={styles.Text_I1242_6364_816_118}>9:41</Text>
</View>
</View>
<View style={styles.View_I1242_6364_816_119}>
<View style={styles.View_I1242_6364_816_120}>
<View style={styles.View_I1242_6364_816_121}>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/42fe/75df/eee86effef9007e53d20453d65f0d730"
}}
style={styles.ImageBackground_I1242_6364_816_122}
/>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/323b/7a56/3bd8d761d4d553ed17394f5c34643bfe"
}}
style={styles.ImageBackground_I1242_6364_816_125}
/>
</View>
<View style={styles.View_I1242_6364_816_126} />
</View>
<View style={styles.View_I1242_6364_816_127}>
<View style={styles.View_I1242_6364_816_128} />
<View style={styles.View_I1242_6364_816_129} />
<View style={styles.View_I1242_6364_816_130} />
<View style={styles.View_I1242_6364_816_131} />
</View>
<ImageBackground
source={{
uri:
"https://s3-us-west-2.amazonaws.com/figma-alpha-api/img/2e76/21a5/ca49045f4b39546b3cfd31fde18b9385"
}}
style={styles.ImageBackground_I1242_6364_816_132}
/>
</View>
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
ScrollView_1: { backgroundColor: "rgba(255, 255, 255, 1)" },
View_2: { height: hp("111%") },
View_1242_6347: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("111%"),
minHeight: hp("111%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(127, 61, 255, 1)"
},
ImageBackground_1242_6348: {
width: wp("93%"),
minWidth: wp("93%"),
height: hp("0%"),
minHeight: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("3%"),
top: hp("9%")
},
View_1242_6353: {
width: wp("35%"),
minWidth: wp("35%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("33%"),
top: hp("14%"),
justifyContent: "center"
},
Text_1242_6353: {
color: "rgba(255, 255, 255, 1)",
fontSize: 19,
fontWeight: "400",
textAlign: "left",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6354: {
width: wp("91%"),
minWidth: wp("91%"),
minHeight: hp("11%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("45%"),
justifyContent: "center"
},
Text_1242_6354: {
color: "rgba(255, 255, 255, 1)",
fontSize: 26,
fontWeight: "700",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6386: {
width: wp("42%"),
minWidth: wp("42%"),
height: hp("9%"),
minHeight: hp("9%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("11%"),
top: hp("59%"),
backgroundColor: "rgba(252, 252, 252, 1)"
},
View_1242_6387: {
width: wp("33%"),
minWidth: wp("33%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("2%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6388: {
width: wp("9%"),
minWidth: wp("9%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(252, 238, 212, 1)"
},
View_1242_6389: {
width: wp("6%"),
minWidth: wp("6%"),
height: hp("3%"),
minHeight: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%"),
backgroundColor: "rgba(0, 0, 0, 0)",
overflow: "hidden"
},
ImageBackground_I1242_6389_280_5910: {
flexGrow: 1,
width: wp("5%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("0%")
},
View_1242_6390: {
width: wp("22%"),
minWidth: wp("22%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("11%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6391: {
width: wp("22%"),
minWidth: wp("22%"),
minHeight: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("1%"),
justifyContent: "flex-start"
},
Text_1242_6391: {
color: "rgba(13, 14, 15, 1)",
fontSize: 14,
fontWeight: "400",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6399: {
width: wp("31%"),
minWidth: wp("31%"),
height: hp("9%"),
minHeight: hp("9%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("58%"),
top: hp("59%"),
backgroundColor: "rgba(252, 252, 252, 1)"
},
View_1242_6400: {
width: wp("22%"),
minWidth: wp("22%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("2%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6401: {
width: wp("9%"),
minWidth: wp("9%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(253, 213, 215, 1)"
},
View_1242_6402: {
width: wp("6%"),
minWidth: wp("6%"),
height: hp("3%"),
minHeight: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%"),
backgroundColor: "rgba(0, 0, 0, 0)",
overflow: "hidden"
},
View_I1242_6402_280_7557: {
flexGrow: 1,
width: wp("4%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("0%")
},
ImageBackground_I1242_6402_280_7558: {
width: wp("4%"),
height: hp("2%"),
top: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%")
},
View_1242_6403: {
width: wp("12%"),
minWidth: wp("12%"),
height: hp("4%"),
minHeight: hp("4%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("11%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_1242_6404: {
width: wp("12%"),
minWidth: wp("12%"),
minHeight: hp("3%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("1%"),
justifyContent: "flex-start"
},
Text_1242_6404: {
color: "rgba(13, 14, 15, 1)",
fontSize: 14,
fontWeight: "400",
textAlign: "center",
fontStyle: "normal",
letterSpacing: 0,
textTransform: "none"
},
View_1242_6363: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("5%"),
minHeight: hp("5%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("106%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I1242_6363_217_6979: {
flexGrow: 1,
width: wp("100%"),
height: hp("5%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I1242_6363_217_6979_108_2809: {
flexGrow: 1,
width: wp("36%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("32%"),
top: hp("3%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_1242_6364: {
width: wp("100%"),
minWidth: wp("100%"),
height: hp("6%"),
minHeight: hp("6%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
backgroundColor: "rgba(0, 0, 0, 0)"
},
View_I1242_6364_816_117: {
flexGrow: 1,
width: wp("14%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("5%"),
top: hp("2%")
},
View_I1242_6364_816_118: {
width: wp("14%"),
minWidth: wp("14%"),
minHeight: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%"),
justifyContent: "flex-start"
},
Text_I1242_6364_816_118: {
color: "rgba(255, 255, 255, 1)",
fontSize: 12,
fontWeight: "400",
textAlign: "center",
fontStyle: "normal",
letterSpacing: -0.16500000655651093,
textTransform: "none"
},
View_I1242_6364_816_119: {
flexGrow: 1,
width: wp("18%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("78%"),
top: hp("2%")
},
View_I1242_6364_816_120: {
width: wp("7%"),
minWidth: wp("7%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("11%"),
top: hp("0%")
},
View_I1242_6364_816_121: {
width: wp("7%"),
height: hp("2%"),
top: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%")
},
ImageBackground_I1242_6364_816_122: {
width: wp("6%"),
minWidth: wp("6%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("0%")
},
ImageBackground_I1242_6364_816_125: {
width: wp("0%"),
minWidth: wp("0%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("6%"),
top: hp("1%")
},
View_I1242_6364_816_126: {
width: wp("5%"),
minWidth: wp("5%"),
height: hp("1%"),
minHeight: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)",
borderColor: "rgba(76, 217, 100, 1)",
borderWidth: 1
},
View_I1242_6364_816_127: {
width: wp("5%"),
height: hp("1%"),
top: hp("0%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%")
},
View_I1242_6364_816_128: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("0%"),
top: hp("1%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I1242_6364_816_129: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("1%"),
top: hp("1%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I1242_6364_816_130: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("3%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
View_I1242_6364_816_131: {
width: wp("1%"),
minWidth: wp("1%"),
height: hp("1%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("4%"),
top: hp("0%"),
backgroundColor: "rgba(255, 255, 255, 1)"
},
ImageBackground_I1242_6364_816_132: {
width: wp("4%"),
minWidth: wp("4%"),
height: hp("2%"),
marginLeft: 0,
marginTop: 0,
position: "absolute",
left: wp("6%"),
top: hp("0%")
}
})
const mapStateToProps = state => {
return {}
}
const mapDispatchToProps = () => {
return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(Blank)
|
$(document).ready(()=>{
gatAllData();
})
let getAllData=()=>{
console.log("making request")
$.ajax({
type:"GET",
datatype:"json",
Url:"artos.json",
success: (data)=>{
console.log(data)
let allPeople = data.people
for(people of allPeople){
let temprow = <div class='row'>
<div class='col'>${perosn.name}</div>
<div class='col'>${perosn.craft}</div>
</div>
$('#showData').append(temprow)
}
},
error: (data) => {
alert("Some error happened")
},
beforesend: ()=>{
//Loader before the success is completed
},
complete:()=>{
// Activity after request is completed
},
timeout: 3000 // this is inn milliseconds
})
}
|
function listCard(params) {
self = this;
}
module.exports = ko.components.register('listCard', {
viewModel: listCard,
template:
`<section class="panel panel-primary">
<!--panel-heading-->
<div class="panel-heading" role="tab">
<div class="panel-title">
<button class="btn btn-icon" type="button">
<span class="btn btn-icon shevron white-shevron-up"></span>
<span class="title" data-bind="text: name">Title</span>
</button>
<!-- ko if: quantity in $data-->
<span data-bind="text: quantity" class="counter"></span>
<!-- /ko -->
</div>
</div><!--panel-heading-->
<!--panel-body-->
<div class="panel-collapse collapse" role="tabpanel">
<div class="panel-body">
<ul data-bind="foreach: items" class="list-group">
<li class="list-group-item">
<span data-bind="text: name" class="name truncate">event name</span>
<!--additional-info-->
<div class="additional-info">
<p data-bind="text: Object.getProp($data, 'dates.start.localDate')" class="date">event date</p>
<span data-bind="if: Object.getProp($data, '_embedded.venues[0].name')">
<p data-bind="text: Object.getProp($data, '_embedded.venues[0].name')" class="venue">event venue</p>
</span>
</div><!--additional-info-->
<button type="button" class="btn btn-icon blue-shevron-right"></button>
</li>
</ul>
</div>
</div><!--panel-body-->
</section>`
});
|
const test = require('tape');
const isWeakMap = require('./isWeakMap.js');
test('Testing isWeakMap', (t) => {
//For more information on all the methods supported by tape
//Please go to https://github.com/substack/tape
t.true(typeof isWeakMap === 'function', 'isWeakMap is a Function');
//t.deepEqual(isWeakMap(args..), 'Expected');
//t.equal(isWeakMap(args..), 'Expected');
//t.false(isWeakMap(args..), 'Expected');
//t.throws(isWeakMap(args..), 'Expected');
t.end();
});
|
import Router from 'vue-router'
import routes from './routes'
//服务端渲染需要
export default ()=>{
return new Router({
routes,
mode: 'history'
})
}
|
(function () {
angular.module('photoGallery').controller('WinningPhotoController', WinningPhotoController);
function WinningPhotoController($scope, $rootScope, winningPhoto) {
var self = this;
self.closeModal = closeModal;
self.winningPhotoFile = winningPhoto.filename;
$rootScope.$broadcast('winning-photo:show');
function closeModal(close) {
$rootScope.$broadcast('winning-photo:hide');
close();
}
}
})();
|
var Note = require('../models/note');
// extracting the server side of things from server.js
module.exports.create = function (req, res) {
var note = new Note(req.body);
note.save(function (err, result) {
// sends back to client via callback
res.json(result);
});
}
module.exports.query = function (req, res) {
// from mongoose
Note.find({}, function (err, results) {
res.json(results);
});
}
|
const utils = require("./utils");
const determinePricing = (quantity, pricePer, location) => {
const priceInCents = utils.normalizePricingToCents(pricePer);
const taxRate = utils.determineTaxRate(location);
const priceBeforeDiscountAndTax = quantity * priceInCents;
const discountRate = 100 - utils.determineDiscount(priceBeforeDiscountAndTax);
const totalPriceInCents =
priceBeforeDiscountAndTax * (1 + taxRate) * (discountRate / 100);
return utils.normalizePricingToDollars(totalPriceInCents);
};
module.exports = {
determinePricing,
};
|
const express = require("express")
const routes = express.Router()
const Usermodel = require("../Models/RegisterSchema")
const bcrypt = require("bcryptjs")
const passport = require("passport")
const JWT = require("jsonwebtoken")
routes.post("/register", async (req, res) => {
const { name, email, pswd, pswd2 } = req.body;
const error = []
if (!name || !email || !pswd || !pswd2) {
error.push({ msg: "Filled this field" })
res.json(error)
}
if (pswd !== pswd2) {
error.push({ msg: "password doset not match" })
}
if (pswd.length < 6) {
error.push({ msg: "password must be 6 chracter" })
}
if (error.length != 0) {
res.json(error)
} else {
let Hash = await bcrypt.hash(pswd2, 10)
let newuser = new Usermodel({
name: name,
email: email,
password: pswd,
password2: Hash
})
newuser.save().then((res) => {
console.log(res);
}).catch((e) => {
console.log("error", e);
})
}
})
routes.post("/Login", (req, res) => {
const { email, pswd } = req.body
Usermodel.findOne({ email }).then((user) => {
console.log(user);
console.log(pswd)
bcrypt.compare(pswd, user.password2, (err, result) => {
if (result == true) {
const payload = {
id: user._id,
name: user.name
}
JWT.sign(payload, "config", (err, response) => {
if (err) {
res.status(500).json({
msg: "Token is invalid",
type: err
})
} else {
let token = {
token: `Bearer ${response}`
}
res.json(token).status(200)
}
})
} else {
res.json("error");
console.log("error")
}
})
})
})
routes.get("/me", passport.authenticate("jwt", { session: false }), (req, res) => {
console.log("user", req);
res.json({
id: req.user.id,
email: req.user.email,
name: req.user.name
})
})
// routes.post("/checktoken", (req, res) => {
// Usermodel.findOne({ _id: req.body.id }).then((users) => {
// res.json({
// name: users.name,
// email: users.email
// })
// })
// let user = await Usermodel.aggregate([
// { $match: { id: "5d89f43ca1ec961754fdcbf6" } }
// ])
// console.log(user);
// })
module.exports = routes
|
module.exports = {
HelperRock: {
1: "",
4: "0x05C3D763a070d01C3731Bb2DECfa76D5Fb74A7Fb",
},
EtherRock: {
1: "0x37504AE0282f5f334ED29b4548646f887977b7cC",
4: "0xBC0dAA15d70d35f257450197c129A220fb1F2955",
},
};
|
const { randomInt } = require('crypto');
const { writeFileSync, readFileSync } = require('fs');
const { resolve } = require('path');
module.exports = function () {
this.rootPath = process.cwd();
this.dest = resolve(this.rootPath, 'serverless.yaml');
// new时读取string
this.destString = readFileSync(
resolve(this.rootPath, 'serverless/serverless.yaml'),
).toString();
/**
* 写入文件
* @param {string} dest 目标地址(默认/serverless)
*/
this.writeFile = dest => {
writeFileSync(dest || this.dest, this.destString);
return this;
};
this.end = this.update = this.writeFile;
/**
* 是否开启风纪委员任务执行
* @param {boolen} isOpenJuryVote
*/
this.openJuryVote = isOpenJuryVote => {
this.destString = this.destString.replace(
/\B@{env\.BILI_JURY_VOTE}\B/g,
`${isOpenJuryVote || false}`,
);
return this;
};
/**
* 更新组件app名
* @param {string} componentAppName 默认''
*/
this.updateComponentAppName = componentAppName => {
this.destString = this.destString.replace(
/\B@{env\.COMPONENT_APP_NAME}\B/g,
componentAppName || `''`,
);
return this;
};
/**
* 函数名
* @param {string} scfName (必须参数)
*/
this.updateSCFName = scfName => {
if (!scfName) {
throw new Error('没有设置serverless函数名,无法进行部署');
}
this.destString = this.destString.replace(/\B@{env\.SCF_NAME}\B/g, scfName);
return this;
};
/**
* 函数运行地域(默认成都)
* @param {string} region
*/
this.updateRegion = region => {
this.destString = this.destString.replace(
/\B@{env\.SCF_REGION}\B/g,
region || 'ap-chengdu',
);
return this;
};
/**
* 函数描述
* @param {string} description
*/
this.updateDescription = description => {
this.destString = this.destString.replace(
/\B@{env\.SCF_DESCRIPTION}\B/g,
description || '可以填写识别该函数是哪个账号用',
);
return this;
};
/**
* 是否执行日常任务
* @param {any} isRun
*/
this.isRunDailyTask = isRun => {
this.destString = this.destString.replace(
/\B@{env\.BILI_DAILY_RUN}\B/g,
`${isRun === false ? false : true}`,
);
return this;
};
/**
* 提交时设置执行时间
* @param {string} dailyRunTime 每日任务时间
*/
this.randomDailyRunTime = dailyRunTime => {
const BILI_DAILY_RUN_TIME = dailyRunTime || '17:30:00-23:40:00';
const taskTime = BILI_DAILY_RUN_TIME.split('-');
const startTime = taskTime[0].split(':');
const endTime = taskTime[1].split(':');
const hours = randomInt(+startTime[0] ?? 19, +endTime[0] + 1 ?? 24);
let minutes = 0;
if (hours == startTime[0]) {
minutes = randomInt(+startTime[1], 60);
} else if (hours == endTime[0]) {
minutes = randomInt(+endTime[1] + 1);
} else {
minutes = randomInt(60);
}
let seconds = 0;
if (hours == startTime[0]) {
seconds = randomInt(+startTime[2], 60);
} else if (hours == endTime[0]) {
seconds = randomInt(+endTime[2] + 1);
} else {
seconds = randomInt(60);
}
const DAILY_CRON_EXPRESSION = `${seconds} ${minutes} ${hours} * * * *`;
this.destString = this.destString.replace(
/(?<=')\@{env.BILI_DAILY_CRON_EXPRESSION}(?=')/g,
`${DAILY_CRON_EXPRESSION}`,
);
return this;
};
/** 风纪任务随机时间设置 */
this.randomJuryRunTime = juryRunTime => {
juryRunTime = juryRunTime || '8-12/20-40';
const time = juryRunTime.split('/').map(el => el.split('-'));
const startHours = randomInt(+time[0][0], +time[0][1]), //10,11
startMinutes = randomInt(6), // 0 - 5
minutes = randomInt(+time[1][0], +time[1][1]),
seconds = randomInt(60);
// const endHours = Math.floor(minutes * 0.667) + startHours;
const endHours = 6 + startHours;
const DAILY_CRON_EXPRESSION = `${seconds} ${startMinutes}/${minutes} ${startHours}-${endHours} * * * *`;
this.destString = this.destString.replace(
/(?<=')@{env.BILI_JURY_CRON_EXPRESSION}(?=')/g,
`${DAILY_CRON_EXPRESSION}`,
);
return this;
};
};
|
const objectMapper = require('../mappers/objects');
exports.bodyToCamelCase = (req, res, next) => {
req.body = objectMapper.keysToCamelCase(req.body);
return next();
};
|
function doOnLoad() {
if (getSetting("configured") != 1) {
setSetting("configured", 1);
loadDefaults(false);
var delayedReload = function() { window.location.reload(); clearInterval(delayedReload); };
setInterval(delayedReload, 3000);
}
var streamUrl = getSetting("streamurl");
if (streamUrl != null && streamUrl != "[none]") {
document.getElementById("streamFrame").src = streamUrl;
}
if (getSetting("streambroken")) {
document.getElementById("streamFrame").src = "streamerror/broken.html";
}
showHideSponsers();
fixStream();
doInterval();
loadRankTotal();
loadSponserPics();
}
function doInterval() {
loadEventData();
}
function loadSponserPics() {
var newpics = JSON.parse(getSetting("sponserpics"));
for (var i=0; i<newpics.length; i++) {
document.getElementById("sponmarq").innerHTML += "<img src=\"" + newpics[i] + "\" height=\"90px\" class=\"pl-5\">";
}
}
function loadRankTotal() {
$.ajax({
type: "GET",
url: tbaUrl("/event/"+getSetting("eventkey")+"/teams/keys"),
dataType: "json",
success: function(data) {
document.getElementById("rankTotal").innerHTML = data.length;
}
});
}
function formatTimeShow(h_24, m) {
var h = h_24 % 12;
if (h === 0) h = 12;
return (h < 10 ? '0' : '') + h + ":" + m + (h_24 < 12 ? ' AM' : ' PM');
}
function loadEventData() {
$.ajax({
type: "GET",
url: tbaUrl("/team/"+getSetting("teamkey")+"/event/"+getSetting("eventkey")+"/status"),
dataType: "json",
success: function(data) {
loadLastMatch(data);
loadNextMatch(data);
loadTeamRank(data);
loadTopRanks();
}
});
}
function loadTeamRank(data) {
var element = document.getElementById("teamRanking");
if (data != null) {
var qualData = data.qual;
if (qualData != null) {
element.innerHTML = qualData.ranking.rank.toString();
} else {
element.innerHTML = "?";
}
}
}
function loadTopRanks() {
$.ajax({
type: "GET",
url: tbaUrl("/event/"+getSetting("eventkey")+"/rankings"),
dataType: "json",
success: function(data) {
var rankData = data.rankings;
if (data != null) {
for (var i=0; i<8; i++) {
document.getElementById("rankTeam"+(i+1).toString()).innerHTML = rankData[i].team_key.toString().replace("frc", "");
if (rankData[i].team_key.toString().replace("frc", "") == getSetting("teamkey").toString().replace("frc", "")) {
document.getElementById("rowTeam"+(i+1).toString()).style = "background-color: lightgreen;";
} else {
document.getElementById("rowTeam"+(i+1).toString()).style = "";
}
}
}
}
});
}
function loadLastMatch(data) {
var lastMatchKey = data.last_match_key;
if (lastMatchKey != null) {
$.ajax({
type: "GET",
url: tbaUrl("/match/"+lastMatchKey+"/simple"),
dataType: "json",
success: function(data) {
document.getElementById("lastRedScore").innerHTML = data.alliances.red.score.toString();
document.getElementById("lastBlueScore").innerHTML = data.alliances.blue.score.toString();
var tempTeamNumber = 0; var tempStart = ""; var tempEnd = "";
for (var i=0; i<3; i++) {
tempTeamNumber = data.alliances.red.team_keys[i].toString().replace("frc", "");
if (tempTeamNumber == getSetting("teamkey").toString().replace("frc", "")) {
tempStart = "<u><strong>"; tempEnd = "</strong></u>";
} else {
tempStart = ""; tempEnd = "";
}
document.getElementById("lastRed"+(i+1).toString()).innerHTML = tempStart + tempTeamNumber + tempEnd;
}
for (var i=0; i<3; i++) {
tempTeamNumber = data.alliances.blue.team_keys[i].toString().replace("frc", "");
if (tempTeamNumber == getSetting("teamkey").toString().replace("frc", "")) {
tempStart = "<u><strong>"; tempEnd = "</strong></u>";
} else {
tempStart = ""; tempEnd = "";
}
document.getElementById("lastBlue"+(i+1).toString()).innerHTML = tempStart + tempTeamNumber + tempEnd;
}
document.getElementById("lastMatchNumber").innerHTML = data.match_number.toString();
if (data.winning_alliance == "red") {
$("#lastWinBlue").addClass("d-none");
$("#lastWinRed").removeClass("d-none");
} else if (data.winning_alliance == "blue") {
$("#lastWinBlue").removeClass("d-none");
$("#lastWinRed").addClass("d-none");
}
}
});
}
}
function loadNextMatch(data) {
var nextMatchKey = data.next_match_key;
if (nextMatchKey != null) {
$.ajax({
type: "GET",
url: tbaUrl("/match/"+nextMatchKey+"/simple"),
dataType: "json",
success: function(data) {
var tempTeamNumber = 0; var tempStart = ""; var tempEnd = "";
for (var i=0; i<3; i++) {
tempTeamNumber = data.alliances.red.team_keys[i].toString().replace("frc", "");
if (tempTeamNumber == getSetting("teamkey").toString().replace("frc", "")) {
tempStart = "<u><strong>"; tempEnd = "</strong></u>";
} else {
tempStart = ""; tempEnd = "";
}
document.getElementById("nextRed"+(i+1).toString()).innerHTML = tempStart + tempTeamNumber + tempEnd;
}
for (var i=0; i<3; i++) {
tempTeamNumber = data.alliances.blue.team_keys[i].toString().replace("frc", "");
if (tempTeamNumber == getSetting("teamkey").toString().replace("frc", "")) {
tempStart = "<u><strong>"; tempEnd = "</strong></u>";
} else {
tempStart = ""; tempEnd = "";
}
document.getElementById("nextBlue"+(i+1).toString()).innerHTML = tempStart + tempTeamNumber + tempEnd;
}
document.getElementById("nextMatchNumber").innerHTML = data.match_number.toString();
}
})
}
}
window.onload = doOnLoad;
window.setInterval(doInterval, 5000);
|
import Vue from 'vue'
import App from './app.vue'
import router from '@/router'
import VConsole from 'vconsole';
import store from '@/store'
import mixins from '@global/mixins'
require('@global/components')
require('@global/directives')
import {project} from '@config'
Vue.config.productionTip = false
if (process.env.NODE_ENV !== 'production' && project.mobile ) {
new VConsole();
}
Vue.mixin({ mixins });
new Vue({
router,
store,
el:'#app',
render: h => h(App)
})
|
const config = {
MAX_ATTACHMENT_SIZE: 5000000,
s3: {
REGION: "ap-northeast-1",
BUCKET: "serverlessknx-notes-app-upload",
},
apiGateway: {
REGION: "ap-northeast-1",
URL: "https://14vdtec3ub.execute-api.ap-northeast-1.amazonaws.com/dev",
},
cognito: {
REGION: "ap-northeast-1",
USER_POOL_ID: "ap-northeast-1_RieD32mhQ",
APP_CLIENT_ID: "ovf94lg10sbsjk6qp22puolsg",
IDENTITY_POOL_ID: "ap-northeast-1:0e383aad-63b2-4ff8-ae83-5d24e1e14a2b",
},
};
export default config;
|
const CompressionPlugin = require("compression-webpack-plugin");
module.exports = {
/**
* baseUrl 为活动名,上线后正式地址为 https://activity.wps.com/xxx
* 上线时需要把 baseUrl 设置为 CDN 地址 https://d3nwz1fzrto4dz.cloudfront.net/xxx
*/
//
publicPath: "", // 本地调试,默认为空
chainWebpack: config => {
// #region 忽略生产环境打包的文件
config.externals({
vue: "Vue",
axios: "axios",
"vue-router": "VueRouter",
vuex: "Vuex",
"vue-i18n": "VueI18n"
// 'element-ui': 'ELEMENT',
});
/**
* cdn 常用的第三方库不用打包,直接从线上拉去,减少包的体积
* 没有cdn的时候就直接在页面中采用 script 标签进行引入
* 参见 pubilc/index.heml
*/
const cdn = {
css: [
// element-ui css
// "//unpkg.com/element-ui/lib/theme-chalk/index.css"
],
js: [
// vue
"//cdn.staticfile.org/vue/2.5.22/vue.min.js",
// vue-router
"//cdn.staticfile.org/vue-router/3.0.2/vue-router.min.js",
// vuex
"//cdn.staticfile.org/vuex/3.1.0/vuex.min.js",
// axios
"//cdn.staticfile.org/axios/0.19.0-beta.1/axios.min.js"
// element-ui js
// "//unpkg.com/element-ui/lib/index.js"
]
};
config.plugin("html").tap(args => {
args[0].cdn = cdn;
return args;
});
// #endregion
// 文件压缩,一般情况下后端都没配置,这里也需要后端进行文件配置
if (process.env.NODE_ENV === "production") {
// #region 启用GZip压缩
config
.plugin("compression")
.use(CompressionPlugin, {
asset: "[path].gz[query]",
algorithm: "gzip",
test: new RegExp("\\.(" + ["js", "css"].join("|") + ")$"),
threshold: 10240,
minRatio: 0.8,
cache: true
})
.tap(args => {});
}
},
// 配置代理
devServer: {
host: "localhost", // 自己电脑ip
port: 9999, // 自定义端口号
https: false,
proxy: {
"/api/": {
// 测试环境
// 开发环境: 'https://micro.api.wps.com'
target: "https://cnodejs.org/",
secure: false // 如果是https接口,需要配置这个参数
}
}
},
productionSourceMap: false
};
|
angular.module('dataCoffee').controller('newPeriodo', newPeriodo);
newPeriodo.$inject = ['$scope', '$http', '$rootScope', '$location'];
function newPeriodo($scope, $http, $rootScope, $location) {
$scope.reset = function (){
$scope.name = '';
}
$scope.salvar = function() {
$scope.data = JSON.stringify({ nome : $scope.name });
$http({ method: 'POST', url: $rootScope.url.new.periodo,
data: $scope.data,
headers: {'Content-Type': 'application/json; charset=utf-8'}
});
alertify.success("Adicionado com sucesso!");
$location.path('periodo/list');
}
}
|
let mongoose = require('mongoose');
let Schema = mongoose.Schema;
let readingSchema = new Schema({
username: String,
todo: String,
isDone: Boolean,
hasAttachment: Boolean
});
module.exports = mongoose.model('Reading', readingSchema);
|
import React from 'react';
import { connect } from 'react-redux';
import { setUsers, setUsersClear, setSearchKey } from '../../Redux/MainGridReducer';
import EditModulePage from './EditModulePage';
import Axios from 'axios';
class EditModulePageAPI extends React.Component {
editUser = (userId, userName, userSurname, userBirth, userPosition, newUserRemoteworking,
userCity, userStreet, userHouse, userApartment, changeKey) => {
debugger;
let actionType = 'PUSH_EDITED_USER';
let searchKey = this.props.searchKey;
if (changeKey === 'userName') {
searchKey = userName;
} else if (changeKey === 'userSurname') {
searchKey = userSurname;
} else if (changeKey === 'userPosition') {
searchKey = userPosition;
} else if (changeKey === 'userCity') {
searchKey = userCity;
}
setSearchKey (searchKey);
let object = { actionType, userId, userName, userSurname, userBirth, userPosition, newUserRemoteworking,
userCity, userStreet, userHouse, userApartment, searchKey };
Axios.post( 'http://testcrm/actions/index.php',object
)
.then(res => {
debugger;
let users = res.data;
let usersCopy = [];
users.map(u => {
u.id = parseInt(u.id);
u.showUser = parseInt(u.showUser);
u.remoteWorking = parseInt(u.remoteWorking);
usersCopy.push(u);
})
this.props.setUsersClear(usersCopy);
}
);
}
render () {
return (
<div>
<EditModulePage users={this.props.users}
choosenUser={this.props.choosenUser}
editUser={this.props.editUser}
pushEditedUser={this.editUser}
searchKey={this.props.searchKey}
/>
</div>
)
}
}
let mapStateToProps = (state) => {
return {
users: state.MainGrid.users,
choosenUser: state.MainGrid.choosenUser,
editUser: state.MainGrid.editUser,
searchKey: state.MainGrid.searchKey,
}
}
export default connect(mapStateToProps, { setUsers, setUsersClear, setSearchKey })(EditModulePageAPI);
|
import {useState} from 'react';
import "./PlayerListItem.scss";
import { FaUser } from "react-icons/fa";
import { IoIosCopy } from "react-icons/io";
import { CopyToClipboard } from 'react-copy-to-clipboard';
const classNames = require('classnames');
function PlayerListItem(props) {
const [copied, setCopied] = useState(false)
const { name, gameIdItem, playerItem } = props;
const copyClass = classNames("copy-message", {"copy-message--show": copied});
const setCopy = () => {
if (copied === false){
setCopied(true)
setTimeout(() => {setCopied(false)}, 2000)
}
}
return (
<div className="player-container">
{gameIdItem && (
<CopyToClipboard text={name}>
<div className="clipboard-content" onClick={() => setCopy(true)} >
<p className="game-id">Game ID:</p>
<h2 className="list-item-text game-id id-text"> {name} <IoIosCopy className="icon clipboard-icon" /><p className={copyClass} style={{display:'hidden', fontSize:'0.1rem' }}>Copied!</p></h2>
</div>
</CopyToClipboard>
)}
{playerItem && (
<p className="list-item-text">
<FaUser className="user-icon" />
{name}
</p>
)}
</div>
);
}
export default PlayerListItem;
|
/*
Copyright (c) 2004-2009, The Dojo Foundation
All Rights Reserved.
Licensed under the Academic Free License version 2.1 or above OR the
modified BSD license. For more information on Dojo licensing, see:
http://dojotoolkit.org/book/dojo-book-0-9/introduction/licensing
*/
/*
Author: unscriptable
Date: Jan 31, 2009
All common classes and "enums" are found here.
For convenience, qualified names are under dojoc.dojocal, rather than
dojoc.dojocal._base.common!
*/
dojo.provide('dojoc.dojocal._base.common');
(function () { // closure for local variables
var dndModes = dojoc.dojocal.DndModes = {
NONE: 0,
DISCRETE: 1,
FLUID: 2
};
var allDayEventsPositions = dojoc.dojocal.AllDayEventPositions = {
HIDDEN: 0,
TOP: 1,
BOTTOM: 2
};
dojo.mixin(dojoc.dojocal, {
// useful constants
hoursPerDay: 24,
minutesPerDay: 24 * 60,
secPerDay: 24 * 60 * 60,
msecPerDay: 24 * 60 * 60 * 1000,
getNodeBox: function (/* DOMNode|_Widget */ obj, /* Boolean? */ asPercent) {
// summary: returns the box for the node
// asPercent: Boolean
// set to true to get the box dimensions as a percent of the offsetParent's dimensions
// TODO: use dojo.marginBox when offsetXXX properties are not available
var node = obj.nodeType ? obj : obj.domNode,
box = new dojoc.dojocal.OffsetBox(node);
if (asPercent) {
var pw = 1 / (node.offsetParent.offsetWidth || Infinity),
ph = 1 / (node.offsetParent.offsetHeight || Infinity);
box.scaleBy(pw, ph);
}
return box;
},
getCoordsBox: function (/* DOMNode|_Widget */ obj, /* Boolean? */ includeScroll) {
// summary: returns the box for the node in reference to the viewport
// includeScroll: Boolean
// set to true to include scroll measurements in the box's offsets
var coords = dojo.coords(obj.nodeType ? obj : obj.domNode, includeScroll);
// convert to OffsetBox-compatible properties
coords.l = coords.x;
coords.t = coords.y;
return new dojoc.dojocal.OffsetBox(coords);
},
setNodeBox: function (/* DOMNode|_Widget */ obj, /* OffsetBox */ box, /* String? */ units) {
var ns = (obj.nodeType ? obj : obj.domNode).style;
if ('l' in box)
ns.left = box.l + (units || 'px');
if ('t' in box)
ns.top = box.t + (units || 'px');
if ('w' in box)
ns.width = box.w + (units || 'px');
if ('h' in box)
ns.height = box.h + (units || 'px');
return obj;
},
createScrollbarStyles: function () {
// summary: creates some styles that help account for the browser's scrollbar width
// Don't call this method. It is called at load time automatically (via dojo.addOnLoad).
// Creates the following styles:
// dojocalScrollbarPaddingH - has padding on the right equal to the scrollbar width
// dojocalScrollbarPaddingV - has padding on the bottom equal to the scrollbar width
// dojocalScrollbarMarginH - has margin on the right equal to the scrollbar width
// dojocalScrollbarMarginV - has margin on the bottom equal to the scrollbar width
// TODO: fix for RTL direction / locales???
var ss = this.getDojocalStylesheet(),
sbw = this.getScrollbarWidth() + 'px',
ruleDefs = [
'.dojocalScrollbarPaddingH { padding-right: ' + sbw + ' }',
'.dojocalScrollbarPaddingV { padding-bottom: ' + sbw + ' }',
'.dojocalScrollbarMarginH { margin-right: ' + sbw + ' }',
'.dojocalScrollbarMarginV { margin-bottom: ' + sbw + ' }'
];
if (ss.cssRules) { // w3c
dojo.forEach(ruleDefs, ss.insertRule, ss);
}
else { // ie
dojo.forEach(ruleDefs, function (def) {
var p = def.indexOf('{');
ss.addRule(def.substr(0, p), def.substring(p + 1, def.indexOf('}')));
});
}
return ss;
},
getCssWorkArounds: function () {
// summary: checks for common browser css deficiencies and returns a list of offenders
// TODO: finish getCssWorkArounds
var workArounds = [];
// rgba: set bg to something simple, then set to rgba(...) and detet if it changed
// Expanding Empty Box: set height and contents and detect height
// PNG transparency: how to do this??????
// Box Offsets: create a child node sized with top and bottom and check height
},
getDojocalStylesheet: function () {
if (!this._djcss)
this._djcss = this.createStylesheet()
return this._djcss;
},
/***** utility functions *****/
// functions that dojo or dijit should have already!!!! (hint, hint)
findAncestorNode: function (/* DOMNode */ node, /* Any */ which, /* Function */ detector) {
// summary:
// finds an ancestor node by using the detector function and the supplied data (which)
// or returns null if no ancestor was found
// Don't use this method. Use getAncestorByXXX methods below.
// which: Any data type
// data to be sent to the detector function to find a match
// detector: Function
// the function to detect whether the correct ancestor has been found
// param 1: the current node being tested; param 2: the which parameter passed to findAncestorNode
while (node && node.nodeType != 9 /* document node */ && !detector(node, which)) {
node = node.parentNode;
}
return node.nodeType != 9 && node || null;
},
getAncestorByTagName: function (/* DOMNode */ node, /* String */ tagName) {
// summary: finds an ancestor that has the specified tagName
tagName = tagName.toUpperCase();
return this.findAncestorNode(node, tagName, function (n, t) { return n.tagName.toUpperCase() == t; });
},
getAncestorByClassName: function (/* DOMNode */ node, /* String */ className) {
// summary: finds an ancestor node that has the specified class
return this.findAncestorNode(node, className, dojo.hasClass);
},
getAncestorByAttrName: function (/* DOMNode */ node, /* String */ attrName) {
// summary: finds an ancestor node that has the specified attribute (of any value)
return this.findAncestorNode(node, attrName, function (n, a) { return n.getAttribute && dojo.hasAttr(n, a); });
},
isAncestorNode: function (/* DOMNode */ node, /* DOMNode */ ancestor) {
return !!this.findAncestorNode(node, ancestor, function (n, a) { return n == a; });
},
getScrollbarWidth: function () {
// something like this exists in dojox I just discovered, but we don't want to rely on dojox
if (!this._scrollbarWidth) {
this._scrollbarWidth = 15;
var testEl = dojo.doc.createElement('DIV');
try {
testEl.style.cssText = 'width:100px;height:100px;overflow:scroll;bottom:100%;right:100%;position:absolute;visibility:hidden;'
dojo.body().appendChild(testEl);
this._scrollbarWidth = testEl.offsetWidth - Math.max(testEl.clientWidth, testEl.scrollWidth);
dojo.body().removeChild(testEl);
}
catch (ex) {
// squelch
}
}
return this._scrollbarWidth;
},
createStylesheet: function (cssText) {
// TODO: why not use dojo's createstylesheet?
var doc = dojo.doc,
node = doc.createElement('style');
// add to head tag (or to body tag, if head is missing)
dojo.query('HEAD,BODY', doc)[0].appendChild(node);
node.setAttribute('type', 'text/css');
// insert css text
// IE6 and Safari 2 need to have cssText or the stylesheet won't get created
cssText = cssText || '#__dummy__ {}';
// IE (hack city)
if (node.styleSheet) {
function setText () {
try { node.styleSheet.cssText = cssText; }
catch (ex) { dojo.debug(ex); }
}
if (node.styleSheet.disabled) setTimeout(setText, 10);
else setText();
}
// w3c
else {
node.appendChild(doc.createTextNode(cssText));
}
return node.sheet || node.styleSheet;
},
/* useful date functions */
dateOnly: function (/* Date */ date) {
// summary: returns the date portion of the Date object
return new Date(date.getFullYear(), date.getMonth(), date.getDate());
},
timeOnly: function (/* Date */ date) {
// summary: returns the time portion of the Date object
var d = new Date(0, 0, 0, date.getHours(), date.getMinutes(), date.getSeconds());
d.setMilliseconds(date.getMilliseconds());
return d;
},
minDate: function (/* Dates... */) {
// summary: returns a new date equal to the smallest of the Date parameters supplied
// example: var earliest = dojoc.dojocal.minDate(date1, date2, date3);
return new Date(Math.min.apply(null, arguments));
},
maxDate: function (/* Dates... */) {
// summary: returns a new date equal to the largest of the Date parameters supplied
// example: var latest = dojoc.dojocal.maxDate(date1, date2, date3);
return new Date(Math.max.apply(null, arguments));
},
getWeekStartDate: function (/* Date */ date, /* Number */ weekStartsOn) {
// summary: returns the date for the start of the week of the given date
return this.dateOnly(dojo.date.add(date, 'day', -date.getDay() + weekStartsOn));
},
getMonthStartDate: function (/* Date */ date, /* Number */ weekStartsOn) {
// summary: returns the date for the start of the month of the given date
// Note: this is not necessarily the 1st of the month! It's the first day in the **grid** which
// could be in the previous month.
// first, grab the beginning of the week
var wStart = this.getWeekStartDate(date, weekStartsOn);
// if the week started in the prev month (then we got it already)
if (wStart.getMonth() != date.getMonth())
return wStart;
// go back a few weeks (approx. day-of-month / 7) to get the right one
else
return this.dateOnly(dojo.date.add(wStart, 'day', -Math.ceil((wStart.getDate() - 1) / 7) * 7));
},
getMonthEndDate: function (/* Date */ date, /* Number */ weekStartsOn) {
// summary: returns the date for the end of the month of the given date
// Note: the end date is always just greater than the actual end
// Note: this is not necessarily the 1st of the next month! It's the first day just off the **grid**
// which could be well into the next month.
// first get one week into next month
var w2ndWeek = dojo.date.add(dojo.date.add(date, 'day', -date.getDate() + 7), 'month', 1);
// return start of that week
return this.getWeekStartDate(w2ndWeek, weekStartsOn);
},
createDojoCalTopic: function (topic, id) {
return ['dojoc.dojocal', id, topic].join('.');
},
undelegate: function (/* Object */ obj) {
// summary: reverses dojo.delegate
return obj.constructor.prototype;
}
});
// create scrollbar helper styles
dojo.addOnLoad(dojo.hitch(dojoc.dojocal, dojoc.dojocal.createScrollbarStyles));
//dojoc.dojocal.UserEvent = {
// uid: '', // unique id (required)
// calendarId: '', // id for calendar to which this event belongs
// startDateTime: '', // js Date object (required)
// duration: 0, // duration in seconds (required)
// summary: '', // text summary / title (required)
// description: '', // a longer description
// isAllDay: false,
// options: { // optional set of options
// eventClass: '', // String
// calendarDef: null, // dojoc.dojocal.CalendarDef, auto-added by calendarId, if not supplied here
// cssStyles: '', // can be used to override styles on the top node, such as font styles
// cssClasses: '' // can be used for ultimate stlying control of the event widget
// },
// recurrence: {
// // TODO: finish recurrence (exceptions, etc.)
// frequency: '', // TBD
// interval: '' // TBD
// }
//};
/**
* dojoc.dojocal.CalendarDef is the collection of event items organized into a user calendar.
*/
dojo.declare('dojoc.dojocal.CalendarDef', null, {
// summary:
// CalendarDef contains a description of the visual aspects of one of a user's calendars
// of events
// id: String
// must be supplied and must be unique across calendars
id: '',
// color: String
// set this to a valid css color for the background of all events in this calendar
color: '#33ff00',
// fontColor: String
// set this to a valid css color for the text of all events in this calendar
fontColor: '#007700',
// defaultEventClass: String
// set this to the dijit class that should be used to create this event's widget
// if specified, overrides class specified by view
defaultEventClass: 'dojoc.dojocal.Event',
constructor: function (params) {
dojo.mixin(this, params);
}
});
///**
// * dojoc.dojocal.UserCalendar is the collection of event items organized into a user calendar.
// */
//dojo.declare('dojoc.dojocal.UserCalendar', null, {
//
// id: '',
// color: '#33ff00',
// fontColor: '#007700',
// defaultEventClass: '', // widget class: if specified, overrides class specified by view
//
// onChangeEvent: function (/* dojoc.dojocal.UserEvent | Array */ event, /* String */ changeType) {},
//
// setColor: function (/* String */ color) {
// this.color = color;
// /* raise topic to change color of event widgets? */
// },
//
// addEvents: function (/* Array of dojoc.dojocal.UserEvent */ events, /* dojoc.dojocal.EventOptions? */ options) {
// dojo.forEach(events, function (event) {
// this._addEvent(event, options);
// }, this);
// this.onChangeEvent(events, 'add');
// },
//
// addEvent: function (/* dojoc.dojocal.UserEvent */ event, /* dojoc.dojocal.EventOptions? */ options) {
// this._addEvent(event, options);
// this.onChangeEvent(event, 'add');
// },
//
// removeEvent: function (/* dojoc.dojocal.UserEvent */ event) {
// var idx = this._findEventPos(event);
// if (idx >= 0) {
// // TODO: allow cancellation of delete
// this.onChangeEvent(event, 'remove');
// this._events.splice(idx, 1);
// }
// },
//
// getEvents: function (/* Date? */ startDate, /* Date? */ endDate) {
// // summary: gets all dates that cross the given date range (or all events if no range is given)
// // startDate: all events must end on or after this date (whole date: not time is considered)
// // endDate: all events must start on or before this date (whole date: not time is considered)
// // Note: startDate and endDate
// // TODO: recurrence?
// // add a day to endDate so that we don't miss events that start any time on the last day
// endDate = dojo.date.add(endDate, 'day', 1);
// if (startDate && endDate) {
// return dojo.filter(this._events, function (e) {
// var end = dojo.date.add(e.data.startDateTime, 'second', e.data.duration); // TODO? assumes seconds!!!!!
// return e.data.startDateTime < endDate && end >= startDate;
// });
// }
// else
// return this._events;
// },
//
// constructor: function (params) {
// dojo.deprecated('dojoc.dojocal.UserCalendar: this is being removed asap. do not use.');
// if (params)
// dojo.mixin(this, params);
// this._events = [];
// this.id = this.id || dijit.getUniqueId(this.declaredClass);
// },
//
// _addEvent: function (/* dojoc.dojocal.UserEvent */ event, /* dojoc.dojocal.EventOptions? */ options) {
// options = options || {};
// options = dojo.mixin({
// eventClass: this.defaultEventClass,
// cssClasses: '',
// color: this.color,
// fontColor: this.fontColor
// }, options);
// event.calendarId = this.id;
// event.guid = event.guid || dijit.getUniqueId(this.declaredClass + 'Event');
// this._events.push({data: event, options: options});
// },
//
// _findEventPos: function (event) {
// // TODO: search by guids????
// var found = -1;
// dojo.some(this._events, function (obj, pos) {
// if (obj.data == event)
// found = pos;
// return found >= 0;
// });
// return found;
// }
//
//});
dojo.declare('dojoc.dojocal.OffsetBox', null, {
l: 0, // left
t: 0, // top
w: 0, // width
h: 0, // height
r: 0, // right
b: 0, // bottom
constructor: function (/* Node|dojoc.dojocal.OffsetBox|dojo.Coords|dojo.marginBox|etc. */ obj) {
/// TODO: use GCS so that the node does not have to be displayed / have offsetXXX properties!!!!
if (obj.nodeType) {
this.l = obj.offsetLeft;
this.t = obj.offsetTop;
this.w = obj.offsetWidth;
this.h = obj.offsetHeight;
}
else {
this.l = obj.l;
this.t = obj.t;
this.w = obj.w;
this.h = obj.h;
}
_fixRandB(this);
},
// TODO: add more boxy methods such as resizeBy, etc.?
sizeTo: function (w, h) {
this.w = _getNum(w, this.w);
this.h = _getNum(h, this.h);
_fixRandB(this);
return this;
},
moveTo: function (l, t) {
this.l = _getNum(l, this.l);
this.t = _getNum(t, this.t);
_fixRandB(this);
return this;
},
scaleBy: function (mx, my, isStationary) {
mx = _getNum(mx, 1);
my = _getNum(my, 1);
this.w = this.w * mx;
this.h = this.h * my;
if (!isStationary) {
this.l = this.l * mx;
this.t = this.t * my;
}
_fixRandB(this);
return this;
},
intersects: function (/* Node|dojoc.dojocal.OffsetBox|dojo.Coords|dojo.marginBox|etc. */ obj) {
// summary: returns true if the box of the passed parameter intersects this box
var test = (obj.r == undefined || obj.b == undefined) ? new dojoc.dojocal.OffsetBox(obj) : obj;
return (this.l <= test.r && this.r >= test.l) && (this.t <= test.b && this.b >= test.t);
},
surrounds: function (/* Node|dojoc.dojocal.OffsetBox|dojo.Coords|dojo.marginBox|etc. */ obj) {
// summary: returns true is the box of the passed parameter completely surrounds this box
var test = (obj.r == undefined || obj.b == undefined) ? new dojoc.dojocal.OffsetBox(obj) : obj;
return (this.l <= test.l && this.r >= test.r) && (this.t <= test.t && this.b >= test.b);
}
});
dojoc.dojocal.OffsetBox.getUnion = function (/* boxes */) {
// summary: computes the aggregate intersection of many boxes
return _box_agg([Math.min, Math.max], arguments);
};
dojoc.dojocal.OffsetBox.getIntersection = function (/* boxes */) {
// summary: computes the aggregate union of many boxes
return _box_agg([Math.max, Math.min], arguments);
}
// private methods for OffsetBox
function _getNum (obj, defaultNum) {
var num = parseFloat(obj);
return isNaN(num) ? defaultNum : num;
};
function _fixRandB (box) {
box.r = box.l + box.w;
box.b = box.t + box.h;
};
function _box_agg (ops, boxes) {
// summary: box aggregation function
var result; // resulting box
dojo.forEach(boxes, function (box) {
if (box) {
if (!result) {
result = new dojoc.dojocal.OffsetBox(box);
}
else {
result.moveTo(ops[0](result.l, box.l), ops[0](result.t, box.t));
result.sizeTo(ops[1](result.r, box.r) - result.l, ops[1](result.b, box.b) - result.t);
}
}
});
return result;
};
})(); // end of closure for local variables
|
({
getSiteURL : function(cmp, event, helper) {
var action = cmp.get('c.getCurrentCommunitySiteUrl');
action.setCallback(this, function (response) {
if (response.getState() == 'SUCCESS') {
cmp.set('v.siteUrl', response.getReturnValue());
}
});
$A.enqueueAction(action);
},
getUserContext: function (cmp, event, helper) {
var action = cmp.get("c.getCurrentUserContext");
action.setCallback(this, function (response) {
if (response.getState() == 'SUCCESS') {
cmp.set('v.userContext', response.getReturnValue());
}
});
$A.enqueueAction(action);
},
getUserCoursesAndProgrammes: function (cmp, event, helper) {
var action = cmp.get("c.getCoursesAndProgrammes");
action.setCallback(this, function (response) {
if (response.getState() == 'SUCCESS') {
cmp.set('v.userCoursesAndProgrammes', response.getReturnValue());
}
//set loadMarkup as true to display markup after server call is done.
cmp.set("v.loadMarkup",true);
});
$A.enqueueAction(action);
},
getCurrentUserRegion: function() {
var regionStorageIndex;
var lssIndex = window.sessionStorage.getItem('LSSIndex:SESSION{"namespace":"c"}');
try {
regionStorageIndex = JSON.parse(lssIndex).regionStorage;
} catch (e) {
regionStorageIndex = '';
}
var region = window.sessionStorage.getItem(regionStorageIndex) || window.sessionStorage.getItem('regionStorage');
return region;
}
})
|
import('./math').then(function(m) {
console.log(m.default(1, 2));
});
|
$(document).ready(function(){
printElementsGroup("best_sellers");
});
|
import React from 'react'
import { StyleSheet } from 'quantum'
import { RowLayout, Layout } from 'bypass/ui/layout'
import { Condition } from 'bypass/ui/condition'
import Toggle from './Toggle'
const styles = StyleSheet.create({
self: {
width: '100%',
background: '#f5f5f5',
},
})
const Controls = ({ show, children, onToggle }) => (
<div className={styles()}>
<RowLayout>
<Layout>
<Condition match={show}>
{children}
</Condition>
</Layout>
<Layout>
<Toggle
toggled={show}
onClick={onToggle}
/>
</Layout>
</RowLayout>
</div>
)
export default Controls
|
let questionCount =0;
const question =document.querySelector(".question");
const option1 =document.querySelector("#option1");
const option2 =document.querySelector("#option2");
const option3 =document.querySelector("#option3");
const option4 =document.querySelector("#option4");
const sumbit =document.querySelector("#sumbit");
const answers = document.querySelectorAll(".answer");
fetch('static/json/fate.json').then(function(response){
return response.json();
}).then((quizDB)=>{console.log(quizDB)
console.log(quizDB.length);
console.log(quizDB[questionCount]);
const loadQuestion =()=>{
var range=quizDB[questionCount];
question.innerHTML = range.question;
option1.innerHTML=range.option_1;
option2.innerHTML=range.option_2;
option3.innerHTML=range.option_3;
option4.innerHTML=range.option_4;
}
loadQuestion();
const getCheckAnswer =()=>{
var answer;
answers.forEach((currentAnsElem)=>{
if(currentAnsElem.checked){
answer=currentAnsElem.id;
}
})
return answer;
}
let score= 0;
const deselAll =()=>{
answers.forEach((ele)=>{ele.checked=false;})
}
sumbit.addEventListener('click',()=>{
const checkedAnswer =getCheckAnswer();
console.log(getCheckAnswer());
if(checkedAnswer===quizDB[questionCount].answer){
score++;
};
deselAll();
questionCount++;
console.log(questionCount);
if(questionCount<quizDB.length){
loadQuestion();
}else{
showScore.innerHTML=`
<h3>You Sored ${score}/${quizDB.length}😙</h3>
<button class = "btn" onclick ="location.reload()">PLAY AGAIN</button>`;
showScore.classList.remove('scoreArea');
}
});
console.log(questionCount);
console.log("hello world");
}).catch(function(error){
console.error('something wrong');
console.error(error);
});
// let showScore =document.querySelector('#showScore');
const getCheckAnswer =()=>{
var answer;
answers.forEach((currentAnsElem)=>{
if(currentAnsElem.checked){
answer=currentAnsElem.id;
}
})
return answer;
}
const deselAll =()=>{
answers.forEach((ele)=>{ele.checked=false;})
}
// let score=0;
// sumbit.addEventListener('click',()=>{
// const checkedAnswer =getCheckAnswer();
// console.log(getCheckAnswer());
// if(checkedAnswer==quizDB[questionCount].answer){
// score++;
// };
// deselAll();
// questionCount++;
// if(questionCount<quizDB.length){
// loadQuestion();
// }else{
// showScore.innerHTML=`
// <h3>You Sored ${score}/${quizDB.length}😙</h3>
// <button class = "btn" onclick ="location.reload()">PLAY AGAIN</button>`;
// showScore.classList.remove('scoreArea');
// }
// })
// const nextQuestion =()=>{
// questionCount++;
// deselAll();
// loadQuestion();
// }
// const prevQuestion =()=>{
// questionCount--;
// if(questionCount<=1){
// questionCount= quizDB.lenght
// }
// loadQuestion();
// }
|
/* eslint-env node, mocha */
const assert = require('assert');
const { Client } = require('../../../src/index.js');
const generateClient = require('../../seed/generated/generateRlayClient.js');
const { Kafka } = require('kafkajs');
const config = require('../../../config.js');
const kafkaClient = new Kafka({
brokers: [config.get('services.kafka.host')],
ssl: true,
sasl: {
mechanism: 'plain',
username: config.get('services.kafka.confluence_api_key'),
password: config.get('services.kafka.confluence_api_secret')
}
});
const producer = kafkaClient.producer()
let client;
const defaultPayload = {
"annotations": [],
"class_assertions": [],
"negative_class_assertions": [],
"object_property_assertions": [],
"negative_object_property_assertions": [],
"data_property_assertions": [],
"negative_data_property_assertions": [],
"type": "Individual"
}
describe('Rlay_Individual', () => {
before(async () => {
await producer.connect();
client = generateClient(new Client({
kafka: {
producer: producer,
topicName: config.get('services.kafka.topic_name')
}
}));
});
describe('.create', () => {
context('same property payload', () => {
it('produces same CID', async () => {
return client.Rlay_Individual.create({
httpConnectionClass: true,
});
// should create two messages at Kafka
});
});
});
});
|
import React from 'react';
import {Popover,Form,Input,Button,Select} from 'antd'
import BaseComponent from "./BaseComponent";
export default class PopoverWrapper extends BaseComponent {
close(){
this.setState({
popover:false
})
}
render() {
let { title,children,content} = this.props;
content = content({instance:this});
return (
<Popover placement="top" onVisibleChange={v=> this.setState({popover:v})} visible={this.state.popover} title={title} content={content} trigger="click">
<Button>{children}</Button>
</Popover>
)
}
}
|
const Keyboard = {
element: {
main: null, /* main keyboard element*/
keyContainer: null, /* keys container*/
keys: [] /* an array of buttons for the keys*/
},
eventHandlers: {
oninput: null /* fire off when keyboard gets input */
},
properties: { /* current state of keyboards*/
value: "", /* current value of keyboard */
capsLock: false,
Shift: false
},
init() { /* initialize the keyboard, this runs when page first loads */
// Create main element,
this.element.main = document.createElement("div"); /* "this" is equal to Keyboard object, create div element virtually inside the JS*/
this.element.keyContainer = document.createElement("div");
// Setup main element, adding classes and acutal keys
this.element.main.classList.add("keyboard"); /* add class keyboard to main div, plus add class keyboard--hidden*/
this.element.keyContainer.classList.add("keyboard__keys"); /* add class keyboard__keys to second div*/
this.element.keyContainer.appendChild(this._createKeys()); // add all created keys to KeyContainer
this.element.keys = this.element.keyContainer.querySelectorAll(".keyboard__key");
// Add to DOM
this.element.main.appendChild(this.element.keyContainer); /* make two divs child-parent relation*/
document.body.appendChild(this.element.main); /* add main keyboard element to physical DOM and all inside it*/
// let text = document.querySelectorAll(".use-keyboard-input").value;
// text += this.properties.value
document.querySelectorAll(".use-keyboard-input").forEach(element => { //select every textarea
this.press(element);
this._triggerEvents("oninput");
// this.changeLang()
this.open(element.value, currentValue => {
// console.log('test =' + currentValue);
element.value = currentValue;
});
});
},
changeLang() {
keyLayout2 = [
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "Backspace",
"й", "ц", "у", "к", "е", "н", "г", "ш", "щ", "з",
"CapsLock", "ф", "ы", "в", "а", "п", "р", "о", "л", "д", "Enter",
"Shift", "я", "ч", "с", "м", "и", "т", "ь", "б", "ю", ".",
" "
]
if (!this.properties.Shift) {
for (let i = 0; i < keyLayout.length; i++) {
this.element.keys[i].innerText = keyLayout2[i]
}
} else {
for (let i = 0; i < keyLayout.length; i++) {
this.element.keys[i].innerText = keyLayout[i]
}
}
this._triggerEvents("oninput");
},
_createKeys() { /* this going to create all HTML for each keys*/
const fragment = document.createDocumentFragment(); //fragment creates a virtual holder for child elements and inserts childs to the DOM
keyLayout = [
"1", "2", "3", "4", "5", "6", "7", "8", "9", "0", "Backspace",
"q", "w", "e", "r", "t", "y", "u", "i", "o", "p",
"CapsLock", "a", "s", "d", "f", "g", "h", "j", "k", "l", "Enter",
"Shift", "z", "x", "c", "v", "b", "n", "m", ",", ".", "?",
" "
];
//Create HTML for an icon
const createIconHTML = (icon_name) => {
return `<i class="material-icons">${icon_name}</i>`;
};
//For each key do next
//let keyLayout = this.;
keyLayout.forEach(key => {
const keyElement = document.createElement("button");
const insertLineBreak = ["Backspace", "p", "Enter", "з", ".", "?"].indexOf(key) !== -1; //if key equal to one of these in the array return true
//Add attribute/classes for each keyElement which is button
keyElement.setAttribute("type", "button");
keyElement.classList.add("keyboard__key");
keyElement.setAttribute("id", key);
//Create special keys
switch (key) {
case "Backspace":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = createIconHTML("backspace") //inserting icon inside button
keyElement.addEventListener("click", () => { //remove last character from object value
this.properties.value = this.properties.value.substring(0, this.properties.value.length - 1);
this._triggerEvents("oninput");
})
break;
case "CapsLock":
keyElement.classList.add("keyboard__key--wide", "keyboard__key--activatable");
keyElement.innerHTML = createIconHTML("keyboard_capslock") //inserting icon inside button
let listenCaps = (e) => {
if (e.key == key || e.button == 0) {
// event.getModifierState && event.getModifierState( 'CapsLock' );
this._toggleCapsLock();
this._triggerEvents("oninput");
keyElement.classList.toggle("keyboard__key--activate", this.properties.capsLock);
}
}
keyElement.addEventListener('click', listenCaps);
window.addEventListener('keydown', listenCaps);
// this._triggerEvents("oninput");
break;
case "Enter":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = createIconHTML("keyboard_return") //inserting icon inside button
keyElement.addEventListener("click", () => {
this.properties.value += "\n";
this._triggerEvents("oninput");
})
break;
case " ":
keyElement.classList.add("keyboard__key--extra-wide");
keyElement.innerHTML = createIconHTML("space_bar") //inserting icon inside button
keyElement.addEventListener("click", () => {
this.properties.value += " ";
this._triggerEvents("oninput");
})
break;
case "Shift":
keyElement.classList.add("keyboard__key--wide");
keyElement.innerHTML = createIconHTML("publish") //inserting icon inside button
let listenShift = (e) => {
console.log('test');
if (e.key == key) {
console.log(e.key);
this._toggleShift();
this.changeLang();
this._triggerEvents("oninput");
keyElement.classList.toggle(this.properties.Shift);
}
}
window.addEventListener('keydown', listenShift);
break;
default:
keyElement.textContent = key.toLowerCase(); //inserting actual text to buttons in lower case
keyElement.addEventListener("click", () => {
//appending pressed button key text to the properties value in lower or capital case
//console.log(this.properties.value);
this.properties.value += this.properties.capsLock ? key.toUpperCase() : key.toLowerCase();
this._triggerEvents("oninput");
})
break;
}
fragment.appendChild(keyElement); //adding keyElement(buttons) into fragment
if (insertLineBreak) {
fragment.appendChild(document.createElement("br")); //when insertLineBreak true insert br tag into fragment
}
});
return fragment;
},
_triggerEvents(handlerName) { /* this going to trigger on of the eventHandlers*/
if (typeof this.eventHandlers[handlerName] == "function") {
this.eventHandlers[handlerName](this.properties.value);
}
},
_toggleCapsLock() { /* toggling the capslock mode*/
this.properties.capsLock = !this.properties.capsLock;
for (const key of this.element.keys) {
if (key.childElementCount === 0) {
key.textContent = this.properties.capsLock ? key.textContent.toUpperCase() : key.textContent.toLowerCase();
}
}
},
_toggleShift() { /* toggling the Shift mode*/
this.properties.Shift = !this.properties.Shift;
for (const key of this.element.keys) {
// if (key.childElementCount === 0) {
// key.textContent = this.properties.Shift ? changeLang() :
// }
}
},
open(initialValue, oninput) { //may not needed, initialValue is initial value of keyboard
this.eventHandlers.oninput = oninput;
},
press(textField) { //may not needed
// const textField = document.querySelectorAll(".use-keyboard-input");
//this._triggerEvents("oninput");
textField.addEventListener("keydown", (e) => {
//this._triggerEvents("oninput");
this.element.keys.forEach(item => {
// console.log(e.key)
if (e.key == item.id) {
item.classList.add("keyboard__key--dark");
setTimeout(function () {
item.classList.remove("keyboard__key--dark");
}, 100)
}
})
})
}
};
window.addEventListener("DOMContentLoaded", function () { /*DOMcontentLoaded because there is no HTML tags for CSS to create, we run script before css*/
Keyboard.init(); /* call init method when DOM or HTML structure loaded*/
})
|
const color = "#000000"
const option = {
stroke: "#000000",
'stroke-width': 2,
'fill-opacity': 0,
};
App.Two = class {
constructor(app, svgElement){
this.app = app;
this.surface = SVG(svgElement.getAttribute('id'))
this.surface.attr('viewBox', [0, 0, svgElement.clientWidth, svgElement.clientHeight].join(' '))
this.element = svgElement
this.canvas = this.surface.group()
this.canvas.rect(40, 40).move(500, 180)
.attr('fill', 'yellow').attr('stroke', 'lightgray')
this.panZoom = svgPanZoom(this.surface.node,
{
viewportSelector: this.canvas,
haltEventListeners: [],
zoomEnabled: false,
panEnabled: false,
minZoom: 0.001,
maxZoom: 1000
});
this.shapes = []
this.index = 0;
this.app = app;
this.editIndex = 0;
this.currentLine;
this.parser = new DOMParser();
var draw = this;
document.addEventListener('keydown', function(e){
if(e.keyCode == 13){
if (app.mode === 'splines') {
draw.shapes[draw.index].draw('done');
draw.shapes[draw.index].off('drawstart');
console.log(draw.shapes[draw.index]);
var path = draw.shapes[draw.index].toCatmullRom().attr('fill', 'none');
draw.shapes[draw.index].node.remove()
app.three.extrusionFromPath(path);
}
else if (app.mode === 'polylines') {
draw.shapes[draw.index].draw('done');
draw.shapes[draw.index].off('drawstart');
app.three.extrusionFromPath(draw.shapes[draw.index]);
}
else if (app.mode === 'svg') {
console.log('svg mode enter');
console.log(draw.currentLine);
app.three.extrusionFromPath(draw.currentLine);
draw.currentLine.remove()
}
draw.index++;
}
});
}
get splines(){
var draw = this;
var app = this.app;
var shapes = this.shapes;
return {
mousedown: event => {
if (app.mode !== 'splines') return;
event.stopPropagation();
if (shapes[draw.index]) {
shapes[draw.index].draw('point', event);
} else {
const shape = draw.canvas.polyline().attr(option);
shapes[draw.index] = shape;
shape.draw(event);
}
},
mouseup: event => {},
mousemove: event => {},
}
}
get freehand(){
var draw = this;
var app = this.app;
var shapes = this.shapes;
return {
click: event => {},
mousedown: event => {
// if (app.mode !== 'freehand') return;
event.stopPropagation();
const shape = draw.canvas.polyline().attr(option);
shape.on('drawstart', function(e){ });
shapes[draw.index] = shape;
shape.draw(event);
},
mousemove: event => {
// if (app.mode !== 'freehand') return;
if (!shapes[draw.index]) return;
shapes[draw.index].draw('point', event);
},
mouseup: event => {
// if (app.mode !== 'freehand') return;
try {
shapes[draw.index].draw('stop', event);
// console.log(shapes[draw.index]);
var reduced = shapes[draw.index].toCatmullRom();
shapes[draw.index].remove();
reduced.simplify()
reduced.attr('stroke', 'black').attr('stroke-width', 2).attr('fill', 'none')
app.three.extrusionFromPath(reduced);
draw.index++;
} catch(e) {
console.log(e);
}
}
};
}
get polylines(){
var draw = this;
var app = this.app;
var shapes = this.shapes;
return {
mousedown: event => {
if (app.mode !== 'polylines') return;
// if (!event.ctrlKey) return
event.stopPropagation();
if (shapes[draw.index]) {
shapes[draw.index].draw('point', event);
} else {
const shape = draw.canvas.polyline().attr(option);
shapes[draw.index] = shape;
shape.draw(event);
}
},
mouseup: event => {},
mousemove: event => {},
}
}
get svg(){
var draw = this;
var app = this.app;
var shapes = this.shapes;
return {
mousedown: event => {
if (app.mode !== 'svg') return;
// if (!event.ctrlKey) return
console.log('svg click');
var svg = SVG.adopt($(event.target).get(0));
console.log(svg);
},
click: event => {},
mouseup: event => {},
mousemove: event => {},
}
}
get svgzoom(){
var draw = this;
var app = this.app;
var shapes = this.shapes;
return {
mousedown: event => {
},
mouseup: event => {},
mousemove: event => {},
click: event => {
console.log('svg click');
console.log(event);
var i = app.three.getIntersectingFace(event, true)
.filter(e => { return e.object.userData.svg })
.map(e => e.object);
app.three.vectorize(i)
},
}
}
get morph(){
var draw = this;
var app = this.app;
var shapes = this.shapes;
var events = this.freehand;
console.log(events);
events.mouseup = function(event){
shapes[draw.index].draw('stop', event);
var reduced = shapes[draw.index].toCatmullRom();
shapes[draw.index].remove();
reduced.simplify()
reduced.attr('stroke', 'black').attr('stroke-width', 2).attr('fill', 'none')
reduced.attr('class', 'reference');
reduced.attr('id', 'hullcurve');
var len = reduced.node.getTotalLength()
}
return events;
}
get none(){
return {
mousedown: event => {},
mouseup: event => {},
mousemove: event => {},
mouseclick: event => {},
}
}
}
App.Two.prototype.addNode = function(svg) {
console.log(svg);
console.log(this.canvas);
}
App.Two.prototype.editLine = function(){
var draw = this;
var app = this.app;
console.log(this.editIndex);
console.log(app.three.scene.children);
var c = app.three.scene
.children
.filter(e => {
return e.type == 'Mesh'
&& e.userData.svg
&& e.userData.camera
});
console.log(c);
if (c.length) {
if (draw.editIndex >= c.length) { draw.editIndex = 0 }
var i = draw.editIndex;
var camera = JSON.parse(c[i].userData.camera)
var svg = c[i].userData.svg;
console.log(draw.parser.parseFromString(svg, "image/svg+xml"));
console.log(draw.canvas);
// svg = svg.replace(/<path /, '<path stroke="DarkRed" fill="none" ');
var loader = new THREE.ObjectLoader();
app.three.scene.remove(c[i])
// app.three.animate()
loader.parse(camera, function(d){
draw.clearCanvas()
app.three.camera.copy(d);
app.three.camera.updateProjectionMatrix();
var s = draw.canvas.svg(svg);
draw.addNode(svg);
console.log(svg);
console.log(s);
// console.log(app.three.camera);
draw.editIndex++;
})
}
}
App.Two.prototype.clearCanvas = function(){
var n = this.canvas.node;
while (n.firstChild) { n.removeChild(n.firstChild) }
}
App.Two.prototype.createSVGPoint = function (v) {
var p = this.surface.node.createSVGPoint()
p.x = v.x; p.y = v.y
return p;
};
App.Two.prototype.unproject = function(vector3d, transform) {
var app = this.app;
var v = vector3d.clone();
v.project( app.three.camera );
v.x = Math.round( ( v.x + 1 ) * app.three.element.offsetWidth / 2 );
v.y = Math.round( ( - v.y + 1 ) * app.three.element.offsetHeight / 2 );
v.z = 0;
if (transform) {
var matrix = this.canvas.node.getCTM().inverse()
var p = this.surface.node.createSVGPoint()
p.x = v.x; p.y = v.y
p = p.matrixTransform(matrix)
v.x = p.x
v.y = p.y
}
return v;
}
App.Two.prototype.drawCatmullRom = function (data,alpha) {
var draw = this;
var app = this.app;
// console.log(data);
var element = this.canvas.path()
.fromPoints(data)
.attr('stroke', 'DarkRed')
.attr('fill', 'none')
return element;
}
App.Two.prototype.zoomAtPoint = function(z, p){ this.panZoom.zoomAtPoint(z, p) };
App.Two.prototype.panBy = function(d){ this.panZoom.panBy(d) };
|
import React from 'react';
import { Route, Redirect } from 'react-router-dom';
import SVG, { Circle, Defs, G, Line, Rect, Text, Use } from 'react-svg-draw';
const lineHeight = '8';
const solidLineDim = { height: lineHeight, width: 70, x:'0', y:'0' };
const dottedLineDim = { height: lineHeight, width: '32', x:'0', x2: '38', y:'0' };
const textDim = { x: 5, height: 25 };
const blockDim = { margin: { top: 5, bottom: 5, left: 5, right: 5 } };
const unitDim = { margin: { top: 5, bottom: 5, left: 5, right: 5 } };
export const SymbolDefs = () => (
<Defs>
<G id='solidLine'>
<Rect x={ solidLineDim.x } y={ solidLineDim.y } width={ solidLineDim.width } height={ solidLineDim.height } style={ solidLineStyle } />
</G>
<G id='dottedLine'>
<Rect x={ dottedLineDim.x } y={ dottedLineDim.y } width={ dottedLineDim.width } height={ dottedLineDim.height } style={ dottedLineStyle } />
<Rect x={ dottedLineDim.x2 } y={ dottedLineDim.y } width={ dottedLineDim.width } height={ dottedLineDim.height } style={ dottedLineStyle } />
</G>
</Defs>
)
export const Block = ({data}) => (
<SVG width={ solidLineDim.width + blockDim.margin.left + blockDim.margin.right } height={ lineHeight * 4 + textDim.height + blockDim.margin.top + blockDim.margin.bottom }>
<SymbolDefs />
<Use xlinkHref={lineStyle(data.line3)} x={ blockDim.margin.left } y={ lineHeight * 0 + blockDim.margin.top } />
<Use xlinkHref={lineStyle(data.line2)} x={ blockDim.margin.left } y={ lineHeight * 2 + blockDim.margin.top } />
<Use xlinkHref={lineStyle(data.line1)} x={ blockDim.margin.left } y={ lineHeight * 4 + blockDim.margin.top } />
<Text x={ blockDim.margin.left + textDim.x } y={ lineHeight * 4 + textDim.height + blockDim.margin.top } style={ textStyle }>{blockName(data)}</Text>
</SVG>
)
export const Unit = ({data}) => (
<SVG width={ solidLineDim.width + unitDim.margin.left + unitDim.margin.right } height={ lineHeight * 10 + textDim.height + unitDim.margin.top + unitDim.margin.bottom }>
<SymbolDefs />
<Use xlinkHref={lineStyle(data.line6)} x={ unitDim.margin.left } y={ lineHeight * 0 + unitDim.margin.top } />
<Use xlinkHref={lineStyle(data.line5)} x={ unitDim.margin.left } y={ lineHeight * 2 + unitDim.margin.top } />
<Use xlinkHref={lineStyle(data.line4)} x={ unitDim.margin.left } y={ lineHeight * 4 + unitDim.margin.top } />
<Use xlinkHref={lineStyle(data.line3)} x={ unitDim.margin.left } y={ lineHeight * 6 + unitDim.margin.top } />
<Use xlinkHref={lineStyle(data.line2)} x={ unitDim.margin.left } y={ lineHeight * 8 + unitDim.margin.top } />
<Use xlinkHref={lineStyle(data.line1)} x={ unitDim.margin.left } y={ lineHeight * 10 + unitDim.margin.top } />
<Text x={ unitDim.margin.left + textDim.x } y={ lineHeight * 10 + textDim.height + unitDim.margin.top } style={ textStyle }>{unitName(data)}</Text>
</SVG>
)
const solidLineStyle = {
stroke: '#006600',
fill: '#ee0000',
}
const dottedLineStyle = {
stroke: '#006600',
fill: '#0000ee',
}
const textStyle = {
}
const lineStyle = ( data ) => (
data ? '#solidLine' : '#dottedLine'
)
const blockName = (data) => {
var name = 'octagon.b';
name += data.line1 ? '1' : '0';
name += data.line2 ? '1' : '0';
name += data.line3 ? '1' : '0';
return data.t(name);
}
const unitName = (data) => {
var name = 'octagon.u';
name += data.line1 ? '1' : '0';
name += data.line2 ? '1' : '0';
name += data.line3 ? '1' : '0';
name += data.line4 ? '1' : '0';
name += data.line5 ? '1' : '0';
name += data.line6 ? '1' : '0';
return data.t(name);
}
|
const gulp = require('gulp');
const autoprefixer = require('gulp-autoprefixer');
gulp.task('autoprefixer', function(){
gulp.src('./dev/*.css')
.pipe(autoprefixer({
browsers: ['last 5 versions'],
cascade: true
}))
.pipe(gulp.dest('./site/'))
});
const htmlmin = require('gulp-htmlmin');
gulp.task('minify', function() {
return gulp.src('./dev/*.html')
.pipe(htmlmin({collapseWhitespace: true}))
.pipe(gulp.dest('./site/'))
});
var imageop = require('gulp-image-optimization');
gulp.task('images', function(cb) {
gulp.src(['./dev/img/**/*.png','src/**/*.jpg','src/**/*.gif','src/**/*.jpeg']).pipe(imageop({
optimizationLevel: 5,
progressive: true,
interlaced: true
})).pipe(gulp.dest('./site/img')).on('end', cb).on('error', cb);
});
gulp.task('default', ['minify', 'images', 'autoprefixer']);
|
// Members
import React from 'react';
import { Link, Route} from 'react-router-dom'
import styles from './style.css'
const Members = ({ match }) => {
return (
<div>
<h2>Member<b>s</b></h2>
<Link to={`${match.url}/member`}><button className={styles.menuButton}>Member</button></Link>
</div>
)
}
export default Members
|
module.exports = function (app) {
app.route('/logout')
.get(function (req, res) {
res.redirect('/login');
})
}
|
angular.module("EcommerceModule").controller("OrderListProducerController", function ($scope, $state, $mdDialog, OrderPageProducerService){
$scope.productData;
$scope.orderData = [];
var getData = function(callback){
OrderPageProducerService.getWaitingOrderDetail().then(
function(response){
$scope.productData = response.data.object;
callback();
},function(error){
console.log(error);
}
)
}
var getOrderData = function(){
if($scope.productData === null || $scope.productData === undefined || $scope.productData.length === 0)
return;
var orderDataIndex=1;
$scope.orderData.push($scope.productData[0].order);
$scope.orderData[0].statusDTO = $scope.productData[0].statusDTO;
for(var i = 1; i < $scope.productData.length; i++){
if($scope.orderData[orderDataIndex-1].idOrder !== $scope.productData[i].order.idOrder){
$scope.orderData.push($scope.productData[i].order);
$scope.orderData[orderDataIndex].statusDTO = $scope.productData[i].statusDTO;
orderDataIndex++;
}
}
}
var searchOrderDetailByOrder = function(orderId){
var orderDetail = [];
for(var i=0; i<$scope.productData.length; i++){
if($scope.productData[i].order.idOrder == orderId){
orderDetail.push($scope.productData[i]);
}
}
return orderDetail;
}
this.openDialog = function(idOrder, ev){
var orderDetail = searchOrderDetailByOrder(idOrder);
$mdDialog.show({
locals: { orderData: orderDetail},
controller: 'OrderDetailProducerDialogController',
controllerAs: "ctrl",
templateUrl: 'views/orderdetaildialog.html',
parent: angular.element(document.body),
targetEvent: ev,
clickOutsideToClose:true,
})
}
this.inprocess = function(orderId, index){
$mdDialog.show(
$mdDialog.confirm()
.clickOutsideToClose(true)
.title('Notification')
.textContent('Do you want to change to in-process status')
.ariaLabel('Alert Dialog Demo')
.ok('Yes')
.cancel("Cancel")
).then(function(){
var data = {
order: {
idOrder: orderId
},
product:{
userDTO:{
userId: ""
}
}
}
OrderPageProducerService.inprocess(data).then(
function(response){
if(response.data.status == 0)
$scope.orderData.splice(index, 1);
else {
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title('Notification')
.textContent("Can't change status, the order has been cancelled")
.ariaLabel('Alert Dialog Demo')
.ok('Yes')
).then(function(){
$state.reload();
})
}
}, function(error){
console.log(error);
}
)
}, function(){})
}
this.fail = function(orderId, index){
$mdDialog.show(
$mdDialog.confirm()
.clickOutsideToClose(true)
.title('Notification')
.textContent('Do you want to change to fail status')
.ariaLabel('Alert Dialog Demo')
.ok('Yes')
.cancel("Cancel")
).then(function(){
var data = {
order: {
idOrder: orderId
},
product:{
userDTO:{
userId: ""
}
}
}
OrderPageProducerService.fail(data).then(
function(response){
if(response.data.status == 0)
$scope.orderData.splice(index, 1);
else {
$mdDialog.show(
$mdDialog.alert()
.clickOutsideToClose(true)
.title('Notification')
.textContent("Can't change status, please reload to update data")
.ariaLabel('Alert Dialog Demo')
.ok('Yes')
).then(function(){
$state.reload();
})
}
}, function(error){
console.log(error);
}
)
}, function(){})
}
getData(getOrderData);
});
|
// scripts.js
var a = prompt("Podaj wartość a:"),
b = prompt("Podaj wartość b:"),
value = (a * a) + (2 * a * b) - (b * b);
console.log('Wynik działania (a * a) + (2 * a * b) - (b * b), gdzie a: ' + a + 'i b: ' + b + ' wynosi: ' + value);
if (value > 0) {
console.log("Wynik dodatni");
} else if (value < 0) {
console.log("Wynik ujemny");
} else {
console.log("Wynik wynosi 0");
}
|
'use strict'
// relative paths (this is to ensure that everything resolves appropriately)
require('app-module-path').addPath(__dirname)
// libs
const sinon = require('sinon')
const expect = require('chai').expect
const chai = require('chai')
const spies = require('chai-spies')
chai.use(spies)
// App
const App = require('../index')
const env = require('../.env')
describe('Db class', function () {
it(`Can connect to mongo database on localhost:${env.mongoDbPort}`, () => {
var spy = sinon.spy()
const Db = require('../inc/db') // will throw error if mongo is not accessible, so rest is for consistency
// set a spy on Db.emit('ready')
Db.on('ready', spy)
// wait for it
setTimeout(() => {
// be sure Db is ready called
sinon.assert.calledOnce(spy)
}, 1000)
})
})
|
const express = require('express');
const TacoController = require('../controllers/TacoController');
const router = express.Router();
const tacoController = new TacoController();
router.get('/', tacoController.get);
router.get('/:id', tacoController.getById);
module.exports = router;
|
import React from 'react';
import {Provider} from 'react-redux';
import {BrowserRouter as Router, Route , Switch} from 'react-router-dom';
import store from './Redux/store';
//Views
import Home from './Views/Home/Home.jsx';
import Receta from './Views/Receta/Receta.jsx';
import SignUp from './Views/SignUp/SignUp.jsx';
import Login from './Views/Login/Login.jsx';
import Ruta from './Views/RotasExtras/Ruta.jsx';
const App=()=> {
return (
<Provider store={store}>
<Router>
<Switch>
<Route exact path="/" component={Home}/>
<Route exact path="/receta/:id" render={props=>{
return(
<Receta id={props.match.params.id}/>
);
}} />
<Route exact path="/signUp" component={SignUp}/>
<Route exact path="/login" component={Login}/>
<Route exact path="/ruta/:id" render={props=>{
return(
<Ruta id={props.match.params.id}/>
);
}} />
<Route path='*' render={()=>{
return(
<div>Vuelve al inicio rufian</div>
)
}}/>
</Switch>
</Router>
</Provider>
);
}
export default App;
|
const repeater = (string, n) => {
return string.repeat(n);
}
|
// Saves options to chrome.storage
function save_options() {
localStorage['leftWidth'] = document.getElementById('leftWidth').value;
var calendarLeft = document.getElementById('calendarLeft').checked;
if(calendarLeft == true)
localStorage['calendarLeft'] = "true";
else
localStorage['calendarLeft'] = "false";
var status = document.getElementById('status');
status.textContent = 'Options saved.';
setTimeout(function() {
status.textContent = '';
}, 750);
}
// Restores select box and checkbox state using the preferences
function restore_options(options) {
document.getElementById('leftWidth').value = options.leftWidth;
if(options.calendarLeft == "true")
document.getElementById('calendarLeft').checked = true;
else
document.getElementById('calendarLeft').checked = false;
}
document.addEventListener('DOMContentLoaded', function() {
chrome.runtime.sendMessage({method: "load"}, restore_options);
});
document.addEventListener('click', save_options);
|
module.exports = {
'url':process.env.STACKABLES_MONGO_URI || process.env.LOCAL_MONGO_URI || process.env.MONGOLAB_URI || null
};
|
dojo.provide("dojox.validate.tests.creditcard");
dojo.require("dojox.validate.creditCard");
tests.register("dojox.validate.tests.creditcard",
[{
name:"isValidLuhn",
runTests: function(tests) {
tests.t(dojox.validate.isValidLuhn('5105105105105100')); //test string input
tests.t(dojox.validate.isValidLuhn('5105-1051 0510-5100')); //test string input with dashes and spaces (commonly used when entering card #'s)
tests.t(dojox.validate.isValidLuhn(38520000023237)); //test numerical input as well
tests.f(dojox.validate.isValidLuhn(3852000002323)); //testing failures
tests.t(dojox.validate.isValidLuhn(18)); //length doesnt matter
tests.f(dojox.validate.isValidLuhn(818181)); //short length failure
}
},
{
name:"isValidCvv",
runTests: function(tests) {
tests.t(dojox.validate.isValidCvv('123','mc')); //string is ok
tests.f(dojox.validate.isValidCvv('5AA','ec')); //invalid characters are not ok
tests.t(dojox.validate.isValidCvv(723,'mc')); //numbers are ok too
tests.f(dojox.validate.isValidCvv(7234,'mc')); //too long
tests.t(dojox.validate.isValidCvv(612,'ec'));
tests.t(dojox.validate.isValidCvv(421,'vi'));
tests.t(dojox.validate.isValidCvv(543,'di'));
tests.t(dojox.validate.isValidCvv('1234','ax'));
tests.t(dojox.validate.isValidCvv(4321,'ax'));
tests.f(dojox.validate.isValidCvv(43215,'ax')); //too long
tests.f(dojox.validate.isValidCvv(215,'ax')); //too short
}
},
{
name:"isValidCreditCard",
runTests: function(tests) {
//misc checks
tests.t(dojox.validate.isValidCreditCard('5105105105105100','mc')); //test string input
tests.t(dojox.validate.isValidCreditCard('5105-1051 0510-5100','mc')); //test string input with dashes and spaces (commonly used when entering card #'s)
tests.t(dojox.validate.isValidCreditCard(5105105105105100,'mc')); //test numerical input as well
tests.f(dojox.validate.isValidCreditCard('5105105105105100','vi')); //fails, wrong card type
//Mastercard/Eurocard checks
tests.t(dojox.validate.isValidCreditCard('5105105105105100','mc'));
tests.t(dojox.validate.isValidCreditCard('5204105105105100','ec'));
tests.t(dojox.validate.isValidCreditCard('5303105105105100','mc'));
tests.t(dojox.validate.isValidCreditCard('5402105105105100','ec'));
tests.t(dojox.validate.isValidCreditCard('5501105105105100','mc'));
//Visa card checks
tests.t(dojox.validate.isValidCreditCard('4111111111111111','vi'));
tests.t(dojox.validate.isValidCreditCard('4111111111010','vi'));
//American Express card checks
tests.t(dojox.validate.isValidCreditCard('378 2822 4631 0005','ax'));
tests.t(dojox.validate.isValidCreditCard('341-1111-1111-1111','ax'));
//Diners Club/Carte Blanch card checks
tests.t(dojox.validate.isValidCreditCard('36400000000000','dc'));
tests.t(dojox.validate.isValidCreditCard('38520000023237','bl'));
tests.t(dojox.validate.isValidCreditCard('30009009025904','dc'));
tests.t(dojox.validate.isValidCreditCard('30108009025904','bl'));
tests.t(dojox.validate.isValidCreditCard('30207009025904','dc'));
tests.t(dojox.validate.isValidCreditCard('30306009025904','bl'));
tests.t(dojox.validate.isValidCreditCard('30405009025904','dc'));
tests.t(dojox.validate.isValidCreditCard('30504009025904','bl'));
//Discover card checks
tests.t(dojox.validate.isValidCreditCard('6011111111111117','di'));
//JCB card checks
tests.t(dojox.validate.isValidCreditCard('3530111333300000','jcb'));
tests.t(dojox.validate.isValidCreditCard('213100000000001','jcb'));
tests.t(dojox.validate.isValidCreditCard('180000000000002','jcb'));
tests.f(dojox.validate.isValidCreditCard('1800000000000002','jcb')); //should fail, good checksum, good prefix, but wrong length'
//Enroute card checks
tests.t(dojox.validate.isValidCreditCard('201400000000000','er'));
tests.t(dojox.validate.isValidCreditCard('214900000000000','er'));
}
},
{
name:"isValidCreditCardNumber",
runTests: function(tests) {
//misc checks
tests.t(dojox.validate.isValidCreditCardNumber('5105105105105100','mc')); //test string input
tests.t(dojox.validate.isValidCreditCardNumber('5105-1051 0510-5100','mc')); //test string input with dashes and spaces (commonly used when entering card #'s)
tests.t(dojox.validate.isValidCreditCardNumber(5105105105105100,'mc')); //test numerical input as well
tests.f(dojox.validate.isValidCreditCardNumber('5105105105105100','vi')); //fails, wrong card type
//Mastercard/Eurocard checks
tests.is("mc|ec", dojox.validate.isValidCreditCardNumber('5100000000000000')); //should match 'mc|ec'
tests.is("mc|ec", dojox.validate.isValidCreditCardNumber('5200000000000000')); //should match 'mc|ec'
tests.is("mc|ec", dojox.validate.isValidCreditCardNumber('5300000000000000')); //should match 'mc|ec'
tests.is("mc|ec", dojox.validate.isValidCreditCardNumber('5400000000000000')); //should match 'mc|ec'
tests.is("mc|ec", dojox.validate.isValidCreditCardNumber('5500000000000000')); //should match 'mc|ec'
tests.f(dojox.validate.isValidCreditCardNumber('55000000000000000')); //should fail, too long
//Visa card checks
tests.is("vi", dojox.validate.isValidCreditCardNumber('4111111111111111')); //should match 'vi'
tests.is("vi", dojox.validate.isValidCreditCardNumber('4111111111010')); //should match 'vi'
//American Express card checks
tests.is("ax", dojox.validate.isValidCreditCardNumber('378 2822 4631 0005')); //should match 'ax'
tests.is("ax", dojox.validate.isValidCreditCardNumber('341-1111-1111-1111')); //should match 'ax'
//Diners Club/Carte Blanch card checks
tests.is("dc|bl", dojox.validate.isValidCreditCardNumber('36400000000000')); //should match 'dc|bl'
tests.is("dc|bl", dojox.validate.isValidCreditCardNumber('38520000023237')); //should match 'dc|bl'
tests.is("dc|bl", dojox.validate.isValidCreditCardNumber('30009009025904')); //should match 'di|bl'
tests.is("dc|bl", dojox.validate.isValidCreditCardNumber('30108009025904')); //should match 'di|bl'
tests.is("dc|bl", dojox.validate.isValidCreditCardNumber('30207009025904')); //should match 'di|bl'
tests.is("dc|bl", dojox.validate.isValidCreditCardNumber('30306009025904')); //should match 'di|bl'
tests.is("dc|bl", dojox.validate.isValidCreditCardNumber('30405009025904')); //should match 'di|bl'
tests.is("dc|bl", dojox.validate.isValidCreditCardNumber('30504009025904')); //should match 'di|bl'
//Discover card checks
tests.is("di", dojox.validate.isValidCreditCardNumber('6011111111111117')); //should match 'di'
//JCB card checks
tests.is("jcb", dojox.validate.isValidCreditCardNumber('3530111333300000')); //should match 'jcb'
tests.is("jcb", dojox.validate.isValidCreditCardNumber('213100000000001')); //should match 'jcb'
tests.is("jcb", dojox.validate.isValidCreditCardNumber('180000000000002')); //should match 'jcb'
tests.f(dojox.validate.isValidCreditCardNumber('1800000000000002')); //should fail, good checksum, good prefix, but wrong length'
//Enroute card checks
tests.is("er", dojox.validate.isValidCreditCardNumber('201400000000000')); //should match 'er'
tests.is("er", dojox.validate.isValidCreditCardNumber('214900000000000')); //should match 'er'
}
}
]);
|
// React
import React, { useState, useEffect } from 'react';
import API from '../utils/API';
import BookCover from '../components/BookCover';
import GenreSelect from '../components/GenreSelect';
import LikeDislike from '../components/LikeDislike';
import TextBox from '../components/TextBox';
const AppFrame = ({ ...props }) => {
const [loading, setLoading] = useState(false);
const [books, setBooks] = useState([]);
const [genre, setGenre] = useState('');
const [genreList, setGenreList] = useState([]);
const [activeBook, setActiveBook] = useState('');
const [activeBookIndex, setActiveBookIndex] = useState(0);
const [maxCount, setMaxCount] = useState(0);
useEffect(() => {
getGenre();
}, []);
useEffect(() => {
// On first render we don't call for books until user selects genre
if (genreList.length > 0 && genre) {
getBooks();
}
}, [genre, genreList]);
// Loads genre type to call for book list
async function getGenre() {
setLoading(true);
try {
var response = await API.getGenre();
setGenreList(response.data.results);
setGenre(response.data.results[0].list_name_encoded);
} catch (error) {
console.error(genreList);
}
}
// Loads all books and sets them to books
async function getBooks() {
try {
var response = await API.getBooks(genre);
setBooks(response.data.results.books);
setMaxCount(response.data.num_results);
setLoading(false);
} catch (error) {
console.error(error);
}
setLoading(false);
}
const handleNext = () => {
setActiveBookIndex((prevActiveBookIndex) => prevActiveBookIndex + 1);
setActiveBook(books[activeBookIndex]);
};
const handleSaveBook = (book) => {
setActiveBookIndex((prevActiveBookIndex) => prevActiveBookIndex + 1);
setActiveBook(books[activeBookIndex]);
// Write logic to connect with API for saving book to library
console.log(`Just added ${activeBook.title} to favorite`);
};
return (
!loading && (
<div>
<BookCover image={books.length > 0 ? books[activeBookIndex].book_image : null} />
<GenreSelect selectOptions={genreList} setGenre={(value) => setGenre(value)} />
<LikeDislike
onHandleSave={handleSaveBook}
onHandleNext={handleNext}
disabled={activeBookIndex === maxCount - 1}
/>
<TextBox bookDetails={books[activeBookIndex]} genre={genre} />
</div>
)
);
};
export default AppFrame;
|
import React from 'react';
import Mixin from './Mixin.jsx'
const Elem = (props) => <div><button className="btn btn-primary" onClick={props.update}>You have clicked me <span className="badge">{props.value}</span> times!</button><br/><br/></div>
export default Elem;
|
import { Logger } from './Logger';
export const DEFAULT_LOGGER = new Logger();
if (!global.METALOG) {
global.METALOG = DEFAULT_LOGGER.log.bind(DEFAULT_LOGGER);
}
export * from './Level';
export * from './LevelSpec';
export * from './Logger';
|
// 优惠管理
SystemLogManagePanel = Ext.extend(Disco.Ext.CrudPanel, {
id: "systemLogManagePanel",
baseUrl: "systemLog.java",
gridSelModel: 'checkbox',
batchRemoveMode: true,
pageSize: 20,
showView: false,
showAdd: false,
showEdit: true,
baseQueryParameter : {
types : 1
},
showRemove:false,
storeMapping: ["id", "user", "vdate","ip","action","cmdName","params"],
initComponent: function() {
this.cm = new Ext.grid.ColumnModel([{
header: "访问者",
sortable: true,
width: 100,
dataIndex: "user",renderer : this.objectRender("name")
},{
header: "访问时间",
sortable: true,
width: 100,
dataIndex: "vdate",renderer:function(v){
var date = new Date(v);
return date.toLocaleString();
}
},{
header: "访问者ip",
sortable: true,
width: 100,
dataIndex: "ip"
},{
header: "访问的action",
sortable: true,
width: 100,
dataIndex: "action"
},{
header: "访问的方法",
sortable: true,
width: 100,
dataIndex: "cmdName",renderer:function(v){return v||"doInit"}
},{
header: "说明",
sortable: true,
width: 100,
dataIndex: "params"
}]);
SystemLogManagePanel.superclass.initComponent.call(this);
}
});
|
function showDistance(speed, time) {
alert(speed * time);
}
showDistance(10, 5);
showDistance(85, 1.5);
showDistance(12, 9);
showDistance(42, 21);
|
const Moniker = require("moniker");
const names = Moniker.generator([
Moniker.adjective,
Moniker.noun,
Moniker.verb,
]);
export default async function handler(req, res) {
res.json(names.choose());
}
|
var maxSumAfterPartitioning = function(A, K) {
let bigArr = [];
let i = 0;
while (i < A.length) {
}
};
|
var texts;
var randquote;
//Tells our console the bot is starting
console.log("The Bot is Starting Now!");
//Require twit package
var Twit = require('twit');
var fs = require('fs');
//comment
preload();
function preload(){
texts = fs.readFileSync("Greetings.txt", "utf8").toString().split("\n");
console.log(texts);
picking();
}
//We need to authemticate our twitter
var T = new Twit({
consumer_key: '73CAn0rBEkLvHHXBPuR4YRoJ2',
consumer_secret: 'rPss5pUsCkwdhKzCYp40vVvubT2yVRLY1W9ZDEXeIjFVBdQsnW',
access_token: '847899075831672833-pRvmEizc9R5pcbAuUQvg2GAPn0SKkUf',
access_token_secret: 'iaEYdqRVeQWzbzWOwtKu70g2YjsvsMfcaCVLp0nfjl8UK',
timeout_ms: 60 * 1000, // optional HTTP request timeout to apply to all requests.
})
//GET = searches twitter by #, location, user, etc.
//POST = Posts tweets
//STREAM = Follows, you can @ them, mentions, you can @ them.
//
// search twitter for all tweets containing the word 'banana' since July 11, 2011
//
/*
var parameters = {
q: 'apple since:2011-07-11',
count: 2,
lang: 'en'
}
T.get('search/tweets', parameters, gotData);
function gotData(err, data, response){
var tweets = data.statuses;
for(var i = 0; i < tweets.length; i++){
console.log(data.statuses[i].text);
}
}
var tweet = {
status: 'hello world!'
}
T.post('statuses/update', tweet, gotData);
*/
/*Post Tweet*/
tweetIt();
//set Interval(tweetIt, 1000*45);
function tweetIt() {
//Find a random #1-100 and multiply by 100, and then round down.
var r = Math.floor(Math.random() * 100);
var tweet = {
status: 'Here is the current random number ' + r + ' #ProvidenceHigh #PHS #ecs #MEMES'
}
T.post('statuses/update', tweet, gotData);
function gotData(err, data, response) {
if (err) {
console.log("Something went wrong!");
} else {
console.log("It Posted!");
}
}
}
//stream function
followTweet();
function followTweet() {
var stream = T.stream('user');
//anytime I gain a follower
picking();
stream.on('follow', followed);
function followed(eventMsg){
var name = eventMsg.source.name;
var screenName = eventMsg.source.screen_name;
picking();
tweetIt2('.@' + screenName + " " + randquote);
console.log('Finished Tweet Json');
var json = JSON.stringify(eventMsg, null, 2);
fs.writeFile("#tweet.json", json);
}
}
function tweetIt2(txt){
var tweet = {
status: txt
}
T.post('statuses/update', tweet, tweeted);
function tweeted(err, data, response){
if (err){
console.log("Something went wrong!");
}
else
{
console.log("You were followed.");
}
}
}
/*var exec = require('child_process').exec;
var cmd = '"C:\Users\17reed.jacob\Desktop\P5ECS-Jacob\processing-3.3\processing-java.exe" --sketch="C:\Users\17reed.jacob\Desktop\P5ECS-Jacob\Lesson 20\circlesketch" --run';
exec(cmd, processing);*/
/*
var fs = require('fs');
processing();
function processing(eventMsg){
//console.log('Finished Image!');
//var json - JSON.stringify(eventMsg, null, 2);
// fs.writeFile("#tweet.json", json);
}
*/
function picking() {
randquote = texts[Math.floor(Math.random() * texts.length)];
console.log(randquote);
}
|
function reverseInParentheses(inputString) {
if (inputString.length < 1) return "";
let level = 0;
let newstring = "";
let lookup = new Array(inputString.length);
lookup.fill("")
for (let i = 0; i < inputString.length; i++) {
let char = inputString[i];
if (char !== "(" && char !== ")") {
lookup[level] = lookup[level].concat(char);
} else if (char === "(") {
level+=1;
// i+=1;
// char = inputString[i];
// lookup[level] = lookup[level].concat(char)
} else {
// i+=1;
lookup[level-1] = lookup[level-1].concat(reverse(lookup[level]))
level-=1;
lookup[level+1] = "";
}
}
// console.log(lookup)
return lookup[0];
}
function reverse(str) {
let newstr = ""
for (let i = str.length-1; i >= 0; i--) {
newstr = newstr.concat(str[i]);
}
return newstr;
}
// console.log(reverseInParentheses("(bar)"))
console.log(reverseInParentheses("foo(bar(baz))blim"))
|
document.addEventListener('DOMContentloaded', () => {
let tl = new TimelineMax();
tl.fromTo('.bg-loader', 1,
{ width: '100%' },
{ width: '0%', ease: Expo.easeInOut })
}
)
|
const users = [
{ name: 'Mark', gender: 'male', salary: '1500' },
{ name: 'Igor', gender: 'male', salary: '500' },
{ name: 'Anna', gender: 'female', salary: '1000' },
{ name: 'John', gender: 'male', salary: '2100' },
{ name: 'Oleh', gender: 'male', salary: '3000' },
{ name: 'Mary', gender: 'female', salary: '1500' },
{ name: 'Pit', gender: 'male', salary: '750' },
{ name: 'Bred', gender: 'male', salary: '1050' },
{ name: 'Tom', gender: 'male', salary: '1500' },
{ name: 'Jery', gender: 'female', salary: '1800' },
{ name: 'Serj', gender: 'male', salary: '2000' },
];
const createElement = (tag, content) => {
const element = document.createElement(tag);
element.innerText = content;
return element;
}
const appendArray = (htmlEl, arrayEls) => {
arrayEls.map(el => htmlEl.appendChild(el))
return htmlEl;
}
const innerTablesRows = users.map((el, i) => {
const index = createElement('th', i + 1);
const name = createElement('td', el.name);
const gender = createElement('td', el.gender);
const salary = createElement('td', el.salary);
return appendArray(
document.createElement('tr'),
[index, name, gender, salary]
);
});
const tbody = document.createElement('tbody')
innerTablesRows.map(el => tbody.appendChild(el));
const index = createElement('th', '#');
const name = createElement('th', 'Name');
const gender = createElement('th', 'Gender');
const salary = createElement('th', 'Salary');
const thead = document.createElement('thead');
const tr = document.createElement('tr');
appendArray(tr, [index, name, gender, salary])
thead.appendChild(tr);
const table = document.createElement('table');
appendArray(table,[thead,tbody])
document.getElementsByClassName('col-12')[0].appendChild(table);
|
'use strict';
import gulp from 'gulp';
import RevAll from 'gulp-rev-all';
import awspublish from 'gulp-awspublish';
import cloudfront from 'gulp-cloudfront';
gulp.task('deploy', function() {
let bucket = 'embed-viewsay',
distributionId = "E1A0KLTDNUDEVM";
if (global.env === "staging") {
bucket = 'embed-staging-viewsay';
distributionId = "E3V4HELJ0ILRJN";
}
const aws = {
"key": "AKIAILU7O2X5ZUUVNE2Q",
"secret": "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",
"accessKeyId": 'AKIAILU7O2X5ZUUVNE2Q',
"secretAccessKey": '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',
"region": "us-east-1",
"distributionId": distributionId,
"params": {
"Bucket" : bucket
},
"patternIndex": /^\/viewsayIframeApi\.[a-f0-9]{8}\.js(\.gz)*$/gi
};
var publisher = awspublish.create(aws),
headers = {'Cache-Control': 'max-age=60, no-transform, public'},
revAll = new RevAll({
dontRenameFile: ['.png','.jpg'],
dontUpdateReference : ['.png','.jpg']
});
return gulp.src('build/**')
.pipe(revAll.revision())
.pipe(awspublish.gzip())
.pipe(publisher.publish(headers))
.pipe(publisher.cache())
.pipe(awspublish.reporter({
states: ['create', 'update', 'delete']
}))
.pipe(cloudfront(aws));
});
|
import "./style.css";
import { useState } from "react";
import ErrorForm from "../ErrorForm";
// para el registro (nuevo usuario) tenemos 2 imputs para el email y la password
const FormularioRegistro = () => {
const [email, setEmail] = useState("");
const [contraseña, setContraseña] = useState("");
const [error, setError] = useState("");
const [echo, setEcho] = useState(false);
// para hacer la logica del formulario le ponemos un onSubmit, es decir cuando el formulario
// se envie ejecutamos la funcion registro que es asyncrona y va a recibir un evento
const registro = async (e) => {
e.preventDefault();
const res = await fetch(`${process.env.REACT_APP_BACKEND_URL}/usuarios`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ email, contraseña }),
});
if (res.ok) {
setError("");
setEcho(true);
} else {
const error = await res.json();
setError(error.message);
}
};
// para no tener que repetirlo siempre hago un componente para los errores
// ademas si todo va bien y recibimos el email y la contraseña quiero que desaparezca el formulario (lo meto entre llaves)
// y uso echo para que aparezca un mensaje de "Te has registrado correctamente. Revisa tu correo para validar tu cuenta"
// !echo - false sacame el formulario sino sacame un div con el mensaje
return (
<>
{!echo ? (
<form className="registro_formulario" onSubmit={registro}>
<div className="contenedor_input">
<label htmlForm="email">Email</label>
<input
id="email"
name="email"
type="email"
value={email}
onChange={(e) => {
setEmail(e.target.value);
}}
></input>
</div>
<div className="contenedor_input">
<label htmlForm="password">Contraseña</label>
<input
id="password"
name="password"
type="password"
value={contraseña}
onChange={(e) => setContraseña(e.target.value)}
></input>
</div>
<input type="submit" value="Registrarse" />
</form>
) : (
<div className="confirmacion_registro">
Te has registrado correctamente. Revisa tu email para validar tu
cuenta
</div>
)}
{error && <ErrorForm error={error} />}
</>
);
};
export default FormularioRegistro;
|
var dir_84d4ec99856759213102e4209c09c524 =
[
[ "backtrace.c", "backtrace_8c.html", "backtrace_8c" ],
[ "common.c", "common_8c.html", "common_8c" ],
[ "graphviz.c", "graphviz_8c.html", "graphviz_8c" ],
[ "lib.h", "debug_2lib_8h.html", "debug_2lib_8h" ],
[ "notify.c", "debug_2notify_8c.html", "debug_2notify_8c" ],
[ "parse_test.c", "parse__test_8c.html", "parse__test_8c" ],
[ "window.c", "debug_2window_8c.html", "debug_2window_8c" ]
];
|
import {
MESSAGES_LOADING,
MESSAGES_LOADED,
SET_CURRENT_MESSAGE,
SEND_MESSAGE,
UPDATE_MESSAGE,
DELETE_MESSAGE,
} from '../actions/types';
const initialState = {
messages: [],
currentMessage: {},
loading: true,
};
export default function (state = initialState, action) {
const { type, payload } = action;
switch (type) {
case MESSAGES_LOADING:
return {
...state,
loading: true,
};
case MESSAGES_LOADED:
return {
...state,
messages: payload,
loading: false,
};
case SET_CURRENT_MESSAGE:
return {
...state,
currentMessage: payload,
loading: false,
};
case SEND_MESSAGE:
return {
...state,
messages: [...state.messages, payload],
loading: false,
};
case UPDATE_MESSAGE:
return {
...state,
currentMessage: payload,
};
case DELETE_MESSAGE:
return {
...state,
messages: state.messages.filter(
(message) => message._id !== payload.id
),
};
default:
return state;
}
}
|
let express = require('express');
let router = express.Router();
let User = require('../models/User');
let Content = require('../models/Content');
let responseData;
router.use((req,res,next) => {
// 防止下次请求的时候把上次的结果给带上
responseData = {
code: 0,
message: ''
};
next();
})
/**
* 用户名不能为空
* 密码不能为空
* 两次输入密码必须一致
*
* 用户名是否已经注册 => 查询数据库
*/
router.post('/user/register', (req, res) => {
let {username, password, repassword} = req.body;
if(username === "") {
responseData.code = 1;
responseData.message = '用户名不能为空';
return res.json(responseData);
}
if(password === "") {
responseData.code = 2;
responseData.message = '密码不能为空';
return res.json(responseData);
}
if (password !== repassword) {
responseData.code = 3;
responseData.message = '两次输入的密码不一样';
return res.json(responseData);
}
User.findOne({
username: username
}).then((userInfo) => {
if(userInfo) {
// 数据库中有
responseData.code = 4;
responseData.message = '用户已经被注册';
return res.json(responseData);
}
// 保存
let user = new User({
username,
password
});
return user.save();
}).then((newUserInfo) => {
responseData.message = '注册成功';
res.json(responseData);
});
});
/**
* 登录
*/
router.post('/user/login', (req, res) => {
let {username,password} = req.body;
if(username === "" || password === "") {
responseData.code = 1;
responseData.message = '用户名或密码不能为空';
return res.json(responseData);
}
User.findOne({
username,
password
}).then((userInfo) => {
if(!userInfo) {
responseData.code = 2;
responseData.message = '用户名或密码错误';
return res.json(responseData);
}
responseData.message = '登录成功';
responseData.userInfo = {
_id: userInfo._id,
username: userInfo.username
};
// 登录成功设置 cookie
req.cookies.set('userInfo', JSON.stringify({
_id: userInfo._id,
username: userInfo.username
}));
return res.json(responseData);
})
});
// 退出
router.get('/user/logout', (req, res) => {
// 清除cookie
req.cookies.set('userInfo', null);
return res.json(responseData);
});
// 获取指定文章的所有评论
router.get('/comment', (req, res) => {
let contentId = req.query.contentid || "";
Content.findOne({
_id: contentId
}).then(content => {
responseData.data = content.comments;
res.json(responseData);
})
});
// 评论
router.post('/comment/post', (req, res) => {
// 内容的 id
let contentId = req.body.contentid || '';
let postData = {
username: req.userInfo.username,
postTime: new Date(),
content: req.body.content
};
// 查询
Content.findOne({
_id: contentId
}).then(content => {
content.comments.push(postData);
return content.save();
}).then(newContent => {
// save的结果
responseData.message = "评论成功";
responseData.data = newContent;
res.json(responseData);
});
});
module.exports = router;
|
"use strict";
let popup = new PopupUtils();
$(function () {
$("#loginBtn").click(function () {
let userName = $("input[name=userName]").val();
let pwd = $("input[name=password]").val();
if (!userName || userName.length < 6) {
popup.layerTips("账号格式错误!");
return false;
} else if (!pwd || pwd.length < 6 || pwd.length > 18) {
popup.layerTips("密码格式错误!");
return false;
}
ajax.sendRequest({
url: "/users/login",
data: $("#loginForm").serialize(),
success: function (data) {
if (data.code === 0) {
popup.layerTips(data.message);
} else {
window.location.href = "/";
}
}, error: function (err) {
console.log(err);
}
})
})
});
|
/**@jsx jsx */
import React, { Fragment } from 'react';
import { jsx, Styled, Flex, Badge } from 'theme-ui';
import { graphql } from 'gatsby';
import Img from 'gatsby-image';
import MDXRenderer from 'gatsby-plugin-mdx/mdx-renderer';
import moment from 'moment';
// importing this locale set the global to french
import 'moment/locale/fr';
import Layout from '../components/Layout';
import Link from '../components/Link';
import SEO from '../components/Seo';
const Category = ({ category, categorySlug }) => (
<Flex
sx={{
flexDirection: 'raw',
justifyContent: 'end',
}}
>
<Badge key={categorySlug} variant="outline" mx="1">
<Link
sx={{
color: 'inherit',
textDecoration: 'none',
}}
to={`/category/${categorySlug}`}
>
{category}
</Link>
</Badge>
</Flex>
);
export default function Post({
data: { mdx },
pageContext: { next, prev },
}) {
const {
title,
description,
date,
card,
banner,
alt
} = mdx.frontmatter;
const {
slug,
language
} = mdx.fields
return (
<Layout frontmatter={mdx.frontmatter}>
<SEO
title={title}
description={description}
slug={slug}
article={true}
card={card}
language={language}
/>
<Flex
sx={{
flexDirection: 'column',
maxWidth: '768px',
mx: 'auto',
pt: ['6rem'],
px: ['1em', '2em']
}}
>
<Styled.h1
sx={{
mt: [1, 4],
mb: ['0.5rem', '1rem'],
px: ['1rem', '2rem'],
fontWeight: 'semi-bold',
letterSpacing: 'tighter',
textAlign: ['left', 'center'],
}}
>
{mdx.frontmatter.title}
</Styled.h1>
{banner && (
<Img
sizes={mdx.frontmatter.banner.childImageSharp.sizes}
alt={alt}
/>
)}
<Flex
sx={{
justifyContent: 'space-between',
alignItems: 'center',
pb: ['0.5rem', '2rem'],
px: ['1rem', 0],
}}
>
<Styled.h5
sx={{
fontWeight: 'medium',
letterSpacing: 'tighter',
}}
>
{language === 'en'
? moment(date)
.locale('en')
.format('MMMM DD, YYYY')
: moment(date)
.locale('fr')
.format('DD MMMM YYYY')}
</Styled.h5>
<Category
categorySlug={mdx.frontmatter.categorySlug}
category={mdx.frontmatter.category}
/>
</Flex>
<div
sx={{
px: ['2rem', 0],
}}
>
<MDXRenderer>{mdx.body}</MDXRenderer>
</div>
<div>
<hr />
</div>
</Flex>
</Layout>
);
}
export const pageQuery = graphql`
query($id: String!) {
mdx(id: { eq: $id } ) {
fields {
slug
language
}
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
banner {
childImageSharp {
sizes(maxWidth: 900) {
...GatsbyImageSharpSizes
}
}
}
alt
card {
childImageSharp {
# Query for the src since we don't pass it to the Img component
fixed(height: 628) {
src
}
}
}
category
keywords
description
categorySlug
}
body
}
}
`;
|
import React from "react";
import {
View,
StyleSheet,
ScrollView,
Dimensions,
Text,
SafeAreaView
} from "react-native";
import LinearGradient from "react-native-linear-gradient";
import Header from "../components/Header";
import Tabs from "../components/Tabs";
import Item from "../components/Item";
import ItemHeader from "../components/ItemHeader";
import Button from "../components/Button";
import PostCard from "../components/PostCard";
import CardWithName from "../components/CardWithName";
const Results = (props) => {
const {
main,
page,
linearGradient,
resultsScrollMain,
resultsScroll,
resultsScrollInner,
resultsScrollText,
bold,
redcolor,
row,
col,
} = styles;
return (
<LinearGradient
start={{ x: 0, y: 0.3 }}
end={{ x: 2, y: 0.3 }}
colors={["#d13139", "#560004", "#560004"]}
style={linearGradient}
>
<View style={main}>
<Header
// iconImageRight={require("./../assets/img/searchIcon.png")}
title="Results"
/>
<ScrollView horizontal style={resultsScrollMain}>
<View style={resultsScroll}>
<View style={resultsScrollInner}>
<Text style={resultsScrollText}>
Torque: <Text style={bold}>250,</Text>
</Text>
<Text style={resultsScrollText}>
RPM: <Text style={bold}>10000,</Text>
</Text>
<Text style={[resultsScrollText, redcolor]}>
HP: <Text style={[bold]}>39.66,</Text>
</Text>
<Text style={resultsScrollText}>
Torque: <Text style={bold}>250,</Text>
</Text>
<Text style={resultsScrollText}>
RPM: <Text style={bold}>10000,</Text>
</Text>
<Text style={[resultsScrollText, redcolor]}>
HP: <Text style={[bold]}>39.66,</Text>
</Text>
</View>
</View>
</ScrollView>
<ScrollView style={{ backgroundColor: "#fff" }}>
<View style={page}>
<View style = {row}>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
<View style = {col}>
<CardWithName
cardBg={require('../assets/img/cardWithName.png')}
cardName="Reliamark Subop Reliamark Subop"
/>
</View>
</View>
</View>
</ScrollView>
</View>
</LinearGradient>
);
};
const styles = StyleSheet.create({
main: {
},
page: {
backgroundColor: "#fff",
paddingBottom: 170,
},
bold: {
fontFamily: "OpenSans-Bold",
fontWeight: "600"
},
redcolor: {
color: "rgb(191, 42, 49)"
},
resultsScrollMain: {
backgroundColor: "rgb(234, 234, 234)",
},
resultsScroll: {
width: '100%',
},
resultsScrollInner: {
paddingVertical: 16,
paddingHorizontal: 16,
flexDirection: "row",
textAlign: 'center'
},
resultsScrollText: {
fontSize: 16.4,
fontFamily: 'OpenSans-Regular',
fontWeight: "normal",
fontStyle: "normal",
letterSpacing: 0,
textAlign: "center",
paddingHorizontal: 5,
},
footerStyle: {
backgroundColor: "#fff"
},
row: {
flexDirection: 'row',
flexWrap:'wrap',
padding: 9,
},
col: {
width: '50%',
padding: 9,
},
});
export default Results;
|
var APE = {Config: {identifier: "ape", init: true, frequency: 0, scripts: []}, Client: function (a) {
if (a) {
this.core = a
}
}};
APE.Client.prototype.eventProxy = [];
APE.Client.prototype.fireEvent = function (c, b, a) {
this.core.fireEvent(c, b, a)
};
APE.Client.prototype.addEvent = function (d, c, a) {
var e = c.bind(this), b = this;
if (this.core == undefined) {
this.eventProxy.push([d, c, a])
} else {
var b = this.core.addEvent(d, e, a);
this.core.$originalEvents[d] = this.core.$originalEvents[d] || [];
this.core.$originalEvents[d][c] = e
}
return b
};
APE.Client.prototype.removeEvent = function (b, a) {
return this.core.removeEvent(b, a)
};
APE.Client.prototype.onRaw = function (c, b, a) {
this.addEvent("raw_" + c.toLowerCase(), b, a)
};
APE.Client.prototype.onCmd = function (c, b, a) {
this.addEvent("cmd_" + c.toLowerCase(), b, a)
};
APE.Client.prototype.onError = function (c, b, a) {
this.addEvent("error_" + c, b, a)
};
APE.Client.prototype.cookie = {};
APE.Client.prototype.cookie.write = function (a, b) {
document.cookie = a + "=" + encodeURIComponent(b) + "; domain=" + document.domain
};
APE.Client.prototype.cookie.read = function (b) {
var e = b + "=";
var a = document.cookie.split(";");
for (var d = 0; d < a.length; d++) {
var f = a[d];
while (f.charAt(0) == " ") {
f = f.substring(1, f.length)
}
if (f.indexOf(e) == 0) {
return decodeURIComponent(f.substring(e.length, f.length))
}
}
return null
};
APE.Client.prototype.load = function (config) {
config = config || {};
config.transport = config.transport || APE.Config.transport || 0;
config.frequency = config.frequency || 0;
config.domain = config.domain || APE.Config.domain || document.domain;
config.scripts = config.scripts || APE.Config.scripts;
config.server = config.server || APE.Config.server;
config.secure = config.sercure || APE.Config.secure;
config.init = function (core) {
this.core = core;
for (var i = 0; i < this.eventProxy.length; i++) {
this.addEvent.apply(this, this.eventProxy[i])
}
}.bind(this);
if (config.transport != 2) {
if (config.domain != "auto") {
document.domain = config.domain
}
if (config.domain == "auto") {
document.domain = document.domain
}
}
var cookie = this.cookie.read("APE_Cookie");
var tmp = eval("(" + cookie + ")");
if (tmp) {
config.frequency = tmp.frequency + 1
} else {
cookie = '{"frequency":0}'
}
var reg = new RegExp('"frequency":([ 0-9]+)', "g");
cookie = cookie.replace(reg, '"frequency":' + config.frequency);
this.cookie.write("APE_Cookie", cookie);
var iframe = document.createElement("iframe");
iframe.setAttribute("id", "ape_" + config.identifier);
iframe.style.display = "none";
iframe.style.position = "absolute";
iframe.style.left = "-300px";
iframe.style.top = "-300px";
document.body.insertBefore(iframe, document.body.childNodes[0]);
var initFn = function () {
iframe.contentWindow.APE.init(config)
};
if (iframe.addEventListener) {
iframe.addEventListener("load", initFn, false)
} else {
if (iframe.attachEvent) {
iframe.attachEvent("onload", initFn)
}
}
if (config.transport == 2) {
var doc = iframe.contentDocument;
if (!doc) {
doc = iframe.contentWindow.document
}
doc.open();
var theHtml = "<html><head>";
for (var i = 0; i < config.scripts.length; i++) {
theHtml += '<script type="text/JavaScript" src="' + config.scripts[i] + '"><\/script>'
}
theHtml += "</head><body></body></html>";
doc.write(theHtml);
doc.close()
} else {
iframe.setAttribute("src", (config.secure ? "https" : "http") + "://" + config.frequency + "." + config.server + '/?[{"cmd":"script","params":{"domain":"' + document.domain + '","scripts":["' + config.scripts.join('","') + '"]}}]');
if (navigator.product == "Gecko") {
iframe.contentWindow.location.href = iframe.getAttribute("src")
}
}
};
if (Function.prototype.bind == null) {
Function.prototype.bind = function (b, a) {
return this.create({bind: b, "arguments": a})
}
}
if (Function.prototype.create == null) {
Function.prototype.create = function (b) {
var a = this;
b = b || {};
return function () {
var c = b.arguments || arguments;
if (c && !c.length) {
c = [c]
}
var d = function () {
return a.apply(b.bind || null, c)
};
return d()
}
}
}
;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.