text
stringlengths
7
3.69M
import React from 'react' import {BsLinkedin,BsGithub,BsInstagram} from 'react-icons/bs' const HeaderSocials = () => { return ( <div className='header_socials'> <a href='https://www.linkedin.com/in/amit-sagar-1a222418b/' target="_blank"><BsLinkedin/></a> <a href='https://github.com/Amit-Sagar' target="_blank"><BsGithub/></a> <a href='https://Instagram.com' target="_blank"><BsInstagram/></a> </div> ) } export default HeaderSocials
Ext.ns('Cneport.ecss.goodsbills'); Cneport.ecss.goodsbills.LogisticsQuery = Ext.extend(Ext.Syis.lib.SyisQueryPanel, { limitSize: 100, type : null, constructor: function(_config) { if (_config == null) { _config = {}; }; Ext.apply(this, _config); var me = this; var conditionItems = [{ layout: 'column', items: [{ columnWidth: .25, layout: 'form', items: [{ xtype: 'textfield', anchor: '95%', name: 'logisticsNo', fieldLabel: '物流运单号' }] }, { columnWidth: .25, layout: 'form', items: [{ xtype: 'textfield', anchor: '95%', name: 'logisticsName', fieldLabel: '物流企业名称' }] }, { columnWidth: .25, layout: 'form', items: [{ xtype: 'textfield', anchor: '95%', name: 'totalLogisticsNo', fieldLabel: '总运单号' }] }, { columnWidth: .25, layout: 'form', items: [{ xtype: 'textfield', anchor: '95%', name: 'orderNo', fieldLabel: '订单编号' }] }] }, { layout: 'column', items: [{ columnWidth: .25, layout: 'form', items: [{ xtype: 'textfield', anchor: '95%', name: 'ecpName', fieldLabel: '电商平台名称' }] }, { columnWidth: .25, layout: 'form', items: [{ xtype: 'textfield', anchor: '95%', name: 'consignee', fieldLabel: '收货人名称' }] }, { columnWidth: .25, layout: 'form', items: [{ xtype: 'datefield', anchor: '95%', name: 'dateFrom', fieldLabel: '入库日期 从', format: 'Y-m-d', listeners: { scope: this, select: function() { this.query_form.find('name', 'dateTo')[0].setMinValue( this.query_form.find('name', 'dateFrom')[0].getValue() ); } } }] }, { columnWidth: .25, layout: 'form', items: [{ xtype: 'datefield', anchor: '95%', name: 'dateTo', fieldLabel: '至', format: 'Y-m-d', listeners: { scope: this, select: function() { this.query_form.find('name', 'dateFrom')[0].setMaxValue( this.query_form.find('name', 'dateTo')[0].getValue() ); } } }] }] }, { layout: 'column', items: [{ columnWidth: .25, layout: 'form', items: [{ xtype : 'combo', anchor : '95%', name : 'ieType', fieldLabel : '进出口标志', hiddenName : 'ieType', emptyText : '全部', mode : 'local', triggerAction : 'all', valueField : 'code', displayField : 'name', editable : false, store : new Ext.data.ArrayStore({ fields : ['code', 'name'], data : [ ['', '全部类型'], ['I', '进口'], ['E', '出口'] ] }) }] }, { columnWidth: .25, layout: 'form', items: [{ xtype: 'textfield', anchor: '95%', name: 'batchNumbers', fieldLabel: '批次号' },{xtype : 'hidden', name : 'queryType',value : ''}] }] }]; var gridColumn = [ new Ext.grid.RowNumberer({ header: '序号', width: 35, align: 'center' }), {header: "<div style='text-align:center'>物流运单号</div>", width : 100, dataIndex: 'logisticsNo', sortable: true}, {header: "<div style='text-align:center'>物流企业名称</div>", width : 180, dataIndex: 'logisticsName', sortable: true}, {header: "<div style='text-align:center'>总运单号</div>", width : 100, dataIndex: 'totalLogisticsNo', sortable: true}, {header: "<div style='text-align:center'>订单编号</div>", width : 100, dataIndex: 'orderNo', sortable: true}, {header: "<div style='text-align:center'>电商平台名称</div>", width : 180, dataIndex: 'ecpName', sortable: true}, {header: "<div style='text-align:center'>收货人名称</div>", width : 80, dataIndex: 'consignee', sortable: true}, {header: "<div style='text-align:center'>入库日期</div>", width : 70, dataIndex: 'updateTime', sortable: true}, {header: "<div style='text-align:center'>进出口标志</div>", width : 90, dataIndex: 'ieTypeText', sortable: true}, {header: "<div style='text-align:center'>状态</div>", width : 70, dataIndex: 'statusText', sortable: true}, {header: "<div style='text-align:center'>比对信息</div>", width : 90, dataIndex: 'compareFlagText', sortable: true, renderer: function(val, col, rec) { if((rec.data.compareFlag !='Y' && rec.data.compareFlag !='N')){ return '未比对'; } else { return val; }} } ]; var gridStore = new Ext.data.JsonStore({ autoLoad: true, url: 'logistics/queryList', root: 'logisList', totalProperty: 'totalRows', baseParams: { queryType : me.type, limit: me.limitSize }, remoteSort : true, fields: [ 'seqNo', 'logisticsNo', 'logisticsName', 'totalLogisticsNo', 'orderNo', 'ecpName', 'consignee', 'updateTime', 'ieTypeText', 'compareFlag', 'statusText', 'compareFlagText' ] }); Cneport.ecss.goodsbills.LogisticsQuery.superclass.constructor.call(this, { queryConditionTitle: '运单信息查询', conditionItems: conditionItems, gridColumn: gridColumn, gridStore: gridStore, hyperLinkData: 'logisticsNo', pageSize: me.limitSize }); this.initCondition(); this.query_form.doLayout(); }, initCondition : function() { if(this.type == 'deleteQuery') { this.query_form.find('name', 'queryType')[0].setValue(this.type); } }, // 查询条件重置 resetCondition: function(){ this.query_form.getForm().reset(); this.initCondition(); }, view: function() { var me = this; var rec = this.query_grid.getSelectionModel().getSelected(); if (rec != undefined) { var win = new Ext.Window({ rec: rec, bufferResize : true, iconCls : 'btn-form', title : '运单信息详情', renderTo : 'syisbillQuery', closable : true, resizable : false, draggable : false, width : Ext.getCmp('frmPanel').getInnerWidth(), height : Ext.getCmp('frmPanel').getInnerHeight(), items : [ new Cneport.ecss.goodsbills.LogisticsInput({ type : me.type, win : this }) ], listeners: { close: function(){ this.query_grid.store.reload(); }, scope: this } }).show(); win.items.get(0).initData(rec); } else { chooseLineAlert(); } } });
const { Schema } = require('mongoose'); const slug = require('slug'); const connection = require('../connections/mongoose/instance'); const { applyElasticPlugin, setEntityFields } = require('../elastic/mongoose'); const { deleteablePlugin, imagePlugin, paginablePlugin, pushIdPlugin, referencePlugin, repositoryPlugin, searchablePlugin, userAttributionPlugin, } = require('../plugins'); const storyUrl = require('../utils/story-url'); const accountService = require('../services/account'); const schema = new Schema({ title: { type: String, required: true, trim: true, }, teaser: { type: String, trim: true, }, body: { type: String, trim: true, }, advertiserName: { type: String, }, placeholder: { type: Boolean, default: false, required: true, es_indexed: true, es_type: 'boolean', }, publishedAt: { type: Date, es_indexed: true, es_type: 'date', }, }, { timestamps: true }); setEntityFields(schema, 'title'); setEntityFields(schema, 'advertiserName'); applyElasticPlugin(schema, 'stories'); schema.plugin(referencePlugin, { name: 'advertiserId', connection, modelName: 'advertiser', options: { required: true, es_indexed: true, es_type: 'keyword' }, }); schema.plugin(referencePlugin, { name: 'publisherId', connection, modelName: 'publisher', options: { required: true }, }); schema.plugin(deleteablePlugin, { es_indexed: true, es_type: 'boolean', }); schema.plugin(pushIdPlugin, { required: true }); schema.plugin(userAttributionPlugin); schema.plugin(imagePlugin, { fieldName: 'primaryImageId' }); schema.plugin(imagePlugin, { fieldName: 'imageIds', multiple: true }); schema.plugin(repositoryPlugin); schema.plugin(paginablePlugin); schema.plugin(searchablePlugin, { fieldNames: ['title', 'advertiserName'] }); schema.virtual('slug').get(function getSlug() { return slug(this.title).toLowerCase(); }); schema.virtual('status').get(function getStatus() { const { publishedAt } = this; if (this.deleted) return 'Deleted'; if (this.placeholder) return 'Placeholder'; if (publishedAt && publishedAt.valueOf() <= Date.now()) return 'Published'; if (publishedAt && publishedAt.valueOf() > Date.now()) return 'Scheduled'; return 'Draft'; }); schema.method('clone', async function clone(user) { const Model = connection.model('story'); const { _doc } = this; const input = { ..._doc, title: `${this.title} copy`, }; ['id', '_id', 'pushId', 'createdAt', 'updatedAt', 'updatedBy', 'createdBy'].forEach(k => delete input[k]); const doc = new Model(input); doc.setUserContext(user); return doc.save(); }); schema.method('getPath', async function getPath() { const advertiser = await connection.model('advertiser').findById(this.advertiserId); return `story/${advertiser.slug}/${this.slug}/${this.id}`; }); schema.method('getUrl', async function getUrl(params) { const account = await accountService.retrieve(); const path = await this.getPath(); return storyUrl(account.storyUri, path, params); }); schema.pre('save', async function checkDelete() { if (!this.isModified('deleted') || !this.deleted) return; const count = await connection.model('campaign').countActive({ storyId: this.id }); if (count) throw new Error('You cannot delete a story that has related campaigns.'); }); schema.pre('save', async function setAdvertiserName() { if (this.isModified('advertiserId') || !this.advertiserName) { const advertiser = await connection.model('advertiser').findOne({ _id: this.advertiserId }, { name: 1 }); this.advertiserName = advertiser.name; } }); schema.pre('save', async function checkCampaigns() { const { publishedAt } = this; if (!this.isModified('publishedAt')) return; const campaigns = await connection.model('campaign').findActive({ storyId: this.id }); campaigns.forEach((campaign) => { if (['Paused', 'Running', 'Scheduled'].includes(campaign.status) && !publishedAt) { // Published date was unset. Do not allow this if associated campaigns are active. throw new Error('Cannot unpublish: there are active campaigns running for this story.'); } if (['Paused', 'Running'].includes(campaign.status) && publishedAt && publishedAt.valueOf() > Date.now()) { // Published date was set and it's greater than a paused/running campaign's start. throw new Error('Cannot change published date: the selected value would conflict with active campaigns.'); } if (campaign.status === 'Scheduled' && publishedAt && publishedAt.valueOf() > campaign.get('criteria.start').valueOf()) { // Published date was set and it's greater than a scheduled campaign's start. throw new Error('Cannot change published date: the selected value would conflict with scheduled campaigns.'); } }); }); schema.post('save', async function handlePublishedAt() { if (this.status === 'Published') { // Find all related campaigns and ensure they're resaved to account for the published changed. const campaigns = await connection.model('campaign').findActive({ storyId: this.id, ready: false }); const promises = campaigns.map(campaign => campaign.save()); await Promise.all(promises); } }); schema.index({ advertiserId: 1 }); schema.index({ placeholder: 1 }); schema.index({ title: 1, _id: 1 }, { unique: true }); schema.index({ title: -1, _id: -1 }, { unique: true }); schema.index({ updatedAt: 1, _id: 1 }, { unique: true }); schema.index({ updatedAt: -1, _id: -1 }, { unique: true }); schema.index({ publishedAt: 1, _id: 1 }, { unique: true }); schema.index({ publishedAt: -1, _id: -1 }, { unique: true }); module.exports = schema;
import defaultSettings from './defaultSettings'; import ApiError from './ApiError'; import { contentTypes, headerNames, httpMethods, requestTypes } from './apiConsts'; const API_ACTION_FLAG = '@@API_ACTION'; const REQUEST_SUFFIX = '_REQUEST'; const REQUEST_FLAG = '@@API_REQUEST'; const SUCCESS_SUFFIX = '_SUCCESS'; const SUCCESS_FLAG = '@@API_RESPONSE_SUCCESS'; const FAIL_SUFFIX = '_FAIL'; const FAIL_FLAG = '@@API_RESPONSE_FAIL'; const hasMetaFlag = (action, flag) => action.meta && action.meta[flag]; export const isApiAction = action => hasMetaFlag(action, API_ACTION_FLAG); export const isRequestApiAction = action => hasMetaFlag(action, REQUEST_FLAG); export const isSuccessApiAction = action => hasMetaFlag(action, SUCCESS_FLAG); export const isFailureApiAction = action => hasMetaFlag(action, FAIL_FLAG); export const getOrigAction = apiAction => apiAction.meta.origAction; export const getOrigActionType = apiAction => getOrigAction(apiAction).type; function buildFetchParams(apiAction) { const { payload } = apiAction; const { request } = payload; const { url, options } = request; return { url, options, }; } export const sendRequest = apiAction => { const { url, options } = buildFetchParams(apiAction); return fetch(url, options); }; export function createResponse(fetchResponse, parsedResponseBody) { const parsedHeaders = extractResponseHeaders(fetchResponse); return { ...fetchResponse, headers: parsedHeaders, body: parsedResponseBody, }; } export function extractResponseHeaders(fetchResponse) { const headers = {}; const headerEntries = [ ...fetchResponse.headers.entries() ]; headerEntries.forEach(([ name, value ]) => { headers[name] = value; }); return headers; } export const handleFetchResponse = (fetchResponse, context) => { const { apiAction, next } = context; const { meta: { settings: { extractResponseBody = defaultSettings.extractResponseBody, rejectBadResponse = defaultSettings.rejectBadResponse, isResponseOk = defaultSettings.isResponseOk, normalize = identityFunc, } }, } = apiAction; if (isResponseOk(fetchResponse)) { return extractResponseBody(fetchResponse) .then(normalize) .then(parsedResponseBody => { const response = createResponse(fetchResponse, parsedResponseBody); next(createResponseAction(apiAction, response)); return { ok: response.ok, response, }; }); } else { const apiError = new ApiError(fetchResponse); if (!rejectBadResponse) { next(createFailureAction(apiAction, apiError)); } return rejectBadResponse ? Promise.reject(apiError) : Promise.resolve(apiError); } }; export const createRequestActionType = type => `${ type }${ REQUEST_SUFFIX }`; export const createSuccessActionType = type => `${ type }${ SUCCESS_SUFFIX }`; export const createFailureActionType = type => `${ type }${ FAIL_SUFFIX }`; export const createRequestAction = (origAction) => { return { type: createRequestActionType(origAction.type), meta: { [REQUEST_FLAG]: true, origAction, }, }; }; export const createResponseAction = (origAction, parsedResponse) => { return { type: createSuccessActionType(origAction.type), payload: { response: parsedResponse, }, meta: { [SUCCESS_FLAG]: true, origAction, }, }; }; export const createFailureAction = (origAction, apiError) => { return { type: createFailureActionType(origAction.type), error: true, payload: apiError, meta: { [FAIL_FLAG]: true, origAction, }, }; }; const identityFunc = x => x; const settingsByRequestType = { [requestTypes.json]: { contentType: contentTypes.json, stringifyBody: body => JSON.stringify(body), }, [requestTypes.formUrlEncoded]: { contentType: contentTypes.formUrlEncoded, stringifyBody: form => Object.entries(form) .map(([ name, value ]) => `${ name }=${ value }`) .join('&') }, }; const createSettingsByRequestType = (requestType, settings) => { let { headers, body } = settings; const requestTypeConfig = settingsByRequestType[requestType]; if (requestTypeConfig) { headers = { [headerNames.contentType]: requestTypeConfig.contentType, ...headers, }; body = body && requestTypeConfig.stringifyBody(body); } return { headers, body, }; }; export const createApiAction = (type, url, method = httpMethods.GET, settings = {}, meta) => { const { options, normalize, extractResponseBody, rejectBadResponse, requestType = defaultSettings.requestType, } = settings; const { body, headers } = createSettingsByRequestType(requestType, settings); return { type, meta: { [API_ACTION_FLAG]: true, settings: { normalize, extractResponseBody, rejectBadResponse, }, ...meta, }, payload: { request: { url, options: { method, body, headers, ...options }, }, }, }; }; export const getResponseFromApiAction = apiAction => apiAction.payload && apiAction.payload.response; export const getResponseBodyFromApiAction = apiAction => getResponseFromApiAction && apiAction.payload.response.body; export const getBodyFromResponseAction = responseAction => responseAction.response.body; export const extractEmptyResponseBody = response => response.text(); export const isErrorResponse = response => response.error;
/** * Created by Administrator on 2016/6/20. */ var SaleHotTemplate={ SaleHotDetailTemp:function(data) { var dom='<div class="cus_info_div">'+ '<div class="wid25 fl tc cus_name min_hei" title="'+data.nickname+'">'+data.nickname+'</div>'+ '<div class="wid20 fl tc min_hei">'+data.create_time+'</div>'+ '<div class="wid15 fl tc min_hei">'+data.balance+'</div>'+ '<div class="wid15 fl tc min_hei">'+data.price+'</div>'+ '<div class="wid15 fl tc min_hei">'+data.per+'</div>'+ '<div class="cle"></div>'+ '</div>'; $("#SaleHot_container").append(dom); } }; //��Ⱦ�б��ҳ�� function SaleHotTList(result){ if(result.data.length===0){ $("#SaleHot_none").show() } for(var i=0;i<result.data.length;i++){ SaleHotTemplate.SaleHotDetailTemp(result.data[i]); $("#SaleHot_none").hide() } $("#cardReview_num").text(result.total); var SaleHot_tot_page=Math.ceil(result.total/$("#SaleHot_pagenum").text()); if(SaleHot_tot_page===0){ SaleHot_tot_page=1; } $("#SaleHot_tot_page").text(SaleHot_tot_page); } //POST���� function GetQueryPostData(){ var limit = $("#SaleHot_pagenum").text(); var offset = ($("#SaleHot_now_page").text()-1)*limit; var start_time= $("#pagetj_start_date").val(); var end_time= $("#pagetj_end_date").val(); var post_data = { "start_time":start_time, "end_time":end_time, "offset":offset, "limit":limit, "nick_name":$("#sale_name").val(), "balance":$("#withdraw").val(), "sale_price":$("#sale_price").val(), "price_per_min":$("#compare_1").val(), "price_per_max":$("#compare_2").val(), "sort":$("#order_value").val() }; return JSON.stringify(post_data); } //�����б� function SaleHotListServerRequest(flag){ if(!flag){ $("#cardReview_now_page").text("1"); } RemoveSaleHot(); AjaxPostData("../Home/SaleHot/QueryAllBankUserRecords",GetQueryPostData(),function(result){ SaleHotTList(result); }); } //�����Ϣ function RemoveSaleHot(){ $("#SaleHot_container").children(".cus_info_div").remove(); } //初始化汇总数据 function InitTotalSaleInfo(){ AjaxPostData("../Home/SaleHot/GetAllGatherInfo",GetQueryPostData(),function(result){ if(result.status = 1){ $("#total_withdraw").text(result.data.balance); $("#total_price").text(result.data.price); } }); } function CheckExport(){ var start_time= $("#pagetj_start_date").val(); var end_time= $("#pagetj_end_date").val(); $("input[name='start_time']").val(start_time); $("input[name='end_time']").val(end_time); $("input[name='nick_name']").val($("#sale_name").val()); $("input[name='balance']").val($("#withdraw").val()); $("input[name='sale_price']").val($("#sale_price").val()); $("input[name='price_per_min']").val($("#compare_1").val()); $("input[name='price_per_max']").val($("#compare_2").val()); return true; } $(function($){ AddNaviListClass("rmz"); RemoveSaleHot(); SaleHotListServerRequest(); InitTotalSaleInfo(); $("#search").click(function(){ InitTotalSaleInfo(); SaleHotListServerRequest(); var end_date=$("#pagetj_end_date").val(); var start_date=$("#pagetj_start_date").val(); if(start_date!="" || end_date!=""){ $("#pagetj_filter .filter_days").attr("class","filter_days") } }); //����ѡ�� $(".filter_days").click(function() { $(".filter_days").removeClass("on_chose"); $(this).addClass("on_chose"); var dataValue = $(".filter_days.on_chose").attr("data-value"); var start_date = ""; var end_date = ""; if(dataValue == "today"){ start_date = GetNowTime.GetToday(); end_date = GetNowTime.GetToday(); $("#pagetj_start_date").val(start_date); $("#pagetj_end_date").val(end_date); }else if(dataValue == "yesterday"){ start_date = GetNowTime.GetYesterday(); end_date = GetNowTime.GetYesterday(); $("#pagetj_start_date").val(start_date); $("#pagetj_end_date").val(end_date); }else if(dataValue == "7day"){ start_date = GetNowTime.GetOneweekAgoDay(); end_date = GetNowTime.GetYesterday(); $("#pagetj_start_date").val(start_date); $("#pagetj_end_date").val(end_date); }else if(dataValue == "30day"){ start_date = GetNowTime.Get30DaysAgoDay(); end_date = GetNowTime.GetYesterday(); $("#pagetj_start_date").val(start_date); $("#pagetj_end_date").val(end_date); }else{ $("#pagetj_start_date").val(""); $("#pagetj_end_date").val(""); } SaleHotListServerRequest(); InitTotalSaleInfo(); }); //����ÿҳ���� $("#SaleHot_limit li").bind("click",function(){ var nlimit=$(this).text(); $("#SaleHot_pagenum").text(nlimit); $("#SaleHot_limit").hide(); SaleHotListServerRequest(); }); //��һҳ����һҳ��ť $("#SaleHot_pre").bind("click",function(){ var nowpage=parseInt($("#SaleHot_now_page").text()); nowpage-=1; if(nowpage<=0){return;} else{ $("#SaleHot_now_page").text(nowpage); SaleHotListServerRequest(1); } }); $("#SaleHot_next").bind("click",function(){ var nowpage=parseInt($("#SaleHot_now_page").text()); var totalpage=parseInt($("#SaleHot_tot_page").text()); nowpage+=1; if(nowpage>totalpage){ return; } else{ $("#SaleHot_now_page").text(nowpage); SaleHotListServerRequest(1); } }); $(".customer_table_head .sort_tab").bind("click",function(){ if($(this).hasClass("sort_desc")){ $(this).parent().children().removeClass("sort_desc").removeClass("sort_asc"); $(this).addClass("sort_asc"); var norder_value=$(this).attr("data-value"); $("#order_value").val(norder_value+" asc"); SaleHotListServerRequest(); } else{ $(this).parent().children().removeClass("sort_desc").removeClass("sort_asc"); $(this).addClass("sort_desc"); var norder_value=$(this).attr("data-value"); $("#order_value").val(norder_value+" desc"); SaleHotListServerRequest(); } }); })
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict' let crypto; exports.verifyCrypto = function() { // if crypto is already loaded, return success if (exports.crypto) { return true; } try { exports.crypto = require('crypto'); // we successfully loaded the crypto library (i.e. nodejs was built with crypto) return true; } catch (err) { // catastrophic failure: we could not load the crypto library. return false; } } // Psuedo-Random Function (PRF) is used to create our master key and also for secret expansion (for key generation) /* PRF input parameters: * secret: PRF secret * label: an ASCII string which will be prefixed to the seed (so that we can create multiple PRF outputs using a single seed, using a different label input for each one) * seed: PRF seed * outputLength: number of bytes to return */ exports.PRF = function(secret, label, seed, outputLength) { if (!exports.verifyCrypto()) return null; // convert label to a buffer (if it is not already a buffer) label = new Buffer(label); // convert seed to a buffer (if it is not already a buffer) seed = new Buffer(seed); // concatenate the label and seed let combinedSeed = Buffer.concat([label, seed]); // split the secret into two halves; if the secret has an odd number of bytes then include the middle byte in each half let secretEachHalfLength = (secret.length / 2) + (secret.length % 2); let secretFirstHalf = secret.slice(0, secretEachHalfLength); let secretSecondHalf = secret.slice((secret.length / 2) - (secret.length % 2), secret.length); // calculate P_MD5 using the first half of the secret let md5Result = P_hash(secretFirstHalf, combinedSeed, outputLength, 'md5'); // calculate P_SHA1 using the first half of the secret let sha1Result = P_hash(secretSecondHalf, combinedSeed, outputLength, 'sha1'); // xor the MD5 and SHA1 results to generate our final result let result = xorBuffers(md5Result, sha1Result); // return our result return result; } // P_hash expands a secret and seed into an arbitrary quantity of output data /* P_hash input parameters: * secret: hash secret * seed: hash seed * outputLength: number of bytes to return * algorithm: hash algorithm {'HMAC','SHA1'} */ function P_hash(secret, seed, outputLength, algorithm) { let result = Buffer.alloc(0); // empty buffer let hmac; // for the initial iteration, set the (initial) data to our seed let data = seed; while (result.length < outputLength) { // calculate the hmac for our current 'data' value (our seed on the initiatial iteration...or an iterative hmac of that seed in later iterations) hmac = exports.crypto.createHmac(algorithm, secret).update(data).digest(); // save this hmac result as the 'data' input for the next iteration let dataForNextIteration = hmac; // concatenate the hmac and our seed data = Buffer.concat([hmac, seed]); // calculate an hmac for the hmac-plus-seed (which we will store in our output) hmac = exports.crypto.createHmac(algorithm, secret).update(data).digest(); // add the hmac to our result result = Buffer.concat([result, hmac]); // restore the saved first-interation-stage hmac as the 'data' input for our next iteration data = dataForNextIteration; } // if our HMAC's output block size resulted in a length which is slightly too big, discard the extra bytes. if (result.length > outputLength) { let truncatedBuffer = Buffer.alloc(outputLength); result.copy(truncatedBuffer, 0, 0, outputLength); result = truncatedBuffer; } // return the hash result (with the number of octects/bytes specified as 'outputLength' by the caller) return result; } function xorBuffers(buffer1, buffer2) { let result = Buffer.alloc(buffer1.length); for (let i = 0; i < result.length; i++) { result[i] = buffer1[i] ^ buffer2[i]; } return result; } exports.createPremasterSecret_FromPresharedKey = function(psk) { let pskBuffer = new Buffer(psk); let pskBufferLength = pskBuffer.length; let premasterSecret = Buffer.alloc(4 + (pskBufferLength * 2)); premasterSecret.writeUInt16BE(pskBufferLength, 0); premasterSecret.writeUInt16BE(pskBufferLength, 2 + pskBufferLength); pskBuffer.copy(premasterSecret, pskBufferLength + 4, 0, pskBufferLength); return premasterSecret; }
import React from 'react'; import './card.styles.css'; import { random } from 'node-forge'; export const Card = props => ( <div className='card-container'> <img alt='monster' src={`https://robohash.org/${props.monster.id + 2}?set=set4&size=180x180`} // src={`https://robohash.org/${props.monster.id * Math.ceil(Math.random() * 10)}?set=set4&size=180x180`} /> <h2> {props.monster.name} </h2> <p> {props.monster.email} </p> </div> );
const {Router} = require('express'); const {check} = require('express-validator'); const { validateJWT,validateFields } = require('../middlewares'); const { existPublicationById, existUserById } = require('../helpers/database-validate'); const { getPublications,createPublication, getPublication, updatePublication, deletePublication } = require('../controllers/publication'); const router = Router(); // Obtener todas las publicaciones del marketplace - publico router.get('/',[ check('postuser','invalid id').isMongoId(), check('postuser').custom(existUserById), validateFields, ],getPublications); // Obtener -publicacion por id router.get('/:id',[ check('id','invalid id').isMongoId(), check('id').custom(existPublicationById), validateFields ],getPublication); // Crear publicacion en el marketplace - privado - cualquier persona con un token valido router.post('/',[ validateJWT, check('description','Description is required').not().isEmpty(), validateFields ],createPublication); // Actualizar privado - cualquiera con token valido router.put('/:id',[ // no mandamos mas validaciones porque tal vez no se quiere actualizar las demas propiedades validateJWT, check('id','invalid id').isMongoId(), check('id').custom(existPublicationById), validateFields ],updatePublication) // Borrar un producto router.delete('/:id',[ validateJWT, check('id','invalid id').isMongoId(), check('id').custom(existPublicationById), validateFields, ],deletePublication) module.exports = router;
/* * jquery scroll text js v1.0 * Copyright (c) 2015 fy98.com * 实现文字跑马灯效果 */ // 1、定义作用域:为插件定义私有作用域,外部代码不能直接访问插件内部的代码,插件内部的代码不污染全局变量 // 2、为jQuery扩展一个插件:为jQuery的实例添加一个扩展方法。该扩展方法可以接收一些参数。 // 3、设置默认值:为扩展方法设置默认值,一般会将默认属性对象定义为defaults。 // 使用$.extend(defaults,options)将默认值和传入的参数进行合并 // 4、支持jQuery的链式调用:循环把每个元素返回。 (function($) { var defaults = { name: 'scroll text plugin', version: '1.0' }; var showName = function(obj) { $(obj).append(function() { return 'name'; }); }; $.fn.scrollText = function(el, options) { // 具体代码实现 this.$element = el, options = $.extend(defaults, options || {}); return this.each(function() { showName(this); }); } })(jQuery);
import m from 'mithril'; import prop from 'mithril/stream'; import _ from 'underscore'; import h from '../h'; import UserFollowBtn from './user-follow-btn'; import userVM from '../vms/user-vm'; const projectContributorCard = { oninit: function(vnode) { const userDetails = prop({}), user_id = vnode.attrs.contribution.user_external_id; if (vnode.attrs.isSubscription) { userVM.fetchUser(user_id, false).then(userData => { userDetails(_.first(userData)); vnode.attrs.contribution.data.profile_img_thumbnail = userDetails().profile_img_thumbnail; vnode.attrs.contribution.data.total_contributed_projects += userDetails().total_contributed_projects; vnode.attrs.contribution.data.total_published_projects += userDetails().total_published_projects; h.redraw(); }); } vnode.state = { userDetails }; }, view: function({state, attrs}) { const contribution = attrs.contribution; return m('.card.card-backer.u-marginbottom-20.u-radius.u-text-center', [ m(`a[href="/users/${contribution.user_id}"][style="display: block;"]`, { onclick: h.analytics.event({ cat: 'project_view', act: 'project_backer_link', lbl: contribution.user_id, project: attrs.project() }) }, [ m(`img.thumb.u-marginbottom-10.u-round[src="${!_.isEmpty(contribution.data.profile_img_thumbnail) ? contribution.data.profile_img_thumbnail : '/assets/catarse_bootstrap/user.jpg'}"]`) ]), m(`a.fontsize-base.fontweight-semibold.lineheigh-tight.link-hidden-dark[href="/users/${contribution.user_id}"]`, { onclick: h.analytics.event({ cat: 'project_view', act: 'project_backer_link', lbl: contribution.user_id, project: attrs.project() }) }, userVM.displayName(contribution.data)), m('.fontcolor-secondary.fontsize-smallest.u-marginbottom-10', `${h.selfOrEmpty(contribution.data.city)}, ${h.selfOrEmpty(contribution.data.state)}`), m('.fontsize-smaller', [ m('span.fontweight-semibold', contribution.data.total_contributed_projects), ' apoiados  |  ', m('span.fontweight-semibold', contribution.data.total_published_projects), ' criado' ]), m('.btn-bottom-card.w-row', [ m('.w-col.w-col-3.w-col-small-4.w-col-tiny-3'), m('.w-col.w-col-6.w-col-small-4.w-col-tiny-6', [ m(UserFollowBtn, { follow_id: contribution.user_id, following: contribution.is_follow }) ]), m('.w-col.w-col-3.w-col-small-4.w-col-tiny-3') ]) ]); } }; export default projectContributorCard;
$(document).ready(function() { $('#letter-a a').click(function() { $('#dictionary').load('a.html'); return false; }); });
'use strict' const bill = document.querySelector('.input--bill') const numberOfPeople = document.querySelector('.input--people') const tipAmount = document.querySelector('.tip-amount') const total = document.querySelector('.total') const resetBtn = document.querySelector('.btn--reset') const buttons = document.querySelector('.grid-buttons') const customAmount = document.querySelector('.input--amount') const peopleError = document.querySelector('.people-error') let percent = 0 buttons.addEventListener('click', e => { e.stopPropagation() if (e.target.parentNode != buttons) return if (e.target.localName == 'button') percent = parseFloat(e.target.textContent) validation() activateResetButton() selectTipButtons(e) }) customAmount.addEventListener('input', e => { if (/\d+/.test(customAmount.value)) percent = parseFloat(customAmount.value) validation() activateResetButton() }) numberOfPeople.addEventListener('input', e => { validation() activateResetButton() }) bill.addEventListener('input', e => { validation() activateResetButton() }) resetBtn.addEventListener('click', e => { bill.value = '' numberOfPeople.value = '' buttons.children[5].value = '' tipAmount.textContent = '0.00' total.textContent = '0.00' resetBtn.classList.add('btn--ghost') selectTipButtons() //restablece los botones a su valor por defecto }) const validation = () => { if (numberOfPeople.value != 0 && bill.value != ' ') { showResult(numberOfPeople.value, bill.value, percent) peopleError.textContent = '' numberOfPeople.classList.remove('input--error') } else showError() } const showResult = (people, bill, percent) => { ;(bill = parseFloat(bill)), (people = parseFloat(people)) if (isNaN(bill)) bill = 0 //para los casos en que bill es '' let tip = (bill * percent) / 100 tipAmount.textContent = (tip / people).toFixed(2) total.textContent = ((bill + tip) / people).toFixed(2) } const showError = () => { peopleError.textContent = 'Can’t be zero' numberOfPeople.classList.add('input--error') } const activateResetButton = () => { resetBtn.classList.remove('btn--ghost') } const selectTipButtons = e => { for (let button of buttons.children) { button.classList.remove('btn--green') button.classList.remove('input--active') } if (e == undefined) return //para restablecer las clases al tocar 'reset' if (buttons.children[5] == e.target) e.target.classList.add('input--active') else if (e.target.parentNode == buttons) e.target.classList.add('btn--green') }
const express = require('express'); const routes = express.Router(); const { User } = require('../model/personClass'); routes.get('/', (req, res) => { res.render('index.html'); }) routes.get('/shedule', (req, res) => { console.log(req.body); res.render('shedule.html'); }) routes.post('/shedule', (req, res) => { const { ci, bdate, fname, lname, usAddress, phone, gender, date } = req.body; const newUser = new User(ci, fname, lname, gender, bdate, usAddress, phone); newUser.saveUser(); res.send('Reserved'); }) routes.post('/', (req, res) => { const body = req.body; const bdate = new Date(body.bdate); const now = new Date(); if ((now.getFullYear() - bdate.getFullYear()) <= 12) { res.send('You are not authorized.'); } res.render('shedule.html', { ...body }) }); module.exports = routes;
import React, { Component } from 'react'; import { Redirect } from 'react-router-dom'; import axios from 'axios'; export class addPlayerLooking extends Component { state = { firstName: '', lastName: '', gender: '', age: 0, email: '', phone: '', ratingMixed: '', ratingDoubles: '', event: '', eventDoubles: false, eventMixed: false, disableButton: false, success: false }; onFirstNameChange = (event) => { this.setState({ firstName: event.target.value }); } onLastNameChange = (event) => { this.setState({ lastName: event.target.value }); } onAgeChange = (event) => { this.setState({ age: event.target.value }); } onEmailChange = (event) => { this.setState({ email: event.target.value }); } tenDigitPhoneNumberMask = (value) => { const length = value.length; //handle masking for 10-digit phone number (999)999-9999 if (length === 1 && value !== "(") { value = "(" + value; } if (length === 5 && value.charAt(4) !== ")") { value = value.substring(0, 4) + ")" + value.charAt(4); } if (length === 9 && value.charAt(9) !== "-") { value = value.substring(0, 8) + "-" + value.charAt(8); } if (length > 13) { value = value.substring(0, 13); } return value; } phoneNumberInputMasking = (event) => { let value = event.target.value; const length = value.length; //check if last keyed value is a number; if not remove last keyed value and return. if (isNaN(value.charAt(length - 1))) { event.target.value = value.substring(0, length - 1); return; } event.target.value = this.tenDigitPhoneNumberMask(value); return value; } onPhoneChange = (event) => { let val = this.phoneNumberInputMasking(event); this.setState({ phone: val }); } onGenderChange = (event) => { let gender; switch (event.target.id) { case "genderMale": gender = "Male"; break; case "genderFemale": gender = "Female"; break; default: break; } this.setState({ gender: gender }); } onMixedRatingChange = (event) => { let newVal; switch (event.target.id) { case "checkMixedRating25": newVal = "2.5"; break; case "checkMixedRating30": newVal = "3.0"; break; case "checkMixedRating35": newVal = "3.5"; break; case "checkMixedRating40": newVal = "4.0"; break; case "checkMixedRating45+": newVal = "4.5+"; break; default: break; } this.setState({ ratingMixed: newVal }); } onDoublesRatingChange = (event) => { let newVal; switch (event.target.id) { case "checkDoublesRating25": newVal = "2.5"; break; case "checkDoublesRating30": newVal = "3.0"; break; case "checkDoublesRating35": newVal = "3.5"; break; case "checkDoublesRating40": newVal = "4.0"; break; case "checkDoublesRating45+": newVal = "4.5+"; break; default: break; } this.setState({ ratingDoubles: newVal }); } onEventChange = (event) => { switch (event.target.id) { case "eventDoubles": this.setState((prevState, props) => { if (prevState.event === "Mixed") { return { eventDoubles: !this.state.eventDoubles, event: "Both" } } else if (prevState.event === "Both") { return { eventDoubles: !this.state.eventDoubles, event: "Mixed" } } else if (prevState.event === "") { return { eventDoubles: !this.state.eventDoubles, event: "Doubles" } } else if (prevState.event === "Doubles") { return { eventDoubles: !this.state.eventDoubles, event: "" } } }); break; case "eventMixed": this.setState((prevState, props) => { if (prevState.event === "Mixed") { return { eventMixed: !this.state.eventMixed, event: "" } } else if (prevState.event === "Both") { return { eventMixed: !this.state.eventMixed, event: "Doubles" } } else if (prevState.event === "") { return { eventMixed: !this.state.eventMixed, event: "Mixed" } } else if (prevState.event === "Doubles") { return { eventDoubles: !this.state.eventDoubles, event: "Both" } } }); break; default: break; } } onSubmitClick = (event) => { // We don't want to let default form submission happen here, which would refresh the page. event.preventDefault(); let payload = { FirstName: this.state.firstName, LastName: this.state.lastName, Gender: this.state.gender, Age: this.state.age, DoublesRating: this.state.ratingDoubles, MixedRating: this.state.ratingMixed, EventNeedingPartner: this.state.event, Email: this.state.email, Phone: this.state.phone } console.log(payload); // axios.post('api/playerlooking/addplayer', payload) axios.post('webapi/api/playerlooking/AddPlayer', payload) .then(response => axios.get('webapi/api/playerlooking/getplayers') // axios.get('api/playerlooking/getplayers') .then(response => { this.setState({ players: response.data, firstName: '', lastName: '', gender: '', age: '', ratingDoubles: '', ratingMixed: '', event: '', email: '', phone: '', disableButton: true, success: true }); }) ) .catch(error => { console.log(error) alert(`${error}. Something went wrong and the system was unable to save you to the list. If this continues to occur please notify Kyle at kyle.savant@batonrougepickleball.com or text at 225-223-8809.`) }); }; render() { let redirect = null; if (this.state.success) { redirect = <Redirect to="/looking" /> } return ( <div> {redirect} <form onSubmit={this.onSubmitClick}> <div> <div className="form-row"> <div className="form-group col-md-4 text-center"> <label htmlFor="birthYear">Age</label> <input type="text" className="form-control text-center" id="age" placeholder="Age" onChange={this.onAgeChange} required /> </div> <div className="form-group col-md-4 text-center"> <label htmlFor="firstName">First Name</label> <input type="text" className="form-control text-center" id="firstName" placeholder="First Name" onChange={this.onFirstNameChange} required /> </div> <div className="form-group col-md-4 text-center"> <label htmlFor="lastName">Last Name</label> <input type="text" className="form-control text-center" id="lastName" placeholder="Last Name" onChange={this.onLastNameChange} required /> </div> </div> <div className="form-row"> <div className="form-group col-md-6 text-center"> <label htmlFor="inputEmail">Email address</label> <input type="email" className="form-control text-center" id="inputEmail" aria-describedby="emailHelp" placeholder="Enter email" onChange={this.onEmailChange} required /> </div> <div className="form-group col-md-6 text-center"> <label htmlFor="phone">Cell Phone Number</label> <input type="text" className="form-control text-center" id="phone" placeholder="Phone Number" onChange={this.onPhoneChange} required /> </div> </div> <div> <div className="form-check col-md-3 form-check-inline text-center"> <label>Select Events Needing a Partner For</label> <br /> <input type="checkbox" className="form-check-input" id="eventDoubles" name="eventsPlaying" onChange={this.onEventChange} /> &nbsp; <label className="form-check-label " htmlFor="eventDoubles">Doubles</label> &nbsp;&nbsp;&nbsp; <input type="checkbox" className="form-check-input" id="eventMixed" name="eventsPlaying" onChange={this.onEventChange} /> &nbsp; <label className="form-check-label" htmlFor="eventMixed">Mixed Doubles</label> </div> <div className="form-check col-md-3 form-check-inline text-center"> <label>Gender</label> <br /> <input type="radio" className="form-check-input" id="genderMale" name="gender" onChange={this.onGenderChange} required /> &nbsp; <label className="form-check-label " htmlFor="genderMale">Male</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="genderFemale" name="gender" onChange={this.onGenderChange} required /> &nbsp; <label className="form-check-label" htmlFor="genderFemale">Female</label> </div> <div className="form-group col-md-3 form-check form-check-inline text-center center-block"> <label>Mixed Doubles Skill Rating</label> <br /> <input type="radio" className="form-check-input" id="checkMixedRating25" name="checkMixedRating" onChange={this.onMixedRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkMixedRating25">2.5</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="checkMixedRating30" name="checkMixedRating" onChange={this.onMixedRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkMixedRating30">3.0</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="checkMixedRating35" name="checkMixedRating" onChange={this.onMixedRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkMixedRating35">3.5</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="checkMixedRating40" name="checkMixedRating" onChange={this.onMixedRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkMixedRating40">4.0</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="checkMixedRating45+" name="checkMixedRating" onChange={this.onMixedRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkMixedRating45">4.5+</label> </div> <div className="form-group col-md-3 form-check form-check-inline text-center center-block"> <label>Doubles Skill Rating</label> <br /> <input type="radio" className="form-check-input" id="checkDoublesRating25" name="checkDoublesRating" onChange={this.onDoublesRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkDoublesRating25">2.5</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="checkDoublesRating30" name="checkDoublesRating" onChange={this.onDoublesRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkDoublesRating30">3.0</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="checkDoublesRating35" name="checkDoublesRating" onChange={this.onDoublesRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkDoublesRating35">3.5</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="checkDoublesRating40" name="checkDoublesRating" onChange={this.onDoublesRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkDoublesRating40">4.0</label> &nbsp;&nbsp;&nbsp; <input type="radio" className="form-check-input" id="checkDoublesRating45+" name="checkDoublesRating" onChange={this.onDoublesRatingChange} onKeyPress={this.onKeyPress} required /> &nbsp; <label className="form-check-label" htmlFor="checkDoublesRating45">4.5+</label> </div> </div> <div className="form-group col-md-12 text-center"> <button disabled={this.state.disableButton} className="btn btn-lg btn-primary" type="submit">Submit</button> </div> </div> </form> </div > ) } } export default addPlayerLooking;
/** * * @description : car diagnostic system * @link : http://sample.ir * @author { Mahdi Imani } * @email : imani.mahdi[a]gmail.com * @copyright 'xxx Co., Ltd.' * * * @version {1.0.0} - 2017/09/07 18:15 * @version {1.0.1} - 2017/09/12 09:30 * * */ // =====| requirment |=================================== var MongoClient = require('mongodb').MongoClient; var ObjectId = require('mongodb').ObjectId; var chalk = require('chalk'); var _ = require('lodash'); // ===| 03 |=====| Configurations |============================== /** * * @description SERVER configuration * */ var config = require('../config/server.config'); var database_url = config.setConfig.database_url(); /********************************************************* * * * 01 Database Variable (MOCK) * * * *********************************************************/ // coperation var account_id_2 = new ObjectId(); var corporation_id_1 = new ObjectId(); var user_id_2 = new ObjectId(); var user_id_3 = new ObjectId(); var wallet_id_2 = new ObjectId(); var vehicle_id_2 = new ObjectId(); var ecu_id_2 = new ObjectId(); // single var account_id_1 = new ObjectId(); var user_id_1 = new ObjectId(); var vehicle_id_1 = new ObjectId(); var ecu_id_1 = new ObjectId(); var invoice_id_1 = new ObjectId(); var invoice_id_2 = new ObjectId(); var wallet_id_1 = new ObjectId(); var discount_id_1 = new ObjectId(); var discount_id_2 = new ObjectId(); var sos_request_id_1 = new ObjectId(); var activity_1 = new ObjectId(); var activity_2 = new ObjectId(); var diag_report_1 = new ObjectId(); var params_report_1 = new ObjectId(); // service center var service_center_id_1 = new ObjectId(); var user_id_4 = new ObjectId(); var user_id_5 = new ObjectId(); // vitrin var vitrin_id_1 = new ObjectId(); var vitrin_id_2 = new ObjectId(); var vitrin_id_3 = new ObjectId(); var vitrin_id_4 = new ObjectId(); var vitrin_id_5 = new ObjectId(); var vitrin_id_6 = new ObjectId(); var vitrin_id_7 = new ObjectId(); var vitrin_id_8 = new ObjectId(); var vitrin_id_9 = new ObjectId(); // vehicle database var vehicle_db_1 = new ObjectId(); var vehicle_db_2 = new ObjectId(); // model var user = [ { "_id": user_id_1, "first_name": "مهدی", "last_name": "ایمانی", "gender": "مرد", "portrait": ["../img/i8g665gt6868.jpg"], "birdthday": "1368/11/04", "national_code": "0011445732", "shenasname": "914510", "reg_city": "تهران", "father_name": "فرناد", "postal_code": "2017813749", "username": "mimani", "passworsd": "1234", "activated": true, "blocked": false, "phones": [ { "title": "شخصی", "type": "mobile phone", "value": "09124184801" } ], "social_nets": [ { "title": "telegram", "value": "@mahdi" } ], "emails": [ { "title": "ایمیل شخصی", "value": "imani.mahdi@gmail.com" } ], }, { "_id": user_id_2, "first_name": "محمد حسین", "last_name": "زارعی", "gender": "مرد", "portrait": ["../img/i8g665gtd15e2001s.jpg"], "birdthday": "1379/07/14", "national_code": "844100445732", "shenasname": "844100445732", "reg_city": "تهران", "father_name": "اصغر", "postal_code": "2017813749", "username": "mhzarei", "passworsd": "1234", "activated": true, "blocked": false, "phones": [ { "title": "شخصی", "type": "mobile phone", "value": "091280410451" } ], "social_nets": [ { "title": "telegram", "value": "@mhz" } ], "emails": [ { "title": "ایمیل شخصی", "value": "mhz1379@gmail.com" } ], }, { "_id": user_id_3, "first_name": "سینا", "last_name": "قصاع", "gender": "مرد", "portrait": ["../img/i8df5g4551fc0115gt.jpg"], "birdthday": "1368/03/18", "national_code": "004514415732", "shenasname": "004514415732", "reg_city": "تهران", "father_name": "میثم", "postal_code": "2017813749", "username": "sghasa", "passworsd": "1234", "activated": true, "blocked": false, "phones": [ { "title": "شخصی", "type": "mobile phone", "value": "09124585302" } ], "social_nets": [ { "title": "telegram", "value": "@g_ghasa" } ], "emails": [ { "title": "ایمیل شخصی", "value": "g_ghasa@tumsc.ac.ir" } ], }, { "_id": user_id_4, "first_name": "علی", "last_name": "تهرانی", "gender": "مرد", "portrait": ["../img/i80002555750f14.jpg"], "birdthday": "1359/05/19", "national_code": "8845415732", "shenasname": "315732", "reg_city": "تهران", "father_name": "عبداله", "postal_code": "2017813749", "username": "atehrani", "passworsd": "1234", "activated": true, "blocked": false, "phones": [ { "title": "شخصی", "type": "mobile phone", "value": "09124585302" } ], "social_nets": [ { "title": "telegram", "value": "@a_tehrani" } ], "emails": [ { "title": "ایمیل شخصی", "value": "tehrani1395@gmail.com" } ], }, { "_id": user_id_5, "first_name": "محمد", "last_name": "تهرانی", "gender": "مرد", "portrait": ["../img/i80002555750f14.jpg"], "birdthday": "1356/10/11", "national_code": "1105488105732", "shenasname": "215001", "reg_city": "تهران", "father_name": "عبداله", "postal_code": "2017813749", "username": "atehrani", "passworsd": "1234", "activated": true, "blocked": false, "phones": [ { "title": "شخصی", "type": "mobile phone", "value": "09124585302" } ], "social_nets": [ { "title": "telegram", "value": "@a_tehrani" } ], "emails": [ { "title": "ایمیل شخصی", "value": "tehrani1395@gmail.com" } ] } ]; var corporation = [ { "_id": corporation_id_1, "title": "شرکت فنی مهندسی مهاب قدس", "eco_code": "135120154151001", "user": [ { "user_id": user_id_3, "role": "ceo" }, { "user_id": user_id_3, "role": "cto" }, { "user_id": user_id_2, "role": "staff" } ], "activated": true, "blocked": false, "phones": [ { "title": "شخصی", "type": "mobile phone", "value": "09124184801" } ], "social_nets": [ { "title": "telegram", "value": "@mahab_ghods" } ], "emails": [ { "title": "ایمیل شخصی", "value": "info@mahab.co.ir" } ], } ] var servie_center = [ { "_id": service_center_id_1, "title": "مرکز فنی تهران", "eco_code": "135121154001114", "user": [ { "user_id": user_id_4, "role": "مدیر عامل" }, { "user_id": user_id_5, "role": "روابط عمومی" }, { "user_id": user_id_5, "role": "staff" } ], "address": { "city": "", "address": "", "location": { "lath": "", "long": "" } }, "activated": true, "blocked": false, "phones": [ { "title": "شخصی", "type": "تلفن اداری", "value": "021-4465-8865" } ], "social_nets": [ { "title": "telegram", "value": "@tehran_technic" } ], "emails": [ { "title": "ایمیل شخصی", "value": "info@tehran-technic.co.ir" } ], "sla": [ { "title": "خدمات فنی در محل", "commission": "10" } ] } ] var account = [ { "_id": account_id_1, "account_grade": "platinum", // platinum, silver, gold "account_type": "single", // corporation, single, group "corporation_id": "", "user": [ { "user_id": user_id_1, "role": "owner" }, { "user_id": user_id_1, "role": "admin" } ], "wallet_id": wallet_id_1, "vehicles": [ { "number": 1, "vehicle_id": vehicle_id_1, "buy_method": "خرید آنلاین", "description": "", "my_car": true, "owner_id": "" } ], "reg_date": "1395/12/26", "expire-date": "2017/12/26", "duration": "365", "activated": true, "blocked": false, "services": [ { "vitrin_id": vitrin_id_1, "access": true, "start": "1395/10/02", "end": "", }, { "vitrin_id": vitrin_id_2, "access": true, "start": "1395/10/02", "end": "", }, { "vitrin_id": vitrin_id_3, "access": true, "start": "1395/10/02", "end": "", }, { "vitrin_id": vitrin_id_4, "access": true, "start": "1395/10/02", "end": "", }, { "vitrin_id": vitrin_id_9, "access": true, "start": "1395/10/02", "end": "", } ] }, { "_id": account_id_2, "account_grade": "platinum", // platinum, silver, gold "account_type": "corporation", // corporation, single, group "corporation_id": corporation_id_1, "user": [ { "user_id": user_id_3, "role": "owner" }, { "user_id": user_id_3, "role": "admin" }, { "user_id": user_id_2, "role": "admin" } ], "wallet_id": wallet_id_2, "vehicles": [ { "number": 1, "vehicle_id": vehicle_id_2, "buy_method": "خرید آنلاین", "description": "", "my_car": true, "owner_id": "" } ], "reg_date": "1395/12/26", "expire-date": "2017/12/26", "duration": "365", "activated": true, "blocked": false, "services": [ { "vitrin_id": vitrin_id_1, "access": true, "start": "1395/10/02", "end": "", }, { "vitrin_id": vitrin_id_2, "access": true, "start": "1395/10/02", "end": "", }, { "vitrin_id": vitrin_id_3, "access": true, "start": "1395/10/02", "end": "", }, { "vitrin_id": vitrin_id_4, "access": true, "start": "1395/10/02", "end": "", } ] } ]; var vitrin = [ { "_id": vitrin_id_1, "type": "service", // product, license, charge, service "abbreviation": "sos", "title": "شبکه امداد فنی", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/sos", "price": "0", "dimension": "ریال", "max_order": "1", "limit": "unlimited", "duration": "", "access_users": ["public", "users", "registered", "vip", "admin"], "attribute": [] }, { "_id": vitrin_id_2, "type": "service", // product, license, charge, service "abbreviation": "lbs", "title": "سرویس های فنی بر پایه موقعیت مکانی", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/lbs", "price": "0", "dimension": "ریال", "max_order": "1", "limit": "unlimited", "duration": "", "access_users": ["public", "users", "registered", "vip", "admin"], "attribute": [] }, { "_id": vitrin_id_3, "type": "service", // product, license, charge, service "abbreviation": "lbs", "title": "سرویس های فنی بر پایه موقعیت مکانی", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/lbs", "price": "600000", "dimension": "ریال", "max_order": "1", "limit": "limited", "duration": "365", "access_users": ["registered", "vip", "admin"], "attribute": [] }, { "_id": vitrin_id_4, "type": "service", // product, license, charge, service "abbreviation": "onltrck", "title": "نظارت دائم بر خدمات", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/onltrck", "price": "0", "dimension": "ریال", "limit": "unlimited", "max_order": "30", "duration": "", "access_users": ["public", "users", "registered", "vip", "admin"], "attribute": [] }, { "_id": vitrin_id_5, "type": "service", // product, license, charge, service "abbreviation": "etax", "title": "عوارض شهری", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/etax", "price": "0", "dimension": "ریال", "max_order": "10000", "limit": "unlimited", "duration": "", "access_users": ["public", "users", "registered", "vip", "admin"], "attribute": [] }, { "_id": vitrin_id_6, "type": "service", // product, license, charge, service "abbreviation": "qr-marker", "title": "سرویس بارکد مصور فروش خودرو", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/qr-marker", "price": "100000", "dimension": "ریال", "max_order": "20", "limit": "unlimited", "duration": "", "access_users": ["public", "users", "registered", "vip", "admin"], "attribute": [] }, { "_id": vitrin_id_7, "type": "license", // product, license, charge, service "abbreviation": "secondary-license", "title": "نسخه مضاعف کاربر شخصی", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/secondary-license", "price": "100000", "dimension": "ریال", "max_order": "30", "limit": "unlimited", "duration": "", "access_users": ["public", "users", "registered", "vip", "admin"], "attribute": [] }, { "_id": vitrin_id_8, "type": "product", // product, license, charge, service "abbreviation": "", "title": "دستگاه دیاگ نسخه سبک", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/secondary-license", "price": "800000", "dimension": "ریال", "max_order": "30", "limit": "unlimited", "duration": "", "access_users": ["public", "users", "registered", "vip", "admin"], "attribute": [ { "title": "wight", "value": "132", "dimension": "kg" } ] }, { "_id": vitrin_id_9, "type": "service", // product, license, charge, service "abbreviation": "remm", "title": "سیستم یادآوری هوشمند", "parent": "", "description": "", "online_refrence": "http://www.sample.ir/docs/service/secondary-license", "price": "0", "dimension": "ریال", "max_order": "1", "limit": "unlimited", "duration": "", "access_users": ["public", "users", "registered", "vip", "admin"], "attribute": [] } ]; var invoice = [ { "_id": invoice_id_1, "systemic_code": "", "type": "invoice", //pre-invoice, invoice "description": "", "seller": { "title": "sample", "eco_code": "1540141101120", "address": "تهران، خیابان شهید مطهری، نبش هتل بزرگ تهران" }, "buyer": user_id_1, "date": "2017/12/12", "time": "13:30", "price": "100000", "discount_id": "0", "dimension": "ریال", "payment-type": "online-saman", "status": true }, { "_id": invoice_id_2, "systemic_code": "", "type": "invoice", //pre-invoice, invoice "description": "", "seller": { "title": "sample", "eco_code": "1540141101120", "address": "تهران، خیابان شهید مطهری، نبش هتل بزرگ تهران" }, "buyer": user_id_1, "date": "2017/12/12", "time": "13:30", "price": "15000000", "discount_id": discount_id_1, "dimension": "ریال", "payment-type": "online-saman", "status": true } ] var transaction = [ { "invoice_id": invoice_id_1, "vitrin_id": "", "wallet_id": "", "title": "شارژ اکانت", "qty": "1", "discount": "0", "credit": "0", "debit": "0", "dimension": "ریال", "type": "بستانکاری", "category": "شارژ کیف پول", "status": true }, { "invoice_id": invoice_id_1, "vitrin_id": vitrin_id_6, "wallet_id": "", "title": "سرویس بارکد مصور فروش خودرو", "qty": "1", "discount": "0", "credit": "0", "debit": "100000", "dimension": "ریال", "type": "بدهکاری", "date": "2017/12/12", "category": "service", "status": true }, { "invoice_id": invoice_id_2, "vitrin_id": vitrin_id_6, "wallet_id": "", "title": "سرویس بارکد مصور فروش خودرو", "qty": "1", "discount": "0", "credit": "", "price": "100000", "dimension": "ریال", "type": "بدهکاری", "date": "2017/12/12", "category": "service", "status": true } ]; var discount = [ { "_id": discount_id_1, "title": "تخفیف عید غدیر خم", "vitrin_id": "", "type": "discount", "price": "", "percent": "30", "max_order": "10", "start": "2017/01/10", "end": "2017/10/01", "code": "et211001" }, { "_id": discount_id_2, "title": "تخفیف عید غدیر خم", "vitrin_id": "", "type": "gift", "price": "100000", "percent": "", "max_order": "10", "start": "2017/01/10", "end": "2017/10/01", "code": "et211001" } ] var wallet = [ { "_id": wallet_id_1, "account_id": account_id_1, "value": "125000", "dimension": "ریال", "gift_id": [], // ==> 'discount_id' "start": "1395/01/12", "end": "2017/12/20" }, { "_id": wallet_id_2, "account_id": account_id_2, "value": "125000", "dimension": "ریال", "gift_id": [], // ==> 'discount_id' "start": "1395/01/12", "end": "2017/12/20" } ]; var vehicle_db = [ { "_id": vehicle_db_1, "type": "موتور", "vehicle_name": "موتور سیکلت", "system": "آپاچی", "type": "cc160", "color": "خاکستری - نوک مداد", "capacity": "1", "cylender": "1", "axis": "2", "wheel": "2" }, { "_id": vehicle_db_2, "type": "خودرو", "vehicle_name": "پراید", "system": "", "type": "x132", "color": "خاکستری - نوک مداد", "capacity": "4", "cylender": "5", "axis": "4", "wheel": "4" } ] var vehicle = [ { "_id": vehicle_id_1, "ecu_id": ecu_id_1, "vehicle_db_id": vehicle_db_1, "iden": "wre5t12", "national_code": "irA54005581004154", "engine_number": "5208980001", "body_number": "NE11d512", "model": "1389", }, { "_id": vehicle_id_2, "ecu_id": ecu_id_2, "vehicle_db_id": vehicle_db_2, "iden": "gret33", "national_code": "irA54002115000141", "engine_number": "7288910001", "body_number": "NE05001545", "model": "1382", } ]; var sos_request = [ { "_id": sos_request_id_1, "account_id": account_id_1, "vehicle_id": vehicle_id_1, "ecu_id": ecu_id_1, "payment_id": "", "servie_center_id": service_center_id_1, "category": "", // NC, commision "diag_report_id": diag_report_1, "params_report_id": params_report_1, "description": "", "activity_id": [activity_1, activity_2], } ]; var activity = [ { "_id": activity_1, "creator_id": user_id_1, "title": "درخواست کمک", "systemic_code": "", "type": "sos", "description": "", "address": { "title": "", "city": "", "address": "", "location": { "lath": "", "long": "" } }, "time": { "generation": { "status": true, "user_id": "", "date": "2017/12/15", "time": "13:10", "description": "" }, "done": { "status": true, "user_id": "", "date": "2017/12/15", "time": "13:10", "description": "" }, "cancellation": { "status": false, "user_id": "", "date": "2017/08/12", "time": "08:50", "description": "" } } }, { "_id": activity_2, "creator_id": user_id_4, "title": "اعزام کارشناس فنی", "systemic_code": "", "type": "sos", "description": "", "address": { "title": "", "city": "", "address": "", "location": { "lath": "", "long": "" } }, "time": { "generation": { "status": true, "user_id": "", "date": "2017/12/15", "time": "13:10", "description": "" }, "done": { "status": true, "user_id": "", "date": "2017/12/15", "time": "13:10", "description": "" }, "cancellation": { "status": false, "user_id": "", "date": "2017/08/12", "time": "08:50", "description": "" } } }, ] var diag_report = [ { "_id": diag_report_1, "account_id": account_id_1, "vehicle_id": vehicle_id_1, "ecu_id": ecu_id_1, "status": "", "description": "", "failure_code": ["5400", "e102", "5310"], "date": "2017/10/12", "time": "12:30" } ] var diag_details = [ { "code": "5400", "title": "", "icon": "alert", "abbreviation": "ert33", "description": "", "tooltips": "", "need_sos": true }, { "code": "e102", "title": "", "icon": "alert", "abbreviation": "tr1010", "description": "", "tooltips": "", "need_sos": true }, { "code": "5310", "title": "", "icon": "alert", "abbreviation": "03474", "description": "", "tooltips": "", "need_sos": true } ] var params_report = [ { "_id": params_report_1, "account_id": account_id_1, "vehicle_id": vehicle_id_1, "ecu_id": ecu_id_1, "date": "2017/12/10", "time": "12:30", "type": "snapShot, average, multi", "parameters": { "ertw": "5200", "tte7": "280" } } ]; // 43 parameters var params_details = [ { "title": "دور موتور", "title_en": "engrine rate", "abrivation": "rpm", "systemic_name": "ertw", "max": "6000", "min": "4000", "optimum": "5000", "dimension": "meter/time", "level": "super dangerous" }, { "title": "سرعت پاشش بنزین", "title_en": "fuel injection rate", "abrivation": "", "systemic_name": "tte7", "max": "300", "min": "250", "optimum": "272", "dimension": "liter/minute", "level": "normal" }, { "title": "کیلومتر کارکرد", "title_en": "usage in kilometer", "abrivation": "", "systemic_name": "ugkm", "max": "300", "min": "250", "optimum": "272", "dimension": "liter/minute", "level": "normal" } ] var ecu_detail = [ { "_id": ecu_id_1, "title": "Bosch", "title_fa": "بوش", "image": "", "model": "2001", "serie": "x22", "producer_country": "آلمان", "company": "سامان سیکلت", "weight": "120gr", "docs": "http://www.sample.ir/technician/y4747588", "technical_sheet": "http://www.bosch.ir/support/car/ecu/x22", }, { "_id": ecu_id_2, "title": "Bosch", "title_fa": "بوش", "image": "", "model": "2011", "serie": "lando", "producer_country": "آلمان", "company": "ایران خودرو", "weight": "120gr", "docs": "http://www.sample.ir/technician/y4747588", "technical_sheet": "http://www.bosch.ir/support/car/ecu/x22", } ]; var ecu_xml = [ { "ecu_id": ecu_id_1, "xml": "http://www.sample.ir/xml/x22.xml", "version": "1.1.51", "release_date": "2017/05/12", "hash_code": "124erx42p915ve", "accesss": ["public", "sample", "registered", "vip"] }, { "ecu_id": ecu_id_2, "xml": "http://www.sample.ir/xml/lando.xml", "version": "1.1.51", "release_date": "2017/05/12", "hash_code": "124erx42p915ve", "accesss": ["public", "sample", "registered", "vip"] }, ]; var session = [ { "user_id": "", "token": "", "reg_date": "", "reg_time": "", "expire_date": "", "expire_time": "" } ]; var user_setting = [ { "user_id": user_id_1, "setting": [ { "platform": "app", "device": "andriod", "mac": "", "theme_name": "classic", "bgColor": "teal", "disactive_sub_system": ["message", "ringtone"], "save_session": false }, { "platform": "web_app", "device": "web_portal", "mac": "", "theme_name": "classic", "bgColor": "gray", "disactive_sub_system": [], "save_session": false }, ], "expire_date": "2017/12/15", "expire_time": "14:30", } ]; var message = [ { "parent_id": "", "type": "message", // chat, message, to_do "still_open": true, // check parent open or not "noreply": false, "sender": { "user_id":user_id_1, "priority": "خیلی فوری", "recive_open_req": true, "favorite": false, }, "reciver": { "user_id":[user_id_2], "recive_open_accept": true, "favorite": false }, "message": { "subject": "تست سیستم پیام", "body": "با سلام، اولین پیام این سیستم ارسال می شود", "date": "", "time": "", "attachment": [], "location": [], "user_operator_id": [] } } ]; var trip = [ { "type": "in_city", // car_pooling, in_city "trip_recorder": "mobile", // mobile, diag_device "account_id": account_id_1, "vehicle_id": vehicle_id_1, "user_id": user_id_1, "popularity": 5, // 5 of 10 "frequent_trip": true, "origin": { "location":{ "lath": "", "long": "" }, "city": "", "address": "", "date": "2017/09/12", "time": "09:32" }, "destination": { "location":{ "lath": "", "long": "" }, "city": "", "address": "", "date": "2017/09/12", "time": "12:32" }, "duration": "04:00", "distance": "35.18", "distance_dimension": "km", "distance_recorder": "ecu", // ecu, mobile, estimation "speed_average": "38.8", "speed_dimension": "km/hr", "speed_recorder": "ecu", // ecu, mobile, estimation } ]; var remmberance = [ { "title": "تعویض روغن خودرو", "priority": "high", "start_date": "2017/09/15", "start_time": "08:30", "iteration": { "repeatable": true, "value": 15, "dimension_value": "day", }, "criteria": [ { "source": "account", "item": "activated", "value": true }, { "source": "account", "item": "blocked", "value": false }, { "source": "account", "item": "account_type", "value": "single" }, { "source": "account", "item": "services", "value": {"vitrin_id": vitrin_id_9, "access": true} }, { "source": "vehicle", // account > vehicle > vehicle_db "item": "type", "value": "خودرو" }, { "source": "params_details", "item": "ugkm", "min": 4000, "min_dimension": "km", "max": 6000, "max_dimension": "km", "value": 5000 } ], "operation": [ { "title": "ارسال پوش نوتیفیکیشن", "abbreviation": "push_not", "destination": [ { "device": "andriod", "icon": "alert", "message": "خودروی شما نیازمند تعویض روغن است." }, { "device": "ios", "icon": "alert", "message": "خودروی شما نیازمند تعویض روغن است." } ], "start": { "after": 5, "after_dimension": "hr", "max_try": 5 }, "end": { "after": 30, "after_dimension": "hr", "max_try": 5 }, "cancellation": { "after": 48, "after_dimension": "hr" } }, { "title": "اعمال تخفیف در کیف پول برای خرید", "abbreviation": "discount", "discount": { "value": 15, "dimension_value": "percent" }, "destination": [ { "device": "andriod", "message": "تخفیف ویژه بمناسبت عید سعید فطر چهت تعویض روغن خودرو" }, { "device": "ios", "message": "تخفیف ویژه بمناسبت عید سعید فطر چهت تعویض روغن خودرو" } ], "start": { "after": 5, "after_dimension": "hr", "max_try": 5 }, "end": { "after": 30, "after_dimension": "hr", "max_try": 5 }, "cancellation": { "after": 48, "after_dimension": "hr" } } ] } ]; var qr = [ { "account_id": account_id_1, "vehicle_id": vehicle_id_1, "params_report_id": params_report_1, "diag_report_id": diag_report_1, "qr_uuid": "45w024s", // random generation http://sample.com/qr/45w024s "sample_market_id": "", "sample_market": true, "printable": false, "start_date": "2017/03/12", "start_time": "13:20", "end_time": "2017/09/12", "start_time": "13:20", "max_visit": "" } ]; /********************************************************* * * * 02 AUTO DATABASE GENERATOR * * * *********************************************************/ /** * * 01 * core function * */ MongoClient.connect(database_url, function (err, db) { if (err) throw err; console.log("\n" + chalk.yellow("==================================================")); console.log("\n" + chalk.yellow("=======|"), " START ", chalk.yellow("|================================")); console.log("\n" + " :::: sample database installation :::: " + "\n\n" ); /** * * 01 * CREATE 'user' collections * * @description create user * */ db.collection("user").insertMany(user, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" user "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount) ); db.close(); }); /** * * 02 * CREATE 'corporation' collections * * @description create corporation * */ db.collection("corporation").insertMany(corporation, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" corporation "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 03 * CREATE 'servie_center' collections * * @description create servie_center * */ db.collection("servie_center").insertMany(servie_center, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" servie_center "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 04 * CREATE 'account' collections * * @description create account * */ db.collection("account").insertMany(account, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" account "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 05 * CREATE 'vitrin' collections * * @description create vitrin * */ db.collection("vitrin").insertMany(vitrin, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" vitrin "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 06 * CREATE 'wallet' collections * * @description create wallet * */ db.collection("wallet").insertMany(wallet, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" wallet "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 07 * CREATE 'invoice' collections * * @description create invoice * */ db.collection("invoice").insertMany(invoice, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" invoice "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 08 * CREATE 'transaction' collections * * @description create transaction * */ db.collection("transaction").insertMany(transaction, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" transaction "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 09 * CREATE 'discount' collections * * @description create discount * */ db.collection("discount").insertMany(discount, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" discount "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 10 * CREATE 'vehicle_db' collections * * @description create vehicle_db * */ db.collection("vehicle_db").insertMany(vehicle_db, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" vehicle_db "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 11 * CREATE 'vehicle' collections * * @description create vehicle * */ db.collection("vehicle").insertMany(vehicle, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" vehicle "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 12 * CREATE 'sos_request' collections * * @description create sos_request * */ db.collection("sos_request").insertMany(sos_request, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" sos_request "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 13 * CREATE 'activity' collections * * @description create activity * */ db.collection("activity").insertMany(activity, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" activity "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 14 * CREATE 'diag_report' collections * * @description create diag_report * */ db.collection("diag_report").insertMany(diag_report, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" diag_report "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 15 * CREATE 'diag_details' collections * * @description create diag_details * */ db.collection("diag_details").insertMany(diag_details, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" diag_details "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 16 * CREATE 'params_report' collections * * @description create params_report * */ db.collection("params_report").insertMany(params_report, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" params_report "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 17 * CREATE 'params_details' collections * * @description create params_details * */ db.collection("params_details").insertMany(params_details, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" params_details "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 18 * CREATE 'ecu_detail' collections * * @description create ecu_detail * */ db.collection("ecu_detail").insertMany(ecu_detail, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" ecu_detail "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 19 * CREATE 'ecu_xml' collections * * @description create ecu_xml * */ db.collection("ecu_xml").insertMany(ecu_xml, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" ecu_xml "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 20 * CREATE 'session' collections * * @description create session * */ db.collection("session").insertMany(session, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" session "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 21 * CREATE 'user_setting' collections * * @description create user_setting * */ db.collection("user_setting").insertMany(user_setting, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" user_setting "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 22 * CREATE 'message' collections * * @description create message * */ db.collection("message").insertMany(message, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" message "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 23 * CREATE 'trip' collections * * @description create trip * */ db.collection("trip").insertMany(trip, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" trip "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 24 * CREATE 'remmberance' collections * * @description create remmberance * */ db.collection("remmberance").insertMany(remmberance, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" remmberance "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); /** * * 25 * CREATE 'qr' collections * * @description create qr * */ db.collection("qr").insertMany(qr, function (err, res) { if (err) throw err; console.log(chalk.bgRed.white(" qr "), " collection created", chalk.green("successfully"), "."); console.log("documents inserted: " + chalk.red(res.insertedCount)); db.close(); }); setTimeout(() => { console.log("\n" + chalk.yellow("=======|"), " FINISH INSTALLATION " , chalk.yellow("|=========================\n")); }, 3000); });
import React from "react"; import { Component } from "react"; import Major from "./UnrelatedMajor.js" const stuff = [ { name: "Computing", rank: 15, salary: 12, desc: "COMP This is the description of this major. It does stuff, stuff, stuff, stuff, stuff, stuff, stuff, stuff, yes, yes, and yes.", jobs: ["Job 1", "Job 2", "Job 3"] }, { name: "Business", rank: 2, salary: 2020000, desc: "BUS This is the description of this major. It does stuff, stuff, stuff, stuff, stuff, stuff, stuff, stuff, yes, yes, and yes.", jobs: ["Job 1", "Job 2", "Job 3"] }, { name: "English", rank: 124, salary: 12034, desc: "ENG This is the description of this major. It does stuff, stuff, stuff, stuff, stuff, stuff, stuff, stuff, yes, yes, and yes.", jobs: ["Job 1", "Job 2", "Job 3"] }, { name: "Art", rank: 1, salary: 12, desc: "ART This is the description of this major. It does stuff, stuff, stuff, stuff, stuff, stuff, stuff, stuff, yes, yes, and yes.", jobs: ["Job 1", "Job 2", "Job 3"] }, { name: "Science", rank: 10, salary: 12, desc: "SCI This is the description of this major. It does stuff, stuff, stuff, stuff, stuff, stuff, stuff, stuff, yes, yes, and yes.", jobs: ["Job 1", "Job 2", "Job 3"] }, ] class Job extends Component { constructor(props) { super(props); this.state = { majors: stuff, sort: ["NONE", 0], searchTerm: '', } this.search = this.search.bind(this); } search(event) { this.setState({searchTerm: event.target.value}, () => this.setState({majors: this.applySearch(stuff)})); } applySearch(items) { let temp = []; items.forEach(major => { if(major.name.toLowerCase().search(this.state.searchTerm.toLowerCase()) != -1) temp.push(major); }) return temp; } sort = type => { let temp = this.applySearch(stuff) if(type == "RANK") { if(this.state.sort[0] != "RANK" || this.state.sort[1] == 0) { temp.sort(function(a, b){ if(a.rank < b.rank) { return -1; } if(a.rank > b.rank) { return 1; } return 0; }) this.setState({sort: ["RANK", 1]}) } else if (this.state.sort[1] == 1) { temp.sort(function(a, b){ if(a.rank > b.rank) { return -1; } if(a.rank < b.rank) { return 1; } return 0; }) this.setState({sort: ["RANK", 2]}); } else { this.setState({sort: ["RANK", 0]}); } } else if (type == "SALARY") { if(this.state.sort[0] != "SALARY" || this.state.sort[1] == 0) { temp.sort(function(a, b){ if(a.salary < b.salary) { return -1; } if(a.salary > b.salary) { return 1; } return 0; }) this.setState({sort: ["SALARY", 1]}) } else if (this.state.sort[1] == 1) { temp.sort(function(a, b){ if(a.salary > b.salary) { return -1; } if(a.salary < b.salary) { return 1; } return 0; }) this.setState({sort: ["SALARY", 2]}); } else { this.setState({sort: ["SALARY", 0]}); } } this.setState({majors: temp}); } render(){ let wrap = { width: "90vw", marginLeft: "auto", marginRight: "auto", height: "fit-content", borderCollapse: "collapse", borderColor: "#dcdcdc", }; return( <div> <div style={{position: "relative"}}> <input style={{border:"1px solid #dcdcdc", position: "absolute"}} value={this.state.searchTerm} type="text" placeholder="Search" onChange={this.search}/> <div style={{position: "absolute",}}>I</div> </div> <table border="1" frame="void" rules="rows" style={wrap}> <colgroup> <col style={{width: "3%", minWidth: "3%"}}/> <col style={{width: "67%", minWidth: "70%"}}/> <col style={{width: "10%", minWidth: "10%"}}/> <col style={{width: "20%", minWidth: "20%"}}/> </colgroup> <tr style={{background: "#f9f9f9", textAlign: "left", padding: "2vw", fontSize: "2.75vh"}}> <th></th> <th>Major</th> <th>Ranking <span onClick={() => this.sort("RANK")}>^</span></th> <th>Salary <span onClick={() => this.sort("SALARY")}>^</span></th> </tr> <tbody> {this.state.majors.map(major => <Major name={major.name} rank={major.rank} salary={major.salary} desc={major.desc} jobs={major.jobs} /> )} </tbody> </table> </div> ); } } export default Job;
const urlParams = new URLSearchParams(window.location.search); const artist = urlParams.get("country"); const url = `https://keadata-ece4.restdb.io/rest/golden-ratio-database?sort=country&q={"$distinct": "country"}`; // API key const key = { headers: { "x-apikey": "6151ddb6dfa7346e2f9690b9" } }; fetch(url, key) .then(function (res) { return res.json(); }) .then(function (data) { handleData(data); }); function handleData(data) { data.forEach(showCountry); } function showCountry(country) { console.log(country); const artistCard = document.querySelector("#country-template").content; const clone = artistCard.cloneNode(true); clone.querySelector(".country-link").textContent = country; clone .querySelector(".country-link") .setAttribute("href", "country.html?country=" + country); const parent = document.querySelector("#country-list"); parent.appendChild(clone); }
const express = require('express') , router = express.Router() , config = require('../config') , users = require('../model/users') ; /* GET users listing. */ router.get('/', function (req, res, next) { users.selectAll (function (err, rows) { if (err) next (err); else res.render ('users', { rows : rows, session: req.session.passport.user }); }); }); router.post('/', function (req, res, next) { var id = req.body.id , name = req.body.name , password = req.body.password , role = req.body.role ; // TODO more correct fieald processing if (id && name && password && role) { // update users.update (id, name, password, role, function (err, result) { if (err) next (err); else res.redirect ('users'); }); } else if (name && password && role) { // append users.insert (name, password, role, function (err, rows) { if (err) next (err); else res.redirect ('users'); }); } else if (id) { // delete users.delete (id, function (err, rows) { if (err) next (err); else res.redirect ('users'); }); } }); router.get('/:id', function (req, res, next) { var title, user; if (req.params.id == 'add') { user = { name:'', password:'', role:'OPERATOR'} } else { user = users.find (req.params.id); } if (user) res.render ('user', { user: user, config: config, session: req.session.passport.user }); else res.render ('nouser', { session: req.session.passport.user }); }); module.exports = router;
export const SET_SIGNUP_TYPE = 'SET_SIGNUP_TYPE'; export const SET_HOST_NAME = 'SET_HOST_NAME'; export const SET_HOST_NAME_BLURRED = 'SET_HOST_NAME_BLURRED'; export const SET_HOST_AGE = 'SET_HOST_AGE'; export const SET_HOST_AGE_BLURRED = 'SET_HOST_AGE_BLURRED'; export const SET_HOST_SEX = 'SET_HOST_SEX'; export const SET_HOST_SEX_BLURRED = 'SET_HOST_SEX_BLURRED'; export const SET_HOST_ADDRESS = 'SET_HOST_ADDRESS'; export const SET_HOST_ADDRESS_BLURRED = 'SET_HOST_ADDRESS_BLURRED'; export const SET_HOST_EMAIL = 'SET_HOST_EMAIL'; export const SET_HOST_EMAIL_BLURRED = 'SET_HOST_EMAIL_BLURRED'; export const SET_HOST_PHONENUMBER = 'SET_HOST_PHONENUMBER'; export const SET_HOST_PHONENUMBER_BLURRED = 'SET_HOST_PHONENUMBER_BLURRED'; export const SET_HOST_DESCRIPTION = 'SET_HOST_DESCRIPTION'; export const SET_HOST_DESCRIPTION_BLURRED = 'SET_HOST_DESCRIPTION_BLURRED'; export const SET_HOST_INTERESTS = 'SET_HOST_INTERESTS'; export const SET_HOST_INTERESTS_BLURRED = 'SET_HOST_INTERESTS_BLURRED'; export const SET_AUDIENCE_NAME = 'SET_AUDIENCE_NAME'; export const SET_AUDIENCE_NAME_BLURRED = 'SET_AUDIENCE_NAME_BLURRED'; export const SET_AUDIENCE_AGE = 'SET_AUDIENCE_AGE'; export const SET_AUDIENCE_AGE_BLURRED = 'SET_AUDIENCE_AGE_BLURRED'; export const SET_AUDIENCE_SEX = 'SET_AUDIENCE_SEX'; export const SET_AUDIENCE_SEX_BLURRED = 'SET_AUDIENCE_SEX_BLURRED'; export const SET_AUDIENCE_ADDRESS = 'SET_AUDIENCE_ADDRESS'; export const SET_AUDIENCE_ADDRESS_BLURRED = 'SET_AUDIENCE_ADDRESS_BLURRED'; export const SET_AUDIENCE_EMAIL = 'SET_AUDIENCE_EMAIL'; export const SET_AUDIENCE_EMAIL_BLURRED = 'SET_AUDIENCE_EMAIL_BLURRED'; export const SET_AUDIENCE_PHONENUMBER = 'SET_AUDIENCE_PHONENUMBER'; export const SET_AUDIENCE_PHONENUMBER_BLURRED = 'SET_AUDIENCE_PHONENUMBER_BLURRED'; export const SET_AUDIENCE_COUNTRY = 'SET_AUDIENCE_COUNTRY'; export const SET_PREVIOUS_PERFORMANCE = 'SET_PREVIOUS_PERFORMANCE';
import DivisionDetails from './DivisionDetails'; export default DivisionDetails;
import cookieUtils from '@utils/cookie' export default { active: 1, oneShow: false, twoShow: false, courseIdSign: '', threeList: [], allTeacher: [], allCourseTeacherList: [], courseStudyProgress: [], courseStudyProgressSaccomplish: [], activeShow: 1, }
import React from 'react' import { Card, Col } from 'antd' function GridCards(props) { return ( // 한 행에 최대 24개 <Col lg={6} md={8} xs={24}> {/* <Card title={props.goodClsf} extra={<a ref="#">More</a>} style={{width: 300}} bordered={false}> <p>{props.goodAbnm}</p> </Card> */} { !!props.goodClsf && <div style={{position: 'relative', margin: '5px'}}> <div> <a href={`/insurance/${props.goodAbnm}`}> <Card title={props.goodClsf} bordered={true}> <p>{props.goodAbnm}</p> </Card> </a> </div> </div> } </Col> ) } export default GridCards
/** * Created by diakabanab on 10/26/2016. */ define(["jquery", "chord/Positions"], function($, Positions) { var Interface = function(container) { this.element = $("<div>", { "id": "Interaction" }).appendTo(container); this.element.on("mousedown", this.mouseup.bind(this)); this.element.on("touchstart", this.touchstart.bind(this)); this.element.on("touchend", this.mouseup.bind(this)); this.element.on("mouseup", this.mouseup.bind(this)); this.onstart = function(){}; this.onend = function(){}; }; /** * Gets the chord at its given position */ Interface.prototype.getChord = function(x, y) { var twoPi = Math.PI * 2; var width = this.element.width; var height = this.element.height; x = ((x - width / 2) / width) * 2; y = ((y - height / 2) / height) * 2; var theta = Math.atan2(y, x); var radius = Math.sqrt(x*x + y*y); var i = 0; for (var letter in Positions.major) { var coordinate = Positions.major[letter]; if (theta > coordinate.startAngle && theta < coordinate.endAngle) { break; } else if (theta + twoPu > coordinate.startAngle && theta + twoPi < coordinate.endAngle) { break; } i++; } if (radius < Positions.innerRadius) { return [Positions.minorOrder[i], "minor"]; } else { return [Positions.majorOrder[i], "major"]; } }; Interface.prototype.mousedown = function(e) { e.preventDefault(); e.stopPropagation(); var res = this.getChord(e.offsetX, e.offsetY); this.onstart(res[0], res[1]); }; Interface.prototype.touchstart = function(e) { e.preventDefault(); e.stopPropagation(); var touches = e.originalEvent.touches; var offset = this.element.offset(); if (touches.length > 0){ var touch = touches[0]; var res = this.getChord(touch.pageX - offset.left, touch.pageY - offset.top); this.onstart(res[0], res[1]); } }; Interface.prototype.mouseup = function(e) { this.onend(); }; return Interface; });
import React from 'react'; import { Link } from 'react-router-dom'; const Navbar = () => { return ( <nav className="flex justify-between items-center h-16 bg-white text-black shadow-sm font-mono font-bold"> <Link to="/" className="pl-8">EGG</Link> <div className="px-4 cursor-pointer md:hidden"> <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z" /></svg> </div> <div className="pr-8 md:block hidden"> <Link to="/">Home</Link> <Link to="/" className="ml-4">About</Link> <Link to="/" className="ml-4">Contact</Link> <Link to="/" className="ml-4">Menu</Link> </div> </nav> ) } export default Navbar
exports.m09 = (id, A187, tampilTanggal, whatsapp, youtube, tampilWaktu, instagram, nomer, aktif) => { return ` ❉──────────❉ *${A187}* ❉──────────❉ 📆 *${tampilTanggal}* 📌STATUS BOT MK: *${aktif}* ━━━━━━━━━━━━━━━━━━━━━ ╔══════════════╗ ✯ MK MODS ✯ ╚══════════════╝ ━━━━━━━━━━━━━━━━━━━━━ *Aqui é o @bot* 🤳⚡ *Sobre as mensagens temporárias* Você pode ativar as mensagens temporárias e enviar mensagens que desaparecem no WhatsApp. Ao ativar esse recurso, as novas mensagens enviadas em uma conversa desaparecerão após 7 dias. A configuração mais recente afeta todas as mensagens de uma conversa, mas as mensagens enviadas ou recebidas antes da ativação das mensagens temporárias não serão afetadas. Em conversas individuais, ambos os usuários podem ativar ou desativar as mensagens temporárias. Já em conversas em grupo, somente os admins podem ativar ou desativar o recurso. Mensagens temporárias desaparecerão mesmo que um usuário não abra o WhatsApp durante sete dias. Contudo, pode ser que a pré-visualização da mensagem seja exibida nas notificações até que o WhatsApp seja aberto. Ao responder diretamente a uma mensagem, ela será exibida acima da sua resposta. Se você responder diretamente a uma mensagem temporária, o texto dessa mensagem poderá ser exibido mesmo depois de sete dias. Se uma mensagem temporária é encaminhada para uma conversa onde as mensagens temporárias estão desativadas, essa mensagem não desaparecerá da conversa para onde foi encaminhada. Se um usuário fizer backup antes de uma mensagem desaparecer, essa mensagem temporária será incluída ao backup. Contudo, a mensagem temporária será apagada quando o usuário restaurar o backup. Observação: use as mensagens temporárias somente com pessoas nas quais você confia. É possível que uma pessoa: Encaminhe ou tire uma captura de tela das mensagens temporárias para salvá-las antes que elas desapareçam. Copie e salve o conteúdo das mensagens temporárias antes que elas desapareçam. Tire uma foto das mensagens temporárias com uma câmera ou outro aparelho antes que elas desapareçam. Arquivos de mídia em mensagens temporárias Por padrão, os arquivos de mídia que você recebe no WhatsApp são automaticamente baixados para suas fotos. Caso as mensagens temporárias estejam ativadas, os arquivos de mídia enviados em uma conversa também desaparecerão, mas estarão salvos nos aparelhos que tenham o download automático ativado. Você pode desativar o download automático no WhatsApp em Configurações/Ajustes > Armazenamento e dados. Para chamar o Menu digite: *@Bot* ╠════════════════════ ║ MAIKON ╚════════════════════` }
$('#alert-message button.close').click(function() { $('#alert-message').slideUp(200); }); $('form .btn-submit').click(function() { $.ajax({ url:$(this).parent().attr('action'), type:'POST', dataType:'json', data:$(this).parent().serialize(), success:function(data) { if (data.status) { $('#alert-message').attr('class', 'alert alert-dismissable alert-' + data.status); $('#alert-message span.message').html(data.message); $('#alert-message').slideDown(200); } }, error:function(jqXHR,textStatus,errorThrown) { $('#alert-message').attr('class', 'alert alert-dismdata.messageissable alert-danger'); $('#alert-message span.message').html(jqXHR.responseText); $('#alert-message').slideDown(200); } }); /*alert($(this).parent().serialize()); alert($(this).parent().attr('action'));*/ });
/** * fetch 网络请求的header,可自定义header 内容 * @type {{Accept: string, Content-Type: string, accessToken: *}} */ import {Toast,Loading} from "./loading" import NetInfo from "@react-native-community/netinfo" import {Alert} from "react-native"; import CONF from "../conf/" import User from "../conf/user"; const Ip=CONF['FETCH_IP']; // const Ip="http://192.168.1.200:9000"; global.imgurl=CONF['IMAGE_IP']; // const Ip="http://221.204.213.211:8083"; let header = { 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', }; let header2 = { 'Accept': 'application/json', 'Content-Type': 'application/json', }; // // let header1 = { // 'Accept': 'application/json', // 'Content-Type': 'multipart/form-data', // }; /**支持上传的图片格式*/ const extgroup=["jpg","JPG","png","PNG","gif","GIF","jpeg"]; /** * GET 请求时,拼接请求URL * @param url 请求URL * @param params 请求参数 * @returns {*} */ const handleUrl = url => params => { if (params) { let paramsArray = [] Object.keys(params).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(params[key]))) if (url.search(/\?/) === -1) { typeof (params) === 'object' ? url += '?' + paramsArray.join('&') : url } else { url += '&' + paramsArray.join('&') } } return url } const handleUrl2 = url => params => { if (params) { let paramsArray = [] Object.keys(params).forEach(key => paramsArray.push(key + '=' + encodeURIComponent(params[key]))) return paramsArray.join('&') } } /** * fetch 网络请求超时处理 * @param original_promise 原始的fetch * @param timeout 超时时间 30s * @returns {Promise.<*>} */ const timeoutFetch = (original_fetch, timeout = 20000) => { // global.timeoutBlock = () => {} let timeoutBlock; let timeout_promise = new Promise((resolve, reject) => { timeoutBlock = (type) => { // 请求超时处理 // if(type=='notauto') // reject('请求取消'); // else reject('请求超时'); } }) // Promise.race(iterable)方法返回一个promise // 这个promise在iterable中的任意一个promise被解决或拒绝后,立刻以相同的解决值被解决或以相同的拒绝原因被拒绝。 let abortable_promise = Promise.race([ original_fetch, timeout_promise ]) setTimeout(() => { timeoutBlock() }, timeout) return abortable_promise } /** * 网络请求工具类 */ export default class HttpUtils { constructor(){ this.current=0; this.picgroup=[]; } static timer=null; /** * 基于fetch 封装的GET 网络请求 * @param method * @param url 请求URL * @param params 请求参数 * @param host * @param head * @returns {Promise} */ static request = async (method,url, params = {},host=Ip,head=1) => { // console.log(host,"debugger --- into ...."); let Interinfo=await NetInfo.fetch(); if(!Interinfo.isConnected) { Toast.show("您当前没有网络,请检查网络连接后重试!"); Loading.hide(); throw "not found network"; } let result; if(method=="get"||method=="GET"){ result = timeoutFetch( fetch(handleUrl(host + '' + url)(params), { method: 'GET', headers: head===1?header:header2 }) ) }else if(method=="post"||method=="POST"){ result = timeoutFetch( fetch(host + '' + url, { method: 'POST', headers:head===1?header:header2, body: head===1?handleUrl2(url)(params):JSON.stringify(params) }) ) }else{ result = timeoutFetch( fetch(host + '' + url, { method: method, headers:head===1?header:header2, body:head===1?handleUrl2(url)(params):JSON.stringify(params) }) ) } return new Promise((resolve, reject)=>{ result .then(response => { if (response.ok) { // console.log(host,"debugger --- http ok 200 into ...."); return response.text() } else { // console.log(host,"debugger --- http ok ??error? into ...."); if(__DEV__) alert('服务器繁忙,请稍后再试;\r\nCode:' + response.status) } }) .then(response => { // console.log("网络请求log"+host,response); console.log(host,"debugger网络请求LOG"+response); try{ response=JSON.parse(response); if(host===CONF.msc){ if(response.result!==1){ if(response.result===9){ Toast.show("登陆重联中..."); //登陆过期 HttpUtils.login(method,url,params) .then((res)=>{ resolve(res); }) .catch((e)=>{ console.log(e); Toast.show("登陆重联失败!"); reject("重联失败"); }) }else{ console.error(response.message); Toast.show(response.message||"网络开小差了,请刷新后重试"); resolve(response); } }else{ resolve(response); } }else{ resolve(response); } }catch (e) { console.error("json解析错误,请检查"); console.log(response); Toast.show("服务器发生错误!"); reject("error"); } }) .catch(error => { Loading.hide(); if(error=="请求超时"||error=="请求取消"){ Toast.show(error); }else{ Toast.show("服务器连接异常!"); } if(__DEV__) console.error(error); reject(error); }) .done() }) } /*上传步骤 * * resKey<Array> eg:["result"<状态码key>,"callbackname"<返回图片list key>] * */ CommonUpload(h,uploadurl,fileDetail,upload_files,resKey){ return new Promise((resolve, reject)=>{ //有文件 if(fileDetail.length>0){ //content 读取缓存token 2 .3 同下面方法 this._fetch(h,uploadurl,fileDetail,this.current,resKey,upload_files,(R)=>{ this.current=0;//清空变量值 Loading.hide(); this.picgroup=[]; resolve(R); },()=>{ this.current=0;//清空变量值 Loading.hide(); this.picgroup=[]; Toast.showLong("不支持的文件类型"); reject("不支持的文件类型"); return ; }) }else{ //没有文件 Loading.hide(); this.picgroup=[]; resolve("no file"); return ; } }); } /*上传过程*/ _fetch(h,uploadurl,fileDetail,currentindex,resKey,upload_files,fn,rejectcallback){ this.current=currentindex; let extary=fileDetail[this.current]["name"].split("."); if(extgroup.indexOf(extary[extary.length-1])===-1){ rejectcallback(); return ; } Loading.show((this.current+1)+"/"+upload_files.length); fetch(h+''+uploadurl,{ method: 'POST', // headers: header1, body: upload_files[this.current], }) .then((response)=>response.text()) .then((responseText)=>{ // console.log('段继龙'+responseText); let res=JSON.parse(responseText); if(res[resKey[0]]===1){ //成功 this.current++; if(this.current<upload_files.length){ //延时回调 HttpUtils.timer=setTimeout(()=>{ HttpUtils.timer&&clearTimeout(HttpUtils.timer); Loading.hide(); this.picgroup.push(res[resKey[1]]); this._fetch(h,uploadurl,fileDetail,this.current,resKey,upload_files,fn,rejectcallback) },1000); }else{ HttpUtils.timer=setTimeout(()=>{ HttpUtils.timer&&clearTimeout(HttpUtils.timer); this.picgroup.push(res[resKey[1]]); fn(this.picgroup); },1000); } }else{ Loading.hide(); this.current=0;//清空变量值 Toast.show(res.message); return ; } }) .catch((error)=>{ if(__DEV__) console.error(error); this.current=0; Loading.hide(); }) } static login(m,u,p){ return new Promise((resolve, reject)=>{ let U=User.useraccount.split("#"); let params={ "username":U[0], "passwd":U[1], "password":U[1], }; HttpUtils.request("post","/api/mobile/member/staticPwd-login.do",params,CONF.msc) .then((e)=>{ if(e.result===1){ //重复登陆ok Toast.show("已连接"); //延迟处理服务器频繁请求 setTimeout(async ()=>{ let res=await HttpUtils.request(m,u,p,CONF.msc); //发起重新请求 resolve(res); },500); // Alert.alert( // '提示', // '已成功连接到服务,点击重试重新获取.', // [ // {text: '重试', onPress: async () => { // let res=await HttpUtils.request(m,u,p,CONF.msc); //发起重新请求 // resolve(res); // }}, // ], // { cancelable: false } // ) }else{ reject("err"); } }) .catch((e)=>{ reject(e.toString()); }) }); } }
/* THE CANVAS HAS 400x200(x,y) PIXELS... EACH PIXEL EQUALS TO 1.75px*/ /* DECLARATIONS */ var minutes = 0; var seconds = 0; var wave = 0; var start = false; /* GAME EVENTS begin */ window.onload = function() { // Called once at beggining /*; CreateEntity("enemy2", 100, 185); randomizeColor(enemy2,256,20,20);*/ }; var TickEvent = setInterval(function() { // Called every frame //collision(); }, 1); function startGame() { playerIndex = CreateEntity("player", 192, 92); entity[playerIndex].object.style.backgroundColor = "blue"; entity[playerIndex].object.style.zIndex = 1000; updateTime(); } /* GAME EVENTS begin */ /* KEYBOARD PRESS begin */ window.addEventListener("keydown", function(e) { if (e.keyCode === 65) { // Press "A" then move to the left leftDown(); } else if (e.keyCode === 68) { // Press "D" then move to the right rightDown(); } else if (e.keyCode === 87) { // Press "W" then jump upDown(); } }); function leftDown() { entity[playerIndex].isMoving = true; entity[playerIndex].direction = "left"; } function leftUp() { if (entity[playerIndex].direction == "left") { entity[playerIndex].isMoving = false; } entity[playerIndex].acceleration = 0; } function rightDown() { entity[playerIndex].isMoving = true; entity[playerIndex].direction = "right"; } function rightUp() { if (entity[playerIndex].direction == "right") { entity[playerIndex].isMoving = false; } entity[playerIndex].acceleration = 0; } function upDown() { if (entity[playerIndex].isJumping === false) { // When player jump, send an negative gravityAcceleration making the gravity goes to the // oposite direction, when the acceleration return to > 0, the player falls. // The smallest is the gravityAcceleration, higher is the jump entity[playerIndex].isJumping = true; entity[playerIndex].gravityAcceleration = -1.3; } } window.addEventListener("keyup", function(e) { if (e.keyCode === 65) { // Release "A" then stop move left leftUp(); } else if (e.keyCode === 68) { // Release "D" then stop move right rightUp(); } }); /* KEYBOARD PRESS end */ /* GAME FUNCTIONS begin */ function randomizeColor(entity, red, green, blue) { let r, g, b; r = Math.floor(Math.random() * red); g = Math.floor(Math.random() * green); b = Math.floor(Math.random() * blue); entity.object.style.backgroundColor = "rgb(" + r + "," + g + "," + b + ")"; } function collision() { for (i = 0; i < entitys.length; i++) { if (entitys[i].name != "player") { if ( entitys[i].posX - 15 < entity[playerIndex].posX && entity[playerIndex].posX < entitys[i].posX + 15 && entitys[i].posY - 15 < entity[playerIndex].posY && entity[playerIndex].posY < entitys[i].posY + 15 ) { gameOver(); } } } } function gameOver() { alert("Game over"); for (i = 0; i < entitys.length; i++) { window[entitys[i].name] = null; } } function updateTimerLabel() { var timer = ""; if (minutes < 10 && seconds < 10) { timer = "0" + minutes + ":" + "0" + seconds; } else if (minutes < 10 && seconds >= 10) { timer = "0" + minutes + ":" + seconds; } else if (minutes >= 10 && seconds < 10) { timer = minutes + ":" + "0" + seconds; } document.getElementById("timer").innerHTML = timer; } function clearTimer() { clearInterval(timerSec); minutes = 0; seconds = 0; } function updateTime() { var timerSec = setInterval(function() { updateWave(); seconds++; if (seconds === 60) { seconds = 0; minutes++; } updateTimerLabel(); }, 1000); } function updateWave() { if (seconds % 10 === 0) { wave++; if (wave < 10) { document.getElementById("wave").innerHTML = "0" + wave; } else { document.getElementById("wave").innerHTML = wave; } let x, y; x = Math.floor(Math.random() * 400); y = Math.floor(Math.random() * 200); //let name = "enemy" + entitys.length; //CreateEntity(name, x, y); } }
'use strict'; const _ = require('lodash'); const CliModule = require('../CliModule'); const Jira = require('../../jira/Jira'); const JiraInstanceDetails = require('../../jira/JiraInstanceDetails'); const Git = require('../../git/Git'); class jiraCliModule extends CliModule{ constructor(vorpal){ super(vorpal); this._init(); } _init(){ let self = this; // eslint-disable-line this._vorpal .command('move-issue <status> [issues...]') .option('--git', 'Retrieve Jira issues from latest git commit in current working directory.') .option('--user <user>', 'Jira username.') .option('--pass <pass>', 'Jira password.') .option('--projectKey <projectKey>', 'The key to the jira project') .description('Move one or more JIRA issues.') .validate(function (args) {// eslint-disable-line if(!process.env.JIRA_USER && !args.options.user){ return 'You MUST supply JIRA_USER environment variables or --user option.'; } else if(!process.env.JIRA_PASS && !args.options.pass){ return 'You MUST supply JIRA_PASS environment variables or --pass option.'; } else if(JiraInstanceDetails.getTransitionIdFromString(args.status) === undefined){ return 'You MUST supply a valid status.'; } else if(!args.options.git && !args.issues){ return 'You MUST supply either --git or the issues to be removed.'; } else if(!args.options.projectKey){ return 'You MUST supply a projectKey use --projectKey.'; } }) .action(function (command) { let issuesToBeMoved = command.issues; let key = _.get(command,'options.projectKey'); let statusWeAreMovingTo = JiraInstanceDetails.getTransitionIdFromString(command.status); let user = _.get(command,'options.user',process.env.JIRA_USER); let pass = _.get(command,'options.pass',process.env.JIRA_PASS); let jiraClient = new Jira( JiraInstanceDetails.baseUrl, user, pass, {} ); let proms = []; return Promise.resolve() .then(()=>{ //pull issue keys from last commit message if (command.options.git) { let git = new Git(); return git.getJiraIssuesFromLastCommit(key) .then((issueKeys)=>{ issuesToBeMoved = issueKeys; }) .catch(Promise.reject); } }) .then(()=>{ this.log(`Moving issues ${issuesToBeMoved} into the ${statusWeAreMovingTo} state...`); issuesToBeMoved.forEach(issueId => { proms.push(jiraClient.moveIssue(issueId,statusWeAreMovingTo)); }); }) .then(()=>{ return Promise.all(proms); }) .then(()=>{ this.log(`YAY we moved your issues (${issuesToBeMoved}) to (${command.status})!!!!`); }) .catch(e=>{ this.log('(ERROR)-> '+e.message); return Promise.reject(e); }); }); } } module.exports = jiraCliModule;
import React from 'react'; import Icon from 'react-native-vector-icons/FontAwesome5'; import {View, Text} from 'native-base'; import PropTypes from 'prop-types'; import {percentage, SCREEN_HEIGHT, SCREEN_WIDTH} from '../../Variables'; const IconList = ({name}) => { const Fonts = percentage(SCREEN_WIDTH, 50); const names = ['psn', 'xbl', 'origin']; return ( <View style={{ backgroundColor: '#EF544A', width: 50, height: 50, borderRadius: 30, padding: 10, alignItems: 'center', justifyContent: 'center', marginBottom: 10, }}> {names.includes(name) ? ( name === 'psn' ? ( <Icon name={'playstation'} style={{ color: '#fff', fontSize: Fonts / 18, fontWeight: '500', alignItems: 'center', justifyContent: 'center', textAlign: 'center', }} /> ) : name === 'xbl' ? ( <Icon name={'xbox'} style={{ color: '#fff', fontSize: Fonts / 18, fontWeight: '500', alignItems: 'center', justifyContent: 'center', textAlign: 'center', }} /> ) : null ) : ( <Icon name={name} style={{ color: '#fff', fontSize: Fonts / 18, fontWeight: '500', alignItems: 'center', justifyContent: 'center', textAlign: 'center', }} /> )} </View> ); }; IconList.propTypes = {}; export default IconList;
import React from 'react' import { StyleSheet, Platform, Image, Text, View } from 'react-native' import Navigation from './navigation/Navigation' import Firebase from './Helpers/Firebase' import {Font} from 'expo' export default class App extends React.Component { constructor() { super() } componentWillMount(){ Firebase.init(); } render() { return <Navigation />; } }
exports.sectionMutations = ` updateSectionDetails(courseId: String!, sectionIndex: Float!, sectionInput: SectionInput): Course deleteSection(courseId: String!, sectionIndex: Float!): Course addSectionToCourse(courseId: String!): Course `;
app.controller('dashboardController', ['$scope', 'userFactory','topicFactory', "$location", function($scope, userFactory, topicFactory, $location){ $scope.newTop = {} //creates a new Topic $scope.newTopic = function(){ $scope.newTop.username = $scope.currentUser.name $scope.newTop._user = $scope.currentUser._id $scope.newTop.posts = 0 topicFactory.newTopic($scope.newTop, function(returnedTopic){ console.log(returnedTopic) $location.url('/dashboard/') $scope.newTop = {} }) } // view function which retrieves all the topics topicFactory.getTopics(function(returnedTopics){ $scope.topics = returnedTopics; }) // checks to see if user is in session if not redirects them to login userFactory.checkUser(function(data){ $scope.currentUser = data.user; if(!$scope.currentUser){ $location.url('/') } }) }]);
import { useState, useEffect } from "react"; import uuid from "react-uuid"; import Sidebar from "./components/Sidebar"; import Main from "./components/Main"; function App() { const [notes, SetNote] = useState(localStorage.getItem('notes') ? JSON.parse(localStorage.getItem('notes')) : []); const [activeNote, setActiveNote] = useState(false); const notes_is_empty = (notes === []); if (notes_is_empty) { localStorage.setItem('notes', notes) } const onAddNote = () => { const newNote = { id: uuid(), title: "Untitled Note", content: "", edited: Date.now(), }; SetNote([newNote, ...notes]); }; useEffect(() => { localStorage.setItem('notes', JSON.stringify(notes)) }) const toggleActiveNote = (target_id) => { setActiveNote(activeNote === target_id ? false : target_id); }; const onDelete = (target_id) => { SetNote(notes.filter((note) => note.id !== target_id)); }; const onEdit = (e, edit_type) => { const activeNoteInfo = notes.find((note) => note.id === activeNote); const editedNote = { id: activeNote, title: [ edit_type === "title" ? e.target.value : activeNoteInfo.title ], content: [ edit_type === "content" ? e.target.value : activeNoteInfo.content ], edited: Date.now(), }; SetNote([editedNote, ...notes.filter((note) => note.id !== activeNote)]); }; const getActiveNote = () => { const activeNoteInfo = notes.find((note) => note.id === activeNote); if (activeNote === false) { //pass }else if (typeof activeNoteInfo === 'undefined') { setActiveNote(false); }else { return(activeNoteInfo); } } return ( <div className="App"> <Sidebar notes={notes} onAddNote={onAddNote} onDelete={onDelete} activeNote={activeNote} setActiveNote={setActiveNote} onToggle={toggleActiveNote} empty={notes_is_empty} /> <Main activeNoteInfo={getActiveNote()} activeNote={activeNote} onEdit={onEdit}/> </div> ); } export default App;
var status_8c = [ [ "MenuStatusLineData", "structMenuStatusLineData.html", "structMenuStatusLineData" ], [ "get_sort_str", "status_8c.html#ac8156953ab9d8f697ac86866bcd3b876", null ], [ "status_format_str", "status_8c.html#a687a918a49621a9f1bef52801def2308", null ], [ "menu_status_line", "status_8c.html#a1becc7497d5ffb91852fa1c7ff0fd5bd", null ], [ "C_StatusChars", "status_8c.html#a694600745dcefa041009f756774860ff", null ] ];
const main = document.querySelector("main"); const voiceSelect = document.getElementById("voice"); const textarea = document.getElementById("text"); const readBtn = document.getElementById("read"); const toggleBtn = document.getElementById("toggle"); const closeBtn = document.getElementById("close"); const message = new SpeechSynthesisUtterance(); function setTextMessage(text) { message.text = text; } function speakText() { speechSynthesis.speak(message); } let voices = []; function getVoice() { voices = speechSynthesis.getVoices(); voices.forEach((voice) => { const option = document.createElement("option"); option.value = voice.name; option.innerText = `${voice.name} ${voice.lang}`; voiceSelect.appendChild(option); }); } speechSynthesis.addEventListener("voiceschanged", getVoice); getVoice(); toggleBtn.addEventListener("click", () => document.getElementById("text-box").classList.toggle("show") ); closeBtn.addEventListener("click", () => document.getElementById("text-box").classList.remove("show") ); function setVoice(e) { message.voice = voices.find((voice) => voice.name === e.target.value); } voiceSelect.addEventListener("change", setVoice); readBtn.addEventListener("click", () => { setTextMessage(textarea.value); speakText(); });
var repeatTime = 0; function func() { } function start(){ console.log("Timer start"); } function stop(){ }
//alert("Check your zipper!"); //For asking a yes or no //confirm("Are you sure that you want to proceed?"); //to capture the response //var userResp = confirm("Are you sure that you want to proceed?"); //console.log(userResp); var userResp = prompt("What is your name?"); console.log(userResp); //Also correct = //var userName = prompt("What is your name?"); //console.log(userName);
import React, { Component } from "react"; class Country extends Component { state = { title: this.props.title, }; render() { var cssClass = this.props.className + " btn btn-danger btn-sm"; return ( <button onClick={() => this.props.onGuess(this.state.title)} className={cssClass} > {this.state.title} </button> ); } } export default Country;
module.exports = (bh) => { bh.match('title', (ctx) => { ctx.tag('h1'); }); };
import { api } from './ApiConfig' export const getAllPods = async () => { try { const response = await api.get('/pods') return response.data } catch (error) { throw error } }
export function isEmpty(string) { return string === null || string === "" || string === undefined; } export function isNotEmpty(string) { return !isEmpty(string); } export function formatDate(date) { let processDate = new Date(date), month = "" + (processDate.getMonth() + 1), day = "" + processDate.getDate(), year = processDate.getFullYear(); if (month.length < 2) month = "0" + month; if (day.length < 2) day = "0" + day; return [year, month, day].join("-"); } export function hasWhiteSpace(s) { return /\s/g.test(s); } export function getWarehouseNameByWarehouseCode(warehouses, selectedCode) { let warehouseName = ""; warehouses.map(warehouse => { if (warehouse.wareHouseCode === selectedCode) { warehouseName = warehouse.name; } return null; }); return warehouseName; } export function changeDateFormat(date, dateFormat) { let processDate = new Date(date), month = "" + (processDate.getMonth() + 1), day = "" + processDate.getDate(), year = processDate.getFullYear(), monthName = processDate.toLocaleDateString("default", { month: "short" }); if (month.length < 2) month = "0" + month; if (day.length < 2) day = "0" + day; switch (dateFormat) { case "dd/MM/yyyy": return [day, month, year].join("/"); case "MM/dd/yyyy": return [month, day, year].join("/"); case "dd/MMM/yyyy": return [day, monthName, year].join("/"); case "MMM/dd/yyyy": return [monthName, day, year].join("/"); default: return [day, month, year].join("/"); } } export function isEvenNumber(number) { if (parseFloat(number) % 2 === 0) { return true; } return false; } export function isConsistWith(pathName, content) { let pathMatched = false; if (content && content.length > 0) { content.map(({ link }) => { if (link === pathName) { pathMatched = true; } return null; }); } return pathMatched; }
//FlickrSwipe Takes photos from Flickr and pushes them into the DOM var api_key = '[YOUR API KEY HERE]'; var photoset_id = '[YOUR PHOTO ALBUM ID HERE]'; var user_id = '[YOUR USER ID HERE]'; var url_photoset = 'https://api.flickr.com/services/rest/?method=flickr.photosets.getPhotos&api_key=' + api_key + '&photoset_id=' + photoset_id + '&user_id=' + user_id + '&format=json&nojsoncallback=1'; $.getJSON(url_photoset, function(data) { for (i = 0; i < data.photoset.photo.length; i++) { var photo_id = data.photoset.photo[i].id; var url_photo = 'https://api.flickr.com/services/rest/?method=flickr.photos.getSizes&api_key=' + api_key + '&photo_id=' + photo_id + '&format=json&nojsoncallback=1'; $.getJSON(url_photo, function(data) { var picture = data.sizes.size.filter(function(size){ return size.label === "Large"; }); var thumbnail = data.sizes.size.filter(function(size){ return size.label === "Small 320"; }); var picture_source = picture[0].source; var picture_height = picture[0].height; var picture_width = picture[0].width; var picture_dimensions = picture_width + 'x' + picture_height; var thumbnail_source = thumbnail[0].source; build_figure(picture_source, picture_dimensions, thumbnail_source); }); // end $.getJSON url photo } // end for loop }); // end $.getJSON url photoset function build_figure(picture_source, picture_dimensions, thumbnail_source) { var fig = document.createElement("figure"); var a = document.createElement("a"); var img = document.createElement("img"); a.setAttribute("href", picture_source); a.setAttribute("itemprop", "contentUrl"); a.setAttribute("data-size", picture_dimensions); a.setAttribute("alt", "PhotoSwipe Photo"); img.setAttribute("src", thumbnail_source); img.setAttribute("itemprop", "thumbnail"); img.setAttribute("alt", "PhotoSwipe Photo Thumbnail"); $(".my-gallery").append(fig);; $(fig).append(a); $(fig).append(img); }
require('dotenv').config({ path: '../.env' }) const express = require('express'); const router = express.Router(); const bcrypt = require('bcrypt'); const jwt = require('jsonwebtoken'); const Joi = require('joi'); const Cloudant = require('@cloudant/cloudant'); const nanoid = require('nanoid'); const { validate_student, validate_professor, validate_login, validate_course, validate_enroll, validate_pending_admin, validate_question, validate_answer } = require('../classes/validators'); const Student = require('../classes/Student'); const Professor = require('../classes/Professor'); const Course = require('../classes/Course'); const Question = require('../classes/Question'); const Answer = require('../classes/Answer'); const auth = require('../middleware/auth_api'); const sleep = require('../helpers/sleep'); router.post('/register/professor', async(req, res) =>{ if ('0'.localeCompare(req.body.gender)) req.body.gender = 'male'; else if ('1'.localeCompare(req.body.gender)) req.body.gender = 'female'; else req.body.gender = 'other'; req.body.age = parseInt(req.body.age) const { error } = validate_professor(req.body); if (error) return res.status(400).send(error.details[0].message); const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); query_response = await users_db.find({ selector: { email: { "$eq": req.body.email } } }); if (query_response.docs[0]) return res.status(404).send('Error: email already in use'); const professor = new Professor(req.body.email, req.body.password, req.body.first_name, req.body.middle_name, req.body.last_name, req.body.age, req.body.gender, req.body.department); const salt = await bcrypt.genSalt(10); professor.password = await bcrypt.hash(professor.password, salt); await users_db.insert(professor); return res.status(201).send({ email: professor.email, first_name: professor.first_name, middle_name: professor.middle_name, last_name: professor.last_name, age: professor.age, gender: professor.gender, department: professor.department }); }); router.post('/register/student', async(req, res) =>{ if ('0'.localeCompare(req.body.gender)) req.body.gender = 'male'; else if ('1'.localeCompare(req.body.gender)) req.body.gender = 'female'; else req.body.gender = 'other'; req.body.age = parseInt(req.body.age); req.body.semester = parseInt(req.body.semester); const { error } = validate_student(req.body); if (error) return res.status(400).send(error.details[0].message); const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const query_response = await users_db.find({ selector: { email: { "$eq": req.body.email } } }); if (query_response.docs[0]) return res.status(400).send('Error: email already in use'); const student = new Student(req.body.email, req.body.password, req.body.first_name, req.body.middle_name, req.body.last_name, req.body.age, req.body.gender, req.body.major, req.body.semester); const salt = await bcrypt.genSalt(10); student.password = await bcrypt.hash(student.password, salt); await users_db.insert(student); return res.status(201).send({ email: student.email, first_name: student.first_name, middle_name: student.middle_name, last_name: student.last_name, age: student.age, gender: student.gender, major: student.major, semester: student.semester }); }); router.post('/login', async(req, res) =>{ console.log("entreee") const { error } = validate_login(req.body); console.log("pase 1"); if(error) return res.status(400).send(error.details[0].message); const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); console.log("pase 2"); const query_response = await users_db.find({ selector: { email: { "$eq": req.body.email } } } ); if (!query_response.docs[0]) return res.status(404).send('Error: incorrect username or password.'); console.log("pase 3"); const user = query_response.docs[0]; const valid = await bcrypt.compare(req.body.password, user.password); if(!valid) return res.status(400).send('Error: incorrect username or password.'); console.log("pase 4"); const token = await jwt.sign({_id: user._id}, process.env.SECRET); user.jwt = token; ['_id', '_rev', 'password'].forEach(value => delete user[value]); console.log(user) res.status(200).send(user); }); router.get('/courses', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; const admin_courses = new Array(); for (let i = 0; i < user.admin_courses.length; i++) { query_response = await courses_db.find({ selector: { _id: { "$eq": user.admin_courses[i] } }, fields: ["name", "id", "key", "term", "year"] }); admin_courses.push(query_response.docs[0]); } if (user.courses) { const courses = new Array(); for (let i = 0; i < user.courses.length; i++) { query_response = await courses_db.find({ selector: { _id: { "$eq": user.courses[i] } }, fields: ["name", "id", "key", "term", "year"] }); courses.push(query_response.docs[0]); } return res.status(200).send({ admin_courses: admin_courses, courses: courses }); } res.status(200).send({ admin_courses: admin_courses }); }); // Look up method, can be more complex router.get('/courses/search/:course', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; if (!user.semester) return res.status(401).send('Error: this user is not able to enroll to courses.'); const limit = req.query.limit || 10; const regex = new RegExp(req.params.course); query_response = await courses_db.find({ selector: { name: { "$regex": regex.source } }, fields: ["name", "id", "term", "year", "admins"], limit: limit }); courses = query_response.docs; for (let i = 0; i < courses.length; i++) { const temp_course = courses[i]; query_response = await users_db.find({ selector: { _id: { "$eq": temp_course.admins[0] } }, fields: ["first_name", "last_name", "department"] }); // First admin of each course is the one who created the course, // therefore it must be a professor. This is used to identify a // course when students enroll. const temp_user = query_response.docs[0]; temp_course.admins = new Array(temp_user); } res.status(200).send(courses); }); router.get('/courses/pending_admins', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const professor = query_response.docs[0]; if (!professor.department) return res.status(401).send('Error: this user is not able to authorize course administration.'); query_response = await courses_db.find({ selector: { admins: { "$elemMatch": { "$eq": professor._id } }, "$not": { pending_admins: {"$size": 0} } }, fields: ["name", "id", "key", "term", "year", "pending_admins"] }); if(!query_response.docs[0]) return res.status(200).send([]); var courses = query_response.docs; const pending_query = new Array(); for (let i = 0; i < courses.length; i++) { const temp_course = courses[i]; for (let j = 0; j < temp_course.pending_admins.length; j++) { pending_query.push({ _id: { "$eq": temp_course.pending_admins[j] } }); } } query_response = await users_db.find({ selector: { "$or": pending_query }, fields: ["_id", "first_name", "middle_name", "last_name", "email"] }); const pending_users = query_response.docs; for (let i = 0; i < courses.length; i++) { for (let j = 0; j < courses[i].pending_admins.length; j++) { var index = pending_users.findIndex(student => student._id === courses[i].pending_admins[j]); courses[i].pending_admins[j] = { first_name: pending_users[index].first_name, middle_name: pending_users[index].middle_name, last_name: pending_users[index].last_name, email: pending_users[index].email } } } res.status(200).send(courses); }); router.get('/courses/:course', auth, async(req, res) =>{ const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": user._id } } }, { admins: { "$elemMatch": { "$eq": user._id } } } ] }, fields: ["_id", "name", "id", "key", "term", "year", "tags", "questions", "instructor"] }); if(!query_response.docs[0]) return res.status(400).send('Error: user is not enrolled in the selected course.'); const course = query_response.docs[0]; var page_num = parseInt(req.query.page_num) || 1; var page_size = parseInt(req.query.page_size) || 5; if(page_num < 1) page_num = 1; if(page_size < 1) page_size = 1; const skip = (page_num-1)*page_size; var questions_ids = course.questions.reverse().splice(skip, page_size); for (let i = 0; i < questions_ids.length; i++) { questions_ids[i] = { "_id": { "$eq": questions_ids[i] } } } query_response = await questions_db.find({ selector: { course: { "$eq": course._id}, "$or": questions_ids }, fields: ["id", "title", "content", "creation_date", "solved", "tags", "no_answers", "views", "instructor"], }); var questions = query_response.docs; questions.sort( (a, b)=>{ return new Date(b.creation_date) - new Date(a.creation_date) }); delete course._id; delete course.questions; res.status(200).send([course, questions]); }); router.get('/courses/:course/pending_admins', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; if (!user.department) return res.status(401).send('Error: this user is not able to authorize course administration.'); query_response = await courses_db.find({ selector: { key: req.params.course, admins: { "$elemMatch": { "$eq": user._id } } }, fields: ["key", "name", "id", "term", "year", "pending_admins"] }); if(!query_response.docs[0]) return res.status(400).send('Error: user is not enrolled in the course.'); const course = query_response.docs[0]; var pending = course.pending_admins; for (let i = 0; i < pending.length; i++) { pending[i] = { _id: { "$eq": pending[i] } }; } query_response = await users_db.find({ selector: { "$or": pending }, fields: ["first_name", "middle_name", "last_name", "email"] }); pending = query_response.docs; delete course.pending_admins; res.status(200).send([course, pending]); }); router.get('/courses/:course/q/:question', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); const answers_db = await cloudant.use('answers'); query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": req.user } } }, { admins: { "$elemMatch": { "$eq": req.user } } } ] }, fields: ["_id", "key"] }); if (!query_response.docs[0]) return res.status(401).send('Error: user is not enrolled in the selected course.'); const course = query_response.docs[0]; query_response = await questions_db.find({ selector: { course: { "$eq": course._id }, id: { "$eq": req.params.question } }, // fields: ["id", "title", "content", "author", "anonymous", "creation_date", "solved", "resolution_date", "tags", "no_answers", "views", "approved", "answers"] }); if (!query_response.docs[0]) return res.status(400).send('Error: could not find question.') var question = query_response.docs[0]; question.views = question.views + 1; await questions_db.insert(question) question.course_id = course.key; if (!question.anonymous) { query_response = await users_db.find({ selector: { _id: { "$eq": question.author } }, fields: ["first_name", "last_name"] }); if (!query_response.docs[0]) return res.status(400).send('Error: could not find author for the question'); question.author = query_response.docs[0].first_name + ' ' + query_response.docs[0].last_name; } var page_num = parseInt(req.query.page_num) || 1; var page_size = parseInt(req.query.page_size) || 5; if (page_num < 1) page_num = 1; if (page_size < 1) page_size = 1; const skip = (page_num - 1) * page_size; var answers_ids = question.answers.reverse().splice(skip, page_size); for (let i = 0; i < answers_ids.length; i++) { answers_ids[i] = { "_id": { "$eq": answers_ids[i] } } } sleep(300); query_response = await answers_db.find({ selector: { question: { "$eq": question._id }, "$or": answers_ids }, fields: ["id", "content", "author", "anonymous", "instructor", "creation_date", "correct", "comments", "no_comments", "approved"] }); var answers = query_response.docs; if (!answers) answers = new Array(); var temp_users = new Array(); for (let i = 0; i < answers.length; i++) { temp_users[i] = { "_id": { "$eq": answers[i].author } } } query_response = await users_db.find({ selector: { "$or": temp_users }, fields: ["_id", "first_name", "last_name"] }); temp_users = query_response.docs; for (let i = 0; i < answers.length; i++) { if(!answers[i].anonymous){ var index = temp_users.findIndex(student => student._id === answers[i].author); answers[i].author = temp_users[index].first_name + ' ' + temp_users[index].last_name; } else{ answers[i].author = 'anonymous'; } } ['answers', '_id', '_rev', 'answers', 'course', 'approved_users'].forEach(value => delete question[value]); answers.sort((a, b) => { return new Date(b.creation_date) - new Date(a.creation_date) }); res.status(200).send([question, answers]) }); router.post('/courses/new_course', auth, async (req, res) => { console.log("creando...") const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; if (!user.department) return res.status(401).send('Error: this user is not authorized to create new courses'); console.log("bodu:", req.body) var course = new Course(req.body.name, req.body.id, req.body.tags, req.body.term, req.body.year); course.admins.push(user._id); console.log("pass 1") const { error } = validate_course(course); if (error) return res.status(400).send(error.details[0].message); query_response = await courses_db.find({ selector: { name: { "$eq": course.name }, term: { "$eq": course.term }, year: { "$eq": course.year }, admins: { "$elemMatch": { "$eq": user._id } } } }); console.log("pass 2") if (query_response.docs[0]) return res.status(400).send('Error: user has already defined a course with the specified name, term and year'); query_response = await courses_db.find({ selector: { key: { "$eq": course.key }, admins: { "$elemMatch": { "$eq": user._id } } } }); console.log("pass 3") // Avoid key collision if (query_response.docs[0]) course.key = nanoid(16); await courses_db.insert(course); query_response = await courses_db.find({ selector: { name: { "$eq": course.name }, admins: { "$elemMatch": { "$eq": user._id } } } }); course = query_response.docs[0]; console.log("pass 4") user.admin_courses.push(course._id); await users_db.insert(user); res.status(201).send([{ name: course.name, id: course.id, key: course.key, tags: course.tags, term: course.term, year: course.year }]); }); router.post('/courses/enroll', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; if (!user.courses) return res.status(401).send('Error: this user is not able to enroll to courses.'); const { error } = validate_enroll(req.body); if (error) return res.status(400).send(error.details[0].message); query_response = await courses_db.find({ selector: { name: { "$eq": req.body.name }, id: { "$eq": req.body.id }, key: { "$eq": req.body.key }, term: { "$eq": req.body.term }, year: { "$eq": req.body.year } } }); if (!query_response.docs[0]) return res.status(400).send('Error: Incorrect course information or it does not exist.'); const course = query_response.docs[0]; if (user.courses.includes(course._id)) return res.status(400).send('Error: The user has already enrolled to this course.'); course.users.push(req.user); await courses_db.insert(course); user.courses.push(course._id); await users_db.insert(user); res.status(200).send({ message: 'User enrolled to the course.', course: course.key, email: user.email, first_name: user.first_name, middle_name: user.middle_name, last_name: user.last_name, major: user.major, }); }); router.post('/courses/enroll_admin', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; if (!user.courses) return res.status(401).send('Error: this user is not able to enroll to courses.'); const { error } = validate_enroll(req.body); if (error) return res.status(400).send(error.details[0].message); query_response = await courses_db.find({ selector: { name: { "$eq": req.body.name }, id: { "$eq": req.body.id }, key: { "$eq": req.body.key }, term: { "$eq": req.body.term }, year: { "$eq": req.body.year } } }); if (!query_response.docs[0]) return res.status(400).send('Error: Incorrect course information or it does not exist.'); const course = query_response.docs[0]; if (user.admin_courses.includes(course._id)) return res.status(400).send('Error: The is already administrator of this course.'); if (course.pending_admins.includes(user._id)) return res.status(400).send('Error: This user has already submitted an application.') course.pending_admins.push(user._id); await courses_db.insert(course); res.status(200).send({ status: 'Application sent. An administrator must approve your application', email: user.email, first_name: user.first_name, middle_name: user.middle_name, last_name: user.last_name, major: user.major, course: course.key }); }) router.post('/courses/:course/pending_admins', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const professor = query_response.docs[0]; if (!professor.department) return res.status(401).send('Error: this user is not able to authorize course administration.'); const { error } = validate_pending_admin(req.body); if (error) return res.status(400).send(error.details[0].message); query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, admins: { "$elemMatch": { "$eq": professor._id } } } }); if (!query_response.docs[0]) return res.status(400).send('Error: Course does not exist.'); const course = query_response.docs[0]; query_response = await users_db.find({ selector: { email: { "$eq": req.body.email } } }); if (!query_response.docs[0]) return res.status(400).send('Error: Could not find user with given email.'); const new_admin = query_response.docs[0]; if (!course.pending_admins.includes(new_admin._id)) return res.status(400).send('Error: user does not have a pending application to become administrator of the selected course.') const pending_index = course.pending_admins.indexOf(new_admin._id); course.pending_admins.splice(pending_index, 1); var status = ''; // If professor approves request if (req.body.verdict) { course.admins.push(new_admin._id); await courses_db.insert(course); new_admin.admin_courses.push(course._id); await users_db.insert(new_admin); status = 'Request for new administrator has been approved.' } else { await courses_db.insert(course); status = 'Request for new administrator has been denied.' } var admin_list = new Array(); for (let i = 0; i < course.admins.length; i++) { query_response = await users_db.find({ selector: { _id: { "$eq": course.admins[i] } }, fields: ["first_name", "middle_name", "last_name", "email"] }); admin_list.push(query_response.docs[0]); } const response = { status: status, name: course.name, id: course.id, term: course.term, year: course.year, admins: admin_list } res.status(200).send(response); }); router.post('/courses/:course/new_question', auth, async (req, res) => { console.log("//////////////////////////") const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); console.log(req.body) var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": user._id } } }, { admins: { "$elemMatch": { "$eq": user._id } } } ] } }); if (!query_response.docs[0]) return res.status(400).send('Error: user is not registered in the indicated course'); const course = query_response.docs[0]; var instructor = false; if(course.admins.includes(user._id)) instructor = true; var question = new Question(req.body.title, req.body.content, user._id, req.body.anonymous, req.body.tags, course._id, instructor); console.log(question) const { error } = validate_question(question); if (error) return res.status(400).send(error.details[0].message); for (let i = 0; i < question.tags.length; i++) { if (!course.tags.includes(question.tags[i])) return res.status(400).send('Error: tag \'' + question.tags[i] + '\' is not a valid tag for the course.') } query_response = await questions_db.find({ selector: { id: { "$eq": question.id }, course: { "$eq": course._id } } }); // Avoid collision of ids for questions of a same course if (query_response.docs[0]) question.id = nanoid(16); await questions_db.insert(question); query_response = await questions_db.find({ selector: { title: { "$eq": question.title }, content: { "$eq": question.content }, author: { "$eq": question.author } } }); question = query_response.docs[0]; course.questions.push(question._id); await courses_db.insert(course); var author = user.first_name + ' ' + user.last_name; if (question.anonymous) author = 'anonymous'; res.status(200).send({ id: question.id, title: question.title, author: author, content: question.content, tags: question.tags, creation_date: question.creation_date, instructor: question.instructor, course: { name: course.name, id: course.id, term: course.term, year: course.year } }) }); router.post('/courses/:course/q/:question/good_question', auth, async(req, res) =>{ const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": user._id } } }, { admins: { "$elemMatch": { "$eq": user._id } } } ] }, fields: ["_id", "key"] }); if (!query_response.docs[0]) return res.status(401).send('Error: user is not enrolled in the selected course.'); const course = query_response.docs[0]; query_response = await questions_db.find({ selector: { course: { "$eq": course._id}, id: { "$eq": req.params.question} } }); if(!query_response.docs[0]) return res.status(400).send('Error: could not find question.') var question = query_response.docs[0]; var message = ''; if(question.approved_users.includes(user._id)){ question.approved--; var index = question.approved_users.indexOf(user._id); question.approved_users.splice(index, 1); message = 'User no longer approves this question.'; }else{ question.approved++; question.approved_users.push(user._id); message = 'User approves this question.'; } sleep(300); await questions_db.insert(question); res.status(200).send({message: message, id: question.id, course: course.key, approved: question.approved}); }); router.post('/courses/:course/q/:question/solved', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": user._id } } }, { admins: { "$elemMatch": { "$eq": user._id } } } ] }, fields: ["_id", "key", "admins"] }); if (!query_response.docs[0]) return res.status(401).send('Error: user is not enrolled in the selected course.'); const course = query_response.docs[0]; if(!course.admins.includes(user._id)) return res.status(401).send('Error: user is not authorized to mark a question as being solved.') query_response = await questions_db.find({ selector: { course: { "$eq": course._id }, id: { "$eq": req.params.question } } }); if (!query_response.docs[0]) return res.status(400).send('Error: could not find question.') var question = query_response.docs[0]; query_response.docs[0]; var message = ''; if (question.solved) { question.solved = false; question.resolution_date = undefined; message = 'User has marked question as not solved.'; } else { question.solved = true; question.resolution_date = new Date(); message = 'User has marked question as solved.'; } sleep(300); await questions_db.insert(question); res.status(200).send({ message: message, id: question.id, course: course.key, solved: question.solved, resolution_date: question.resolution_date }); }); //** new */ router.post('/courses/:course/q/:question/new_answer', auth, async(req, res) =>{ const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); const answers_db = await cloudant.use('answers'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": user._id } } }, { admins: { "$elemMatch": { "$eq": user._id } } } ] } }); if (!query_response.docs[0]) return res.status(400).send('Error: user is not registered in the indicated course'); const course = query_response.docs[0]; query_response = await questions_db.find({ selector: { id: { "$eq": req.params.question}, course: { "$eq": course._id} } }); if(!query_response.docs[0]) return res.status(400).send('Error: could not find question for the selected course.'); const question = query_response.docs[0]; var instructor = false; if(course.admins.includes(user._id)) instructor = true; var answer = new Answer(req.body.content, user._id, req.body.anonymous, question._id, instructor); query_response = await answers_db.find({ selector: { id: { "$eq": answer.id}, question: { "$eq": question._id} } }); if(query_response.docs[0]) answer.id = nanoid(16); const { error } = validate_answer(answer); if(error) return res.status(400).send(error.details[0].message); await answers_db.insert(answer); query_response = await answers_db.find({ selector: { id: {"$eq": answer.id}, question: {"$eq": question._id}, author: { "$eq": user._id} } }); answer = query_response.docs[0]; if(question.answers.length === 0) question.no_answers = false; question.answers.push(answer._id); await questions_db.insert(question); var author = user.first_name + ' ' + user.last_name; if (answer.anonymous) author = 'anonymous'; res.status(200).send({ id: answer.id, author: author, content: answer.content, creation_date: answer.creation_date, instructor: answer.instructor, question: question.id }) }); //** new */ router.post('/courses/:course/q/:question/a/:answer/good_answer', auth, async(req, res) =>{ const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); const answers_db = await cloudant.use('answers'); query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": req.user } } }, { admins: { "$elemMatch": { "$eq": req.user } } } ] } }); if (!query_response.docs[0]) return res.status(400).send('Error: user is not registered in the indicated course'); const course = query_response.docs[0]; query_response = await questions_db.find({ selector: { id: { "$eq": req.params.question }, course: { "$eq": course._id } } }); if (!query_response.docs[0]) return res.status(400).send('Error: could not find question for the selected course.'); const question = query_response.docs[0]; query_response = await answers_db.find({ selector: { id: { "$eq": req.params.answer}, question: { "$eq": question._id} } }); if(!query_response.docs[0]) return res.status(400).send('Error: could not find answer for the selected course'); const answer = query_response.docs[0]; var message = ''; if (answer.approved_users.includes(req.user)) { answer.approved--; var index = answer.approved_users.indexOf(req.user); answer.approved_users.splice(index, 1); message = 'User no longer approves this answer.'; } else { answer.approved++; answer.approved_users.push(req.user); message = 'User approves this answer.'; } sleep(300); await answers_db.insert(answer); res.status(200).send({ message: message, id: answer.id, question: question.id, approved: answer.approved }); }); //** new */ router.post('/courses/:course/q/:question/a/:answer/correct_answer', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); const answers_db = await cloudant.use('answers'); query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": req.user } } }, { admins: { "$elemMatch": { "$eq": req.user } } } ] } }); if (!query_response.docs[0]) return res.status(400).send('Error: user is not registered in the indicated course'); const course = query_response.docs[0]; if (!course.admins.includes(req.user)) return res.status(401).send('Error: user is not allowed to verify this answer.') query_response = await questions_db.find({ selector: { id: { "$eq": req.params.question }, course: { "$eq": course._id } } }); if (!query_response.docs[0]) return res.status(400).send('Error: could not find question for the selected course.'); const question = query_response.docs[0]; sleep(300); query_response = await answers_db.find({ selector: { id: { "$eq": req.params.answer }, question: { "$eq": question._id } } }); if (!query_response.docs[0]) return res.status(400).send('Error: could not find answers for the selected course'); const answer = query_response.docs[0]; var message = ''; if (answer.correct) { answer.correct = false; message = 'User has unmarked this answer as correct.'; } else { answer.correct = true; message = 'User has marked this answer as correct.'; } await answers_db.insert(answer); await questions_db.insert(question); res.status(200).send({ message: message, id: answer.id, question: question.id, correct: answer.correct }); }); router.delete('/courses/:course/leave', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; query_response = await courses_db.find({ selector: { key: req.params.course, users: { "$elemMatch": { "$eq": user._id } } } }); if (!query_response.docs[0]) return res.status(400).send('Error: user is not enrolled to the selected course.') const course = query_response.docs[0]; var index = course.users.indexOf(user._id); course.users.splice(index, 1); await courses_db.insert(course); index = user.courses.indexOf(course._id); user.courses.splice(index, 1); await users_db.insert(user); res.status(200).send({ message: 'User left the course.', course: { name: course.name, id: course.id, term: course.term, year: course.year } }); }); router.delete('/courses/:course/leave_admin', auth, async (req, res) => { const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; query_response = await courses_db.find({ selector: { key: req.params.course, admins: { "$elemMatch": { "$eq": user._id } } } }); if (!query_response.docs[0]) return res.status(400).send('Error: user is not administrator of the selected course.') const course = query_response.docs[0]; var index = course.admins.indexOf(user._id); course.admins.splice(index, 1); await courses_db.insert(course); index = user.admin_courses.indexOf(course._id); user.admin_courses.splice(index, 1); await users_db.insert(user); res.status(200).send({ message: 'User left administration for the course.', course: { name: course.name, id: course.id, term: course.term, year: course.year } }); }); router.delete('/courses/:course/q/:question', auth, async(req, res) =>{ const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const users_db = await cloudant.db.use('users'); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); var query_response = await users_db.find({ selector: { _id: { "$eq": req.user } } }); if (!query_response.docs[0]) return res.status(400).send('Error: incorrect username.'); const user = query_response.docs[0]; query_response = await courses_db.find({ selector: { key: req.params.course, $or:[ { admins: { "$elemMatch": { "$eq": user._id } } }, { users: { "$elemMatch": { "$eq": user._id} } } ] } }); if (!query_response.docs[0]) return res.status(400).send('Error: user is enrolled in the selected course.') const course = query_response.docs[0]; query_response = await questions_db.find({ selector: { id: req.params.question, course: course._id } }); if(!query_response.docs[0]) return res.status(404).send('Error: could not find question for the selected course.') const question = query_response.docs[0]; if(question.author !== user._id) return res.status(401).send('Error: user is not the author of the question.') var index = course.questions.indexOf(question._id); course.questions.splice(index, 1); await courses_db.insert(course); await questions_db.destroy(question._id, question._rev); res.status(200).send({ message: 'Question deleted.' }); }); //** new */ router.delete('/courses/:course/q/:question/a/:answer', auth, async(req, res) =>{ const cloudant = await Cloudant({ url: process.env.cloudant_url + ':' + process.env.cloudant_port }); const courses_db = await cloudant.use('courses'); const questions_db = await cloudant.use('questions'); const answers_db = await cloudant.use('answers'); query_response = await courses_db.find({ selector: { key: { "$eq": req.params.course }, "$or": [ { users: { "$elemMatch": { "$eq": req.user } } }, { admins: { "$elemMatch": { "$eq": req.user } } } ] } }); if (!query_response.docs[0]) return res.status(400).send('Error: user is not registered in the indicated course'); const course = query_response.docs[0]; query_response = await questions_db.find({ selector: { id: { "$eq": req.params.question }, course: { "$eq": course._id } } }); if (!query_response.docs[0]) return res.status(400).send('Error: could not find question for the selected course.'); const question = query_response.docs[0]; query_response = await answers_db.find({ selector: { id: { "$eq": req.params.answer }, question: { "$eq": question._id } } }); if (!query_response.docs[0]) return res.status(400).send('Error: could not find the answer for the selected course'); const answer = query_response.docs[0]; if(answer.author !== req.user) return res.status(401).send('Error: user is not authorized to delete this answer.'); sleep(300); var index = question.answers.indexOf(answer._id); question.answers.splice(index, 1); await questions_db.insert(question); await answers_db.destroy(answer._id, answer._rev); res.status(200).send({ message: 'Answer deleted.' }); }); module.exports = router;
var User = require('../models/User'); var userController = { /* Expects an object with the following format: { email: 'john@doe.com', password: 'mypassword', deviceToken: 'fadsiuahebasgndoidszdaioewfnroawen' } */ create: function(body, cb) { var user = new User({ email: body.email, password: body.password, deviceToken: body.deviceToken }); user.save(function(err) { if (err) { cb('Error saving new user: ' + err, null, null); } else { cb(null, 'Successfully saved new user!', user); } }); }, /* Takes and ID and returns the user via the callback, literally just a simplified db query */ getUser: function(id, cb) { User.findById(id, function(err, user) { cb(err, user); }); } }; module.exports = userController;
Ext.define('HSF.model.Speakers', { extend: 'Ext.data.Model', config: { fields: ['firstName', 'lastName', 'img', 'shortDesc', 'description'] } })
/** * 命令式编程:将数组元素变成3倍 * @param {*} arr */ const triple = (arr) => { let results = [] for (let i = 0; i < arr.length; i++) { results.push(arr[i] * 3) } return results } /** * 声明式编程:将数组元素变成3倍 * @param {*} arr */ const triple2 = (arr) => arr.map((currentItem) => currentItem * 3) console.log(triple([1,2,3])) console.log(triple2([1,2,3])) /** * 头等函数 */ // const log = (content) => console.log(content) // const err = (content) => console.error(content) // const arrFunc = [ // log, err // ] // const hashFunc = { // log, err // } // const exec = (func, content) => func && func(content) // exec(log, "hello") // const compute = () => (a, b) => a + b // compute()(1, 3) // const mix = (a) => (b) => (c) => a + b * c // mix(1, 2, 3) // /** // * 纯函数 // */ // const log1 = (content) => console.log(content) // let context = "browser:" // const log2 = (content) => console.log(context, content) // /** // * 引用透明 // */ // const plus = (a, b) => a + b // const plus2 = () => { // return plus(1, 2) + 3 // } // const plus3 = () => { // return 3 + 3 // } // plus2()
import React, { useState, useContext } from 'react'; import { GlobalContext } from './Context/GlobalState' export const Add = () => { const [text, setText] = useState(''); const [amount, setAmount] = useState(0); const { Add } = useContext(GlobalContext) const AddBokk = e => { e.preventDefault(); const newBook = { id: Math.floor(Math.random() * 1000000000), text, amount: +amount } console.log(newBook.id) Add(newBook); setText(''); setAmount(""); } return ( < div > < h3 style = { { color: "blue" } } > Add Transaction < /h3> < label htmlFor = "text" > Text < /label> < input type = "text" value = { text } onChange = { (e) => setText(e.target.value) } / > < label > Amount < /label> < p > (negative - expense, positive - income...) < /p> < input type = "text" value = { amount } onChange = { (e) => { setAmount(e.target.value); console.log(e.target.value); } } / > < br / > < input type = "submit" value = "ADD" onClick = { AddBokk } / > < / div > ) }
/** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } * Time Complexity : O(n) -> Have to traverse through all nodes once to get the sum. * Space Complexity: Max stack depth is O(D), where D is the depth of the tree. */ /** * @param {TreeNode} root * @return {number} */ var sumRootToLeaf = function(root) { if(root === null){ return 0; } return sumOfRootToLeaf(root, 0, 0); }; var sumOfRootToLeaf = function(node, currSum, result){ if(node.left == null && node.right === null){ // Reached a left node add to the result and return it. return result + currSum*2 + node.val; }else if(node.left === null && node.right !== null){ // Left node is null get sum from the right nodes. return sumOfRootToLeaf(node.right, currSum*2 + node.val, result); }else if(node.right === null && node.left !==null){ // Right node is null return from left nodes return sumOfRootToLeaf(node.left, currSum*2 + node.val, result); } else { // Has both left and right nodes, return from both directions. return sumOfRootToLeaf(node.left, currSum*2 + node.val, result) + sumOfRootToLeaf(node.right, currSum*2 + node.val, result); } };
const Like = { like: async function (userId, attachedId, type) { return { userId, attachedId, type, } }, LIKE_TYPES: { TOPIC: 'topic', REPLY: 'reply', USER: 'user' } } module.exports = Like
import React from 'react' const Overlay = props => { return ( <div className="overlay" style={props.canEdit ? { opacity: '1', zIndex: '1' } : null}> {props.children} </div> ) } export default Overlay
import React from 'react'; const Header = props => { return ( <div className="navbar" id="navbar"> <div className="header-title">Robofriends</div> {props.children} </div> ); }; export default Header;
export default { 'CODE_ERR_NETWORK': -1, 'CODE_OK': 0, 'CODE_ERR_APP': 1000, 'CODE_ERR_MSG': 1001, 'CODE_ERR_PARAM': 1002, 'CODE_ERR_NO_PRIV': 1003, }
import React from 'react' import PhotoHeader from '../PhotoHeader' import "./style.css" const Profile = (props) => ( <div> <PhotoHeader photo={props.photo} /> <h1 className="display-2">{props.petName}</h1> <hr /> <br /> <h3>Birthday: 2008-07-31</h3> <h3>Breed: Mix</h3> <h3>Color: White</h3> <h3>Markings: None</h3> <h3>Weight: 30lbs</h3> <h3>Preferred Food Brand: Wellness</h3> <h3>Microchip Number: 123</h3> <h3>Rabies Tag Number: 321</h3> <h3>Insurance: None</h3> <h3>Medications: None</h3> <h3>Allergies: Seasonal</h3> <h3>Special Care Notes: None</h3> <footer /> </div> ) export default Profile
import { withRouter } from "react-router"; import React from "react"; import "../CSS/Store-fin.css"; class Storefin extends React.Component { handleToHomePage = () => { this.props.history.push("/"); }; render() { return ( <div className="storefin"> <h1>出品完了しました</h1> <button className='backhome' onClick={this.handleToHomePage}>ホームへ</button> </div> ); } } export default withRouter(Storefin);
// const n = 5; // const lost = [2, 4]; // const reserve = [1, 3, 5]; const n = 5; const lost = [2, 4]; const reserve = [3]; // const n = 3; // const lost = [3]; // const reserve = [1]; function solution(n, lost, reserve) { let answer = 0; let arr = []; arr[0] = 0; for (let i = 1; i <= n; i++) { arr[i] = 1; //한벌씩 있다고 하자 } arr[n + 1] = 0; for (let i = 0; i < lost.length; i++) { arr[lost[i]] -= 1; //잃어버린 애들 빼준다 } for (let i = 0; i < reserve.length; i++) { arr[reserve[i]] += 1; //여벌있는 애들 더해준다. } //0인애들 중에 양쪽에 2개인애들을 찾아 1로 만들어준다 for (let i = 1; i <= n; i++) { if (arr[i] === 0) { if (arr[i - 1] === 2) { arr[i - 1] = 1; arr[i] = 1; } else if (arr[i + 1] === 2) { arr[i + 1] = 1; arr[i] = 1; } } } answer = arr.filter((a) => a >= 1).length; return answer; } console.log(solution(n, lost, reserve));
import * as action from '../../src/redux/cars/actions' import * as api from '../../src/networkservices/cars' import {getCars} from '../../src/redux/cars/saga' import MockData from '../../MockData' // we can do saga testing without "redux-saga-test-plan" lib, but its really // good libarary for end to end saga testing. We can test exact effects and // their ordering or just test your saga put's a specific action at some point, import {expectSaga} from 'redux-saga-test-plan'; import * as matchers from 'redux-saga-test-plan/matchers'; import {throwError} from 'redux-saga-test-plan/providers'; import {call} from 'redux-saga/effects'; describe('cars saga', () => { it('should test saga', async() => { const carList = { carList: MockData.CAR_LIST.data.vehicles.edges, pageInfo: { hasNextPage: MockData.CAR_LIST.data.vehicles.pageInfo.hasNextPage, totalCount: MockData.CAR_LIST.data.vehicles.totalCount }, resetPage: false } return expectSaga(getCars, { payload: { nextPage: true, resetPage: false, skip: 10, take: 10 } }).provide([ [ call(api.getCarsList, { skip: 10, take: 10 }), MockData.CAR_LIST ] ]) .put({type: action.CAR_LIST_SUCCESS, payload: carList}) .dispatch({ type: action.GET_CAR_REQUEST, payload: { nextPage: true, resetPage: false, skip: 10, take: 10 } }) .run(); }); it('handles errors', () => { const error = new Error('error'); return expectSaga(getCars, { payload: { nextPage: true, resetPage: false, skip: 10, take: 10 } }).provide([ [ matchers .call .fn(api.getCarsList), throwError(error) ] ]) .put({type: action.CAR_LIST_FAILED, error: true, payload: error}) .dispatch({ type: action.GET_CAR_REQUEST, payload: { nextPage: true, resetPage: false, skip: 10, take: 10 } }) .run(); }); });
'use strict'; module.exports.hello = async (event, context) => { // OR include configuration options const mysql = require('serverless-mysql')({ backoff: 'decorrelated', base: 5, cap: 200 }) mysql.config({ host : process.env.ENDPOINT, database : process.env.DATABASE, user : process.env.USERNAME, password : process.env.PASSWORD }) return { statusCode: 200, body: JSON.stringify({ message: 'Go Serverless v1.0! Your function executed successfully!', input: event, }), }; // Use this code if you don't use the http event with the LAMBDA-PROXY integration // return { message: 'Go Serverless v1.0! Your function executed successfully!', event }; };
module.exports = { apps: [ { name: "Nuvem42", script: "./src/bin/www", watch: true, instances: 2, }, ], };
/// <reference path="../Lib/phaser.d.ts"/> var MonkeyRun; (function (MonkeyRun) { var Emitter = /** @class */ (function () { function Emitter(game, width, gravity, keys) { this.game = game; this.emitter = this.game.add.emitter(0, 0, 20); this.emitter.width = width; this.emitter.gravity = gravity; this.emitter.setAlpha(1, 0.5); this.emitter.minParticleScale = 0.2; this.emitter.maxParticleScale = 0.3; this.emitter.makeParticles(keys); } Emitter.prototype.update = function () { var _this = this; this.emitter.forEachAlive(function (particle) { particle.alpha = particle.lifespan / _this.emitter.lifespan; }, this); }; Emitter.prototype.start = function (x, y, explode, lifespan, quantity) { this.emitter.x = x; this.emitter.y = y; this.emitter.bounce.setTo(0.9, 0.9); this.emitter.angularDrag = 0; this.emitter.start(explode, lifespan, 0, quantity, true); }; return Emitter; }()); MonkeyRun.Emitter = Emitter; })(MonkeyRun || (MonkeyRun = {}));
import React from "react"; import { Textarea, Card, Input, InputGroup, CardStack, Button, Intent, Notice } from "amino-ui"; import { useInput } from "react-hanger"; import { useDispatch } from "react-redux"; import { push } from "connected-react-router"; export const AdminSetup = () => { const name = useInput(""); const website = useInput(""); const startsAt = useInput(""); const endsAt = useInput(""); const teamSize = useInput(""); const description = useInput(""); const dispatch = useDispatch(); const goto = url => dispatch(push(url)); const save = e => { e.preventDefault(); goto("/"); }; return ( <CardStack> <form onSubmit={save}> <Notice intent={Intent.Primary}> Before you continue, fill out the event details </Notice> <Card> <InputGroup> <Input {...name} label="Event name" required /> <Input {...website} label="Event website" required type="url" /> <Input {...startsAt} label="Starts at" /> <Input {...endsAt} label="Ends at" /> <Input {...teamSize} label="Max team size" /> <Textarea label="Description" /> </InputGroup> <Button intent={Intent.Primary}>Continue</Button> </Card> </form> </CardStack> ); };
var quotes = [{ 'author': '- Yoda', 'quote': 'When 900 years old, you reach… Look as good, you will not.' }, { 'author': '- Senator palpatine', 'quote': 'The Dark Side of the Force is the pathway to many abilities some consider to be.. Unnatural.' }, { 'author': '- Count Dooku', 'quote': 'I sense great fear in you, Skywalker. You have hate… you have anger… but you don’t use them.' }, { 'author': '- Darth vader', 'quote': 'Luke, you can destroy the Emperor. He has foreseen this. It is your destiny. Join me, and together we can rule the galaxy as father and son.' }, { 'author': '- Princess leila', 'quote': 'Aren\'t you a little short for a storm trooper?' }, { 'author': '- Yoda', 'quote': 'Mmm. Lost a planet, Master Obi-Wan has. How embarrassing.' }, { 'author': '- Qui-Gon Jinn', 'quote': 'Your focus determines your reality' }, { 'author': '- Yoda', 'quote': 'Do. Or do not. There is no try.' }, { 'author': '- Obi-Wan-Kenobi', 'quote': 'In my experience there is no such thing as luck.' }, { 'author': '- Yoda', 'quote': 'If once you start down the dark side, forever will it dominate your destiney, consume you it will, as it did Obi-Wan\'s apprentice' }, { 'author': '- Darth Vader', 'quote': 'The Force is strong with this one.' }]; // The button used to generate a random quote var GenerateButton = React.createClass({ render: function () { return ( <div className="ui label" data-content={this.props.content} data-variation="mini inverted" data-position="top center"> <button className={"circular massive ui blue icon button"+(this.props.disabled?" disabled":"")} onClick={this.props.onclick} id={this.props.id}> <i className={"icon "+this.props.icon}></i> </button> </div> ); } }); // The list of search results var ResultList = React.createClass({ render: function () { return ( <div className="ui inverted relaxed divided list"> { this.props.items.map(function(q, i) { return ( <div className="item" onClick={this.props.onclick} key={i}> {q.quote + " " + q.author} </div> ) }, this) } </div> ); } }); var QuoteLayer = React.createClass({ getInitialState: function() { return { quote: this.props.quotes[parseInt(Math.random()*this.props.quotes.length)], selectedQuotes: this.props.quotes, } }, randomQuote: function (event) { var tq; if(event.target.id == "glb") { tq = this.props.quotes; } else { tq = this.state.selectedQuotes; } var quote = tq[parseInt(Math.random()*tq.length)]; this.setState({ quote: quote }); }, selectQuote: function (event) { this.setState({ quote: event.target.innerText }); }, searchQuote: function (event) { var re; var inputElement = $("input#sglb, input#saut")[0]; var search_author = $("#search-author").hasClass("checked"); if (typeof event == "object") { re = new RegExp(event.target.value.toLowerCase()); } else { re = new RegExp($("input#sglb, input#saut")[0].value.toLowerCase()); } var filtedQuotes = this.props.quotes.filter(function (q) { if (!search_author) { return re.test(q.author.toLowerCase()) || re.test(q.quote.toLowerCase()); } else { return re.test(q.author.toLowerCase()); } }); this.setState({ selectedQuotes: filtedQuotes }); }, searchAuthor: function () { this.searchQuote(); }, render: function() { var displayedQuote = this.state.quote; var glButton = null; var search_author = $("#search-author").hasClass("checked"); var empty = !($("#sglb").val() || $("#saut").val()); if (typeof displayedQuote == "string") { var text = displayedQuote; } else { var text = displayedQuote.quote + " " + displayedQuote.author; } var quotesList = []; if(!empty) { quotesList = this.state.selectedQuotes; } return ( <div> <div className="ui container" id="header"> <h1 id="quote">{text}</h1> </div> <div className="ui two column six wide center aligned grid"> <div className="column"> <GenerateButton content="Generate a random quote" onclick={this.randomQuote} icon="refresh" id="glb" /> </div> <div className="column"> <GenerateButton content="Generate from the list below" onclick={this.randomQuote} icon="repeat" d="sel" disabled={empty}/> </div> </div> <div className="ui two column center aligned grid"> <div className="two column centered row"> <div className="ten wide column" id="fields"> <div className="ui left icon input"> <input type="text" placeholder={search_author?"Search Author...":"Search..."} className="ui input" id={search_author?"saut":"sglb"} onChange={this.searchQuote} /> <i className="search icon"></i> </div> </div> <div className="two wide center aligned column" id="fields"> <div className="ui toggle checkbox" id="search-author"> <input type="checkbox" name="search-author" tabIndex="0" className="hidden"/> <label htmlFor="search-author" onClick={this.searchAuthor} className="blue">Search Author</label> </div> </div> </div> <div className="twelve wide column padding-top-0"> <ResultList items={quotesList} onclick={this.selectQuote}/> </div> </div> </div> ); } }); $(document).ready(function () { ReactDOM.render( <QuoteLayer quotes={quotes}/>, document.getElementById('container') ); $("#container .ui.label").popup() $('#search-author').checkbox({ onChecked: function() { $('.ui.modal') .modal({ closable: false, onApprove: function() { $('#search-author').addClass('disabled'); }, onDeny: function() { $('#search-author input').prop('checked', false); } }) .modal('show'); } }); $("button").on("click", function () { $(this).addClass("spin"); setTimeout(function () { $(this).removeClass("spin"); }.bind(this), 600); }); });
const {router} = require('../../../config/expressconfig') const Review = require('../../models/review') let updateReview = router.patch('/update-review/:id',async (req,res)=>{ const id = req.params.id const data =await Review.findByIdAndUpdate(id,req.body) if(data && data.length != 0){ return res.json({ msg: 'review updated successfully', data: data }) } else { return res.json({ msg: "review can not be updated" }) } }) module.exports = {updateReview}
import { getOrderDetails, getRecoverList, updateApirec, cancelOrder } from '@/api/orderMan' import { Message } from 'element-ui' export default { data() { return { topData: {}, count: 0, count1: 0, list: [], cancelReasonName: '', cancelOrder: false, assign: true, assignPopus: false, assignObj: {}, recoverList: [], formData: { page: 1, limit: 10, orderId: '' }, recoverFrom: { page: 1, limit: 10 } } }, created() { this.topData = JSON.parse(sessionStorage.getItem('userInfo')) console.log(this.topData) this.formData.orderId = this.$route.params.id this.getList() this.getRecoverList() }, methods: { handleSizeChange(val) { this.formData.limit = val this.getList() }, handleCurrentChange(val) { this.formData.page = val this.getList() }, handleSizeChange1(val) { this.recoverFrom.limit = val this.getRecoverList() }, handleCurrentChange1(val) { this.recoverFrom.page = val this.getRecoverList() }, getList() { getOrderDetails(this.formData).then(res => { this.list = res.data.data this.count = res.data.count this.topData.address = res.data.address this.topData.addressArea = res.data.addressArea this.topData.remark = res.data.remark this.topData.reserveTime = res.data.reserveTime this.topData.receiveTime = res.data.receiveTime console.log(res) }) }, // 取消订单 cancel() { this.cancelOrder = true }, assignOrder() { this.assign = false }, // 获取回收员列表 getRecoverList() { getRecoverList(this.recoverFrom).then(res => { this.recoverList = res.data.data this.count1 = res.data.count console.log(res) }) }, // 关闭弹窗 handleClose() { this.cancelOrder = false this.assignPopus = false // this.assign = false }, // 指派订单 sureAssign(item) { this.assignPopus = true this.assignObj = item console.log(item) }, // 返回 back() { this.assign = !this.assign }, // 取消订单 cancellation() { if (!this.cancelReasonName) { Message({ message: '取消原因不能为空!', type: 'error' }) return } else { const formData = { orderId: this.topData.orderId, cancelReasonName: this.cancelReasonName } cancelOrder(formData).then(res => { if (res.code === 0) { Message({ message: res.msg, title: res.msg, type: 'success' }) this.$router.go(-1) } console.log(res) }) } }, // 确定指派 sureOrder() { const formData = { orderId: this.topData.orderId, userId: this.assignObj.userId } updateApirec(formData).then(res => { if (res.code === 0) { Message({ message: res.msg, title: res.msg, type: 'success' }) this.$router.go(-1) } }) } } }
import {StyleSheet} from 'react-native'; import theme from '../../theme.style'; export default StyleSheet.create({ container: { flex: 1, marginLeft: theme.HMARGINS, marginRight: theme.HMARGINS, }, greetingContainer: { marginTop: theme.VMARGINS * 2, }, greeting: { ...theme.HEADER, }, name: { ...theme.HEADER, }, text: { ...theme.BODY, }, header: { ...theme.HEADER2, marginTop: theme.VMARGINS, }, book: { ...theme.body, marginTop: 4, }, sectionHeader: { paddingTop: theme.VMARGINS, backgroundColor: theme.GRAY, ...theme.HEADER3, }, });
/** * 取引履歴検索サンプル * @ignore */ const moment = require('moment'); const pecorino = require('../'); async function main() { await pecorino.mongoose.connect(process.env.MONGOLAB_URI); const actionRepo = new pecorino.repository.Action(pecorino.mongoose.connection); const actions = await pecorino.service.account.searchTransferActions({ accountId: '5aeadf43a05f55009c25c5ae' })({ action: actionRepo }); console.log(actions.map((a) => `${moment(a.endDate).format('YYYY-MM-DD HH:mm')} ${a.typeOf} ${a.amount} ${a.recipient.name} @${a.purpose.typeOf}`).join('\n')); } main() .then(() => { console.log('success!'); }) .catch(console.error) .then(() => { pecorino.mongoose.disconnect(); });
var gulp = require('gulp'); var $ = require('gulp-load-plugins')(); var packager = require('electron-packager'); gulp.task('download:font', function (done) { var urls = [ "http://mplus-fonts.osdn.jp/webfonts/mplus-2m-regular.ttf", "http://mplus-fonts.osdn.jp/webfonts/mplus-2p-regular.ttf", ]; var fs = require('fs'); var path = require('path'); var dirname = "font" if (fs.existsSync(dirname)) { // Already exists. Skip downloading font. return done(); } fs.mkdirSync(dirname); console.log('downloading web font.'); process.on('download', function(i) { var url = urls[i]; if (!url) { return done(); } console.log(url); var http = require(url.split(':')[0]); http.get(url, function(res) { var filename = path.join(dirname, path.basename(url)); var output = fs.createWriteStream(filename); res.pipe(output); res.on('end', function() { process.nextTick(function() { process.emit('download', ++i); }) }); }).on('error', function(err) { console.log('error', err); }); }) process.emit('download', 0); }); gulp.task('compile', function(){ var host = process.argv[3] ? process.argv[3].split('--host=').pop() : ''; if (!host) { host = "https://score.sakura.tductf.org"; } return gulp.src('src/**/*.{js,jsx}') .pipe($.replace('SCORE_SERVER_URL', host)) .pipe( $.babel({ stage: 0 }) ) .pipe(gulp.dest('js')); }); var commonOption = { dir: './', out: 'release', name: 'Lepus-CTF', arch: 'all', platform: 'all', asar: true, ignore: [ './node_modules/electron*', './node_modules/.bin', './release/', './src/', './.git*' ], version: '0.30.6' } gulp.task('package:darwin', ['compile'], function (done) { var option = commonOption; option.platform = 'darwin'; option.arch = 'x64'; packager(option, function (err, path) { done(); }); }); gulp.task('package:linux:ia32', ['compile'], function (done) { var option = commonOption; option.platform = 'linux'; option.arch = 'ia32'; packager(option, function (err, path) { done(); }); }); gulp.task('package:linux:x64', ['compile'], function (done) { var option = commonOption; option.platform = 'linux'; option.arch = 'x64'; packager(option, function (err, path) { done(); }); }); gulp.task('package:win32:ia32', ['compile'], function (done) { var option = commonOption; option.platform = 'win32'; option.arch = 'ia32'; packager(option, function (err, path) { done(); }); }); gulp.task('package:win32:x64', ['compile'], function (done) { var option = commonOption; option.platform = 'win32'; option.arch = 'x64'; packager(option, function (err, path) { done(); }); }); gulp.task('package:all', [ 'package:darwin', 'package:linux:ia32', 'package:linux:x64', 'package:win32:ia32', 'package:win32:x64'], function (done) { done(); });
import React from 'react' import { connect } from 'react-redux' function CompB(props) { const {count} = props return ( <p>{count}</p> ) } const mapStateToProps = state=> { return state } export default connect(mapStateToProps)(CompB)
module.exports = { Closet: require("./closet"), User: require("./User"), UserSession: require("./UserSession") };
/** * Up Korean Medicine table. * * @param {object} knex * */ exports.up = function(knex) { console.log('generating korean medicine table'); return knex.schema.createTable('korean_medicine', table => { table.increments('id').primary().unsigned(); table.string('Title').notNullable(); table.string('Content', 5000).notNullable(); table.timestamp('created_at'); table.timestamp('updated_at'); }); }; /** * Drop Korean Medicine table. * * @param {object} knex * */ exports.down = function(knex) { console.log('dropping korean medicine table'); return knex.schema.dropTable('korean_medicine'); };
/* *var arr=[1,2,3] *media = 2 *tamanho = 3 *somatorio = 6 *desvioMedioAbsoluto resultado esperado = 0.6667 */ 'use strict' var media = require('./mediaAritmetica.js') var tamanho = require('./tamanho.js') function desvioMedioAbsoluto (arr) { return (1 / tamanho(arr)) * (arr.map((elemen) => { return (Math.abs(elemen - media(arr))) }).reduce((a, b) => { return (a + b) }) ) } module.exports = desvioMedioAbsoluto
import React, { useState } from "react"; import LogoutModal from "../logout/modal"; import { darkGray } from "../../../styles/color"; import { Link } from "react-router-dom"; const UserMenuModal = () => { const [isModalShown, toggleModal] = useState(false); return ( <div className="menuContainer"> <p>no_name</p> <ul> <li> <Link to="/anonymatter/account"> <i className="far fa-user" /> <span>My Tweets</span> </Link> </li> <li> <i className="fas fa-cog" /> <span>My Tweets</span> </li> <li onClick={() => toggleModal(true)}> <i className="fas fa-sign-out-alt" /> <span>Log out</span> </li> </ul> {isModalShown && <LogoutModal toggleModal={toggleModal} />} <style jsx>{` .menuContainer { position: absolute; right: 30px; border: 1.5px solid ${darkGray}; } ul { list-style: none; } `}</style> </div> ); }; export default UserMenuModal;
import request from '../utils/request'; //添加用户 export function add_User(params) { return request.post('/user', params); } //更新用户 export function updata_User(params) { return request.put('/user/user', params); } //获取所有身份ID export function get_Id(params) { return request.get('/user/user', params); } //获取所有身份ID(1) export function getAll_Id(params) { return request.get('/user/identity', params); } //添加身份 export function add_Identityr(params) { return request.get('/user/identity/edit', {params}); } //添加api接口权限 export function add_Api_jurisdiction(params) { return request.get('/user/authorityApi/edit', {params}); } //获取所有视图 export function get_View(params) { return request.get('/user/view_authority'); } //添加视图接口权限 export function add_View(params) { return request.get('/user/authorityView/edit', {params}); } //获取所有api接口权限 export function get_Api_Authority(params) { return request.get('/user/api_authority'); } //给身份设置api接口权限 export function identityr_Jurisdiction(params) { return request.post('/user/setIdentityApi', params); } //给身份设置视图权限 export function view_Jurisdiction(params) { return request.post('/user/setIdentityView', params); }
const router = require('express').Router(); const clientController = require('../controllers/client.controller'); const { auth } = require('../utils/auth'); const { formData } = require('../utils/formData'); router.route('/').get(auth, clientController.show); router.route('/').post(clientController.signup); router.route('/').put(auth, formData, clientController.update); router.route('/').delete(auth, clientController.destroy); module.exports = router;
/* * configurePlace.js requires oauth2client.js to provide the Oauth2ServerFlow function * * The following html is required for configurePlace.js to work * <div id="j-card-authentication" class="j-card" > <p>The remote systems (Jive &amp; GitHub) require you to grant access before proceeding.</p> <div> <a id="github4jive-jive-authorize" href="javascript:void(0);" style="display: none;">Authorize Jive</a> <div id="github4jive-jive-authorize-success" style="display: none;"> <span>Jive Authorized - OK</span> </div> </div> <br/> <div> <a id="github4jive-github-authorize" href="javascript:void(0);" style="display: none;">Authorize GitHub</a> <div id="github4jive-github-authorize-success" style="display: none;"> <span>GitHub Authorized - OK</span> </div> </div> </div> <div id="j-card-configuration" class="j-card" style="display: none;"> <br/> <div class="form-group"> <label for="projectList">Repository: </label> <div class="bootstrap-select-overlay"> <span id="loader" ><span></span></span><select id="projectList" class="form-control"></select> </div> </div> <div class="form-group"> <input id="github4jive-enable-submit" type="button" value="Save" class="btn btn-primary"/> </div> </div> This is the bare minimum to allow a tile to configure the place it is on for Github4Jive. Because basicOauthFlow can be used in apps as well it does not handle closing of the tile/app. It instead emits an event "github4jiveConfigDone" when it has finished its configuration. Use this event to then do any additional configuration required for the tile/app and then close it. DO NOT close the tile by listening for github4jive-enable-submit click. This will cancel requests that are in progress that will break the basicOauthFlow configuration. The configurePlace.js also emits "github4jiveAuthorized" when it has passed the authorization phase. Use this event to initialize any elements that require querying GitHub or Jive. The repository list is automatically populated. The j-card-configuration and j-card-action panels will be unhidden automatically if they are present when this event is triggered. */ var place, placeUrl, placeProps, previousRepo; var contentObject; var jiveDone = false; var githubDone = false; var host; $("body").append("<link />"); /* * This function is called when both GitHub and Jive have authorized the user. * The j-card-configuration id is unhid. And the github4jiveAuthorized Event * is thrown for custom configurations to setup their forms. The configuration * panel should have a select list with id "projectList" to populate the repository list. */ function AllAuthorized() { $("#j-card-authentication").hide(); $("#j-card-configuration").show(); $("#j-card-action").show(); $(document).trigger("github4jiveAuthorized"); gadgets.window.adjustHeight(); // do this here in case the pre-auth callback above wasn't called // set up a query to get this user's list of repositories $("#loader").addClass("j-loading-big"); osapi.http.get({ 'href': host + '/github/user/repos?' + "&ts=" + new Date().getTime() + "&place=" + encodeURIComponent(placeUrl), //"&query=" + query, 'format': 'json', 'authz': 'signed' }).execute(function (response) { if (response.status >= 400 && response.status <= 599) { alert("ERROR!" + JSON.stringify(response.content)); } var data = response.content; for (var i = 0; i < data.length; i++) { var opt; var name = data[i].fullName; if (name === previousRepo) { opt = "<option value=" + data[i].name + " selected>" + data[i].fullName + "</option>"; } else { opt = "<option value=" + data[i].name + ">" + data[i].fullName + "</option>"; } $("#projectList").append(opt); } $("#loader").removeClass("j-loading-big"); }); } function BothAreDone() { return jiveDone && githubDone; } function ProceedWhenReady() { if (BothAreDone()) { AllAuthorized(); } } /** * @param {string} system must be either "jive" or "github" * @param {integer} popupWidth in pixels * @param {function} successfulCallback the function to call when the Oauth dance completes */ function setupOAuthFor(system, popupWidth, successCallBack) { var ticketErrorCallback = function () { console.log('ticketErrorCallback error'); }; var jiveAuthorizeUrlErrorCallback = function () { console.log('jiveAuthorizeUrlErrorCallback error'); }; var preOauth2DanceCallback = function () { console.log("preOauth2DanceCallback"); }; var onLoadCallback = function (config, identifiers) { onLoadContext = { config: config, identifiers: identifiers }; }; var authorizeUrl = host + '/' + system + '/oauth/authorize'; var viewerID = new Date().getTime(); OAuth2ServerFlow({ serviceHost: host, grantDOMElementID: '#github4jive-' + system + '-authorize', ticketErrorCallback: ticketErrorCallback, jiveAuthorizeUrlErrorCallback: jiveAuthorizeUrlErrorCallback, oauth2SuccessCallback: successCallBack, preOauth2DanceCallback: preOauth2DanceCallback, onLoadCallback: onLoadCallback, authorizeUrl: authorizeUrl, jiveOAuth2Dance: system === "jive", context: {"place": placeUrl}, popupWindowWidth: popupWidth || 350, popupWindowHeight: 500 }).launch({'viewerID': viewerID}); } function launchGitHub3LeggedOAuth() { setupOAuthFor("github", 500, function (ticketID) { if (ticketID) { githubDone = true; $('#github4jive-github-authorize').slideUp('fast'); $('#github4jive-github-authorize-success').slideDown('fast', ProceedWhenReady); } }); } function launchJive3LeggedOAuth() { setupOAuthFor("jive", 500, function (ticketID) { if (ticketID) { jiveDone = true; $('#github4jive-jive-authorize').slideUp('fast'); $('#github4jive-jive-authorize-success').slideDown('fast', ProceedWhenReady); } }); } var app = { currentView: gadgets.views.getCurrentView().getName(), currentViewerID: -1, initGadget: function () { console.log('initGadget ...'); }, handleContext: function (context) { console.log('handleContext ...'); if (context) { osapi.jive.corev3.resolveContext(context, function (result) { if (result.content.contentID) {// called from Content Action. contentObject = result.content; placeUrl = result.content.parentPlace.uri; } else { place = result.content; placeUrl = result.content.resources.self.ref; } // // launch the 3-legged OAuth dance with GitHub // to acquire an OAuth access token on the behalf of the current user // for use in the backend service to access GitHub APIs // launchGitHub3LeggedOAuth(); // // launch the 3-legged OAuth dance with Jive // to acquire an OAuth access token on the behalf of the current user // for use in the backend service to access Jive APIs // launchJive3LeggedOAuth(); //This function is used right below it. function setupPlaceConfig(p) { place = p; place.getExtProps().execute(function (props) { placeProps = props.content; if ("true" === placeProps.github4jiveEnabled) { console.log('initializing UI for already configured place'); previousRepo = placeProps.github4jiveRepoOwner + "/" + placeProps.github4jiveRepo; } else { console.log('initializing UI for UNconfigured place'); } //double check server side configuration with ext props osapi.http.get({ 'href': host + '/github4jive/place/isConfigured?' + "&ts=" + new Date().getTime() + "&place=" + encodeURIComponent(placeUrl), 'format': 'json', 'authz': 'signed' }).execute( function (response) { var config = response.content; githubDone = config.github; jiveDone = config.jive; //make ui changes based on which systems are configured if (BothAreDone()) { AllAuthorized(); } else { if (config.github) { $('#github4jive-github-authorize-success').slideDown('fast'); } else { $('#github4jive-github-authorize').slideDown('fast'); } if (config.jive) { $('#github4jive-jive-authorize-success').slideDown('fast'); } else { $('#github4jive-jive-authorize').slideDown('fast'); } gadgets.window.adjustHeight(); } }); }); } //if place was not picked up from the context resolver then grab it from the url if (!place) { osapi.jive.corev3.places.get({"uri": placeUrl}).execute(setupPlaceConfig); } else { setupPlaceConfig(place); } }); $("#github4jive-enable-submit").click(function () { console.log('Saving GitHub4Jive Repository Information'); console.log('context has content callback'); var fullName = $("#projectList option:selected").text(); var parts = fullName.split("/"); var owner = parts[0]; var repoName = parts[1]; // // create extended properties on the place // linking it to the remote github repo // place.createExtProps({ "github4jiveEnabled": true, "github4jiveRepo": repoName, "github4jiveRepoOwner": owner }).execute(function (resp) { console.log('resp: {' + JSON.stringify(resp) + '}'); // // create webhooks for shadowing issues as jive discussions // osapi.http.post({ 'href': host + "/github4jive/place/setupDiscussionWebhooks?" + "ts=" + new Date().getTime() + "&place=" + encodeURIComponent(placeUrl), 'format': 'json', 'authz': 'signed' }).execute(function (response) { console.log(response); $(document).trigger("github4jiveConfigDone"); }); }); }); } } }; gadgets.util.registerOnLoadHandler(gadgets.util.makeClosure(app, app.initGadget)); //defined in oAuth2Client if (realTile) { // register a listener for embedded experience context opensocial.data.getDataContext().registerListener('org.opensocial.ee.context', function (key) { var data = opensocial.data.getDataContext().getDataSet(key); var resolverTransform = data.container; if (resolverTransform.type == 600) { resolverTransform.type = "osapi.jive.core.Project"; } if (resolverTransform.type == 700) { resolverTransform.type = "osapi.jive.core.Group"; } if (resolverTransform.type == 14) { resolverTransform.type = "osapi.jive.core.Space"; } app.handleContext(resolverTransform); }); } else { gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.group.config", callback: app.handleContext }); gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.project.config", callback: app.handleContext }); gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.space.config", callback: app.handleContext }); gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.group.newIssue", callback: app.handleContext }); gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.project.newIssue", callback: app.handleContext }); gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.space.newIssue", callback: app.handleContext }); gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.discussion.reopenIssue", callback: app.handleContext }); gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.discussion.closeIssue", callback: app.handleContext }); gadgets.actions.updateAction({ id: "com.jivesoftware.addon.github4jive.discussion.changeLabels", callback: app.handleContext }); }
import React from 'react' import App, { Container } from 'next/app' import Router from 'next/router' import Link from 'next/link' Router.events.on('routeChangeStart', url => { console.log('Navigating to:', url) }) Router.events.on('routeChangeComplete', url => { console.log('Completed navigation to: ', url) }) export default class MyApp extends App { static async getInitialProps({ Component, router, ctx }) { let pageProps = {} if (Component.getInitialProps) { pageProps = await Component.getInitialProps(ctx) } return { pageProps } } render() { const { Component, pageProps } = this.props return ( <Container> <ul> <Link href="/"> <a style={{ paddingRight: '8px' }}>Home</a> </Link> <Link href="/about"> <a style={{ paddingRight: '8px' }}>About</a> </Link> <Link href="/contact"> <a style={{ paddingRight: '8px' }}>Contact</a> </Link> <Link href="/pricing"> <a style={{ paddingRight: '8px' }}>Pricing</a> </Link> </ul> <hr /> <Component {...pageProps} /> </Container> ) } }
$(document).ready(function () { $.get('https://swapi-api.hbtn.io/api/films/?format=json', function (data) { const list = $('UL#list_movies'); data.results.forEach(movie => { list.append('<LI>' + movie.title + '</LI>'); }); }); });
'use strict' var user = require("./UserController") var tweet = require("./TweetController"); const { use } = require("../routes/userRoutes"); function commands(req, res){ var command = req.body.command.split(' '); switch(command[0].toLowerCase()){ case 'add_tweet': //return res.send({ message: "Este es el comando de añadir un tweet" }); tweet.crearTweet(req, res); break; case 'delete_tweet': //return res.send({ message: "Este es el comando de eliminar un tweet" }) tweet.eliminarTweet(req,res); break; case 'edit_tweet': //return res.send({ message: "Este es el comando para editar un tweet" }) tweet.editarTweet(req, res); break; case 'view_tweets': //return res.send({ message: "Este es el comando para ver tweets" }) user.showTweets(req, res); break; case 'follow': //return res.send({ message: "Este es el comando de dar follow" }) user.follow(req, res); break; case 'unfollow': //return res.send({ message: "Este es el comando para dejar de seguir" }) user.unfollow(req, res); break; case 'profile': //return res.send({ message: "Este es el comando para ver el perfil del usuario logueado" }) user.showProfile(req, res); break; case 'login': //return res.send({ message: "Este es el comando para loguearse" }) user.login(req, res); break; case 'register': //return res.send({ message: "Este es el comando para registrarse" }) user.registrar(req, res); // return res.send(command[2]) break; case 'like_tweet': tweet.likeTweet(req, res); break; case 'dislike_tweet': tweet.dislikeTweet(req, res); break; case 'reply_tweet': tweet.comentar(req, res); break; case 'retweet': tweet.retweet(req, res); break; default: return res.send({message: '-------------Comandos Válidos-------------', añadir_tweet: 'add_tweet + textoDelTweet', eliminar_tweet: 'delete_tweet + idTweet', editar_tweet: 'edit_tweet + idTweet + textoDelNuevoTweet', ver_tweets: 'view_tweets + username', follow: 'follow + username', unfollow: 'unfollow + username', ver_perfil: 'profile + username', login: 'login + username + password + true', registrarse: 'register + username + password', like: 'like_tweet + idTweet', dislike: 'dislike_tweet + idTweet', comentar: 'reply_tweet + idTweet + texto de respuesta', retweeetear: 'retweet + idTweet + comentario(opcional)'}) //console.log('add_tweet + textoDelTweet') //console.log('delete_tweet + idTweet') //console.log('edit_tweet + idTweet textoDelNuevoTweet') //console.log('view_tweets + username') //console.log('follow + username') //console.log('unfollow + username') //console.log('profile + username') //console.log('login + username password') //console.log('register + username password') } } module.exports={ commands }
import { Link } from "react-router-dom"; import './Menu.css'; import{useState}from 'react' <meta name="viewport" content="width=device-width, initial-scale=1"></meta> function Menu(){ return( <div className="col-6 col-s-9 Menu"> <div className="Menu-header"> <div className="Menu-Back-Button"> Menu <Link to = "/profile"> <img src= "back-32.png" align ="left"/> </Link> </div> </div> <div className="col-3 col-s-3 Menu-box"> <div className=" Menu-column"> <div className=" Menu-row"> <Link to = "/MangoSetting"> <button> <img src="mango-192.png" width="150px" height = "150px" class ="responsive"/> <div className = "SettingName"> <h3>Mango setting</h3> </div> </button> </Link> <Link to = "/AccountSetting"> <button> <img src="mango-192.png" width="150px" height = "150px" class ="responsive"/> <div className = "SettingName"> <h3>Account setting</h3> </div> </button> </Link> <Link to ="/FriendSetting"> <button> <img src="mango-192.png" width="150px" height = "150px" class ="responsive"/> <div className = "SettingName"> <h3>Friend setting</h3> </div> </button> </Link> </div> <div className="Menu-row"> <Link to ="/AdvanceSetting"> <button> <img src="mango-192.png" width="150px" height = "150px" class ="responsive"/> <div className = "SettingName"> <h3>Advance setting</h3> </div> </button> </Link> <Link to ="NotificationSetting"> <button> <img src="mango-192.png" width="150px" height = "150px" class ="responsive"/> <div className = "SettingName"> <h3>Notification Setting </h3> </div> </button> </Link> <Link to = "GameSetting"> <button> <img src="mango-192.png" width="150px" height = "150px" class ="responsive"/> <div className = "SettingName"> <h3>Game setting </h3> </div> </button> </Link> </div> </div> </div> </div> ); }; export default Menu;
const assert = require('assert'); const { callbackify } = require('util'); const net = require('net'); const urlParse = u => { assert(typeof u === 'string'); const parts = {}; const o = u.split(':'); if (o.length > 1) { parts.port = parseInt(o.pop()); } else { parts.port = 80; } parts.hostname = o.pop().split('//').pop(); return parts; }; module.exports = (url, opts, cb) => { if (typeof opts === 'function') { cb = opts; opts = {}; } opts = Object.assign({ timeout: 1000 }, opts); assert(typeof opts.timeout === 'number'); const fn = () => new Promise(resolve => { const socket = new net.Socket(); url = urlParse(url); const onError = () => { socket.destroy(); resolve(false); }; socket.setTimeout(opts.timeout); socket.on('error', onError); socket.on('timeout', onError); socket.connect(url.port, url.hostname, () => { socket.end(); resolve(true); }); }); if (typeof cb === 'function') { const cfn = callbackify(fn); cfn(cb); } else { return fn(); } };
const mongoose=require('mongoose') const blogSchema=new mongoose.Schema({ blogImageOriginalName:{ type:String, required:true }, blogImageName:{ type:String, required:true }, blogImageURL:{ type:String, required:true }, blogTitle:{ type:String, required:true }, blogDescription:{ type:String, required:true }, userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' } },{timestamps:true}) module.exports = blogSchema;
import React, { Component } from "react"; import MyIcon from "../common/MyIcon/MyIcon"; import s from "./NavBar.module.scss"; import { connect } from "react-redux"; import { showNewGameForm } from "../../actions/modalActions"; import LinkButton from "../common/LinkButton"; class NavBar extends Component { renderMenu() { return ( <div> <LinkButton to="/home">Home</LinkButton> <button onClick={e => this.props.showNewGameForm()}>Create Game</button> </div> ); } render() { const { username, points } = this.props.auth; return ( <div className={s.NavBar}> <MyIcon /> <div className={s.navBarDetails}> <h4>{username}</h4> <div>{points}</div> </div> {this.renderMenu()} </div> ); } } const mapStateToProps = state => { return { auth: state.auth }; }; const mapDispatchToProps = dispatch => { return { showNewGameForm() { dispatch(showNewGameForm()); } }; }; export default connect( mapStateToProps, mapDispatchToProps )(NavBar);
// const { date } = require("joi"); /* Global Variables */ const baseUrl = 'http://api.openweathermap.org/data/2.5/weather?zip='; const apiKey = '&APPID=a99947cad1fc2318badc6cdaa7bd2b03&units=imperial'; // Create a new date instance dynamically with JS let d = new Date(); let newDate = (d.getMonth()+1) +'.'+ d.getDate()+'.'+ d.getFullYear(); // Add slot that will be triggered when the generate button is clicked document.getElementById('generate').addEventListener('click', () => { let feelings = document.getElementById('feelings').value; console.log(12); console.log(feelings); let zip = document.querySelector('#zip').value; if(!zip){ alert("EMPTY zip code input!!"); return; } console.log(zip); getData(baseUrl, zip, apiKey) .then((data) => { postData('/add', { date: newDate, temp: data, feelings: feelings, }); }) .then(() => updateUI('/all')); }) // Function to get the data from wheather api const getData = async (baseURL, zip, key)=>{ const res = await fetch(baseURL+zip+key) try { const data = await res.json(); return data.main.temp; } catch(error) { console.log("error", error); } } // Function to update the project's data using /add const postData = async ( url = '', data = {})=>{ const response = await fetch(url, // Object contains metadata about req. { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }); try { const newData = await response.json(); console.log(newData); return newData }catch(error) { console.log("error", error); } }; // Function to pull the data from the /all end point then update the UI const updateUI = async (url)=>{ const res = await fetch(url); try { const data = await res.json(); document.querySelector('#date').innerHTML = data.date; console.log(data); document.querySelector('#temp').innerHTML = data.temp; document.querySelector('#content').innerHTML = data.feelings; return; } catch(error) { console.log("error", error); } }
var stage, counter = 0; var text, pause; function init () { stage = new createjs.Stage("canvas"); stage.on("mouseleave", function (evt) { if(!isEndOfGame){ createjs.Ticker.paused = true; pause = new createjs.Shape(); pause.graphics.beginFill("#e2895f").drawRoundRect(stage.canvas.width / 3 - 40, 40, 80, stage.canvas.height - 80, 10) .drawRoundRect(2 * stage.canvas.width / 3 - 40, 40, 80, stage.canvas.height - 80, 10) pause.alpha = 0.5; stage.addChild(pause); } }) stage.on("mouseenter", function (evt) { if(!isEndOfGame){ createjs.Ticker.paused = false; stage.removeChild(pause); } }) var background = new createjs.Shape(); background.graphics.beginFill("#f4f3f2").drawRoundRect(0, 0, stage.canvas.width, stage.canvas.height, 10); stage.addChild(background); createCircle(); createjs.Ticker.on("tick", tick); createjs.Ticker.setFPS(30); createjs.Ticker.paused = true; text = new createjs.Text(counter.toString(), "20px Arial", "#ff7700"); text.x = 5; text.y = 5; stage.addChild(text); } function createCircle(){ var tempCircle = new createjs.Shape(); var randomNo = Math.round(Math.random() * 2); var color = ["#00ffb6", "#b600ff", "#ffb600"]; tempCircle.graphics.beginFill(color[randomNo]).drawCircle(0, 0, 40); tempCircle.x = 40 + (Math.random() * (stage.canvas.width - 80)); tempCircle.y = 40 + (Math.random() * (stage.canvas.height - 80)); tempCircle.on("click", function(evt) { stage.removeChild(this); createjs.Tween.removeTweens(this); createCircle(); counter++; }); createjs.Tween.get(tempCircle) .to({scaleX: 0.2, scaleY: 0.2, alpha: 0.1}) .to({scaleX: 1, scaleY: 1, alpha: 1}, (500 - 10 * counter < 0) ? 0 : (500 - 10 * counter), createjs.Ease.bounceOut) .wait((200 - 5 * counter < 0) ? 0 : (200 - 5 * counter)) .to({scaleX: 0, scaleY: 0, alpha: 0}, (500 - 10 * counter < 0) ? 0 : (500 - 10 * counter), createjs.Ease.backIn) .call(youLost); stage.addChild(tempCircle); } var isEndOfGame = false; function youLost(){ isEndOfGame = true; alert("You lost the game! \nYour final score was " + counter +" clicked balls. Good job!"); var button = new createjs.Shape(); //button.graphics.beginFill("green").drawRoundRect(stage.canvas.width/2 - 50, stage.canvas.height / 2 - 50 , 100, 100, 10); button.graphics.beginFill("#e2895f").drawPolyStar(stage.canvas.width / 2, stage.canvas.height / 2, stage.canvas.height / 3, 3, 0, 0); button.on("click", function (evt){ location.reload(); }) stage.addChild(button); } function tick (event) { text.text = "Score: " + counter.toString(); stage.update(); }
(function() { 'use strict'; angular .module('app.chat') .directive('tzMessageList', tzMessageList); function tzMessageList($window, $timeout, storeService, selectorsService, _) { return { restrict: 'A', link: tzMessageListLinker }; function tzMessageListLinker(scope, element) { var alreadyAtBottom = true; var observer = new $window.MutationObserver(scrollToBottom); var throttledOnScrollHandler = _.throttle(scrollHandler, 250); var activeChannelId = selectorsService.activeChannelFilterSelector(storeService.getState()); var storeUnsubscribe = storeService.subscribe(storeSubscriber); observer.observe(element.children('md-list').get(0), {childList: true}); element.on('scroll.tzMessageList', throttledOnScrollHandler); $timeout(scrollToBottom); // Handle scrolling to bottom after refresh/app start. function scrollToBottom() { if (alreadyAtBottom) { element.scrollTop(element.prop('scrollHeight')); } } function isAtBottom() { var scrollTop = element.scrollTop(); var maxHeight = element.prop('scrollHeight') - element.prop('clientHeight'); return scrollTop >= maxHeight; } function scrollHandler() { alreadyAtBottom = isAtBottom(); } function storeSubscriber() { var channelId = selectorsService.activeChannelFilterSelector(storeService.getState()); if (activeChannelId !== channelId) { alreadyAtBottom = true; activeChannelId = channelId; scrollToBottom(); } } scope.$on('$destroy', function() { element.off('.tzMessageList'); observer.disconnect(); storeUnsubscribe(); }); } } })();
/* Batch variable that holds the * * */ import { vehicleAdd } from "./actions"; let updateStack = { set addUpdate(item) { this.test++ if (this.updatingVehicles.includes(item.id)) { //Item is already in stack this.modified++ this.actions[item.id] = { ...this.actions[item.id], ...item, content: { ...this.actions[item.id].content, ...item.content } } // switch (item.api) { // case "HSL": // // this.actions[item.id] = { // ...this.actions[item.id], // ...item, // content: { // ...this.actions[item.id].content, // ...item.content // } // } // break; // // default: // break; // } } else { this.updatingVehicles.push(item.id) if (item.content.content) { console.log(item.content) } this.actions[item.id] = vehicleAdd(item.id, item.displayName, item.vehicleType, item.api, item.coordinates, item.content) } }, get batchedActions () { let out = [] this.updatingVehicles.forEach(id => { out.push(this.actions[id]) }) // console.log("Modified:", this.modified, this.test) return out }, get countBatched () { return this.updatingVehicles.length }, set reset(i) { this.updatingVehicles = [] this.actions = {} this.modified = 0 this.test = 0 }, updatingVehicles: [], actions: {}, modified: 0, test: 0 }; export default updateStack;
$document.ready(function() { $('.colorpicker').simpleColor({ cellWidth: 9, cellHeight: 9, border: '1px solid #333333' }); });
import React, { useState } from 'react'; import NavMenu from './components/NavMenu/NavMenu.js'; import About from '/Users/l/my-react-website/src/components/NavMenu/About.js'; import Contact from './/components/NavMenu/Contact'; import Projects from '/Users/l/my-react-website/src/components/NavMenu/Projects.js'; import Home from './components/NavMenu/Home'; import Blog from './components/NavMenu/Blog'; import Resume from './components/NavMenu/Resume'; import Dropdown from './components/NavMenu/Dropdown'; import {BrowserRouter as Router, Route, Switch } from 'react-router-dom'; import Hamburger from './components/Hamburger/Hamburger'; import Logo from './components/Logo/Logo'; import GlobalStyle from './globalStyles.js'; import Combining from './components/pages/Combining.js'; import LearningCoding from './components/pages/LearningCoding.js'; import Schedule from './components/pages/Schedule.js'; import Drumkit from './components/Projects/Drumkit.js'; function App() { const [open, setOpen] = useState(false); const toggle = () => { setOpen(!open) } return ( <Router> <div> <GlobalStyle /> <Logo /> <Hamburger toggle={toggle} /> <Dropdown open={open} toggle={toggle} /> <NavMenu /> <Switch> <Route exact path='/'> <Home /> </Route> <Route exact path='/about'> <About /> </Route> <Route exact path='/blog'> <Blog /> </Route> <Route exact path='/projects'> <Projects /> </Route> <Route exact path='/resume'> <Resume /> </Route> <Route exact path='/contact'> <Contact /> </Route> <Route exact path='/combining'> <Combining /> </Route> <Route exact path='/learningcoding'> <LearningCoding /> </Route> <Route exact path='/schedule'> <Schedule /> </Route> </Switch> </div> </Router> ); } export default App;
import React,{Component} from 'react'; import Icon from 'react-native-vector-icons/Ionicons'; import {View, Text, ScrollView,TouchableOpacity,TextInput,Dimensions} from 'react-native'; var {height, width} = Dimensions.get('window'); export default class SearchScreen extends Component{ render(){ return( <ScrollView> <View style={{backgroundColor:'#fff' ,flexDirection:'row',borderWidth:2,borderColor:'#2f9676',borderRadius:1 ,margin:10,alignItems:'center'}}> <Icon style={{opacity:0.8, marginLeft:10, marginRight:5}} name="ios-search" size={18} color={'#606064'} /> <TextInput onSubmitEditing={()=>alert('ok rồi đấy!')} height={38} placeholder='Sản phẩm thương hiệu và mọi thứ!' style={{fontSize:13, backgroundColor:'#fff'}}></TextInput > </View> </ScrollView> ); } }
import React, { useState, useEffect } from "react"; import "../../styles/Light.css"; function Light() { const [active1, setactive1] = useState(" "); const [active2, setactive2] = useState(" "); const [active3, setactive3] = useState(" "); ///function OnLight (event) const OnLight = event => { if (event.target.classList.contains("red")) { setactive1("selected"); setactive2(" "); setactive3(" "); } else if (event.target.classList.contains("yellow")) { setactive2("selected"); setactive1(" "); setactive3(" "); } else if (event.target.classList.contains("green")) { setactive3("selected"); setactive2(" "); setactive1(" "); } }; return ( <div className="First-container traffic"> <div id="red" className={"red " + active1} onClick={event => { OnLight(event); }} /> <div id="yellow" className={"yellow " + active2} onClick={event => { OnLight(event); }} /> <div id="green" className={"green " + active3} onClick={event => { OnLight(event); }} /> </div> ); } export default Light;
module.exports = { get_user : 'SELECT * FROM USER WHERE email=?', create_user :'INSERT INTO USER(user, email, password) VALUES(?,?,?)', get_comments :'SELECT USER.user, COMMENTS.comment FROM COMMENTS INNER JOIN USER ON USER.id = COMMENTS.user', create_comment : 'INSERT INTO COMMENTS(user, comment) VALUES(?,?)', create_token: 'INSERT INTO TOKENS(user,token) VALUES(?,?)', findByToken: 'SELECT USER.user FROM USER INNER JOIN TOKENS ON TOKENS.user = USER.id WHERE USER.id = ?' }
'use strict'; angular.module('mean.system').controller('HeaderController', ['$scope', 'Global', function ($scope, Global) { $scope.global = Global; var MenuItem = function(title, link) { this.title = title; this.link = link; }; $scope.menu = [ new MenuItem('Articles', 'articles'), new MenuItem('Create New Article', 'create') ]; $scope.isCollapsed = false; }]);
export let initialState={ isError:false, message:'', course:'', chapterId:'', subjectId:'', };
// Exports function for creating a new template. var Crypto = require("crypto"); var execFile = require("child_process").execFile; var File = require("fs"); var Path = require("path"); var Zip = require("./zip"); // Template will have accessor methods for these fields. var TEMPLATE = [ "passTypeIdentifier", "teamIdentifier", "backgroundColor", "foregroundColor", "labelColor", "logoText", "organizationName", "suppressStripShine", "webServiceURL"]; // Supported passbook styles. var STYLES = [ "boardingPass", "coupon", "eventTicket", "generic", "storeCard" ]; // Top-level passbook fields. var TOP_LEVEL = [ "authenticationToken", "backgroundColor", "barcode", "description", "foregroundColor", "labelColor", "locations", "logoText", "organizationName", "relevantDate", "serialNumber", "suppressStripShine", "webServiceURL"]; // These top level fields are required for a valid passbook var REQUIRED_TOP_LEVEL = [ "description", "organizationName", "passTypeIdentifier", "serialNumber", "teamIdentifier" ]; // Passbook structure keys. var STRUCTURE = [ "auxiliaryFields", "backFields", "headerFields", "primaryFields", "secondaryFields", "transitType" ]; // Supported images. var IMAGES = [ "background", "footer", "icon", "logo", "strip", "thumbnail" ]; // These images are required for a valid passbook. var REQUIRED_IMAGES = [ "icon", "logo" ]; // Create a new template. // // style - Passbook style (coupon, eventTicket, etc) // fields - Passbook fields (passTypeIdentifier, teamIdentifier, etc) function createTemplate(style, fields) { return new Template(style, fields); } // Create a new template. // // style - Passbook style (coupon, eventTicket, etc) // fields - Passbook fields (passTypeIdentifier, teamIdentifier, etc) function Template(style, fields) { if (!~STYLES.indexOf(style)) throw new Error("Unsupported passbook style " + style); this.style = style; this.fields = cloneObject(fields); this.keysPath = "keys"; } // Sets path to directory containing keys and password for accessing keys. // // path - Path to directory containing key files (default is 'keys') // password - Password to use with keys Template.prototype.keys = function(path, password) { if (path) this.keysPath = path; if (password) this.password = password; } // Create a new passbook from a template. Template.prototype.createPassbook = function(fields) { // Combine template and passbook fields var combined = {}; for (var key in this.fields) combined[key] = this.fields[key]; for (var key in fields) combined[key] = fields[key]; return new Passbook(this, combined); } // Accessor methods for template fields. // // Call with an argument to set field and return self, call with no argument to // get field value. // // template.passTypeIdentifier("com.example.mypass"); // console.log(template.passTypeIdentifier()); TEMPLATE.forEach(function(key) { Template.prototype[key] = function(value) { if (arguments.length == 0) { return this.fields[key]; } else { this.fields[key] = value; return this; } } }); // Create a new passbook. // // tempplate - The template // fields - Passbook fields (description, serialNumber, logoText) function Passbook(template, fields) { this.template = template; this.fields = cloneObject(fields); // Structure is basically reference to all the fields under a given style // key, e.g. if style is coupon then structure.primaryFields maps to // fields.coupon.primaryFields. var style = template.style; this.structure = this.fields[style]; if (!this.structure) this.structure = this.fields[style] = {}; this.images = {}; } // Accessor methods for top-level fields (description, serialNumber, logoText, // etc). // // Call with an argument to set field and return self, call with no argument to // get field value. // // passbook.description("Unbelievable discount"); // console.log(passbook.description()); TOP_LEVEL.forEach(function(key) { Passbook.prototype[key] = function(value) { if (arguments.length == 0) { return this.fields[key]; } else { this.fields[key] = value; return this; } } }); // Accessor methods for structure fields (primaryFields, backFields, etc). // // Call with an argument to set field and return self, call with no argument to // get field value. // // passbook.headerFields({ key: "time", value: "10:00AM" }); // console.log(passbook.headerFields()); STRUCTURE.forEach(function(key) { Passbook.prototype[key] = function(value) { if (arguments.length == 0) { return this.structure[key]; } else { this.structure[key] = value; return this; } } }); // Accessor methods for images (logo, strip, etc). // // Call with an argument to set the image and return self, call with no // argument to get image value. // // passbook.icon(function(callback) { ... }; // console.log(passbook.icon()); // // The 2x suffix is used for high resolution version (file name uses @2x // suffix). // // passbook.icon2x("icon@2x.png"); // console.log(passbook.icon2x()); IMAGES.forEach(function(key) { Passbook.prototype[key] = function(value) { if (arguments.length == 0) { return this.images[key]; } else { this.images[key] = value; return this; } } var double = key + "2x"; Passbook.prototype[double] = function(value) { if (arguments.length == 0) { return this.images[double]; } else { this.images[double] = value; return this; } } }); // Load all images from the specified directory. Only supported images are // loaded, nothing bad happens if directory contains other files. // // path - Directory containing images to load Passbook.prototype.loadImagesFrom = function(path) { var self = this; var files = File.readdirSync(path); files.forEach(function(filename) { var basename = Path.basename(filename, ".png"); if (/@2x$/.test(basename) && ~IMAGES.indexOf(basename.slice(0, -3))) { // High resolution self.images[basename.replace(/@2x/, "2x")] = Path.resolve(path, filename); } else if (~IMAGES.indexOf(basename)) { // Normal resolution self.images[basename] = Path.resolve(path, filename); } }); return this; } // Validate passbook, throws error if missing a mandatory top-level field or image. Passbook.prototype.validate = function() { for (var i in REQUIRED_TOP_LEVEL) { var key = REQUIRED_TOP_LEVEL[i]; if (!this.fields[key]) throw new Error("Missing field " + key); } for (var i in REQUIRED_IMAGES) { var key = REQUIRED_IMAGES[i]; if (!this.images[key]) throw new Error("Missing image " + key + ".png"); } } // Returns the pass.json object (not a string). Passbook.prototype.getPassbookJSON = function() { var fields = cloneObject(this.fields); fields.formatVersion = 1; return fields; } // Generate the passbook. // // Callback receives: // error - Something went wrong // buffer - Contents of Passbook (Buffer) Passbook.prototype.generate = function(callback) { var self = this; var zip = new Zip(); // Validate before attempting to create try { this.validate(); } catch (error) { callback(error); return; } // Create pass.json var passJson = new Buffer(JSON.stringify(this.getPassbookJSON()), "utf-8"); // Get image from key function getImage(key, done) { var image = self.images[key]; if (typeof image == "string" || image instanceof String) { // image is a filename, load from disk File.readFile(image, function(error, buffer) { if (!error) self.images[key] = buffer; done(error, buffer); }); } else if (image instanceof Buffer) { done(null, image); } else if (typeof image == "function") { // image is a function, call it to obtain image try { image(function(error, buffer) { if (!error) self.images[key] = buffer; done(error, buffer); }); } catch (error) { done(error); } } else if (image) { // image is not a supported type done(new Error("Cannot load image " + key + ", must be String (filename), Buffer or function")); } else done(); } // Add next pair of images from the list of keys function addNextImage(imageKeys, files, done) { var imageKey = imageKeys[0]; if (imageKey) { // Add normal resolution getImage(imageKey, function(error, buffer) { if (error) { done(error); } else { if (buffer) { files[imageKey + ".png"] = buffer; } // Add high resolution getImage(imageKey + "2x", function(error, buffer) { if (error) { done(error); } else { if (buffer) files[imageKey + "@2x.png"] = buffer; addNextImage(imageKeys.slice(1), files, done); } }); } }); } else done(); } // These are all the files that will show in the manifest var files = { "pass.json": passJson }; // Start adding all the images addNextImage(IMAGES, files, function(error) { if (error) { callback(error); } else { // Now that we have a map of all the images, add them to the zip Object.keys(files).forEach(function(filename) { zip.addFile(filename, files[filename]); }); // Calculate the manifest and add it as well var manifest = createManifest(files); zip.addFile("manifest.json", new Buffer(manifest, "utf-8")); // Sign the manifest and add the signature signManifest(self.template, manifest, function(error, signature) { if (error) { callback(error); } else { zip.addFile("signature", signature); // Create Zip file zip.generate(function(error, buffer) { callback(error, buffer); }); } }); } }); } // Creates a manifest from map of files. Returns as a string. function createManifest(files) { var manifest = {}; for (var filename in files) { var file = files[filename]; var sha = Crypto.createHash("sha1").update(file).digest("hex"); manifest[Path.basename(filename)] = sha; } return JSON.stringify(manifest); } // Signs a manifest and returns the signature. function signManifest(template, manifest, callback) { var identifier = template.passTypeIdentifier().replace(/^pass./, ""); var args = [ "smime", "-sign", "-binary", "-signer", Path.resolve(template.keysPath, identifier + ".pem"), "-certfile", Path.resolve(template.keysPath, "wwdr.pem"), ]; args.push("-passin", "pass:" + template.password) var sign = execFile("openssl", args, { stdio: "pipe" }, function(error, stdout, stderr) { if (error) { callback(new Error(stderr)); } else { var signature = stdout.split(/\n\n/)[3]; callback(null, new Buffer(signature, "base64")); } }); sign.stdin.write(manifest); sign.stdin.end(); } // Clone an object by copying all its properties and returning new object. // If the argument is missing or null, returns a new object. function cloneObject(object) { var clone = {}; if (object) { for (var key in object) clone[key] = object[key]; } return clone; } module.exports = createTemplate;
import React from "react"; import { act, render, fireEvent } from "@testing-library/react"; import { CastTableRow } from "../CastTableRow"; jest.mock("react-router-dom", () => ({ useHistory: () => ({ push: jest.fn(), }), })); describe("CastTableRow", () => { let props; beforeEach(() => { props = { actor: { name: "Foobar", character: "Chewbacca", id: 42, profile_path: "", }, }; }); it("should present a cast member", () => { const { container, getByText } = render(<CastTableRow {...props} />); getByText(/foobar/i); getByText(/chewbacca/i); fireEvent.click(container.querySelector("#Cast-42")); }); });
var express = require('express'); var router = express.Router(); //message array const message=[ { text:"Hi", user:"root", added:new Date() }, { text:"Heyy", user:"user", added:new Date() } ]; /* GET home page. */ //root path that will render the index file from the view router.get('/', function(req, res,next) { res.render('index', { title:'Mini-message-board' ,message:message }); //making the message available to template along with the title }); router.get('/new',function(req,res,next){ res.render('form'); }) //using the data from the form router.post('/new',function(req,res,next){ message.push({ text: req.body.messagetext, user: req.body.messageuser, added: new Date() }) res.redirect('/'); //send user back to the index page after submitting the form }) module.exports = router;
var logger = require('../utils/logger'); exports.handleStatusCallback = function(publisher) { return function(request, response) { logger.info('status callback: CallSid: ' + request.body.CallSid + ', From: ' + request.body.From + ', To: ' + request.body.To + ', Direction: ' + request.body.Direction + ', CallStatus: ' + request.body.CallStatus); var status = request.body.CallStatus; if (status && (status == 'completed' || status == 'busy' || status == 'failed' || status == 'no-answer' || status == 'canceled')) { logger.info('status callback: CallSid: ' + request.body.CallSid + ', CallStatus == "' + status + '" so publishing call ended event'); publisher.publishCallEnded( request.body.CallSid, request.body.From, request.body.To, request.body.Direction, request.body.CallStatus); } response.end(); } }; exports.handleHangUp = function() { return function(request, response) { var message = request.query["message"]; if (message == null || message.length == 0) { // default message message = 'The issue has been resolved or the broker has hung up. Good bye.' } response.render('twiml/hang-up', { message: message }); } };
import _ from 'lodash'; import { Strategy as LocalStrategy } from 'passport-local'; import { User, Status } from '../../model'; export default new LocalStrategy({ usernameField: 'email', passwordField: 'password', passReqToCallback: false, }, (email, password, done) => { new User({ email }).fetch().then((user) => { if (!user) return done(null, false); if (user.checkPassword(password)) { if (_.includes([Status.INACTIVE], user.get('status'))) { return done(null, false); } return done(null, user.toJSON()); } return done(null, false); }); });
const webpack = require('webpack') const MiniCssExtractPlugin = require('mini-css-extract-plugin') const { merge } = require('webpack-merge') const baseWebpackConfig = require('./webpack.base.conf') // DEV config const devWebpackConfig = merge(baseWebpackConfig, { mode: 'development', devtool: 'eval-cheap-source-map', stats: 'minimal', devServer: { static: { directory: baseWebpackConfig.externals.paths.dist }, port: 4000, client: { overlay: { warnings: true, errors: true } } }, module: { rules: [{ test: /\.s[ac]ss$/, use: [ // 'style-loader', { loader: MiniCssExtractPlugin.loader, options: { publicPath: '../' } }, { loader: 'css-loader', options: { sourceMap: true } }, { loader: 'sass-loader', options: { sourceMap: true } } ] }] }, plugins: [ new webpack.SourceMapDevToolPlugin({ filename: '[file].map' }) ] }) module.exports = new Promise((resolve, reject) => { resolve(devWebpackConfig) })
// src/components/Form.js import { useEffect, useState } from "react"; import Ingredient from "./Ingredient"; function Form() { var [list, setList] = useState(3); function submitForm(event) { event.preventDefault(); var ingredients = []; event.target["ingredients[]"].forEach(ingredient => ingredients.push(ingredient.value)); console.log({ name: event.target["name"].value, description: event.target["description"].value, ingredients }); } function enterMagic(event) { if (event.code === "Enter") { setList(list + 1); } } useEffect(function() { var lastInput = [...document.querySelectorAll("fieldset input")].pop(); lastInput?.focus(); }, [list]); return ( <form onSubmit={submitForm}> <div className="inputGroup"> <label htmlFor="name">Name</label> <input type="text" id="name" name="name" /> </div> <div className="inputGroup"> <label htmlFor="description">Description</label> <textarea id="description" name="description"></textarea> </div> <fieldset> <legend>Ingredients</legend> <div> <button type="button" onClick={() => setList(list + 1)}>+</button> <button type="button" onClick={() => setList(list > 0 ? list - 1 : 0)}>-</button> </div> {[...Array(list)].map((dims, i) => list === i + 1 ? <Ingredient key={i} onKeyUp={enterMagic}/> : <Ingredient key={i} />)} </fieldset> <button type="submit">Save recipe</button> </form> ); } export default Form;