text stringlengths 7 3.69M |
|---|
import React from "react";
// import Button from './Button';
export default class Counter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
onClickMinus(e) {
let currentCount = this.state.count;
this.setState({ ...this.state, count: --currentCount });
}
onClickPlus(e) {
let currentCount = this.state.count;
this.setState({ ...this.state, count: ++currentCount });
}
render() {
return (
<div className="counter">
<button onClick={this.onClickMinus.bind(this)}>Minus</button>
<div className="count">
<p>Current count:</p>
<section className={`displayNumber`}>{this.state.count}</section>
</div>
<button onClick={this.onClickPlus.bind(this)}>Plus</button>
</div>
);
}
}
|
const { create } = require('./create');
const { subscribe } = require('./subscribe');
const TOPICS = [
'info.address',
'info.phone-number',
];
create(TOPICS);
subscribe(TOPICS);
|
var CallidForm;
var pageSize = 25;
var p_id = document.getElementById('p_id').value;
var user_id = document.getElementById('u_id').value;
var boolPassword = true;//secretcopy
var info_type = "users";
var secret_info = "user_email;user_id";
//商品主料位管理Model
Ext.define('gigade.PaperAnswer', {
extend: 'Ext.data.Model',
fields: [
{ name: "answerID", type: "string" },
{ name: "paperID", type: "string" },
{ name: "paperName", type: "string" },
{ name: "userid", type: "string" },
{ name: "userMail", type: "string" },
{ name: "order_id", type: "string" },
{ name: "classID", type: "string" },
{ name: "className", type: "string" },
{ name: "answerContent", type: "string" },
{ name: "classContent", type: "string" },
{ name: "classType", type: "string" },
{ name: "answerDate", type: "string" }
]
});
var PaperAnswerStore = Ext.create('Ext.data.Store', {
autoDestroy: true,
pageSize: pageSize,
model: 'gigade.PaperAnswer',
proxy: {
type: 'ajax',
url: '/Paper/GetPaperAnswerList',
reader: {
type: 'json',
root: 'data',
totalProperty: 'totalCount'
}
}
// autoLoad: true
});
var sm = Ext.create('Ext.selection.CheckboxModel', {
listeners: {
selectionchange: function (sm, selections) {
Ext.getCmp("gdPaperAnswer").down('#edit').setDisabled(selections.length == 0);
}
}
});
Ext.define('gigade.Paper', {
extend: 'Ext.data.Model',
fields: [
{ name: "paperID", type: "int" },
{ name: "paperName", type: "string" }]
});
var PaperStore = Ext.create('Ext.data.Store', {
autoDestroy: true,
//pageSize: pageSize,
model: 'gigade.Paper',
//autoLoad: true,
proxy: {
type: 'ajax',
url: '/Paper/GetPaperList?isPage=false',
actionMethods: 'post',
reader: {
type: 'json',
root: 'data'
//totalProperty: 'totalCount'
}
}
// autoLoad: true
});
PaperAnswerStore.on('beforeload', function () {
Ext.apply(PaperAnswerStore.proxy.extraParams, {
paper_id: Ext.getCmp('paper').getValue(),
//paper_id:p_id,
user_id: user_id
});
});
Ext.onReady(function () {
var gdPaperAnswer = Ext.create('Ext.grid.Panel', {
id: 'gdPaperAnswer',
title: '問卷內容',
store: PaperAnswerStore,
width: document.documentElement.clientWidth,
columnLines: true,
frame: true,
columns: [
{ header: "流水號", dataIndex: 'answerID', width: 80, align: 'center' },
//{ header: "問卷編號", dataIndex: 'paperID', width: 80, align: 'center' },
{ header: "問卷名稱", dataIndex: 'paperName', width: 150, align: 'center' },
{ header: "用戶編號", dataIndex: 'userid', width: 80, align: 'center' },
{
header: "用戶郵箱", dataIndex: 'userMail', width: 150, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {//secretcopy
return "<span onclick='SecretLogin(" + record.data.answerID + ")' >" + value + "</span>";
}
},
//{ header: "題目編號", dataIndex: 'classID', width: 80, align: 'center' },
{ header: "訂單編號", dataIndex: 'order_id', width: 80, align: 'center' },
{ header: "題目名稱", dataIndex: 'className', width: 150, align: 'center' },
{
header: "答案", dataIndex: '', width: 200, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
switch (record.data.classType) {
case "SC":
case "MC":
return record.data.classContent;
case "SL":
case "ML":
return record.data.answerContent;
}
}
},
{
header: "題目類型", dataIndex: 'classType', width: 80, align: 'center',
renderer: function (value, cellmeta, record, rowIndex, columnIndex, store) {
switch (value) {
case "SC":
return "單選";
case "MC":
return "多選";
case "SL":
return "單行";
case "ML":
return "多行";
}
}
},
{ header: "作答時間", dataIndex: 'answerDate', width: 150, align: 'center' }
],
tbar: [
{
xtype: 'button', text: '匯出', id: 'outexcel', hidden: false, iconCls: 'icon-excel', handler: function () {
var paper_id = Ext.getCmp('paper').getValue();
window.open('/Paper/OutExcel?paper_id=' + paper_id + '&user_id=' + user_id);
}
},
'->',
{
xtype: 'combobox', editable: false, fieldLabel: "問卷名稱", labelWidth: 60, id: 'paper', store: PaperStore, queryMode: 'remote', lastQuery: '', displayField: 'paperName', valueField: 'paperID'
},
//{ xtype: 'combobox', editable: false, fieldLabel: "題目", labelWidth: 55, id: 'title', store: PaperStore, displayField: 'paperName', valueField: 'paperID', value: 0 },
{
text: SEARCH,
iconCls: 'icon-search',
id: 'btnQuery',
handler: Query
}
],
bbar: Ext.create('Ext.PagingToolbar', {
store: PaperAnswerStore,
pageSize: pageSize,
displayInfo: true,
displayMsg: NOW_DISPLAY_RECORD + ': {0} - {1}' + TOTAL + ': {2}',
emptyMsg: NOTHING_DISPLAY
}),
listeners: {
scrollershow: function (scroller) {
if (scroller && scroller.scrollEl) {
scroller.clearManagedListeners();
scroller.mon(scroller.scrollEl, 'scroll', scroller.onElScroll, scroller);
}
}
}
});
Ext.create('Ext.container.Viewport', {
layout: 'fit',
items: [gdPaperAnswer],
renderTo: Ext.getBody(),
autoScroll: true,
listeners: {
resize: function () {
gdPaperAnswer.width = document.documentElement.clientWidth;
this.doLayout();
}
}
});
ToolAuthority();
PaperStore.load({
callback: function () {
PaperStore.insert(0, { paperID: '0', paperName: '請選擇' });
if (p_id != '') {
Ext.getCmp('paper').setValue(p_id);
}
else {
Ext.getCmp("paper").setValue(0);
}
//PaperAnswerStore.load({ params: { start: 0, limit: 25, paper_id: Ext.getCmp('paper').getValue(), user_id: user_id } });
}
});
//var p = Ext.getCmp('paper').getValue();
});
function SecretLogin(rid) {//secretcopy
var secret_type = "10";//參數表中的"試用試吃活動"
var url = "/Paper/PaperAnswerList";
var ralated_id = rid;
//點擊機敏信息先保存記錄在驗證密碼是否需要輸入
boolPassword = SaveSecretLog(url, secret_type, ralated_id);//判斷5分鐘之內是否有輸入密碼
if (boolPassword != "-1") {//不准查看
if (boolPassword) {//超過5分鐘沒有輸入密碼
//參數1:機敏頁面代碼,2:機敏資料主鍵,3:是否彈出驗證密碼框,4:是否直接顯示機敏信息6.驗證通過后是否打開編輯窗口 7:客戶信息類型user:會員 order:訂單 vendor:供應商 8:客戶id9:要顯示的客戶信息
// function SecretLoginFun(type, relatedID, isLogin, isShow, editO, isEdit) {
SecretLoginFun(secret_type, ralated_id, true, true, false, url, null, null, null);//先彈出驗證框,關閉時在彈出顯示框
} else {
SecretLoginFun(secret_type, ralated_id, false, true, false, url, null, null, null);//先彈出驗證框,關閉時在彈出顯示框
}
}
}
/*************************************************************************************查詢*************************************************************************************************/
function Query(x) {
if (Ext.getCmp('paper').getValue() != '0') {
PaperAnswerStore.removeAll();
Ext.getCmp("gdPaperAnswer").store.loadPage(1, {
params: {
paper_id: Ext.getCmp('paper').getValue(),
user_id: user_id
}
});
}
else {
Ext.Msg.alert(INFORMATION,"請選擇搜索條件!");
}
}
/*************************************************************************************新增*************************************************************************************************/
onAddClick = function () {
//addWin.show();
editPaperFunction(null, PaperAnswerStore);
}
/*************************************************************************************編輯*************************************************************************************************/
onEditClick = function () {
var row = Ext.getCmp("gdPaperAnswer").getSelectionModel().getSelection();
//alert(row[0]);
if (row.length == 0) {
Ext.Msg.alert(INFORMATION, NO_SELECTION);
} else if (row.length > 1) {
Ext.Msg.alert(INFORMATION, ONE_SELECTION);
} else if (row.length == 1) {
editPaperFunction(row[0], PaperAnswerStore);
}
}
|
public var startPosition : float;
public var destinationPosition : float;
public var targetPosition : float;
public var xAxisMovement : boolean = true;
public var moveSpeed : float = 3.0;
private var waitingAtDestinationPosition : boolean = false;
private var pauseTimer : float = 0.0;
public var pauseDuration : float = 4.0;
private var act : boolean = false;
function Activate(){
if(Network.isServer)
networkView.RPC("RPCActivateInternal", RPCMode.AllBuffered);
}
@RPC
function RPCActivateInternal(){
targetPosition = destinationPosition;
act = true;
}
function Update () {
if(waitingAtDestinationPosition){
pauseTimer += Time.deltaTime;
if(pauseTimer >= pauseDuration){
waitingAtDestinationPosition = false;
pauseTimer = 0.0;
act = true;
}
} else if (act) {
if(xAxisMovement){
if(!Mathf.Approximately(transform.position.x, targetPosition)) {
transform.position.x = Mathf.MoveTowards(transform.position.x, targetPosition, moveSpeed * Time.deltaTime);
} else {
if(targetPosition == destinationPosition){
waitingAtDestinationPosition = true;
targetPosition = startPosition;
act = false;
}
}
} else { // zAxisMovement
if(!Mathf.Approximately(transform.position.z, targetPosition)) {
transform.position.z = Mathf.MoveTowards(transform.position.z, targetPosition, moveSpeed * Time.deltaTime);
} else {
if(targetPosition == destinationPosition){
waitingAtDestinationPosition = true;
targetPosition = startPosition;
act = false;
}
}
}
}
} |
module.exports = {
db: 'knex', // knex / mongodb
name: 'person', // table name
cols: {
firstName: {
label: 'First Name',
multiKey: true,
type: 'string', // Number (Integer, Decimal), Boolean, Date (datetime, date, time)
formEditor: '',
// '=,!=,like,>=,<=,>,<' - compare operator
// AND, OR - boolean operator
},
lastName: {
label: 'Last Name',
multiKey: true,
type: 'string', // Number (Integer, Decimal), Boolean, Date (datetime, date, time)
formEditor: '',
},
country: {
label: 'Country', // key value...
type: 'autocomplete', // single select
options: {
tableName: 'country',
limit:8,
key: 'name'
}
},
sex: {
label: 'Sex',
type: 'select',
options: [
{ key: '', txt: '' },
{ key: 'M', txt: 'Male' },
{ key: 'F', txt: 'Female' }
]
},
weightKg: {
label: 'Weight kg',
type: 'decimal',
required: true
},
heightCm: {
label: 'Height cm',
type: 'integer',
required: true
},
dateOfBirth: {
label: 'Date Of Birth',
type: 'date'
},
timeOfBirth: {
label: 'Time Of Birth',
type: 'time'
},
testDateTime: {
label: 'Test Date Time',
type: 'datetime'
},
updated_by: { label: 'Updated By', auto: 'user' },
updated_at: { label: 'Updated At', auto: 'ts' }
},
// generated values
pk: '', // either pk or multikey
multiKey: [],
required: [],
auto: [],
nonAuto: []
// {id: 1, name: 'book1', categoryId: 1, rating: 5, yearPublished: '2004', created_at: mkDt() },
} |
const BN = require('bn.js')
const { AionLong } = require('aion-rlp')
function prefix_remove(hex){
if (typeof hex === 'string' && hex.indexOf('0x') >= 0) {
if(hex.length == 2)
return ''
else
return hex.substr(2, hex.length -1)
}
return hex
}
function prefix_prepend(hex) {
if (hex.indexOf('0x') < 0)
hex = '0x' + hex
return hex
}
function to_buffer(val) {
if (val === undefined || val === null) {
return Buffer.from([])
}
// buffer or array
if (Array.isArray(val) === true || Buffer.isBuffer(val) === true) {
return Buffer.from(val)
}
// number
// if (isNumber(val) === true || BN.isBN(val) === true) {
if (BN.isBN(val) === true) {
return Buffer.from(new BN(val, 10).toArray())
}
// string
if (typeof val === 'string') {
return Buffer.from(prefix_remove(val), 'hex')
}
// anything else
return Buffer.from(val, 'hex')
}
function buffer_to_uint8_array(buf){
let ab = new ArrayBuffer(buf.length);
let view = new Uint8Array(ab);
for (let i = 0, m = buf.length; i < m; ++i) {
view[i] = buf[i];
}
return ab;
}
const MAX_LONG = new BN('9223372036854775807')
function to_long(val) {
let num
if (
val === undefined ||
val === null ||
val === '' ||
val === '0x'
) {
return null
}
if (typeof val === 'string') {
if (
val.indexOf('0x') === 0 ||
val.indexOf('0') === 0 ||
isHex(val) === true ||
isHexStrict(val) === true
) {
num = new BN(removeLeadingZeroX(val), 16)
} else {
num = new BN(val, 10)
}
}
if (typeof val === 'number') {
num = new BN(val)
}
return new AionLong(num)
}
module.exports = {
prefix_remove,
prefix_prepend,
to_buffer,
to_long
} |
//https://github.com/mosharof85/assignment-3
/*
PROBLEM 01
*/
function kilometerToMiter(kilometer) {
if(kilometer < 0){
return "Invalid value";
}
var meter = kilometer * 1000;
return meter;
}
/*
PROBLEM 02
*/
function budgetCalculator(nosOfWatch, nosOfMobile, nosOfLatop){
var priceOfWatch = 50;
var priceofMobile = 100;
var priceOfLaptop = 500;
var total = 0;
if(nosOfWatch > 0){
total = total + (priceOfWatch * nosOfWatch);
}
if(nosOfMobile > 0){
total = total + (priceofMobile * nosOfMobile);
}
if(nosOfLatop > 0){
total = total + (priceOfLaptop * nosOfLatop);
}
return total;
}
/*
PROBLEM 03
*/
function hotelCost(nosOfDays) {
var hotelExpense = 0;
if(nosOfDays <0){
return "Invalid Value";
}
else
{
//Calculation of first phase
if(nosOfDays <= 10){
hotelExpense = nosOfDays * 100;
}
//Calculation of second phase
else if (nosOfDays <= 20){
var expenseOfFirstTenDays = 10 * 100;
var nosOfRemainingDays = nosOfDays - 10;
var expenseOfSecondTenDays = nosOfRemainingDays * 80;
hotelExprese = expenseOfFirstTenDays + expenseOfSecondTenDays;
}
//Calculation of third phase
else{
var expenseOfFirstTenDays = 10 * 100;
var expenseOfSecondTenDays = 10 * 80;
var nosOfRemainingDays = nosOfDays - 20;
var expenseOfRemainingDays = nosOfRemainingDays * 50;
hotelExpense = expenseOfFirstTenDays + expenseOfSecondTenDays + expenseOfRemainingDays;
}
return hotelExpense;
}
}
/*
PROBLEM 04
*/
function megaFriend(friends){
var maxLength = 0;
for (var i=0; i < friends.length; i++){
var currentNameLength = friends[i].length;
if(currentNameLength > maxLength){
maxLength = currentNameLength;
}
}
return maxLength;
}
|
import {FETCH_PRODUCTS, FILTER_PRODUCTS_BY_SIZE, ORDER_PRODUCTS_BY_PRICE, ADD_TO_CART, REMOVE_FROM_CART} from "../types";
import Data from '../data.json';
export const fetchProducts = () => async(dispatch) => {
const res = Data;
dispatch({
type: FETCH_PRODUCTS,
payload: res.products
});
}
export const filterProducts = (products, size) => (dispatch) => {
dispatch({
type: FILTER_PRODUCTS_BY_SIZE,
payload: {
size: size,
items:
size === ""
? products
: products.filter((x) => x.availableSizes.indexOf(size) >= 0),
},
});
};
export const sortProducts = (filteredProducts, sort) => (dispatch) => {
let order = sort;
let sortedData;
if (order == "Lowest") {
sortedData = filteredProducts.sort(function (a, b) {
return a.price - b.price
});
} else {
sortedData = filteredProducts.sort(function (a, b) {
return b.price - a.price
});
}
console.log(sortedData);
dispatch({
type: ORDER_PRODUCTS_BY_PRICE,
payload: {
sort: sort,
items: sortedData.slice(0,6),
},
});
};
export const getAddtoCardId = (allItems, cartData, id) => async(dispatch)=> {
let result;
if (typeof(cartData) != "undefined" && cartData !== null && cartData.filter(data => data._id == id).length) {
let selectedItem = cartData.filter(data => data._id == id)
selectedItem[0].count++;
result = [...cartData.filter(item => item._id !== id), ...selectedItem]
} else {
let particularData = allItems.filter(data => data._id == id)
let selectedItem = {
_id: particularData[0]._id,
title: particularData[0].title,
image: particularData[0].image,
price: particularData[0].price,
count: '1'
}
if(typeof(cartData) == "undefined" || cartData == null)
cartData = [];
result = cartData.concat(selectedItem);
}
localStorage.setItem('cartData', JSON.stringify(result));
dispatch({
type: ADD_TO_CART,
payload: {
items: result
},
});
}
export const removeFromCart = (cartData, id) => async(dispatch) => {
if(typeof(cartData)!= 'undefined' && cartData !== null && cartData.length!=0)
cartData = [...cartData.filter(data => data._id != id)]
localStorage.setItem('cartData', JSON.stringify(cartData));
dispatch({
type: REMOVE_FROM_CART,
payload: {
items: cartData
},
});
} |
function messageRecieved(){
console.log("test")
$("#submitButton").fadeOut();
var para = $("<p>Your message has been received!</p>");
$("#submitDiv").append(para);
return false;
} |
import { Utils } from '../../../helpers/Utils';
export class ImageStorage {
constructor() {
this.collection = [];
this.randomNum = Utils.getRandomNum(10);
}
loadImages() {
const rawCollection = this.collection;
this.removeCollection();
rawCollection.forEach(link => {
const loader = new Promise(resolve => {
const img = new Image();
img.src = link;
img.addEventListener('load', () => {
resolve(img);
});
});
loader
.then(img => {
this.collection.push(img.src);
})
.catch(err => console.log(err));
});
}
getRandomImage() {
this.randomNum = Utils.getRandomNum(this.collection.length - 1);
return this.collection[this.randomNum];
}
getImage() {
return this.collection[this.randomNum];
}
getNextImg() {
this.randomNum++;
if (this.randomNum > this.collection.length - 1) {
this.randomNum = 0;
}
return this.getImage();
}
getPrevImg() {
this.randomNum--;
if (this.randomNum < 0) {
this.randomNum = this.collection.length - 1;
}
return this.getImage();
}
removeCollection() {
this.collection = [];
}
}
|
import React from 'react'
import PropTypes from 'prop-types';
import { Link } from 'react-router'
import './RequestForm.css'
const RequestForm = ({
onSubmit,
onChange,
errors,
user
}) => (
<div className="container">
<div className="request-panel">
<form className="col s12" action="/" onSubmit={onSubmit}>
<h4 className="center-align">House Search Request Form</h4>
{errors.summary && <div className="row"><p className="error-message">{errors.summary}</p></div>}
<div className="row">
<div className="input-field col s6">
<input className="validate" id="city" type="text" name="city" required="" aria-required="true" onChange={onChange}/>
<label htmlFor="city">City</label>
</div>
<div className="input-field col s6">
<input className="validate" id="areas" type="text" name="areas" required="" aria-required="true" onChange={onChange}/>
<label htmlFor="areas">Areas</label>
</div>
</div>
{errors.city && <div className="row"><p className="error-message">{errors.city}</p></div>}
{errors.areas && <div className="row"><p className="error-message">{errors.areas}</p></div>}
<div className="row">
<div className="input-field col s6">
<input className="validate" id="min_bedroom" name="min_bedroom" type="number" required="" aria-required="true" min="0" step="1" onChange={onChange}/>
<label htmlFor="min_bedroom">Min Bedroom</label>
</div>
<div className="input-field col s6">
<input className="validate" id="max_bedroom" name="max_bedroom" required="" aria-required="true" type="number" min="0" step="1" onChange={onChange}/>
<label htmlFor="max_bedroom">Max Bedroom</label>
</div>
</div>
{errors.min_bedroom && <div className="row"><p className="error-message">{errors.min_bedroom}</p></div>}
{errors.max_bedroom && <div className="row"><p className="error-message">{errors.max_bedroom}</p></div>}
<div className="row">
<div className="input-field col s6">
<input className="validate" id="min_price" type="number" required="" aria-required="true" name="min_price" min="0" step="1" onChange={onChange}/>
<label htmlFor="min_price">Min Price</label>
</div>
<div className="input-field col s6">
<input className="validate" id="max_price" type="number" required="" aria-required="true" name="max_price" min="0" step="1" onChange={onChange}/>
<label htmlFor="max_price">Max Price</label>
</div>
</div>
{errors.min_price && <div className="row"><p className="error-message">{errors.min_price}</p></div>}
{errors.max_price && <div className="row"><p className="error-message">{errors.max_price}</p></div>}
<div className="row">
<div className="input-field col s6">
<input className="validate" id="hour" type="number" name="time_to_work_hour" min="0" step="1" onChange={onChange}/>
<label htmlFor="hour">Time to Work(Hour)</label>
</div>
<div className="input-field col s6">
<input className="validate" id="minute" type="number" min="0" name="time_to_work_minute" step="1" max="59" onChange={onChange}/>
<label htmlFor="minute">Time to Work(Minute)</label>
</div>
</div>
{errors.time_to_work_hour && <div className="row"><p className="error-message">{errors.time_to_work_hour}</p></div>}
{errors.time_to_work_minute && <div className="row"><p className="error-message">{errors.time_to_work_minute}</p></div>}
<div className="row">
<div className="input-field col s6">
<input className="validate" id="hour" type="number" name="departure_to_work_hour" min="0" step="1" max="23" onChange={onChange}/>
<label htmlFor="hour">Departure to Work(Hour)</label>
</div>
<div className="input-field col s6">
<input className="validate" id="minute" type="number" min="0" name="departure_to_work_minute" step="1" max="59" onChange={onChange}/>
<label htmlFor="minute">Departure to Work(Minute)</label>
</div>
</div>
{errors.departure_to_work_hour && <div className="row"><p className="error-message">{errors.departure_to_work_hour}</p></div>}
{errors.departure_to_work_minute && <div className="row"><p className="error-message">{errors.departure_to_work_minute}</p></div>}
<div className="row">
<div className="input-field col s12">
<input className="validate" id="delta_minute" type="number" name="delta_minute" min="0" step="1" onChange={onChange}/>
<label htmlFor="delta_minute">Time to Work Delta(Minute)</label>
</div>
</div>
{errors.delta_minute && <div className="row"><p className="error-message">{errors.delta_minute}</p></div>}
<div className="row">
<div className="input-field col s12">
<input className="validate" id="work_addr" type="text" required="" aria-required="true" name="work_addr" onChange={onChange}/>
<label htmlFor="work_addr">Work Place Address</label>
</div>
</div>
{errors.work_addr && <div className="row"><p className="error-message">{errors.work_addr}</p></div>}
<div className="row">
<label htmlFor="travel_mode">Travel Mode</label>
<p>
<input className="with-gap" name="travel_mode" value="transit" type="radio" id="transit" required onChange={onChange} />
<label htmlFor="transit">Transit</label>
</p>
<p>
<input className="with-gap" required name="travel_mode" type="radio" value="driving" id="driving" onChange={onChange} />
<label htmlFor="driving">Driving</label>
</p>
<p>
<input className="with-gap" required name="travel_mode" type="radio" value="walking" id="walking" onChange={onChange}/>
<label htmlFor="walking">Walking</label>
</p>
<p>
<input className="with-gap" required name="travel_mode" type="radio" id="bicycling" value="bicycling" onChange={onChange} />
<label htmlFor="bicycling">Bicycling</label>
</p>
</div>
<div className="row">
<label>Private Bathroom</label>
<p>
<input className="with-gap" value="true" required name="private_bath" type="radio" id="private_bath_yes" onChange={onChange} />
<label htmlFor="private_bath_yes">Yes</label>
</p>
<p>
<input className="with-gap" value="false" required name="private_bath" type="radio" id="private_bath_no" onChange={onChange} />
<label htmlFor="private_bath_no">No</label>
</p>
</div>
<div className="row right-align">
<input type="submit" className="waves-effect waves-light btn indigo lighten-1" value='Submit'/>
</div>
</form>
</div>
</div>
)
RequestForm.propTypes = {
onSubmit: PropTypes.func.isRequired,
onChange: PropTypes.func.isRequired,
errors: PropTypes.object.isRequired,
request_form: PropTypes.object.isRequired
}
export default RequestForm
|
window.onload=function(){
isHavePhone();
isUserName();
$("#personGo").click(function(){
var userName= $("#username").val();
var siteId = $("#siteId").val();
window.location.href= ctx+"/weChatPublicNum/goToPerson?userName="+userName+"&siteId="+siteId;
});
$("#message").click(function(){
window.location.href=ctx+"/ProtalUserManage/goToMessagePage";
});
var mess = $("#mess").val();
if(mess==0){
$("#message").removeClass("on");
}else{
$("#message").addClass("on");
}
}
//判断是否有图片
function isHavePhone(){
var imgSrc = $('#phoneurl').val();
var weiSrc = $("#weixinurl").val();
if(imgSrc){
$('.photo').css('background','#fff url(http://oss.kdfwifi.net/user_pic/'+imgSrc+') no-repeat center');
$('.photo').css('background-size','cover');
}else{
$('.photo').css('background','#fff url('+weiSrc+') no-repeat center');
$('.photo').css('background-size','cover');
}
}
//用户名切成232***223的格式
function isUserName(){
var username = $("#username").val();
var name = username.substring(0,3);
var end = username.substring(7,username.length);
var allname = name+"****"+end;
$('.phone').html(allname);
}
function msg(code,str){
console.log(1)
$('.altMask > div').removeClass('true');
$('.altMask > div').removeClass('false');
$('.altMask').css('display','block');
$('.msg').text(str);
if(code==0){
$('.altMask > div').addClass('false');
$('.altMask > div').animate({top:'25%'},400);
setTimeout(function(){
$('.altMask > div').animate({top:'-160px'},200,function(){
$('.altMask').css('display','none');
});
},2900);
}else{
$('.altMask > div').addClass('true');
$('.altMask > div').animate({top:'25%'},400,function(){
setTimeout(function(){
$('.altMask > div').animate({top:'-160px'},400,function(){
$('.altMask').css('display','none');
});
},2900);
});
}
} |
import React from 'react'
import $$ from 'jquery'
import './commonvalidation.scss'
import validForm from './validationrules'
import util from './../../common/common'
class InputText extends React.Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {
pageLabel: "",
message: ""
}
}
handleChange(e) {
var setErroNode = function (event, _this, message) {
let errorMsg = message
if (!$$(event.target).parents(_this.props.errorplacement).next('p.invalid').length) {
$$(event.target).parents(_this.props.errorplacement).after('<p class="invalid">' + errorMsg + '</p>')
if (_this.props.errorBorderPlacement) {
$$(event.target).parents(_this.props.errorBorderPlacement).addClass('invalid-bdr')
} else {
$$(event.target).parents(_this.props.errorplacement).addClass('invalid-bdr')
}
} else {
$$(event.target).parents(_this.props.errorplacement).next('p.invalid').remove()
if (_this.props.errorBorderPlacement) {
$$(event.target).parents(_this.props.errorBorderPlacement).removeClass('invalid-bdr')
} else {
$$(event.target).parents(_this.props.errorplacement).removeClass('invalid-bdr')
}
$$(event.target).parents(_this.props.errorplacement).after('<p class="invalid">' + errorMsg + '</p>')
if (_this.props.errorBorderPlacement) {
$$(event.target).parents(_this.props.errorBorderPlacement).addClass('invalid-bdr')
} else {
$$(event.target).parents(_this.props.errorplacement).addClass('invalid-bdr')
}
}
_this.props.callback(e.target.value)
}
var removeErrorNode = function (event, _this) {
$$(e.target).parents(_this.props.errorplacement).next('p.invalid').remove()
if (_this.props.errorBorderPlacement) {
$$(event.target).parents(_this.props.errorBorderPlacement).removeClass('invalid-bdr')
} else {
$$(event.target).parents(_this.props.errorplacement).removeClass('invalid-bdr')
}
_this.props.callback(e.target.value)
}
let st = {}
switch (this.props.name) {
case 'ssn':
st = validForm.ssn(e.target.value)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
case 'multiplepayment':
if (!validForm.multiplepayment(e.target.value, this.props.months, this.props.offertype)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_50'))
} else {
removeErrorNode(e, this)
}
break;
case 'card':
if (!validForm.card(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_51'))
} else {
removeErrorNode(e, this)
}
break;
case 'bespoke':
st = validForm.bespoke(e.target.value, this.props.gfamount, this.props.minimum)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
case 'phone':
st = validForm.phone(e.target.value, e.target.id)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
case 'homephone':
st = validForm.homephone(e.target.value, e.target.id)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
case 'cellphone':
st = validForm.cellphone(e.target.value, e.target.id)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
case 'workphone':
st = validForm.workphone(e.target.value, e.target.id)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
case 'address1':
case 'address2':
st = validForm.billAddress(e.target.value, e.target.id)
if (!st) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_85'))
} else {
removeErrorNode(e, this)
}
break;
case 'city':
st = validForm.billCity(e.target.value, e.target.id)
if (!st) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_86'))
} else {
removeErrorNode(e, this)
}
break;
case 'postalCode':
st = validForm.billZip(e.target.value, e.target.id)
if (!st) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_87'))
} else {
removeErrorNode(e, this)
}
break;
case 'username':
case 'email':
if (this.props.name === 'username' || this.props.name.indexOf('email') === 0) {
if (!validForm.email(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_53'))
} else {
removeErrorNode(e, this)
}
}
break;
case 'mcmno':
st = validForm.mcmAccountNumber(e.target.value)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
case 'cardName':
if (!validForm.cardName(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_55'))
} else {
removeErrorNode(e, this)
}
case 'cardLastName':
if (!validForm.cardLastName(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_55'))
} else {
removeErrorNode(e, this)
}
break;
case 'cvv':
if (!validForm.cvv(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_56'))
} else {
removeErrorNode(e, this)
}
break;
case 'expiryDate':
if (!validForm.expiryDate(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_57'))
} else {
removeErrorNode(e, this)
}
break;
case 'rNumber':
if (!validForm.rNumber(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_58'))
} else {
removeErrorNode(e, this)
}
break;
case 'accNumber':
st = validForm.mcmAccountNumber(e.target.value)
if (!st.status) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_59'))
} else {
removeErrorNode(e, this)
}
break;
case 'billAddress':
if (!validForm.billAddress(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_60'))
} else {
removeErrorNode(e, this)
}
break;
case 'billCity':
if (!validForm.billCity(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_61'))
} else {
removeErrorNode(e, this)
}
break;
case 'billZip':
if (!validForm.billZip(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_62'))
} else {
removeErrorNode(e, this)
}
break;
case 'lastname':
if (!validForm.lastName(e.target.value)) {
setErroNode(e, this, util.getErrorString('lbl_validation_msg_63'))
} else {
removeErrorNode(e, this)
}
break;
case 'dobmonth':
st = validForm.month(e.target.value)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
case 'dobyear':
st = validForm.year(e.target.value)
if (!st.status) {
setErroNode(e, this, st.msg)
} else {
removeErrorNode(e, this)
}
break;
}
}
render() {
return (
<input type="text" name={this.props.name} id={this.props.id} className={this.props.className} value={this.props.value} placeholder={this.props.placeholder} onChange={this.handleChange} />
)
}
}
export default InputText
|
export const rootPath = 'http://localhost:3004'; |
import styled from "styled-components";
import HeaderLogo from '../../images/header/header.png'
import Bg from '../../images/header/vector.png'
export const Body = styled.div`
width: 100%;
height: 964px;
background-image: url(${Bg});
background-position: bottom;
background-size: cover;
`
export const Headers = styled.div`
width: 1152px;
height: 900px;
background-image: url(${HeaderLogo});
background-size: cover;
background-position: center;
margin: 55px auto;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding-left: 217px;
padding-right: 217px;
`
export const Title = styled.div`
font-size: 64px;
line-height: 68px;
text-align: center;
color: #090B37;
`
export const Desc = styled.div`
font-size: 22px;
line-height: 32px;
text-align: center;
color: #3C2B84;
margin: 28px 0 34px;
`
export const InputBox = styled.div`
height: 80px;
width: 640px;
background: #FFFFFF;
border: 2px solid #090B37;
box-sizing: border-box;
box-shadow: 1px 1px 0px #090B37;
border-radius: 200px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 27px 8px 27px 38px;
`
export const Input = styled.input`
font-size: 17px;
line-height: 26px;
text-decoration-line: underline;
color: #A0A0A0;
border: none;
outline: none;
width: 100%;
padding: 0 5px;
`
export const ArrowBox = styled.div`
width: 120px;
height: 64px;
background: #090B37;
border-radius: 50px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
transition: all 0.3s linear;
:active{
transform: scale(0.8);
}
svg{
width: 24px;
color: #fff;
}
`
export const Commit = styled.div`
width: 608px;
display: flex;
padding-left: 15px;
p{
font-size: 17px;
line-height: 26px;
color: #3C2B84;
padding: 23px 0 0 15px;
}
` |
import React from "react"
export class FooterComponent extends React.Component{
render(){
return(
<>
<div>
<br/>
<h3>Hubungi kami</h3>
0812 xxxx xxxx (A.N. Gunadi) <br/>0821 xxxx xxxx (A.N. Heri)
</div><br/>
<div style={{borderTop:"solid 1px black"}}>
<br/>
Mandiri Kitchen 2020 all rights reserved
</div><br/>
</>
)
}
} |
///////////------------------------------------------------------- THA Day 7 Installing Community Packages From npm ------------------------------------------------//////////
______________________________________________________________________________________________________________________________________________________________________________
=>First create .json for dependencies for the app
=>So we first create app and list dependencies for nodejs app
>npm init
=>for versioning : 1.0.0 (major.minor.bug fixes)
Now,
>npm install --save express
>for seeing live changes while exec like live server in react, in nodejs we have nodemon.
>npm install save-dev nodemon (for dev env not prod env)
we are doing server programming with data send with http methods. browser sends requests. We need to process it and give responses to client .
keep in mind : Security , Performance, Edge cases (backend me me bottom to top approch hoti h)
////------------------ code index.js --------------------------////
const express = require('express'); //express ek function defination (export = e;) ko pass karta h
const app = express(); // usko hame const app = express(); se call karna padta h
we now // CRUD -> Create => POST | Read => GET | Update => PUT | Delete => DELETE
app.get('/',(req, res) => {
res.send("Hello");
});
OR
const slash = (req,res)=> {
res.send("hello");
}
************* For GET Methods *************
app.get('/',slash);
app.get('/url',slash);
app.listen(5000);
*************other methods***************
For sending requests use POSTMAN software or Browser
app.post('/',slash);
app.put('/',slash);
app.delete('/',slash);
To run:
go to chrome :localhost:5000/
OR
Postman : localhost:5000/
****************sending other respsone things*********
app.get('/',(req,res)=>{
res.send({a:"name"}); //sending objs
res.send(a = []); //sending array
});
****************HTTP response status codes***********
200 OK (The request has succeeded)
201 Update(created)
400 Client Error (Bad Request)
500 Server Error (Internal Server Error)
**************** sending json************
app.get('/',(req,res)=>{
res.sendStatus(200); //sending status
res.json({a:"name"}); //res.send bahut comman hota h ilsiye ham speciality ke liye Object ke liye res.JSON use karte h
});
***********pipelining means (res object ke sath two fun. call karna)*************
app.get('/',(req,res)=>{
//code for db update
res.status(200).send("Database not connecting");
});
***********http request variables*************
app.get('/products',(req,res)=>{
res.send(req.query.limit);
});
***********http req variables v2*************
app.get('/ab?cd',(req,res)=>{ //for abcd or acd (there are b are optional)
res.send('abcd');
});
***********http req variables v3*************
app.get('/ab+cd',(req,res)=>{ // RegEx = for many bbbbbbb
res.send('abcd');
});
***********http req variables v4*************
app.get('/ab*cd',(req,res)=>{ //
res.send('abcd');
});
***********http req variables v4*************
app.get('/ab(cd)?e',(req,res)=>{ // RegEx = cd are optional
res.send('abcd');
});
***********http req variables v4*************
app.get('/a/',(req,res)=>{ // RegEx = start with a
res.send('abcd');
});
***********http req variables v5*************
app.get('/.*fly$/',(req,res)=>{ //regex butterfly
res.send('abcd');
});
***********http req variables v4*************
app.get('/user/:usrid/books/:bkid',(req,res)=>{
console.log(req.query); //query var
res.send(req.params); //dynamic var
});
*****************POSTMAN examples************
localhost:5000/ GET
localhost:5000/ POST
localhost:5000/ PUT
localhost:5000/ DELETE
//Sending varibles to server with get
Postman url => localhost:5000/products?limit=50&qry=something
//changing varibles but same response
Postman url => localhost:5000/ab?cd
//variables multiple times in req
Postman url => localhost:5000/abbbbbbbbbbbbbcd
//variables starting with a req > /a/
Postman url => localhost:5000/abbbcd
|
import expect from 'expect';
import React from 'react';
import { mount } from 'enzyme';
import CommentBody from '../../components/CommentBody';
function setup(deleted = false, body = 'Test text') {
const component = mount(
<CommentBody deleted={deleted} body={body} />
);
return {
component,
p: component.find('p')
};
}
describe('CommentBody', () => {
it('should display comment text', () => {
const { p } = setup();
expect(p.text()).toMatch(/^Test text/);
});
describe('when deleted is true', () => {
it('should show comment was deleted', () => {
const { p } = setup(true);
expect(p.text()).toMatch(/^This comment was deleted/);
});
});
});
|
const express = require('express');
const app = express();
// const session = require('express-session');
const http = require('http').Server(app);
// const io = require('socket.io')(http);
const morgan = require('morgan');
app.use(morgan("dev"));
const ApiRouter = require('./routers/api_router');
// app.use(session({
// secret: 'tundip',
// resave: true,
// saveUninitialized: true,
// cookie: { maxAge:1000*60*60*24*7 }
// }));
app.use(function (req, res, next) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers");
next();
});
app.get('/',(req,res) => res.send('ok babe'));
app.use('/api',new ApiRouter().getRouter());
module.exports = http; |
import React from "react";
import styles from "../styles/CarouselItem.module.css";
import board from "../assets/images/board.png";
export default function CarouselItem() {
return (
<div className={styles.item}>
{/* <span className={styles.bgElement}></span> */}
<div className={styles.imageContainer}>
<img src={board}></img>
<span className={styles.imgBG}></span>
</div>
<div className={styles.info}>
<span className={styles.category}>FUNBOARDS</span>
<h3 className={styles.title}>Chilli Rare Bird</h3>
<div>
<span className={styles.price}>$890</span>
<span className={styles.buy}>BUY</span>
</div>
</div>
</div>
);
}
|
const path = require('path');
const CopyPlugin = require('copy-webpack-plugin');
module.exports = {
entry: [
'./src/index.js',
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
],
output: {
filename: 'main.js',
path: path.resolve(__dirname, 'dist'),
},
devServer: {
inline: true,
hot: false,
host: '0.0.0.0',
port: 3000,
historyApiFallback: true,
},
module: {
rules: [
{
test: /\.(sass|scss)/,
loader:
'style-loader!css-loader!sass-loader?sourceMap',
},
{
test: /\.html$/,
exclude: /node_modules/,
use: { loader: 'html-loader' },
},
],
},
plugins: [
new CopyPlugin([
{ from: './src/index.html', to: './' },
{ from: './src/api/', to: './api/' },
]),
],
};
|
const fs = require('fs');
const path = require('path');
const uid = require('uid');
const update= {
/*-------------Private---------------*/
path: global._db,
requirements:['hash','question','image','answer','choices','explanation'],
/*-------------PUBLIC---------------*/
details(target, name, description){
console.log('Updating Details: ' + target +'...');
const dir = path.join(this.path, target, 'index.json');
const parent = path.join(dir,'..', '..','index.json');
console.log(dir);
console.log(parent);
if(!fs.existsSync(dir)){
console.log('File Error');
return { status:'ERR', message:'File Error: Course Does Not Exist'}
}
data = fs.readFileSync(dir)
try {
data = JSON.parse(data)
} catch (e) {
console.log('JSON Error');
return { status:'ERR', message:'JSON Error: Course File is Corrupted'}
}
data.name = name;
data.description = description;
fs.writeFileSync(dir, JSON.stringify(data))
return {
status:'OK', ...data
}
},
course(code, name, description){
const dir = path.join(this.path, code, 'index.json');
const parent = path.join(this.path, 'index.json');
if(!fs.existsSync(dir)){
console.log('File Error');
return { status:'ERR', message:'File Error: Course Does Not Exist'}
}
if(!fs.existsSync(parent)){
console.log('File Error');
return { status:'ERR', message:'File Error: Index Does Not Exist'}
}
try {
data = JSON.parse(fs.readFileSync(dir))
data.name = name;
data.description = description;
fs.writeFileSync(dir, JSON.stringify(data))
} catch (e) {
console.log('JSON Error');
console.log(e);
return { status:'ERR', message:'JSON Error: Cannot write to course'}
}
try {
file = JSON.parse(fs.readFileSync(parent))
file.data[code].name = name;
file.data[code].description = description;
fs.writeFileSync(parent, JSON.stringify(file))
} catch (e) {
console.log('JSON Error');
console.log(e);
return { status:'ERR', message:'JSON Error: Cannot write to index'}
}
return { status:"OK", message:"Update Complete" }
},
category(course, code, name, description){
const dir = path.join(this.path, course, code, 'index.json');
const parent = path.join(this.path, course, 'index.json');
if(!fs.existsSync(dir)){
console.log('File Error');
return { status:'ERR', message:'File Error: Course Does Not Exist'}
}
if(!fs.existsSync(parent)){
console.log('File Error');
return { status:'ERR', message:'File Error: Index Does Not Exist'}
}
try {
data = JSON.parse(fs.readFileSync(dir))
data.name = name;
data.description = description;
fs.writeFileSync(dir, JSON.stringify(data))
} catch (e) {
console.log('JSON Error');
console.log(e);
return { status:'ERR', message:'JSON Error: Cannot write to course'}
}
try {
file = JSON.parse(fs.readFileSync(parent))
file.data[code].name = name;
file.data[code].description = description;
fs.writeFileSync(parent, JSON.stringify(file))
} catch (e) {
console.log('JSON Error');
console.log(e);
return { status:'ERR', message:'JSON Error: Cannot write to index'}
}
return { status:"OK", message:"Update Complete" }
},
subject(course, category, code, name, description){
const dir = path.join(this.path, course, category, code, 'index.json');
const parent = path.join(this.path, course, category, 'index.json');
if(!fs.existsSync(dir)){
console.log('File Error');
return { status:'ERR', message:'File Error: Course Does Not Exist'}
}
if(!fs.existsSync(parent)){
console.log('File Error');
return { status:'ERR', message:'File Error: Index Does Not Exist'}
}
try {
data = JSON.parse(fs.readFileSync(dir))
data.name = name;
data.description = description;
fs.writeFileSync(dir, JSON.stringify(data))
} catch (e) {
console.log('JSON Error');
console.log(e);
return { status:'ERR', message:'JSON Error: Cannot write to course'}
}
try {
file = JSON.parse(fs.readFileSync(parent))
file.data[code].name = name;
file.data[code].description = description;
fs.writeFileSync(parent, JSON.stringify(file))
} catch (e) {
console.log('JSON Error');
console.log(e);
return { status:'ERR', message:'JSON Error: Cannot write to index'}
}
return { status:"OK", message:"Update Complete" }
},
// append subject data
append(course, category, subject, token, image){
console.log('New Token');
//validate token
this.requirements.forEach(req=>{
if(!token.hasOwnProperty(req)){
console.log('Missing: ' + req);
return {status:'ERR', message:'Missing: ' + req }
}
})
// validate paths
const courseDir = path.join(this.path, course);
if(!fs.existsSync(courseDir)){
console.log('Course not found!');
return {status:'ERR', message:'Path Error: Course' }
}
const categoryDir = path.join(courseDir, category);
if(!fs.existsSync(categoryDir)){
console.log('Category not found!');
return {status:'ERR', message:'Path Error: Category' }
}
const subjectDir = path.join(categoryDir, subject);
if(!fs.existsSync(subjectDir)){
console.log('Subject not found!');
return {status:'ERR', message:'Path Error: Subject' }
}
//open paths
try {
course = JSON.parse(fs.readFileSync(path.join(courseDir,'index.json')))
} catch (e) {
console.log('JSON Error (course): ' + e);
return {status:'ERR', message:'JSON Error: Course' }
}
try {
category = JSON.parse(fs.readFileSync(path.join(categoryDir,'index.json')))
} catch (e) {
console.log('JSON Error (category): ' + e);
return {status:'ERR', message:'JSON Error: Category' }
}
try {
subject = JSON.parse(fs.readFileSync(path.join(subjectDir,'index.json')))
} catch (e) {
console.log('JSON Error (subject): ' + e);
return {status:'ERR', message:'JSON Error: Subject' }
}
if(token.image!=="none"){
var base64Data = image.replace(/^data:image\/png;base64,/, "");
fs.writeFileSync(path.join(subjectDir,`${token.hash}.${token.image}`), base64Data, 'base64')
}
//Update subject
subject.data.push(token)
category.count++;
course.count++;
// Write
fs.writeFileSync(path.join(subjectDir,'index.json'),JSON.stringify(subject))
fs.writeFileSync(path.join(categoryDir,'index.json'),JSON.stringify(category))
fs.writeFileSync(path.join(courseDir,'index.json'),JSON.stringify(course))
return { status:'OK' }
},
index(){
const dir = this.path
let data = {};
let count = 0;
const files = fs.readdirSync(dir)
files.forEach((item, i) => {
file = path.join(dir,item);
if(fs.lstatSync(file).isDirectory()){
console.log(item);
if(fs.existsSync(path.join(file, 'index.json'))){
try {
chunk = JSON.parse(fs.readFileSync(path.join(file, 'index.json')))
console.log(chunk);
data[item] = {name:chunk.name, description:chunk.description, count:chunk.count }
count+= chunk.count;
} catch (e) {
console.log('Index Updater: Failed at ' + file);
}
}
}
});
// update index file
try {
let index = JSON.parse(fs.readFileSync(path.join(dir,'index.json')))
index.data = data;
console.log(index.data);
fs.writeFileSync( path.join(dir,'index.json'), JSON.stringify(index))
console.log('Index File Updated: ' + path.join(dir,'index.json'));
} catch (e) {
fs.writeFileSync(
path.join(dir,'index.json'),
JSON.stringify(
{
version:0,
data:data,
description:"",
count:count,
themes:['default']
}
)
)
}
}
}
module.exports = update
|
var crypto = require('crypto');
function Commit() {
this.id = null;
this.parentIds = [];
this.name = '';
this.properties = {};
this.changes = {};
}
Commit.prototype.sign = function() {
this.id = null;
var sha = crypto.createHash('sha1');
var json = JSON.stringify(this) + (new Date().getTime()) + Math.random();
sha.update(json);
this.id = sha.digest('hex');
}
module.exports = Commit;
|
window.onerror = function(message, source, lineno, colno, error) {
console.error(error)
};
navigator.spatialNavigationEnabled = false;
const params = new URLSearchParams(window.location.hash); // google return it in the hash weirdly
const access_token = params.get('#access_token')
if(access_token){
window.localStorage.setItem('access_token', access_token)
console.log("set access token", access_token)
window.location.href = 'app.html'
} else {
console.log("access token null. redirecting to login")
}
|
var http = require('http');
var fs = require('fs');
var net = require('net');
var url = require('url');
var qs = require('querystring');
var WebSocketServer = require('ws').Server
, wss = new WebSocketServer({ host: 'localhost', port: 8000 });
const HTTP_PORT = 8080;
const APORT = 3000;
const WSPORT = 8000;
const BLACKLIST_PATH = 'blocked.txt';
const HTML_PATH = 'index.html';
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
client.send(data);
});
};
wss.on('connection', function(ws) {
console.log("connection");
});
function handleHttpRequest(request, response) {
// Send url and method to admin console
var data = request.method + " " + request.url;
wss.broadcast(data);
// open file
fs.readFile(BLACKLIST_PATH, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
// Check if request blacklisted
if (data.includes(request.headers['host'])) {
response.writeHead(404);
response.write("Blocked by proxy");
response.end();
}
else {
var proxy_request = http.request({
hostname: request.headers['host'],
method: request.method,
path: request.url,
headers: request.headers
});
proxy_request.addListener('response', function (proxy_response) {
proxy_response.addListener('data', function(chunk) {
response.write(chunk, 'binary');
});
proxy_response.addListener('end', function() {
response.end();
});
response.writeHead(proxy_response.statusCode, proxy_response.headers);
});
request.addListener('data', function(chunk) {
proxy_request.write(chunk, 'binary');
});
request.addListener('end', function() {
proxy_request.end();
});
}
});
}
function handleAdminRequest(request, response) {
if (request.method == "GET"){
fs.readFile(HTML_PATH, 'utf8', function (err,data) {
if (err) {
response.writeHead(404);
response.write("404 - Not found");
console.log(err);
}
else {
response.writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': data.length });
response.write(data);
}
response.end();
});
}
else if (request.method == "POST") {
var body = '';
request.on('data', function (data) {
body += data;
// Too much POST data, kill the connection!
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6)
request.connection.destroy();
});
request.on('end', function () {
var post = qs.parse(body);
console.log(post.site);
fs.appendFile(BLACKLIST_PATH, post.site + "\n", 'utf8', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
});
response.write("Hello");
response.end();
}
else {
console.log("err: " + request.method);
response.end();
}
}
// Setup servers
var proxy = http.createServer(handleHttpRequest);
// Handle HTTPS
proxy.on('connect', (request, cltSocket, head) => {
var srvUrl = url.parse(`http://${request.url}`);
// Send to admin console
var data = request.method + " " + request.url;
wss.broadcast(data);
fs.readFile(BLACKLIST_PATH, 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
if (data.includes(srvUrl.hostname)) {
console.log("Blocked");
cltSocket.write('HTTP/1.1 404 Not Found\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
cltSocket.end();
} else {
// connect
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
});
}
});
});
proxy.listen(HTTP_PORT);
http.createServer(handleAdminRequest).listen(APORT);
|
import { find } from "lodash"
// "Mock" database is simply programmer-deined data ====
const agents = [
{ id: 1, firstName: 'Larry', middleInitial: 'L', lastName: 'Thomas'},
{ id: 2, firstName: 'Bill', middleInitial: 'R', lastName: 'Lewis' }
]
const authors = [
{ id: 1, firstName: 'Tom', middleInitial: 'W',lastName: 'Coleman', agent: find(agents,{id: 1})},
{ id: 2, firstName: 'Sashko', middleInitial: 'L', lastName: 'Stubailo', agent: find(agents,{id: 2})},
{ id: 3, firstName: 'Mikhail', middleInitial: 'R', lastName: 'Novikov', agent: find(agents, {id: 1}) },
];
const posts = [
{ id: 1, authorId: 1, title: 'Introduction to GraphQL',articleType: 'REVIEW' },
{ id: 2, authorId: 2, title: 'GraphQL Rocks', articleType: 'OPINION' },
{ id: 3, authorId: 2, title: 'Advanced GraphQL', articleType: 'TECHNICAL' },
{ id: 4, authorId: 3, title: 'Launchpad is Cool', articleType: 'OPINION' },
]
export { agents, authors, posts }
|
document.addEventListener("DOMContentLoaded", async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id },
function: calculatePlaylistLength,
});
});
function calculatePlaylistLength(){
let arr = []
document.querySelectorAll(".ytd-thumbnail-overlay-time-status-renderer").forEach( item => {
arr.push((item.innerHTML).toString())
})
arr = arr.filter(line => line !== "")
arr = arr.map(str => str.substr(3))
arr = arr.map(str => str.slice(0, -1))
arr = arr.map( str => str.split(":") )
arr = arr.map(time => parseInt(time[0]) * 60 + parseInt(time[1]) )
let sum = arr.reduce((total, item) => total + item)
alert(`Total: ${Math.floor(sum / 3600)}h ${Math.floor((sum % 3600) / 60)}m ${sum % 60}s`)
}
|
adminModule.controller('homepageController', HomepageController);
HomepageController.$inject = [
'homepageRequest'
];
function HomepageController(homepageRequest) {
var ctrl = this;
ctrl.notifications = 0;
ctrl.guides = 0;
ctrl.regids = 0;
ctrl.init = init;
ctrl.getNotificationsCount = getNotificationsCount;
ctrl.getGuidesCount = getGuidesCount;
ctrl.getRegIdsCount = getRegIdsCount;
function init() {
ctrl.getNotificationsCount();
ctrl.getGuidesCount();
ctrl.getRegIdsCount();
}
function getNotificationsCount() {
homepageRequest.getNotificationsCount().then(function (data) {
animateToValue(data, 'layout_notifications')
});
}
function getGuidesCount() {
homepageRequest.getGuidesCount().then(function (data) {
animateToValue(data, 'layout_guides')
});
}
function getRegIdsCount() {
homepageRequest.getRegIdsCount().then(function (data) {
animateToValue(data, 'layout_users')
});
}
function animateToValue(value, id_layout) {
$({someValue: 0}).animate({someValue: value}, {
duration: 2000,
easing: 'swing',
step: function () {
$('#' + id_layout).text(
commaSeparateNumber(Math.round(this.someValue))
);
}
});
}
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return val;
}
} |
import {SearchBox} from "./SearchBox";
import {Filters} from "./Filters";
import {Sentence} from "./Sentence";
import urlifyFactory from 'urlify';
import {SelectedFilters} from "./SelectedFilters";
import {LoadingComponent} from "../LoadingComponent/LoadingComponent";
export const SearchComponent = {
data: function() {
return {
filtersInitialized: false,
showSentence: false,
keyword: null,
preparedEbaySites: [],
}
},
template: `<div class="AdvancedSearch" id="AdvancedSearchId">
<search-box
v-on:submit="submit"
v-on:on-search-term-change="onSearchTermChange">
</search-box>
<selected-filters v-if="areSingleAddFiltersSelected"></selected-filters>
<!-- <transition name="fade">
<sentence
v-if="showSentence"
v-bind:sentenceData="sentenceData"
v-bind:showSentence="showSentence">
</sentence>
</transition>-->
</div>`,
computed: {
sentenceData: function() {
return {
filters: this.filters,
keyword: this.keyword,
}
},
getFilters() {
return this.$store.getters.getFilters;
},
areSingleAddFiltersSelected() {
return this.$store.getters.areSingleAddFiltersSelected;
}
},
methods: {
onSearchTermChange(searchTerm) {
if (isEmpty(searchTerm)) {
this.$store.dispatch('destroyEntireState');
this.showSentence = false;
return false;
}
this.$store.commit('searchInitialiseEvent', {
initialised: false,
});
this.$store.commit('listingInitialiseEvent', {
initialised: false,
});
this.$store.commit('ebaySearchListing', {
siteInformation: null,
items: null,
});
this.$store.commit('totalListing', null);
this.showSentence = true;
this.keyword = searchTerm;
},
submit(keyword) {
if (isEmpty(keyword)) {
this.$store.dispatch('destroyEntireState');
return false;
}
this.keyword = keyword;
const urlify = urlifyFactory.create({
addEToUmlauts: true,
szToSs: true,
spaces: "-",
nonPrintable: "-",
trim: true
});
const model = this.createModel();
this.$store.commit('ebaySearchListing', {
siteInformation: null,
items: null,
});
this.$store.commit('totalListing', null);
this.$store.commit('modelWasCreated', model);
this.$store.commit('modelWasUpdated', model);
this.$store.commit('searchInitialiseEvent', {
searchUrl: `/search/${urlify(this.keyword)}`,
initialised: true,
});
setTimeout(() => scrollToElement(document.getElementById('ListingChoiceComponentId'), 200));
},
createModel() {
return {
keyword: this.keyword,
filters: this.getFilters,
pagination: {
limit: 8,
page: 1,
},
locale: this.$localeInfo.locale,
internalPagination: {
limit: 80,
page: 1
},
globalId: null,
}
}
},
components: {
'search-box': SearchBox,
'filters': Filters,
'sentence': Sentence,
'selected-filters': SelectedFilters,
'loading-component': LoadingComponent,
}
}; |
let apiJoiner = require("./api-joiner.js")
try {
apiJoiner.joinDocs({
// folder path where all the docs are placed
"docsPath": "./docs",
// prefix to be used for output file name. file name e.g. some-api-2019-02-15T14:06:22.117Z
"combinedDocPrefix": "some-api",
// Open API 3 document info object
"docInfo": {
"title": "Some API",
"description": "Some API description",
"version": "v1",
"x-logo": {
"url": "logo.svg"
}
},
// Server url for the apis
"serverUrl": "http://some.api",
// function to process the path before it is added to combined doc
"pathProcessor": pathProcessor
})
} catch (e) {
console.log("Error in joining docs " + e)
}
/**
* This is optional function in case you want to do some
* custom processing before the api endpoint path is
* added to the combined doc
* In this example, this function is removing any version details
* and trailing slashes from the path
* And it also throws exception for duplicate path
*/
function pathProcessor(combinedDoc, path1, docTitle) {
// replace v1, /v1 & trailing slashes
let path = path1
.replace("/v1", "")
.replace("v1", "")
.replace(/(\/+$)/g, "")
if (path[0] != "/") {
path = "/" + path
}
let pathExists = combinedDoc.paths[path] != undefined
if (pathExists) {
throw "Duplicate path " + path + " in the doc " + docTitle
}
return path
}
|
/*
BLE Central
This example uses Don Coleman's BLE Central Plugin for Apache Cordova
to create a central server that connects and sends data to the Light Blue Bean.
created 29 Mar 2015
by Maria Paula Saba
*/
/* global mainPage, deviceList, refreshButton */
/* global connectedPage, resultDiv, messageInput, sendButton, disconnectButton */
/* global ble */
/* jshint browser: true , devel: true*/
'use strict';
var DEVICE = 'MyBean';
var scratchServiceUUID = 'A495FF20-C5B1-4B44-B512-1370F02D74DE';
var scratchCharacteristicUUID = 'A495FF21-C5B1-4B44-B512-1370F02D74DE';
var app = {
initialize: function() {
this.bindEvents(); //binding event listeners to DOM in the app
connectedPage.hidden = true; //hides the HTML elements for the second page
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false); //runs onDeviceReady function whenever the device is ready (loaded)
refreshButton.addEventListener('touchstart', this.refreshDeviceList, false); //on touch of the Refresh button, runs refreshDeviceList function
deviceList.addEventListener('touchstart', this.connect, false); //on touch of device list, connect to device
randomButton.addEventListener('touchstart', this.sendData, false);
disconnectButton.addEventListener('touchstart', this.disconnect, false);
},
onDeviceReady: function() {
app.refreshDeviceList();
},
refreshDeviceList: function() {
deviceList.innerHTML = ''; // empties the list
ble.scan([], 5, app.onDiscoverDevice, app.onError); //scans for BLE devices
},
onDiscoverDevice: function(device) {
//only shows devices with the name we're looking for
if(device.name === DEVICE) {
//creates a HTML element to display in the app
var listItem = document.createElement('li'),
html = '<b>' + device.name + '</b><br/>' +
'RSSI: ' + device.rssi + ' | ' +
device.id;
listItem.innerHTML = html;
listItem.dataset.deviceId = device.id; //save the device ID in the DOM element
listItem.setAttribute("class", "result"); //give the element a class for css purposes
deviceList.appendChild(listItem); //attach it in the HTML element called deviceList
}
},
connect: function(e) {
//get the device ID from the DOM element
var deviceId = e.target.dataset.deviceId,
onConnect = function() {
//saves device ID to buttons - needed later
disconnectButton.dataset.deviceId = deviceId;
randomButton.dataset.deviceId = deviceId;
resultDiv.innerHTML = "Click to send data";
//show next page
app.showConnectPage();
};
//connect functions asks for the device id, a callback function for when succeeds and one error functions for when it fails
ble.connect(deviceId, onConnect, app.onError);
},
sendData: function() {
var deviceId = event.target.dataset.deviceId;
var r = Math.random()*255;
var g = Math.random()*255;
var b = Math.random()*255;
var data = new Uint8Array(3);
data[0] = r;
data[1] = g;
data[2] = b;
// send data to the bean
ble.write(deviceId, scratchServiceUUID, scratchCharacteristicUUID, data.buffer, app.onSuccess(data), app.onError);
},
disconnect: function(event) {
//gets device ID from disconnect button
var deviceId = event.target.dataset.deviceId;
ble.disconnect(deviceId, app.showStartPage, app.onError);
},
showStartPage: function() {
startPage.hidden = false;
connectedPage.hidden = true;
},
showConnectPage: function() {
startPage.hidden = true;
connectedPage.hidden = false;
},
onError: function(reason) {
alert("ERROR: " + reason); // real apps should use notification.alert
},
onSuccess: function(data){
alert("data written: "+data[0]+", "+data[1]+", "+data[2]);
}
};
|
const Discord = require("discord.js");
const fs = require("fs");
const ms = require("ms");
var mongoose = require("mongoose");
mongoose.Promise = global.Promise;mongoose.connect(process.env.MONGO_URL);
var User = require('./../schemas/user_model.js');
var Item = require('./../schemas/shop_model.js');
function isNumeric(value) {
return /^\d+$/.test(value);
}
function random(min, max) {
var result = Math.floor(Math.random() * (max - min + 1)) + min;
return (result);
}
function playcf(user, toPlay, message){
var user_obj = User.findOne({userID: message.member.id}, function(err, found_user){
if (err)
console.log("WTF there is an error: " + err);
else {
if (!user_obj)
console.log("User not found");
else {
var chickenPower = 50;
if (user.chickenPower && user.chickenPower != 0)
chickenPower = user.chickenPower;
var cfResult = random(1, 100);
if (cfResult <= chickenPower){
if (chickenPower < 75)
chickenPower += 1;
found_user.chickenPower = chickenPower;
found_user.retrocoinCash += toPlay;
message.channel.send({embed: {
color: 1613918,
title: `**Курочка выиграла и стала сильнее!**`,
description: "Боевая мощь курочки (шанс выиграть) повышена: " + chickenPower +"%",
timestamp: new Date(),
footer: {
icon_url: message.author.avatarURL,
text: `© ${message.member.displayName}`
},
}});
}
else{
found_user.retrocoinCash -= toPlay;
found_user.chickenPower = 0;
var index = user.inv.indexOf("Курочка 🐔");
var newinv = user.inv;
newinv.splice(index, 1);
found_user.inv = newinv;
message.channel.send({embed: {
color: 14504004,
title: `**Твоя курочка погибла!**`,
timestamp: new Date(),
footer: {
icon_url: message.author.avatarURL,
text: `© ${message.member.displayName}`
},
}});
}
found_user.lastCF = Date.now();
found_user.save(function(err, updatedObj){
if (err)
console.log(err);
});
}
}
});
}
module.exports.run = async (bot, message, args) => {
//message.delete().catch(O_o=>{});
var casino_channel = message.guild.channels.find(`name`, "🎰казино_экономика");
if (message.channel.name != "🎰казино_экономика" && message.channel.name != "🌎general_bots"){
message.delete(3000);
return message.reply(`в курочку можно играть только в ${casino_channel}`).then(msg => msg.delete(10000));
}
var user_obj = await User.findOne({userID: message.member.id}, function(err, found_user){});
if (typeof user_obj === 'undefined' || user_obj === null)
return message.reply("пользователь не найден в базе");
//чекаем есть ли у него Курочка в инвентаре
if (user_obj.inv.includes("Курочка 🐔") == false)
return message.reply("у тебя нету 🐔");
//чекаем играл ли человек недавно в курочку
if (user_obj.lastCF){
var dateTime = Date.now();
var timestamp = Math.floor(dateTime/1000);
var timestampLimit = Math.floor(user_obj.lastCF/1000) + 15;
if (timestampLimit > timestamp)
return message.reply(`твоя курочка только-только подралась! Дай ей чуть передохнуть :thinking:`);
}
//чекаем сделал ли типуля ставку и достаточно ли у него денег в базе
if (args[0] && isNumeric(args[0]) == true){
let toPlay = Number(args[0]);
if (toPlay >= 100){
if ((user_obj.retrocoinCash - toPlay) >= 0){
message.channel.send({
files: [{
attachment: 'https://retrobotproject.herokuapp.com/images/chicken.gif',
name: 'chicken.gif'
}]
}).then(msg => msg.delete(4000));
setTimeout(function(){
playcf(user_obj, toPlay, message)
}, 5000);
return;
}
else{
return message.reply("у тебя не хватит на это ретриков!");
}
}
else{
return message.reply("минимальная стака - 100 ретриков!");
}
}
return message.reply("нужно сделать ставку, от 100 ретриков и выше!")
}
module.exports.help = {
name: "cf"
}
|
import React from 'react';
import {ModalWithDrag, SuperTable} from '../../../components';
import showPopup from '../../../standard-business/showPopup';
import helper from "../../../common/common";
class AddDialog extends React.Component {
constructor(props) {
super(props);
this.state = {
visible: true,
tableItems: props.tableItems,
filterInfo: {}
}
}
onHandleCheck= (isAll, checked, rowIndex) => {
isAll && (rowIndex = -1);
let tableItems = [...this.state.tableItems];
if (rowIndex === -1) {
tableItems = this.state.tableItems.map(item => ({...item, checked}));
}else {
tableItems[rowIndex] = {...tableItems[rowIndex], checked};
}
this.setState({...this.state, tableItems});
};
onHandleOk = () => {
const checkedItems = this.state.tableItems.filter(item => item.checked === true);
if (checkedItems.length < 1) return helper.showError(`请先勾选记录`);
this.setState({visible: false, res: checkedItems.map(item => ({...item, checked: undefined}))});
};
toTable = () => {
const props = {
filterInfo: this.state.filterInfo,
items: this.state.tableItems,
cols: this.props.tableCols,
maxHeight: '500px',
callback: {
onCheck: this.onHandleCheck,
onTableChange: (sortInfo, filterInfo) => {this.setState({filterInfo})}
}
};
return <SuperTable {...props} />;
};
getModeProps = () => {
return {
title: '添加快捷菜单',
okText: '确定',
cancelText: '取消',
visible: this.state.visible,
maskClosable: false,
width: 600,
onOk: this.onHandleOk,
onCancel: () => this.setState({visible: false}),
afterClose: () => this.props.afterClose(this.state.res)
};
};
render() {
return (
<ModalWithDrag {...this.getModeProps()}>
{this.toTable()}
</ModalWithDrag>
);
}
}
export default (tableItems, tableCols) => {
return showPopup(AddDialog, {tableItems, tableCols}, true);
};
|
const fs = require('fs')
const glob = require('glob')
const path = require('path')
const {testAsync} = require('./helpers')
const {convert} = require('../src')
/**
* Tests conversion of files in `fixtures`
*
* Each fixture file is read in and then exported to the same format
* with `-out` appended to the filename. e.g. `paragraphs.md` is exported to `paragraphs-out.md`.
*/
testAsync('Fixtures: round trips', async assert => {
let inputs = glob.sync(path.join(__dirname, 'fixtures', '*'))
for (let input of inputs) {
// Skip output files
if (input.includes('-out.')) continue
// Generate output and expected file names
const match = path.basename(input).match(/^([^-.]+)(-[^.]+)?(\..+)?$/)
const ext = match[3] || ''
const output = path.join(__dirname, 'fixtures', `${match[1]}${match[2] || ''}-out${ext}`)
const expected = path.join(__dirname, 'fixtures', `${match[1]}${ext}`)
assert.comment(`Converting ${path.basename(input)} to ${path.basename(output)}`)
// Skip, skipped files
if (input.includes('-skip.')) {
assert.skip('Skipping')
continue
}
try {
await convert(input, output, fs, fs, null, null, {
eol: 'lf' // Force 'lf' so that line endings are as expected on Windows
})
} catch (error) {
// Skip test if converter not found
if (error.message.match(/^No converter/)) {
assert.skip(error.message)
} else {
assert.fail(error)
console.error(error)
}
continue
}
let stats = fs.lstatSync(expected)
if (stats.isFile()) {
const message = `${path.basename(output)} == ${path.basename(expected)}`
let expectedString
let actualString
if (ext === '.xlsx' || ext === '.ods') {
assert.skip(`Can not currently test "${message}"`)
continue
} else {
expectedString = fs.readFileSync(expected).toString().trim()
actualString = fs.readFileSync(output).toString().trim()
}
// Compare expected and actual output
if (expectedString.length < 100 & actualString.length < 100) assert.equal(actualString, expectedString, message)
else assert.ok(actualString === expectedString, message)
} else if (stats.isDirectory()) {
// Compare file list
const expectedFiles = fs.readdirSync(expected)
const actualFiles = fs.readdirSync(output)
const message = `${path.basename(output)} == ${path.basename(expected)}`
assert.deepEqual(expectedFiles, actualFiles, message)
}
}
assert.end()
})
|
jasmine.getEnv().defaultTimeoutInterval = 50000;
var openpublish = require("../src/index");
var bitcoin = require("bitcoinjs-lib");
var File = require("file-api").File;
var blockcast = require("blockcast");
var fs = require('fs');
var crypto = require("crypto");
var request = require("request");
var commonBlockchain;
if (process.env.CHAIN_API_KEY_ID && process.env.CHAIN_API_KEY_SECRET) {
var ChainAPI = require("chain-unofficial");
commonBlockchain = ChainAPI({
network: "testnet",
key: process.env.CHAIN_API_KEY_ID,
secret: process.env.CHAIN_API_KEY_SECRET
});
}
else {
commonBlockchain = require("mem-common-blockchain")();
}
var createRandomString = function(length) {
var characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
var output = '';
for (var i = 0; i < length; i++) {
var r = Math.floor(Math.random() * characters.length);
output += characters.substring(r, r + 1);
}
return output;
};
var createRandomFile = function(options, callback) {
var fileName = options.fileName;
var string = options.string;
var path = "./test/" + fileName;
fs.writeFile(path, string, function(err) {
callback(path);
});
};
var address = "n3PDRtKoHXHNt8FU17Uu9Te81AnKLa7oyU";
var privateKeyWIF = "KyjhazeX7mXpHedQsKMuGh56o3rh8hm8FGhU3H6HPqfP9pA4YeoS";
var sha1 = "dc724af18fbdd4e59189f5fe768a5f8311527050";
var bitstore = require('bitstore')({
privateKey: privateKeyWIF,
network: 'testnet'
});
var signFromPrivateKeyWIF = function(privateKeyWIF) {
return function(txHex, callback) {
var tx = bitcoin.Transaction.fromHex(txHex);
var key = bitcoin.ECKey.fromWIF(privateKeyWIF);
tx.sign(0, key);
var txid = tx.getId();
var signedTxHex = tx.toHex();
callback(false, signedTxHex, txid);
}
};
var signRawTransaction = signFromPrivateKeyWIF(privateKeyWIF);
var commonWallet = {
signRawTransaction: signRawTransaction,
address: address
}
describe("open-publish", function() {
var fileBuffer = new Buffer("testing");
var fileName = "test.txt";
var fileType = "text/plain";
var fileTitle = "A text file for testing";
var fileKeywords = "test, text, txt";
var fileBtih = "335400c43179bb1ad0085289e4e60c0574e6252e";
var fileSha1 = "dc724af18fbdd4e59189f5fe768a5f8311527050";
var testData0 = {
op: "r",
btih: fileBtih,
sha1: fileSha1,
name: fileName,
size: fileBuffer.length,
type: fileType,
title: fileTitle,
keywords: fileKeywords
}
var file = new File({
name: fileName,
type: fileType,
buffer: fileBuffer
});
it("should publish a small text file", function(done) {
openpublish.register({
file: file,
title: fileTitle,
keywords: fileKeywords,
commonWallet: commonWallet,
commonBlockchain: commonBlockchain
}, function(err, receipt) {
var data = receipt.data;
expect(data.op).toBe("r");
expect(data.btih).toBe(fileBtih);
expect(data.sha1).toBe(fileSha1);
expect(data.name).toBe(fileName);
expect(data.size).toBe(fileBuffer.length);
expect(data.type).toBe(fileType);
expect(data.title).toBe(fileTitle);
expect(data.uri).not.toBeDefined();
expect(data.keywords).toBe(fileKeywords);
var blockcastTx = receipt.blockcastTx;
expect(blockcastTx.txid).toBeDefined();
expect(blockcastTx.transactionTotal).toBe(5);
done();
});
});
it("should find an open publish transaction", function(done) {
openpublish.register({
file: file,
title: fileTitle,
keywords: fileKeywords,
name: fileName,
sha1: fileSha1,
btih: fileBtih,
size: fileBuffer.legnth,
type: fileType,
commonWallet: commonWallet,
commonBlockchain: commonBlockchain
}, function(err, receipt) {
var blockcastTx = receipt.blockcastTx;
var txid = blockcastTx.txid;
setTimeout(function() {
openpublish.scanSingle({
txid: txid,
commonBlockchain: commonBlockchain
}, function(err, data) {
expect(data.op).toBe("r");
expect(data.btih).toBe(fileBtih);
expect(data.sha1).toBe(fileSha1);
expect(data.name).toBe(fileName);
expect(data.size).toBe(fileBuffer.length);
expect(data.type).toBe(fileType);
expect(data.title).toBe(fileTitle);
expect(data.uri).not.toBeDefined();
expect(data.keywords).toBe(fileKeywords);
done();
});
}, 1500);
});
});
it("should post to bitstore and then register with open publish", function(done) {
var randomBufferSize = 48;
var randomFileName = 'randomFile.txt';
var randomString = createRandomString(randomBufferSize);
createRandomFile({string: randomString, fileName: randomFileName}, function(path) {
var randomFile = new File(path);
bitstore.files.put(path, function (err, res) {
var receipt = res.body;
var uri = receipt.uri;
var bistoreSha1 = receipt.hash_sha1;
var bitstoreMimetype = receipt.mimetype;
expect(receipt.size).toBe(randomBufferSize);
expect(receipt.mimetype).toBe('text/plain');
expect(receipt.filename).toBe(randomFileName);
expect(uri).toBeDefined();
// update
randomFile.size = randomBufferSize; // this janky File object we're using needs a little help figuring out the size
openpublish.register({
uri: uri,
file: randomFile,
commonWallet: commonWallet,
commonBlockchain: commonBlockchain
}, function(err, receipt) {
var blockcastTx = receipt.blockcastTx;
var txid = blockcastTx.txid;
expect(txid).toBeDefined();
setTimeout(function() {
blockcast.scanSingle({
txid: txid,
commonBlockchain: commonBlockchain
}, function(err, message) {
var data = JSON.parse(message);
expect(data.op).toBe("r");
expect(data.sha1).toBe(bistoreSha1);
expect(data.name).toBe(randomFileName);
expect(data.size).toBe(randomBufferSize);
expect(data.type).toBe(bitstoreMimetype);
expect(data.uri).toBe(uri);
request(uri, function(err, res, body) {
expect(body).toBe(randomString);
done();
});
});
}, 3000);
});
});
});
});
it("should tip an openpublish document", function(done) {
var amount = 20000;
var destination = "mqMsBiNtGJdwdhKr12TqyRNE7RTvEeAkaR";
openpublish.tip({
destination: destination,
sha1: sha1,
amount: amount,
commonWallet: commonWallet,
commonBlockchain: commonBlockchain
}, function(error, tipTx) {
expect(tipTx.tipDestinationAddress).toBe(destination);
expect(tipTx.openpublishSha1).toBe(sha1);
expect(tipTx.tipAmount).toBe(amount);
expect(tipTx.txid).toBeDefined();
expect(tipTx.propagateResponse).toBe('success');
done();
});
});
it("should scan an opentip", function(done) {
var txid = "7235a656b4f3e578e00c9980d4ea868d8de89a8616e019ccf68db9f0c1d1a6ff";
openpublish.scanSingle({
txid: txid,
commonBlockchain: commonBlockchain
}, function(err, tip) {
expect(tip.openpublishSha1).toBe(sha1);
expect(tip.tipAmount).toBe(20000);
expect(tip.tipDestinationAddresses[0]).toBe("mqMsBiNtGJdwdhKr12TqyRNE7RTvEeAkaR");
done();
});
});
}); |
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const reportSchema = new Schema({
beneficiary: { type: Schema.Types.ObjectId, ref: 'Beneficiary' },
date: Date,
arrivalFrenchLevel: String,
exitFrenchLevel: String,
perceivedAmeliorationFrenchLevel: Boolean,
commentsFrenchLevel: String,
confidenceGain: String,
isAssociationUseful: Boolean,
commentsOnAssociation: String,
personalFeedback: String,
associationFeedback: String,
journeyFeedback: String,
peopleMetFeedback: String,
takenSteps: String,
goals: String,
created: Date,
});
const Report = mongoose.model('Report', reportSchema);
module.exports = Report;
|
const nconf = require('nconf');
const path = require('path');
nconf
.argv()
.env(['PORT', 'NODE_ENV', 'NODE_PREFIX'])
// Override with current environment (ex production) if exists
.add('environment', {
type: 'file',
file: path.join(__dirname, 'dev.json'),
})
.defaults({
PORT: 8081,
REDIS_DB: 9,
APP_DIR: __dirname,
BASE_DIR: __dirname.replace('/app', ''),
});
module.exports = nconf;
|
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const methodOverride = require('method-override');//forms don't support PUT method
mongoose.connect('mongodb+srv://amdin-abel:admin123@cluster0.u7t9t.mongodb.net/cat_db?retryWrites=true&w=majority', {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.set('useFindAndModify', false);
app.use(bodyParser.urlencoded({extended: true}));
app.set('view engine', 'ejs');
app.use(methodOverride('method'));
//Schema setup: id, url, value.
const catSchema = new mongoose.Schema({
id: String,
url: String,
vote: Number,
});
//Compile Model
const Cat = mongoose.model('Cat', catSchema);
app.get('/', (req, res) => {
Cat.find({}, (err, allCats) => {
if(err) {
console.log(err);
} else {
const upVoted = allCats.filter(cats => cats.vote === 1);
const downVoted = allCats.filter(cats => cats.vote === 0);
const randomCat = allCats[Math.floor(Math.random() * allCats.length)];
res.render('index', {randomCat, upVoted});
}
})
});
app.put('/upvote/:id', (req, res) => {
Cat.findByIdAndUpdate(req.params.id, {vote:1}, (err, updated) => {
if(err) {
console.log(err);
} else {
res.redirect('/');
}
})
})
app.put('/downvote/:id', (req, res) => {
Cat.findByIdAndUpdate(req.params.id, {vote:0}, (err, updated) => {
if(err) {
console.log(err);
} else {
res.redirect('/');
}
})
})
app.listen(process.env.PORT || 3000, () => {
console.log('Server is running on PORT:3000');
}) |
/*
In the classic problem of the Towers of Hanoi, you have 3 rods and N disks of
different sizes which can slide onto any tower. The puzzle starts with disks
sorted in ascending order of size from top to bottom (e.g., each disk sits on
top of an even larger one). You have the following constraints:
(A) Only one disk can be moved at a time.
(B) A disk is slid off the top of one rod onto the next rod.
(C) A disk can only be placed on top of a larger disk.
Write a program to move the disks from the first rod to the last using Stacks.
*/
var path = require('path')
, Stack = require(path.resolve(__dirname, 'chapter-3-0')).Stack
var Hanoi = module.exports = function(diskCount) {
this.diskCount = diskCount
this.rods = [ new Stack(), new Stack(), new Stack() ]
for (var i = 0; i < this.diskCount; i++) {
this.rods[0].push(this.diskCount - i)
}
}
Hanoi.prototype.play = function() {
var disk, target, diskSize;
var moves = 0;
while (!this.won()) {
this.printState()
var rod = this.pickRod()
if (target = this.findTarget(rod.top)) {
target.push(rod.pop().data)
}
moves++
}
this.printState()
console.log('Won in ' + moves + ' steps!')
}
Hanoi.prototype.won = function() {
return this.rods[this.rods.length - 1].length() === this.diskCount
}
Hanoi.prototype.pickRod = function() {
var result = null
while (!result) {
var diskSize = Math.ceil(Math.random() * this.diskCount)
result = this.findRod(diskSize)
}
return result
}
Hanoi.prototype.findRod = function(diskSize) {
for (var i = this.rods.length - 1; i >= 0; i--) {
var rod = this.rods[i]
if (rod.top && (rod.top.data === diskSize)) {
return rod
}
}
return null
}
Hanoi.prototype.findTarget = function(disk) {
var possibleTargets = []
if (disk === null) {
return null
}
for (var i = this.rods.length - 1; i >= 0; i--) {
var rod = this.rods[i]
if ((rod.top === null) || (rod.top.data > disk.data)) {
return rod
}
}
return null
}
Hanoi.prototype.printState = function() {
console.log()
this.rods.forEach(function(rod, i) {
var current = rod.top
, result = []
while (current) {
result.push(current.data)
current = current.next
}
console.log("Rod " + i + ":", result)
})
}
|
import config from './../config'
function AjaxModule(setting = config) {
var vm = this
vm.setting = setting
vm.server = setting.server
vm.debug = function(data) {
if(vm.setting.debug == true) {
console.log(data)
}
}
vm.startLoading = function() {
$('#dimmer').addClass('ui active dimmer')
$('#loader').addClass('ui active loader')
}
vm.stopLoading = function() {
setTimeout(function () {
$('#loader').removeClass('ui active loader')
$('#dimmer').removeClass('ui active dimmer')
}, 500)
}
/**
* Mengirimkan Request ke server dengan method GET
*/
vm.get = function(url, data = null, successCallback, errorCallback) {
vm.startLoading()
axios.get(vm.server + url, data).then(function(response) {
if(response.status == 200) {
vm.stopLoading()
successCallback(response)
} else {
vm.stopLoading()
errorCallback(response)
}
vm.debug(response)
}).catch(function(err) {
vm.stopLoading()
errorCallback(err.response)
vm.debug(err)
})
}
vm.post = function(url, data = null, successCallback, errorCallback) {
vm.startLoading()
axios.post(vm.server + url, data).then(function(response) {
if(response.status == 200 ) {
vm.stopLoading()
successCallback(response)
} else {
vm.stopLoading()
errorCallback(response)
}
vm.debug(response)
}).catch(function(err) {
vm.stopLoading()
errorCallback(err.response)
vm.debug(err)
})
}
vm.put = function(url, data = null, successCallback, errorCallback) {
vm.startLoading()
axios.put(vm.server + url, data).then(function(response) {
if(response.status == 200 ) {
vm.stopLoading()
successCallback(response)
} else {
vm.stopLoading()
errorCallback(response)
}
vm.debug(response)
}).catch(function(err) {
vm.stopLoading()
errorCallback(err.response)
vm.debug(err)
})
}
vm.delete = function(url, data = null, successCallback, errorCallback) {
vm.startLoading()
axios.delete(vm.server + url, data).then(function(response) {
if(response.status == 200 ) {
vm.stopLoading()
successCallback(response)
} else {
vm.stopLoading()
errorCallback(response)
}
vm.debug(response)
}).catch(function(err) {
vm.stopLoading()
errorCallback(err.response)
vm.debug(err)
})
}
/**
* Fetch data from server
*/
vm.fetch = function(url, data = null, successCallback, errorCallback) {
axios.get(vm.server + url, data).then(function(response) {
if(response.status == 200) {
successCallback(response)
} else {
errorCallback(response)
}
vm.debug(response)
}).catch(function(err) {
errorCallback(err.response)
vm.debug(err)
})
}
}
export default AjaxModule
|
import React, { useState, useEffect } from 'react';
import './App.css';
import Form from './Form'
import axios from 'axios'
import * as yup from 'yup'
// 👉 the URL for our [GET] and [POST] requests
const url = 'https://reqres.in/api/users'
// 👉 the shape of the state that drives the form
const initialFormValues = {
///// TEXT INPUTS /////
name: '',
email: '',
///// DROPDOWN /////
password: '',
///// CHECKBOXES /////
termsOfService: false,
}
// 👉 the shape of the validation errors object
const initialFormErrors = {
name: '',
email: '',
password: '',
termsOfService: false,
}
// 🔥 STEP 7 - WE NEED TO BUILD A SCHEMA FOR VALIDATION
const formSchema = yup.object().shape({
name: yup
.string()
.required('Name is required!'),
email: yup
.string()
.email('a VALID email is required')
.required('Email is required!'),
password: yup
.string()
.required('Password is required!'),
termsOfService: yup
.boolean()
.required("You must agree!!")
.oneOf([true], "You must agree to the Terms of Service!")
})
export default function App() {
const [users, setUsers] = useState([])
const [formValues, setFormValues] = useState(initialFormValues)
// 🔥 STEP 1 - WE NEED STATE TO KEEP TRACK OF WHETHER SUBMIT BUTTON IS DISABLED!
const [formDisabled, setFormDisabled] = useState(true)
// 🔥 STEP 2 - WE NEED STATE TO KEEP TRACK OF THE VALIDATION ERRORS!
const [formErrors, setFormErrors] = useState(initialFormErrors)
const getUser = () => {
// 🔥 STEP 3 - WE NEED TO FETCH FRIENDS FROM THE API!
// and set them in state
axios.get(url)
.then(res => {
console.log(res.data.data)
setUsers(res.data.data)
})
.catch(err => {
console.log("error!")
})
}
useEffect(() => {
getUser()
}, [])
const postUser = user => { // minus id
// 🔥 STEP 5 - WE NEED A FUNCTION TO POST A NEW FRIEND TO THE API!
// and set the updated list of friends in state
// the endpoint responds (on success) with the new friend (with id !!)
axios.post(url, user)
.then(res => {
setUsers([...users, res.data])
// setUsers(res.data)
// console.log(users)
})
.catch(err => {
console.log(err)
})
}
useEffect(() => {
formSchema.isValid(formValues)
.then(valid => { // either true or false
setFormDisabled(!valid)
})
}, [formValues])
const onSubmit = evt => {
evt.preventDefault()
const newUser = {
name: formValues.name,
email: formValues.email,
password: formValues.password,
termsOfService: formValues.termsOfService
}
postUser(newUser)
setFormValues(initialFormValues)
}
const onInputChange = evt => {
const name = evt.target.name
const value = evt.target.value
yup
.reach(formSchema, name)
.validate(value)
.then(valid => {
setFormErrors({
...formErrors,
[name]: "",
})
})
.catch(err => {
setFormErrors({
...formErrors,
[name]: err.errors[0]
})
})
setFormValues({
...formValues,
[name]: value,
})
}
const onCheckboxChange = evt => {
const name = evt.target.name
const isChecked = evt.target.checked
yup
.reach(formSchema, name)
.validate(isChecked)
.then(valid => {
//happy path
//CLEAR ERROR
setFormErrors({
...formErrors,
[name]: "",
})
})
.catch(err => {
setFormErrors({
...formErrors,
[name]: err.message
})
})
setFormValues({
...formValues,
[name]: isChecked,
})
}
return (
<div className="App">
<h1>Friend Form</h1>
<Form
values={formValues}
onInputChange={onInputChange}
onCheckboxChange={onCheckboxChange}
onSubmit={onSubmit}
disabled={formDisabled}
errors={formErrors}
/>
{
users.map(user => {
return (
<pre>{JSON.stringify(user, null, 2)}</pre>
)
})
}
</div>
);
}
|
var namespacede_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1errorhandling =
[
[ "PDERuntimeException", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1errorhandling_1_1_p_d_e_runtime_exception.html", "classde_1_1telekom_1_1pde_1_1codelibrary_1_1ui_1_1errorhandling_1_1_p_d_e_runtime_exception" ]
]; |
import React from "react";
function BenefitGroup(props) {
return (
<div className="benefit-group">
<div className="benefit-group-img">{props.icon}</div>
<div className="benefit-group-text">
<p>{props.text}</p>
</div>
</div>
);
}
export default BenefitGroup;
|
import React from 'react';
import RatingStar from '../rating/star_rating_container';
import axios from 'axios';
import SearchNav from '../nav/search_nav_container';
class ReviewForm extends React.Component{
constructor(props){
super(props);
// this.state = this.props.review;
this.state = Object.assign({}, {imageUrls: [],imageFiles: [], loading: true}, this.props.review);
this.handleSubmit = this.handleSubmit.bind(this);
this.starRateValueChange = this.starRateValueChange.bind(this);
this.uploadMultipleFiles = this.uploadMultipleFiles.bind(this);
}
handleSubmit(e){
e.preventDefault();
const formData = new FormData();
formData.append('rate', this.state.rate);
formData.append('comment', this.state.comment);
formData.append('businessId', this.props.businessId);
let {imageFiles} = this.state;
if (imageFiles.length > 0) {
for (let i = 0; i < imageFiles.length; i++) {
formData.append('reviewImage'+i, imageFiles[i],imageFiles[i].name);
}
}
this.props.submitReview(this.props.businessId, formData);
this.props.history.push(`/businesses/${this.props.businessId}`);
}
update(field){
return e => this.setState({[field]: e.currentTarget.value});
}
starRateValueChange(newRate){
this.setState({rate: newRate}, ()=> console.log(this.state))
}
uploadMultipleFiles(e) {
e.preventDefault();
let files = Array.from(e.target.files)
let allowedExtension = ['jpeg', 'jpg', 'png'];
for (let i = 0; i < files.length; i++) {
if(!allowedExtension.includes(e.target.files[0].name.split('.').pop().toLowerCase())){
// window.showAlert("only jpeg, jpg and png are allowed.", 'alert-danger');
return;
}}
for (let i = 0; i < files.length; i++){
let fileReader = new FileReader();
fileReader.onloadend = () => {
this.setState({
imageFiles: [...this.state.imageFiles, files[i]],
imageUrls: [...this.state.imageUrls, fileReader.result]
});
};
fileReader.readAsDataURL(files[i])
}
};
handleRemoveImage(url, file){
let allUrls = this.state.imageUrls;
this.state.imageUrls.forEach((itr,i) => {
if (itr == url) {
allUrls.splice(i, 1)
}
});
let allFiles = this.state.imageFiles;
this.state.imageFiles.forEach((itr,i) => {
if (itr == file) {
allFiles.splice(i, 1)
}
});
this.setState({
imageFiles: [...allFiles],
imageUrls: [...allUrls]
});
}
update(field) {
return (event) => {this.setState({[field]: event.target.value});}
}
render(){
let placeHolder = 'Your review helps others learn about great local businesses.\n\n Please don’t review this business if you received a freebie for writing this review, or if you’re connected in any way to the owner or employees.'
return(
<div>
<div className="search-nav">
<SearchNav />
</div>
<form encType="multipart/form-data" className="review-form" onSubmit={this.handleSubmit}>
<ul className="form-wrapper">
<h3 className="form-header">Business Name</h3>
<li className="form-row">
<div className="inputs-wrapper">
<RatingStar name="rate" onChange={(newRate)=>this.starRateValueChange(newRate)}/>
<textarea name="comment" className="comment-style" rows="10" value={this.state.comment} onChange={this.update('comment')}
placeholder={placeHolder}
></textarea>
</div>
</li>
<li className="form-row">
<h5 className="form-title-2">Attach Photos<span className="subtitle">optional</span></h5>
</li>
<li className="form-row">
<input name="files" type="file" className="form-control-file" id='input_file'
onChange={this.uploadMultipleFiles} multiple />
</li>
<li className="form-row">
<button className="signup-btn" type="submit">{this.props.formType}</button>
</li>
</ul>
</form>
</div>
);
}
}
export default ReviewForm; |
var express = require('express');
var router = express.Router();
var auth2Controller = require('../controllers/auth2Controller.js');
/*
* GET
*/
router.get('/', auth2Controller.handleCallback);
module.exports = router;
|
const router = require('express').Router();
const path = require('path');
const uniqid = require('uniqid');
const db = require('../../db');
const fs = require('fs');
router.post("/", (req, res, next) => {
Promise.resolve()
.then(() => new Promise((resolve, reject) => {
if(!req.isAuthenticated())
{
return reject('Unauthenticated');
}
return resolve();
}))
.then(() => new Promise((resolve, reject) => {
if(!(req.files && req.files.avatar)) return reject('Please upload a file');
return resolve();
}))
.then(() => new Promise((resolve, reject) => {
let name = req.files.avatar.name.split('.');
let ext = name.pop();
name = name.join('');
if(!['png', 'jpg'].includes(ext))
{
return reject('only .png and .jpg files are available');
}
let newName = `${name}${Date.now()}.${ext}`;
let targetPath = path.join(__dirname, `../../public/avatars/${newName}`);
let publicPath = `/public/avatars/${newName}`;
req.files.avatar.mv(targetPath, (err) => {
if(err)
{
return reject(err);
}
return resolve(publicPath);
})
}))
.then((publicPath) => new Promise((resolve, reject) => {
db.query('UPDATE users SET avatar = ? WHERE _ID = ?', [publicPath, req.user]).then(() => {
return resolve(publicPath);
}).catch((err) => {
return reject(err);
})
}))
.then((publicPath) => {
req.ser.json({pathName});
req.ser.done();
})
.catch((err) => {
req.ser.status(500);
req.ser.json({error:err});
req.ser.done();
})
});
module.exports = router;
|
import React from "react";
const Course = ({ courses }) => {
return (
<>
{courses.map((course) => {
return (
<div key={course.id}>
<Header course={course} />
<Content course={course} />
<Total course={course} />
</div>
);
})}
</>
);
};
const Header = ({ course }) => {
return <h2>{course.name}</h2>;
};
const Total = ({ course }) => {
const sum = course.parts.reduce((sum, part) => sum + part.exercises, 0);
return <p>Total of {sum} exercises</p>;
};
const Part = (props) => {
return (
<p>
{props.part.name} {props.part.exercises}
</p>
);
};
const Content = ({ course }) => {
if (typeof course.parts !== "undefined") {
return (
<div>
{course.parts.map((part) => (
<Part part={part} key={part.id} />
))}
</div>
);
} else {
return (
<div>
<p>No course information</p>
</div>
);
}
};
export default Course;
|
import React, { Component } from 'react';
import './userbase-charts.js';
import './userbase.css';
class Userbase extends Component {
constructor () {
super();
this.state = { users: [], non_hormonal: [], triphasic: [], monophasic: [], progestin: [] };
}
render() {
return (
<div id='userbase'>
<svg id="svg1"></svg>
<svg id="svg2"></svg>
<svg id="svg3"></svg>
</div>
)
}
}
export default Userbase;
|
import React, { useState } from 'react';
import {
Container,
Row,
Col,
Breadcrumb,
Card,
Form,
Button
} from "react-bootstrap";
import { AiOutlineHome } from 'react-icons/ai';
import styles from './styles.module.css'
import { connect } from 'react-redux';
import { safeAccess } from '../../../../services/misc';
import CpfCnpj from "@react-br-forms/cpf-cnpj-mask";
import JsonCountry from '../../../../services/stateCountry.json';
import { putUpdateUserCompany } from '../../../../api/company';
import { setUserData } from '../../../../redux/actions/authActions';
import { setUserDataCompany } from '../../../../redux/actions/userDataCompanyActions';
import { useAlert } from "react-alert";
import Reload from '../../../../components/Reload';
function Account(props) {
const alert = useAlert();
const {
userCompany,
setUserData,
setUserCompany
} = props;
const [cpfCnpj, setCpfCnpj] = useState(userCompany.CNPJ);
//const [mask, setMask] = useState("");
const [nameCompany, setNameCompany] = useState(userCompany.name);
const [cnaeCompany, setCnaeCompany] = useState(userCompany.cd_cnae);
const [street, setStreet] = useState(userCompany.nm_rua);
const [state, setState] = useState(userCompany.sg_estado);
const [streetNumber, setStreetNumber] = useState(userCompany.cd_numero);
const [district, setDistrict] = useState(userCompany.nm_bairro);
const [city, setCity] = useState(userCompany.nm_cidade);
const [country] = useState('Brasil');
const [email, setEmail] = useState(userCompany.nm_email);
const [phone, setPhone] = useState(userCompany.cd_telefone);
const [reload, setReload] = useState(false);
const handlerUpdateUser = async () => {
let data = {
cd_empresa: userCompany.cd_empresa,
cd_bairro: userCompany.cd_bairro,
cd_endereco: userCompany.cd_endereco,
cd_estado: userCompany.cd_estado,
cd_pais: userCompany.cd_pais,
cd_cidade: userCompany.cd_cidade,
cd_contato: userCompany.cd_contato,
nameCompany,
cnaeCompany,
cpfCnpj,
street,
district,
streetNumber,
city,
country,
email,
phone,
state
}
const resultUpdate = await putUpdateUserCompany(data);
if (resultUpdate.status === 200) {
setUserCompany(resultUpdate.data.body)
alert.success('Usuário atualizado com sucesso')
setTimeout(function () {
setReload(false)
const token = safeAccess(resultUpdate.data, ['body', 'token'], undefined);
setUserData(token)
window.location.reload();
}, 3000);
} else {
setReload(false)
alert.error('Não foi possível atualizar os dados')
}
}
return (
<Container fluid style={{ padding: 20 }} >
<Card style={{ padding: 40 }} >
<h3> {userCompany.name}</h3>
<Breadcrumb>
<AiOutlineHome style={{ marginRight: 10 }} />
<Breadcrumb.Item href="dashboard">Home / Edite o seu cadastro</Breadcrumb.Item>
</Breadcrumb>
<div style={{ marginTop: 50 }} />
<Row>
<Col xs={12} md={12} lg={12} >
<Row>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Nome da empresa</Form.Label>
<Form.Control size="lg" type="text" placeholder="..."
value={nameCompany}
onChange={(event) => {
setNameCompany(event.target.value);
}}
/>
</Col>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Cnae da empresa</Form.Label>
<Form.Control size="lg" type="text" placeholder="..."
value={cnaeCompany}
onChange={(event) => {
setCnaeCompany(event.target.value);
}}
/>
</Col>
<Col xs={12} sm={12} md={6} lg={4} >
<Form.Label>Digite um CNPJ</Form.Label>
<CpfCnpj
className={styles.cpfCnpj}
placeholder="...."
value={cpfCnpj}
onChange={(event, type) => {
setCpfCnpj(event.target.value);
//setMask(type === "CPF");
}}
/>
</Col>
<h4 style={{ marginTop: 30 }}>Endereço </h4>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Rua</Form.Label>
<Form.Control size="lg" type="text" placeholder="..."
value={street}
onChange={(event) => {
setStreet(event.target.value);
}}
/>
</Col>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Bairro</Form.Label>
<Form.Control size="lg" type="text" placeholder="..."
value={district}
onChange={(event) => {
setDistrict(event.target.value);
}} />
</Col>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Estado</Form.Label>
<Form.Select size="lg" style={{ color: 'gray' }}
onChange={(event) => {
setState(event.target.value);
}}
value={state}
>
{JsonCountry.UF.map((e, key) =>
<option value={e.sigla} key={key}>{e.nome}</option>
)}
</Form.Select>
</Col>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Cidade</Form.Label>
<Form.Control size="lg" type="text" placeholder="..."
value={city}
onChange={(event) => {
setCity(event.target.value);
}}
/>
</Col>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Número</Form.Label>
<Form.Control size="lg" type="text" placeholder="..."
value={streetNumber}
onChange={(event) => {
setStreetNumber(event.target.value);
}}
/>
</Col>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Pais</Form.Label>
<Form.Select size="lg" style={{ color: 'gray' }}>
<option>Brasil</option>
</Form.Select>
</Col>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Email</Form.Label>
<Form.Control size="lg" type="email" placeholder="..."
value={email}
onChange={(event) => {
setEmail(event.target.value);
}}
/>
</Col>
<Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Telefone</Form.Label>
<Form.Control size="lg" type="phone" placeholder="..."
value={phone}
onChange={(event) => {
setPhone(event.target.value);
}}
/>
</Col>
{/* <Col xs={12} sm={12} md={6} lg={4} style={{ padding: 10 }}>
<Form.Label>Digite sua senha</Form.Label>
<Form.Control size="lg" type="password" placeholder="..."
value={passwordOne}
onChange={(event) => {
setPasswordOne(event.target.value);
}}
/>
</Col> */}
<Col xs={12} style={{ marginTop: 50, textAlign: 'center' }}>
<Button className="btnEdit" onClick={() => {
handlerUpdateUser();
setReload(true)
}}>Cadastrar</Button>
</Col>
</Row>
</Col>
</Row>
{reload && (
<Reload />
)}
</Card>
</Container>
)
}
const mapStateToProps = (state) => {
return {
userCompany: safeAccess(state, ['userDataCompanyReduecer', 'data'], undefined),
};
};
const mapDispatchToProps = (dispatch) => {
return {
setUserData: (value) => dispatch(setUserData(value)),
setUserCompany: (value) => dispatch(setUserDataCompany(value)),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Account); |
require('dotenv').config()
module.exports = {
"development": {
username: process.env.DEV_DB_USER,
password: process.env.DEV_DB_PASSWORD,
"database": "lecture",
host: process.env.DEV_DB_HOST,
"dialect": "mysql",
"operatorsAliases": false
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
username: process.env.PROD_DB_USER,
password: process.env.PROD_DB_PASSWORD,
"database": "lecture",
host: process.env.PROD_DB_HOST,
"dialect": "mysql",
"operatorsAliases": false,
"logging": false
}
}
|
import React from 'react';
import Clock from 'react-live-clock';
import ReactFitText from 'react-fittext';
import logo from './logo.svg';
import './App.css';
import { Link } from 'react-router-dom';
import NavigationBar from './NavigationBar';
function App() {
return (
<div className="App">
<NavigationBar/>
<h1 style={{backgroundColor: "gray"}}>Your ticket handeling Solution </h1>
<ReactFitText compressor={9}>
<h6><Clock format={'dddd, MMMM Mo, YYYY, h:mm:ss A'} style={{backgroundColor:'yellow' }} ticking={true} interval={1000} timezone={'US/CT'} /></h6>
</ReactFitText>
</div>
);
}
export default App;
|
import isNumeric from './is-numeric'
export default function isInteger(thing) {
if (isNumeric(thing)) {
const parsed = parseFloat(thing)
return parsed === Math.floor(parsed)
}
else {
return false
}
}
|
import {dbConn} from "../dbutils/db.config"
export default class ClientApp {
constructor({id, nume, prenume, email, parola, varsta, greutate, inaltime, sex, bmi, status, poza,descriere}) {
this.id = id;
this.nume = nume;
this.prenume = prenume;
this.email = email;
this.parola = parola;
this.varsta = varsta;
this.greutate = greutate;
this.inaltime = inaltime;
this.sex = sex;
this.bmi = bmi;
this.status = status;
this.poza = poza;
this.descriere = descriere;
}
static async create(newClient, result) {
dbConn.query("INSERT INTO client set ?", newClient, function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res.insertId);
}
});
};
static async findByEmail(email, result) {
dbConn.query("SELECT * from client where email = ? ", [email], function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
});
};
static async findAll(result) {
dbConn.query("SELECT * from client", function (err, res) {
if (err) {
console.log("error: ", err);
result(null, err);
} else {
result(null, res);
console.log(result)
}
});
};
static async findById(id, result) {
dbConn.query("SELECT * from client where id = ? ", id, function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
});
};
static async findByEmailAndPassword(email, parola, result) {
dbConn.query("SELECT * from client where email = ? and parola=?",[ email, parola], function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
});
};
static async findByEmail(email, result) {
dbConn.query("SELECT * from client where email = ?",[ email], function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
});
};
static async update(client, result) {
dbConn.query("UPDATE client SET nume=?,prenume=?,sex=?,poza=?,descriere=?,varsta=?,inaltime=?,bmi=?,status=? where id=?", [client.nume, client.prenume, client.sex,client.poza,client.descriere,client.varsta,client.inaltime,client.bmi,client.status, client.id], function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
});
}
static async updateGreutate(greutate,bmi,status,id, result) {
dbConn.query("UPDATE client SET greutate=?,bmi=?,status=? where id=?", [ greutate,bmi,status ,id], function (err, res) {
if (err) {
console.log("error: ", err);
result(err, null);
} else {
result(null, res);
}
});
}
} |
'use strict';
/**
* Module dependencies.
*/
const
mongoose = require('mongoose'),
timestamp = require('mongoose-timestamp');
/**
* Query Model Definition.
* @type {Schema}
*/
const QuerySchema = new mongoose.Schema({
from: Object,
query: String,
offset: String
});
QuerySchema.plugin(timestamp);
mongoose.model('Query', QuerySchema);
module.exports = exports = QuerySchema; |
// this is bar.js
console.log('inside bar.js'); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.removeAudiosGroup = exports.findAudioGroup = exports.addAudiosGroup = exports.audioRepo = void 0;
const AudiosGroupRepository_1 = require("./AudiosGroupRepository");
const useCases_1 = require("./useCases");
exports.audioRepo = new AudiosGroupRepository_1.AudiosGroupRepository();
exports.addAudiosGroup = new useCases_1.AddAudiosGroup(exports.audioRepo);
exports.findAudioGroup = new useCases_1.FindAudioGroup(exports.audioRepo);
exports.removeAudiosGroup = new useCases_1.RemoveAudiosGroup(exports.audioRepo);
|
import shared from "../shared";
import sharedWeb from "../shared-web";
describe("ArticleList tests on web", () => {
shared();
sharedWeb();
});
|
const createTrackingObject = user => {
if (!user) {
throw new Error(
"Cannot create inline manual player without an user object!"
);
}
const { id: uid, email, firstName, lastName, createdAt } = user;
return {
uid,
email,
username: email,
name: `${firstName} ${lastName}`,
created: Date.parse(createdAt) / 1000
};
};
export const createInlineManualPlayer = user => {
window.inlineManualTracking = createTrackingObject(user);
return new Promise(resolve => {
// Inline Manual Player script is injected as the first script.
const script = document.getElementsByTagName('script')[0];
// Wait for script to load.
script.addEventListener('load', ev => {
// Create a player instance.
const player =
window.createInlineManualPlayer(window.inlineManualPlayerData);
// Wait for the player instance to finish init.
player.setCallbacks({
onInit: player => resolve(player),
});
});
});
};
export const updateInlineManualPlayer = user => {
window.inlineManualTracking = createTrackingObject(user);
if (
Object.prototype.hasOwnProperty.call(window, "inline_manual_player") &&
Object.prototype.hasOwnProperty.call(window.inline_manual_player, "update")
) {
window.inline_manual_player.update();
}
};
|
const sgMail = require('@sendgrid/mail');
var config = require("../config").config;
function MailHelper(apiKey){
sgMail.setApiKey(apiKey);
}
MailHelper.prototype.send = function(to, subject, message, from){
var promise = new Promise((resolve, reject)=>{
const msg = {
to: to,
from: from || 'jifcom@gmail.com',
subject: subject,
text: message.text
};
sgMail.send(msg).then((res)=>{
resolve(res);
}).catch((err)=>{
reject(err);
})
})
return promise;
}
module.exports = MailHelper; |
import angular from 'angular';
import 'bootstrap/dist/css/bootstrap.css';
import angularMeteor from 'angular-meteor';
import template from './regisComponent.html';
import { Maindocs } from '../../api/assets/maindocs.js';
import { Items } from '../../api/assets/items.js';
import { Vendors } from '../../api/assets/vendors.js';
import { Contracts } from '../../api/assets/contracts.js';
import { Departments } from '../../api/assets/departments.js';
import { Warehouses } from '../../api/assets/warehouses.js';
import { Zones } from '../../api/assets/zones.js';
import { Regisdocs } from '../../api/assets/regisdocs.js';
import { Rfidlist } from '../../api/assets/rfidlist.js';
class RegisComponentCtrl {
constructor($scope) {
$scope.viewModel(this);
this.subscribe('maindocs');
this.subscribe('items');
this.subscribe('vendors');
this.subscribe('contracts');
this.subscribe('departments');
this.subscribe('warehouses');
this.subscribe('zones');
this.subscribe('regisdocs');
this.subscribe('rfidlist');
this.helpers({
items(){
return Items.find({});
},
vendors(){
return Vendors.find({});
},
contracts(){
return Contracts.find({});
},
departments(){
return Departments.find({});
},
warehouses(){
return Warehouses.find({});
},
zones(){
return Zones.find({});
},
regisdocs(){
/*var tmp = Regisdocs.find({}, {rfid:1, _id:0});*/
return Regisdocs.find({});
},
maindocs(){
//return Maindocs.find({});
var doc = Maindocs.find({}, {sort: [ ["createAt", "desc"], ["id", "asc"] ] }).map(
function (item) {
return {id: item.id, balance: item.balanceAmount, item: item};
}
);
var tmp = {};
for(var i in doc){
tmp[doc[i].id] = doc[i].item;
}
var result = [];
for(var i in tmp){
result.push(tmp[i]);
}
return result;
}
});
}
addMaindoc(newMaindoc, rfids){
var tmp = {};
for(var i=0; i<newMaindoc.receiveAmount; i++)
tmp[rfids[i].rfid] = "R";
newMaindoc['rfid'] = tmp;
Session.set("newMaindoc", newMaindoc);
Session.set("newRfids", tmp);
Meteor.call('maindocs.getMaxId', function(error, result){
var maindocs = Session.get("newMaindoc");
maindocs.id = (parseInt(result) + 1) + '';
maindocs.orderAmount = 0;
maindocs.receiveAmount = Number(maindocs.receiveAmount);
maindocs.balanceAmount = maindocs.receiveAmount;
maindocs.receiveDate = new Date(maindocs.receiveDate);
maindocs.actionDate = maindocs.receiveDate;
maindocs.createdAt = new Date();
console.log(maindocs);
//Overide existing session
Session.set("newMaindoc", maindocs);
/*
* Execute insert method which will be a different scope again.
*/
Meteor.call('maindocs.insert', maindocs, function(error, result){
Meteor.call('rfidlist.getMaxId', function(error, result){
var newId = parseInt(result);
var rfidlist = Session.get("newRfids");
var maindocs = Session.get("newMaindoc");
for(r in rfidlist){
var rfid = {};
newId++;
rfid.id = newId + '';
rfid.maindocNo = maindocs.id;
rfid.rfid = r;
rfid.status = rfidlist[r];
rfid.createdAt = new Date();
console.log(rfid);
Meteor.call('rfidlist.insert', rfid, function(error, result){
if(error){
console.log(error);
}
Meteor.call('regisdocs.remove', function(error, result){
if(error){
console.log(error);
}
});
});
}
});
});
});
}
removeMaindoc(id) {
console.log("Remove maindoc id: " + id);
Meteor.call('maindocs.remove', id);
}
getItemById(id){
Meteor.call('items.getById', id);
}
}
export default angular.module('regisComponent', [
angularMeteor
]).component('regisComponent', {
templateUrl: 'imports/components/regisComponent/regisComponent.html',
controller: ['$scope', RegisComponentCtrl]
}).filter('range', function() {
return function(input, total) {
total = parseInt(total);
for (var i=0; i<total; i++)
input.push(i);
return input;
};
}); |
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const safeEval = require('safe-eval');
class MapReduceSlave {
constructor({port, name}) {
this.port = port;
this.app = express();
this.app.use(bodyParser.json());
this.app.post('/map', (req, res) => {
const func = req.body && req.body.func;
if (func && this.callback) {
try {
const executeFunction = safeEval(func);
const result = this.callback(executeFunction);
res.send({ success: true, result });
} catch (error) {
res.send({ success: false, error });
}
} else if (!func) {
res.send({ success: false, error: 'The function is missing in request!' });
} else {
res.send({ success: false, error: 'No callback subscribed yet!' });
}
});
this.app.listen(port, () => {
console.log(`${name} node started and listen ${port} port!`);
});
}
onMap(callback) {
this.callback = callback;
}
}
class MapReduceMaster {
constructor({ port, name, slavePorts }) {
this.port = port;
this.app = express();
this.app.use(bodyParser.json());
this.app.post('/map-reduce', async (req, res) => {
const { mapper, reducer } = req.body;
const mapResults = await Promise.all(slavePorts.map(async (slavePort) => {
const resp = await axios.post(`http://127.0.0.1:${slavePort}/map`, { func: mapper });
const body = resp.data;
if (body.success) {
return body.result;
} else {
throw body.error;
}
}))
const grouped = this.groupByKey(mapResults);
const reducerFunction = safeEval(reducer.func);
try {
for (const key in grouped) {
grouped[key] = grouped[key].reduce(reducerFunction,reducer.start);
}
} catch (error) {
res.send({ success: false, error });
}
res.send({ success: true, result: grouped });
});
this.app.listen(port, () => {
console.log(`${name} node started and listen ${port} port!`);
});
}
groupByKey(maps) {
return maps
.reduce((acc,prev) => [...acc, ...prev],[])
.reduce((acc,prev) => [...acc, ...prev],[])
.reduce((acc,el) => {
if (acc[el.key]) {
acc[el.key].push(el.value);
} else {
acc[el.key] = [el.value];
}
return acc;
}, {});
}
}
class MapReduceClient {
constructor({ masterPort }) {
this.masterPort = masterPort;
}
map(fn) {
this.mapper = fn;
return this;
}
async reduce(fn, start) {
if (!this.mapper) {
throw new Error('Cannot reduce without map function!');
}
const response = await axios.post(`http://127.0.0.1:${this.masterPort}/map-reduce`, {
mapper: this.mapper.toString(),
reducer: {
start,
func: fn.toString(),
}
});
return response.data;
}
}
module.exports = {
MapReduceSlave,
MapReduceMaster,
MapReduceClient,
} |
import React, { Component } from "react";
import { NativeModules } from 'react-native'
const { InAppUtils } = NativeModules
//import {InAppUtils} from 'react-native-in-app-utils';
export const PaymentIOS = () => {
var productIdentifiers = [
'com.MobioTV.app.Okal',
];
//console.log(InAppUtils.loadProducts);
InAppUtils.loadProducts(productIdentifiers,(errorOuter, product) => {
//console.log('errorOuter:', errorOuter)
//console.log('loadProducts:', product);
// console.log('loadProductsError:', error)
InAppUtils.purchaseProduct(productIdentifiers[0], (errorInner, response) => {
//console.log('purchaseProductError:', errorInner);
// console.log('purchaseProduct:', response)
// console.log('error:', error)
// alert(response);
// alert(error);
// NOTE for v3.0: User can cancel the payment which will be available as error object here.
if(response && response.productIdentifier) {
alert('Purchase Successful', 'Your Transaction ID is ' + response.transactionIdentifier);
//unlock store here.
}
});
});
InAppUtils.canMakePayments((canMakePayments) => {
//alert(canMakePayments)
if(!canMakePayments) {
Alert.alert('Not Allowed', 'This device is not allowed to make purchases. Please check restrictions on device');
}
});
}
|
import ExpoPixi, { PIXI } from 'expo-pixi';
export default async context => {
//http://pixijs.io/examples/#/basics/basic.js
const app = ExpoPixi.application({
context,
});
/// TODO: this
var sprites = new PIXI.particles.ParticleContainer(10000, {
scale: true,
position: true,
rotation: true,
uvs: true,
alpha: true,
});
app.stage.addChild(sprites);
// create an array to store all the sprites
var maggots = [];
var totalSprites = app.renderer instanceof PIXI.WebGLRenderer ? 10000 : 100;
for (var i = 0; i < totalSprites; i++) {
// create a new Sprite
var dude = await ExpoPixi.spriteAsync(require('../../assets/pixi/tinyMaggot.png'));
dude.tint = Math.random() * 0xe8d4cd;
// set the anchor point so the texture is centerd on the sprite
dude.anchor.set(0.5);
// different maggots, different sizes
dude.scale.set(0.8 + Math.random() * 0.3);
// scatter them all
dude.x = Math.random() * app.renderer.width;
dude.y = Math.random() * app.renderer.height;
dude.tint = Math.random() * 0x808080;
// create a random direction in radians
dude.direction = Math.random() * Math.PI * 2;
// this number will be used to modify the direction of the sprite over time
dude.turningSpeed = Math.random() - 0.8;
// create a random speed between 0 - 2, and these maggots are slooww
dude.speed = (2 + Math.random() * 2) * 0.2;
dude.offset = Math.random() * 100;
// finally we push the dude into the maggots array so it it can be easily accessed later
maggots.push(dude);
sprites.addChild(dude);
}
// create a bounding box box for the little maggots
var dudeBoundsPadding = 100;
var dudeBounds = new PIXI.Rectangle(
-dudeBoundsPadding,
-dudeBoundsPadding,
app.renderer.width + dudeBoundsPadding * 2,
app.renderer.height + dudeBoundsPadding * 2
);
var tick = 0;
app.ticker.add(function() {
// iterate through the sprites and update their position
for (var i = 0; i < maggots.length; i++) {
var dude = maggots[i];
dude.scale.y = 0.95 + Math.sin(tick + dude.offset) * 0.05;
dude.direction += dude.turningSpeed * 0.01;
dude.x += Math.sin(dude.direction) * (dude.speed * dude.scale.y);
dude.y += Math.cos(dude.direction) * (dude.speed * dude.scale.y);
dude.rotation = -dude.direction + Math.PI;
// wrap the maggots
if (dude.x < dudeBounds.x) {
dude.x += dudeBounds.width;
} else if (dude.x > dudeBounds.x + dudeBounds.width) {
dude.x -= dudeBounds.width;
}
if (dude.y < dudeBounds.y) {
dude.y += dudeBounds.height;
} else if (dude.y > dudeBounds.y + dudeBounds.height) {
dude.y -= dudeBounds.height;
}
}
// increment the ticker
tick += 0.1;
});
};
|
import {Modal, Button} from "react-bootstrap"
import {Link} from "react-router-dom"
function AlertModal(props) {
return (
<Modal
{...props}
size="md"
aria-labelledby="contained-modal-title-vcenter"
centered
>
<Modal.Header closeButton>
<Modal.Title id="contained-modal-title-vcenter">
You are not logged
</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
You must login before. You can login in <Link to="/login">here</Link>
</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={props.onHide}>Close</Button>
</Modal.Footer>
</Modal>
);
}
export default AlertModal |
// Include gulp and webpack
var gulp = require('gulp');
var handlebars = require('gulp-compile-handlebars');
var rename = require('gulp-rename');
var browserSync = require('browser-sync').create();
var del = require('del');
var runSequence = require('run-sequence');
var paths = {
templates: 'src/templates/**/*.hbs'
};
// Start task defs
// 'clean' - clean the build folder
gulp.task('clean', function() {
return del(['./build/**/*']);
});
// 'html' - compiles hbs files to the build folder
gulp.task('html', function () {
var templateData = {
},
options = {
partials : {
defaultContent : '<h2>Condenser</h2>'
},
batch : ['./src/templates/scope-and-closures'],
helpers : {
}
}
return gulp.src('src/templates/*.hbs')
.pipe(handlebars(templateData, options))
.pipe(rename({
extname: ".html",
basename: "index"
}))
.pipe(gulp.dest('./build'));
});
// 'browser-sync' - starts a server at localhost:3000
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "./build"
}
});
gulp.watch("src/templates/**/*.hbs", ['html']);
gulp.watch("build/*.html").on('change', browserSync.reload);
});
// 'default' - separating the build tasks out
gulp.task('default', ['clean'], function(cb) {
runSequence('html', 'browser-sync', cb);
});
|
/**
* Bottom View
* @author Daniel Negri
*/
var styles = require("/styles/BottomViewStyles").bottomViewStyles;
var settings = require('/common/commons').settings;
BottomView = function() {
var self = this;
self.id = "BOTTOM_VIEW";
return self;
};
BottomView.prototype.initialize = function() {
var self = this;
self.view = Titanium.UI.createView(styles.bottomView);
self.initializeLogo();
self.initializeProgressBar();
self.view.show();
};
BottomView.prototype.initializeLogo = function() {
var self = this;
self.logoImage = Titanium.UI.createImageView(styles.olympicsLogo);
self.view.add(self.logoImage);
};
BottomView.prototype.initializeProgressBar = function() {
var self = this;
self.baseLevelBar = Titanium.UI.createView(styles.baseLevelBar);
self.view.add(self.baseLevelBar);
self.currentLevelBar = Titanium.UI.createView(styles.currentLevelBar);
self.view.add(self.currentLevelBar);
self.milestoneLevelBar = Titanium.UI.createView(styles.milestoneLevelBar);
self.view.add(self.milestoneLevelBar);
};
BottomView.prototype.updatedContent = function() {
var self = this;
};
exports.BottomView = BottomView; |
var FolderSeagame = {"Folder":
[
{
"menu_folder":"300",
"menu_pid": "0",
"menu_name": "Sea games 26",
"menu_uname": "SEA GAMES 26",
"menu_path": "/tin/",
"menu_show":"0"
},
{
"menu_folder":"301",
"menu_pid": "TOÀN CẢNH",
"menu_name": "Toàn cảnh",
"menu_uname": "TOÀN CẢNH",
"menu_path": "/tin/toan-canh/",
"menu_sub": "/tin/toan-canh/",
"menu_show":"0"
},
{
"menu_folder":"302",
"menu_pid": "TOÀN CẢNH",
"menu_name": "Chân dung",
"menu_uname": "CHÂN DUNG",
"menu_path": "/tin/chan-dung/",
"menu_sub": "/tin/toan-canh/",
"menu_show":"0"
},
{
"menu_folder":"303",
"menu_pid": "TOÀN CẢNH",
"menu_name": "Tiêu điểm trong ngày",
"menu_uname": "TIÊU ĐIỂM TRONG NGÀY",
"menu_path": "/tin/tieu-diem-trong-ngay/",
"menu_sub": "/tin/toan-canh/",
"menu_show":"0"
},
{
"menu_folder":"304",
"menu_pid": "TOÀN CẢNH",
"menu_name": "Nhật ký seagame 26",
"menu_uname": "NHẬT KÝ SEAGAME 26",
"menu_path": "/tin/nhat-ky-seagames26/",
"menu_sub": "/tin/toan-canh/",
"menu_show":"0"
},
{
"menu_folder":"305",
"menu_pid": "TOÀN CẢNH",
"menu_name": "Hình ảnh đẹp",
"menu_uname": "HÌNH ẢNH ĐẸP",
"menu_path": "/tin/hinh-anh-dep/",
"menu_sub": "/tin/toan-canh/",
"menu_show":"0"
},
{
"menu_folder":"306",
"menu_pid": "LỊCH ĐẤU",
"menu_name": "Lịch đấu",
"menu_uname": "LỊCH ĐẤU",
"menu_path": "/tin/lich-dau/",
"menu_sub": "/tin/",
"menu_show":"0"
},
{
"menu_folder":"307",
"menu_pid": "XẾP HẠNG",
"menu_name": "Xếp hạng",
"menu_uname": "XẾP HẠNG",
"menu_path": "/tin/xep-hang/",
"menu_sub": "/tin/",
"menu_show":"0"
},
{
"menu_folder":"308",
"menu_pid": "BÓNG ĐÁ",
"menu_name": "Bóng đá",
"menu_uname": "BÓNG ĐÁ",
"menu_path": "/tin/bong-da/",
"menu_sub": "/tin/bong-da/",
"menu_show":"0"
},
{
"menu_folder":"309",
"menu_pid": "BÓNG ĐÁ",
"menu_name": "Lịch phát sóng trực tiếp",
"menu_uname": "LỊCH PHÁT SÓNG TRỰC TIẾP",
"menu_path": "/tin/lich-phat-song-truc-tiep/",
"menu_sub": "/tin/bong-da/",
"menu_show":"0"
},
{
"menu_folder":"310",
"menu_pid": "BÓNG ĐÁ",
"menu_name": "Lịch thi đấu bóng đá",
"menu_uname": "LỊCH THI ĐẤU BÓNG ĐÁ",
"menu_path": "/tin/lich-thi-dau-bong-da/",
"menu_sub": "/tin/bong-da/",
"menu_show":"0"
},
{
"menu_folder":"311",
"menu_pid": "BÓNG ĐÁ",
"menu_name": "Góc chuyên gia",
"menu_uname": "GÓC CHUYÊN GIA",
"menu_path": "/tin/goc-chuyen-gia/",
"menu_sub": "/tin/bong-da/",
"menu_show":"0"
},
{
"menu_folder":"312",
"menu_pid": "BÓNG ĐÁ",
"menu_name": "U23 Việt Nam",
"menu_uname": "U23 VIỆT NAM",
"menu_path": "/tin/u23-viet-nam/",
"menu_sub": "/tin/bong-da/",
"menu_show":"0"
},
{
"menu_folder":"313",
"menu_pid": "BÓNG ĐÁ",
"menu_name": "Futsal",
"menu_uname": "FUTSAL",
"menu_path": "/tin/futsal/",
"menu_sub": "/tin/bong-da/",
"menu_show":"0"
},
{
"menu_folder":"314",
"menu_pid": "BÓNG ĐÁ",
"menu_name": "Xệp hạng bóng đá",
"menu_uname": "XẾP HẠNG BÓNG ĐÁ",
"menu_path": "/tin/xep-hang-bong-da/",
"menu_sub": "/tin/bong-da/",
"menu_show":"0"
},
{
"menu_folder":"315",
"menu_pid": "BÓNG ĐÁ",
"menu_name": "Dự đoán trúng thưởng",
"menu_uname": "DỰ ĐOÁN TRÚNG THƯỞNG",
"menu_path": "/tin/du-doan-bong-da/",
"menu_sub": "/tin/bong-da/",
"menu_show":"0"
},
{
"menu_folder":"316",
"menu_pid": "MÔN KHÁC",
"menu_name": "Môn khác",
"menu_uname": "MÔN KHÁC",
"menu_path": "/tin/mon-khac/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"317",
"menu_pid": "MÔN KHÁC",
"menu_name": "Bắn cung,bắn súng",
"menu_uname": "BẮN CUNG,BẮN SÚNG",
"menu_path": "/tin/ban-cung-ban-sung/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"318",
"menu_pid": "MÔN KHÁC",
"menu_name": "Billiards&Snooker",
"menu_uname": "BILLIARDS&SNOOKER",
"menu_path": "/tin/billiards-snooker/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"319",
"menu_pid": "MÔN KHÁC",
"menu_name": "Bóng bàn, bóng rổ",
"menu_uname": "BÓNG BÀN,BÓNG RỔ",
"menu_path": "/tin/bong-ban-bong-ro/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"320",
"menu_pid": "MÔN KHÁC",
"menu_name": "Cầu lông, tennis",
"menu_uname": "CẦU LÔNG, TENNIS",
"menu_path": "/tin/cau-long-tennis/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"321",
"menu_pid": "MÔN KHÁC",
"menu_name": "Cờ vua",
"menu_uname": "CỜ VUA",
"menu_path": "/tin/co-vua/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"322",
"menu_pid": "MÔN KHÁC",
"menu_name": "Điền kinh",
"menu_uname": "ĐIỀN KINH",
"menu_path": "/tin/dien-kinh/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"323",
"menu_pid": "MÔN KHÁC",
"menu_name": "Đua thuyền",
"menu_uname": "ĐUA THUYỀN",
"menu_path": "/tin/dua-thuyen/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"324",
"menu_pid": "MÔN KHÁC",
"menu_name": "Thể dục dụng cụ",
"menu_uname": "THỂ DỤC DỤNG CỤ",
"menu_path": "/tin/the-duc-dung-cu/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"325",
"menu_pid": "MÔN KHÁC",
"menu_name": "Thể thao dưới nước",
"menu_uname": "THỂ THAO DƯỚI NƯỚC",
"menu_path": "/tin/the-thao-duoi-nuoc/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"326",
"menu_pid": "MÔN KHÁC",
"menu_name": "Võ thuật, Quyền anh",
"menu_uname": "VÕ THUẬT, QUYỀN ANH",
"menu_path": "/tin/vo-thuat-quyen-anh/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"327",
"menu_pid": "MÔN KHÁC",
"menu_name": "Môn thể thao khác",
"menu_uname": "MÔN THỂ THAO KHÁC",
"menu_path": "/tin/mon-the-thao-khac/",
"menu_sub": "/tin/mon-khac/",
"menu_show":"0"
},
{
"menu_folder":"328",
"menu_pid": "DỰ ĐOÁN",
"menu_name": "Dự đoán",
"menu_uname": "DỰ ĐOÁN",
"menu_path": "/tin/du-doan-the-le/",
"menu_sub": "/tin/du-doan-the-le/",
"menu_show":"0"
},
{
"menu_folder":"329",
"menu_pid": "DỰ ĐOÁN",
"menu_name": "Thể lệ",
"menu_uname": "THỂ LỆ",
"menu_path": "/tin/du-doan-the-le/",
"menu_sub": "/tin/du-doan-the-le/",
"menu_show":"0"
},
{
"menu_folder":"330",
"menu_pid": "DỰ ĐOÁN",
"menu_name": "Dự đoán huy chương",
"menu_uname": "DỰ ĐOÁN HUY CHƯƠNG",
"menu_path": "/tin/du-doan-huy-chuong/",
"menu_sub": "/tin/du-doan-the-le/",
"menu_show":"0"
},
{
"menu_folder":"331",
"menu_pid": "DỰ ĐOÁN",
"menu_name": "Dự đoán bóng đá",
"menu_uname": "DỰ ĐOÁN BÓNG ĐÁ",
"menu_path": "/tin/du-doan-bong-da/",
"menu_sub": "/tin/du-doan-the-le/",
"menu_show":"0"
},
{
"menu_folder":"332",
"menu_pid": "TIN BÊN LỀ",
"menu_name": "Tin bên lề",
"menu_uname": "TIN BÊN LỀ",
"menu_path": "/tin/tin-ben-le/",
"menu_sub": "/tin/tin-ben-le/",
"menu_show":"0"
},
{
"menu_folder":"333",
"menu_pid": "BẠN ĐỌC VIẾT",
"menu_name": "Bạn đọc viết",
"menu_uname": "BẠN ĐỌC VIẾT",
"menu_path": "/tin/ban-doc-viet/",
"menu_sub": "/tin/ban-doc-viet/",
"menu_show":"0"
},
{
"menu_folder":"334",
"menu_pid": "BẠN ĐỌC VIẾT",
"menu_name": "Tin nhắn cổ động",
"menu_uname": "TIN NHẮN CỔ ĐỘNG",
"menu_path": "/tin/tin-nhan-co-dong/",
"menu_sub": "/tin/ban-doc-viet/",
"menu_show":"0"
},
{
"menu_folder":"335",
"menu_pid": "BẠN ĐỌC VIẾT",
"menu_name": "Tôi & SEA Games",
"menu_uname": "TÔI & SEA GAMES",
"menu_path": "/tin/cam-nhan/",
"menu_sub": "/tin/ban-doc-viet/",
"menu_show":"0"
}
]
};
|
function func() {
console.log("Do nothing");
}
func(); |
const initialState = {
transaction: {},
validating: false,
errors: []
}
const transactionReducer = (state = initialState, action) => {
switch (action.type) {
case 'VALIDATING':
return {...state, validating: action.switch}
case 'PENDING_TRANSACTION':
return {...state, transaction: action.transaction}
case 'COMPLETED_TRANSACTION':
return {...state, transaction: {}}
case 'TRANSACTION_ERRORS':
return {...state, errors: action.errors}
case 'CLEAR_TRANSACTION_ERRORS':
return {...state, errors: []}
default:
return state
}
}
export default transactionReducer
|
import React from 'react';
import { shallow } from 'enzyme';
import renderer from 'react-test-renderer';
import { BrowserRouter as Router } from 'react-router-dom';
import App from './App';
import { Layout } from './../../containers';
import routes from './../../routes';
describe('App suite', () => {
it('renders App without any state injected', () => {
const comp = (
<App
render={({ username, isLoading }) => {
const routing = routes({
username: username,
isLoading: isLoading
});
return (
<Router>
<Layout routes={routing} onChange={() => {}} />
</Router>
);
}}
/>
);
const component = shallow(comp);
const tree = renderer.create(comp).toJSON();
expect(component).toBeDefined();
expect(tree).toMatchSnapshot();
});
});
|
import {
GET_QUESTION_REQUEST,
GET_QUESTION_SUCCESS,
GET_QUESTION_FAILURE
} from '../constants/question.constants';
const questionInstitution = {
loading: false,
question: [],
countQuetion: 0,
qtdQuestion: [],
message: '',
};
export default function questionReducer(state = questionInstitution, action) {
switch (action.type) {
//GET QUESTION
case GET_QUESTION_REQUEST:
return { ...state, loading: true };
case GET_QUESTION_SUCCESS: {
const { data, count } = action;
return { ...state, question: data, countQuetion: count,loading: false, };
}
case GET_QUESTION_FAILURE:
return { ...state, loading: false };
default:
return state;
}
}
|
class PokerHand extends WinningHands {
card_value_count(value) {
let sum= 0;
this.handPile().forEach ( card => {
if ( card.value === value ) {
sum += 1;
}
});
return sum;
}
handTypes() {
return [
'RoyalFlush',
'StraightFlush',
'FourKind',
'House',
'Flush',
'Straight',
'ThreeKind',
'TwoPair',
'OnePair',
'HighCard'
];
}
set_card(n) {
return this.handPile().find ( card => ( this.card_value_count(card.value) == n ));
}
rank() {
for (var i = 0; i < this.handTypes().length; i++) {
const handType = this.handTypes()[i];
if (this[`is${handType}`]()) {
return handType;
}
}
}
isEqual(otherPokerHand) {
return this.rank() === otherPokerHand.rank();
}
isGreaterThan(otherPokerHand) {
return this.handTypes().indexOf(this.rank()) < this.handTypes().indexOf(otherPokerHand.rank());
}
highCard() {
const sorted = sort(this.handPile());
return sorted[sorted.length-1];
}
cardsWithout(valueArr) {
const filtered = [];
this.handPile().forEach( card => {
if ( !valueArr.includes(card.value) ) {
filtered.push(card);
}
});
return filtered;
}
any(valueOrSuit) {
for (var i = 0; i < this.handPile().length; i++) {
if ( this.handPile()[i].value === valueOrSuit ||
this.handPile()[i].suit === valueOrSuit ) {
return true;
}
}
return false;
}
isHighCard() {
return true;
}
isRoyal() {
const royals = this.handPile()[0].royals();
const hand = this.handPile().map(
card => ( card.value ));
let count = 0;
return royals.every( royalValue => (hand.includes(royalValue)) );
}
isOnePair() {
return this.pairs().length === 1;
}
isTwoPair() {
return this.pairs().length === 2;
}
isThreeKind() {
for (var i = 0; i < this.handPile().length; i++) {
if ( this.card_value_count(this.handPile()[i].value) === 3 ) {
return true;
}
}
return false;
}
isFlush() {
const suits = {
clubs: 0,
spades: 0,
hearts: 0,
diamonds: 0
};
for (var i = 0; i < this.handPile().length; i++) {
const suit = this.handPile()[i].suit;
suits[suit] += 1;
if ( suits[suit] > 4 ) {
return true;
}
}
return false;
}
isFourKind() {
for (var i = 0; i < this.handPile().length; i++) {
if ( this.card_value_count(this.handPile()[i].value) === 4 ) {
return true;
}
}
return false;
}
isHouse() {
return this.isThreeKind() && this.isOnePair();
}
isStraightFlush() {
if ( !this.isStraight() ) {
return null;
}
const comparator = new Hand(this.isStraightHelper(), []);
return comparator.isStraight() && comparator.isFlush();
}
isRoyalFlush() {
if ( !this.isStraight() ) {
return null;
}
const comparator = new Hand(this.isStraightHelper(), []);
return comparator.isRoyal() && comparator.isStraightFlush();
}
isStraight() {
return !!this.isStraightHelper();
}
isStraightHelper() {
let straight;
const values = this.hand[0].values();
const hand = unique( sort(this.handPile()).reverse().map(
card => ( card.value )));
if ( this.any('ace') && this.any('two') ) {
straight = values.slice(0, 4).concat(['ace']);
} else {
for (var i = 0; i < hand.length-4; i++) {
const sample = hand.slice(i, i+5);
const start = values.indexOf(sample[sample.length-1]);
straight = values.slice(start, start+5);
if ( straight.every( card => sample.indexOf(card) > -1 ) ) {
return this.handPile().filter( card => (straight.includes(card.value)));
}
}
}
if (straight === undefined) {
return null;
}
if ( straight.every( card => hand.indexOf(card) > -1 ) ) {
return this.handPile().filter( card => (straight.includes(card.value)));
} else {
return null;
}
}
}
|
import React from "react";
import ReactDOM from "react-dom";
import Greeter from "./components/greeter";
import Post from "./components/post";
ReactDOM.render(
<div>
<Greeter message="Students"/>
<Greeter message="Michael"/>
<Greeter />
<Post/>
</div>,
document.getElementById('root'));
|
function submitdoc() {
$("#linktitle").removeClass("error");
$("#dochelp").text("");
if($("#title").val().length == 0){
$("#linktitle").removeClass();
$("#linktitle").addClass("control-group error");
return false;
}
if($("#doc").val().length == 0){
$("#dochelp").text("请选择文件");
return false;
}
if($("#doc").val().split(".").pop() in {doc:1, docx:1, ppt:1, pptx:1, xls:1, pdf:1} ) {
$("#docbtn").addClass("disabled");
}
else {
$("#dochelp").text("暂时不支持该文档格式");
return false;
}
}
|
import propserv from '../services/property-services';
export const search_action = "search_action"
export const display_listings = "display_listings"
export function do_search_listings(obj){
return {
type : search_action,
proptype : obj.proptype,
propadd : obj.propadd,
proplocal : obj.proplocal,
propmun : obj.propmun
}
}
export function do_display_listings(listings){
return {
type : display_listings,
listings : listings
}
} |
const formatTime = date => {
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds()
return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
n = n.toString()
return n[1] ? n : '0' + n
}
function checkPhone(phone) {
var reg = /^1[34578]\d{9}$/
if (reg.test(phone)) {
return true
} else {
return false
}
}
function checkAge(age) {
var reg = /^(?:[1-9][0-9]?|1[01][0-9]|120)$/
if (reg.test(age)) {
return true
} else {
return false
}
}
function checkName(name) {
var reg = /^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,6}$/
if (name.match(reg)) {
return true
} else {
return false
}
}
function checkPwd(pwd) {
if (pwd.length == 0) {
return 0
} else if (pwd.length != 6) {
return -1
} else {
return 1
}
}
function checkIDcard(Idcard) {
var reg = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/
if (reg.test(Idcard)) {
return true
} else {
return false
}
}
module.exports = {
formatTime: formatTime,
checkPhone: checkPhone,
checkName: checkName,
checkIDcard: checkIDcard,
checkAge: checkAge,
checkPwd: checkPwd
}
|
function towns(input){
function roundToTwo(num) {
return +(Math.round(num + "e+2") + "e-2");
}
const result = [];
const [townLabel, latitudeLabel, longitudeLabel] = input[0].substring(2, input[0].length - 2).split(' | ');
for (let i = 1; i < input.length; i++){
let [town, latitude, longitude] = input[i].substring(2, input[i].length - 2).split(' | ');
latitude = Number(Number(latitude).toFixed(2));
longitude = Number(Number(longitude).toFixed(2));
result.push({[townLabel]: town, [latitudeLabel]: latitude, [longitudeLabel]: longitude});
}
return JSON.stringify(result);
}
console.log(towns([
'| Town | Latitude | Longitude |',
'| Sofia | 42.696552 | 23.32601 |',
'| Beijing | 39.913818 | 116.363625 |']
));
console.log(towns([
'| Town | Latitude | Longitude |',
'| Veliko Turnovo | 43.0757 | 25.6172 |',
'| Monatevideo | 34.50 | 56.11 |']
)); |
'use strict';
module.exports = function(Hospital) {
/**
* Model specific code goes here. All business logic
* related to the model like remoteMethods will be defined here
*/
};
|
var tokki = angular.module("directives").directive("nuevaCategoria", ["tokkiApi", "rutService", "$modal",
function(tokkiApi, rutService, $modal){
return {
restrict: "E",
templateUrl: "components/nuevaCategoria/nuevaCategoria.html",
scope: {sm: "=", lg: "=", block: "=", categorias: "="},
link: function(scope, ele, attr){
var modal = $modal({scope: scope, templateUrl: 'components/nuevaCategoria/form.html', show: false});
ele.on("click touchstart", function(){
modal.$promise.then(modal.show);
});
},
controller: ["$scope", "$rootScope", function($scope, $rootScope) {
$scope.nuevaCategoria = function(categoria){
tokkiApi.save({action: "categorias", categoria: categoria})
.$promise.then(function(response){
swal("Categoria " + categoria + " creada", "", "success");
$scope.categorias.push({
id: response.id,
categoria: categoria
})
}, function(response){
swal("ERROR", response.data, "error");
})
}
}]
}
}
])
|
'use strict'
/**
* @module AWSService
* @description AWS Service
*/
module.exports = class AWSService extends Service {
}
|
#!/usr/bin/env node
import { existsSync } from 'fs'
import arg from 'next/dist/compiled/arg/index.js'
import { resolve } from 'path'
import * as Log from '../build/output/log'
import { cliCommand } from '../bin/next'
import build from '../build'
import { printAndExit } from '../server/lib/utils'
const nextBuild: cliCommand = (argv) => {
const validArgs: arg.Spec = {
// Types
'--help': Boolean,
'--profile': Boolean,
'--debug': Boolean,
// Aliases
'-h': '--help',
'-d': '--debug',
}
let args: arg.Result<arg.Spec>
try {
args = arg(validArgs, { argv })
} catch (error) {
if (error.code === 'ARG_UNKNOWN_OPTION') {
return printAndExit(error.message, 1)
}
throw error
}
if (args['--help']) {
printAndExit(
`
Description
Compiles the application for production deployment
Usage
$ next build <dir>
<dir> represents the directory of the Next.js application.
If no directory is provided, the current directory will be used.
Options
--profile Can be used to enable React Production Profiling
`,
0
)
}
if (args['--profile']) {
Log.warn('Profiling is enabled. Note: This may affect performance')
}
const dir = resolve(args._[0] || '.')
// Check if the provided directory exists
if (!existsSync(dir)) {
printAndExit(`> No such directory exists as the project root: ${dir}`)
}
async function preflight() {
const { getPackageVersion } = await import('../lib/get-package-version')
const semver = await import('next/dist/compiled/semver').then(
(res) => res.default
)
const reactVersion: string | null = await getPackageVersion({
cwd: dir,
name: 'react',
})
if (
reactVersion &&
semver.lt(reactVersion, '17.0.1') &&
semver.coerce(reactVersion)?.version !== '0.0.0'
) {
Log.warn(
'React 17.0.1 or newer will be required to leverage all of the upcoming features in Next.js 11.' +
' Read more: https://nextjs.org/docs/messages/react-version'
)
} else {
const reactDomVersion: string | null = await getPackageVersion({
cwd: dir,
name: 'react-dom',
})
if (
reactDomVersion &&
semver.lt(reactDomVersion, '17.0.1') &&
semver.coerce(reactDomVersion)?.version !== '0.0.0'
) {
Log.warn(
'React 17.0.1 or newer will be required to leverage all of the upcoming features in Next.js 11.' +
' Read more: https://nextjs.org/docs/messages/react-version'
)
}
}
}
return preflight()
.then(() => build(dir, null, args['--profile'], args['--debug']))
.catch((err) => {
console.error('')
console.error('> Build error occurred')
printAndExit(err)
})
}
export { nextBuild }
|
import {Row,Col} from 'antd'
import '../static/css/choose.css'
function Choose(){
return (
<>
<div className="choose_middle">
<Row className="choose_middle_ad">
广告位
</Row>
<Row className="choose_middle_two">
<Col span={10}>
<div className="choose_middle_left">
<header>男生盒子</header>
<div className="choose_middle_pic">
<img src="http://bpic.588ku.com/element_pic/17/12/25/8b2d72ee81b9dc1341e61281fabd7254.jpg"/>
</div>
<div className="choose_note">
放入一张男生纸条
</div>
<div className="choose_note">
抽取一张男生纸条
</div>
</div>
</Col>
<Col span={10}>
<div className="choose_middle_right">
<header>女生盒子</header>
<div className="choose_middle_pic">
<img src="http://bpic.588ku.com/element_pic/17/12/25/8b2d72ee81b9dc1341e61281fabd7254.jpg"/>
</div>
<div className="choose_note">
放入一张女生纸条
</div>
<div className="choose_note">
抽取一张女生纸条
</div>
</div>
</Col>
</Row>
</div>
<div className="footer">
<span>玩家须知</span>
</div>
</>
)
}
export default Choose |
import React, {
Component,
} from 'react';
import { SelectOptionStyles, formFieldStyles } from '../styles';
import {
Text,
TouchableOpacity,
View,
} from 'react-native';
import { optionContextTypes, selectOptionPropTypes } from '../propTypes/selectField';
const propTypes = {
...selectOptionPropTypes,
};
const defaultProps = {
};
const contextTypes = {
...optionContextTypes,
};
export default class SelectOption extends Component {
componentWillMount() {
if (this.context.theme) {
this.activeColor = this.context.theme.activeColor;
this.activeTextColor = this.context.theme.activeTextColor;
this.disabledColor = this.context.theme.disabledColor;
this.disabledTextColor = this.context.theme.disabledTextColor;
}
}
handleOnPress = () => {
if (!this.props.disabled) {
this.context.handleOnPress(String(this.props.value));
}
}
render() {
const selected = this.props.selected;
const disabled = this.props.disabled;
return (
<TouchableOpacity
onPress={this.handleOnPress}
disabled={disabled}
style={[{ flex: 1, flexBasis: 0 }]}
>
<View
style={[
SelectOptionStyles.container,
selected && SelectOptionStyles.selected,
selected && Boolean(this.activeColor) && { backgroundColor: this.activeColor },
disabled && SelectOptionStyles.disabled,
disabled && Boolean(this.disabledColor)
&& { backgroundColor: this.disabledColor },
]}
>
<Text
style={[
formFieldStyles.inputText,
SelectOptionStyles.text,
Boolean(this.props.textStyle) && this.props.textStyle,
selected && SelectOptionStyles.selectedText,
selected && Boolean(this.activeTextColor) && { color: this.activeTextColor },
disabled && SelectOptionStyles.disabledText,
disabled && Boolean(this.disabledTextColor)
&& { color: this.disabledTextColor },
]}
>{this.props.text}</Text>
</View>
</TouchableOpacity>
);
}
}
SelectOption.propTypes = propTypes;
SelectOption.defaultProps = defaultProps;
SelectOption.contextTypes = contextTypes;
|
(function() {
'use strict';
angular
.module('captura18App')
.controller('DistritosController', DistritosController);
DistritosController.$inject = ['Distritos'];
function DistritosController(Distritos) {
var vm = this;
vm.distritos = [];
loadAll();
function loadAll() {
Distritos.query(function(result) {
vm.distritos = result;
vm.searchQuery = null;
});
}
}
})();
|
const solution = {
0 : {
type: "number",
equations : [],
variables : {
'':"",
},
solution : 0.3773,
unit: "mm",
},
1 : {
type: "number",
equations : [],
variables : {
'':"",
},
solution : 0.740,
unit: "mm",
},
2 : {
type: "number",
equations : [],
variables : {
'':"",
},
solution : 145.412,
unit: "kN",
},
3 : {
type: "string",
solution : "Tensile",
},
4 : {
type: "number",
equations : [],
variables : {
'':"",
},
solution : 54.588,
unit: "kN",
},
5 : {
type: "string",
solution : "Compressive",
},
}
// Find a way to specify sets of equations being solved at any stage,
// and the values that are assigned to variables in them at that time.
const TRAINING=true;
|
import { titlePlugin } from '@freesewing/plugin-title'
import { base } from './base.mjs'
const pluginTitle = ({ points, Point, paths, Path, macro, options, store, part }) => {
if (['title', 'all'].indexOf(options.plugin) !== -1) {
if (options.titleMeta) store.set('data.for', 'Some user')
else store.unset('data.for')
points.a = new Point(20, 0)
macro('title', {
at: points.a,
nr: options.titleNr,
title: options.titleTitle ? 'Title here' : false,
prefix: 'prefix',
rotation: options.titleRotate,
scale: options.titleScale,
})
// Prevent clipping of text
paths.box = new Path().move(new Point(10, -45)).line(new Point(120, 35)).attr('class', 'hidden')
}
return part
}
export const title = {
name: 'plugintest.title',
after: base,
options: {
titleNr: { count: 1, min: 0, max: 100, menu: 'title' },
titleTitle: { bool: true, menu: 'title' },
titleMeta: { bool: true, menu: 'title' },
titleScale: { pct: 100, min: 10, max: 200, menu: 'title' },
titleRotate: { deg: 0, min: -360, max: 360, menu: 'title' },
},
plugins: titlePlugin,
draft: pluginTitle,
}
|
var nodify = 'phantomjs-nodify/nodify.js';
phantom.injectJs(nodify);
nodify.run(
function() {
var page = require('webpage').create();
var fs = require("fs");
var system = require('system');
var url = require('url');
var knox = require('knox');
var client = knox.createClient(
{
key: 'AKIAJO4HRLEH2M6O62PQ'
, secret: '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'
, bucket: 'pharos.wal.sh'
});
var h3 = '-------------------------------';
var h4 = 'h4. ';
// Use to force a timeout on the page
var timeout = 6000;
page.lastRequest = new Date();
page.onLoadStarted = function () {
// console.log('\n\n--------------- onLoadStarted \n');
// console.log('Start loading...');
};
page.onLoadFinished = function (status) {
// console.log('\n\n--------------- onLoadFinished \n', status);
// console.log('Loading finished.');
};
page.onConsoleMessage = function(msg) {
// console.log(msg);
};
page.onError = function (msg, trace) {
// console.log(msg);
};
page.onResourceRequested = function (request) {
var parsed = url.parse(request.url, true, true);
// console.log(parsed);
// We need to see which of the tags is being called
if(parsed.host.indexOf('bkrtx.com') !== -1) {
console.log('\n\n', h4, 'onResourceRequests : bkrtx.com', parsed.host, parsed.pathname);
}
// Show the site id and the block of parameters
if(parsed.host.indexOf('bluekai.com') !== -1) {
console.log('\n\n', h4, 'onResourceRequests : bkrtx.com', parsed.host, parsed.pathname);
console.log('\n- ', parsed.host, parsed.pathname, '\n{code}\n', parsed.query, '\n{code}');
// var phints = parsed.query.phint;
// for (var i = 0; i < phints; i++) {
// console.log(phints[i]);
// }
}
};
// Find all network requests to the container
page.onResourceReceived = function (response) {
page.lastRequest = new Date();
};
var uriQueue = [
// 'https://www.shopping.hp.com/webapp/shopping/cart_detail.do?view_cart=checkout',
// 'https://www.shopping.hp.com/webapp/shopping/cart_detail.do?view_cart=checkout&hpanalyticsdev=',
'http://www.shopping.hp.com/webapp/shopping/cto.do?hpanalyticsdev=',
// 'http://www.shopping.hp.com/en_US/home-office/-/products/Desktops/HP-TouchSmart-All-in-One/A5W91AV?hpanalyticsdev=',
'http://www.shopping.hp.com/en_US/home-office/-/products/Desktops/HP-TouchSmart-All-in-One/A5W91AV?production',
// 'http://www.hp.com/?production', // custom hosted
'http://www.hp.com/?hpanalyticsdev=', // custom hosted
// 'http://www.nhincuoi.com/hinh-anh-vui-cuoi/anh-hai-huoc-20-06-2012-65251', // coretag
'http://www.cbssports.com/', // static
'http://www.zillow.com/homedetails/1925-W-13th-St-Ashtabula-OH-44004/72398383_zpid/',
'http://wal.sh/bk/tags/tests/100-doTag.html',
'http://wal.sh/bk/tags/tests/102-noframe.html',
'http://wal.sh/bk/tags/tests/103-noframe-script-head.html',
'http://wal.sh/bk/tags/tests/104-frame-script-head.html',
'http://wal.sh/bk/tags/tests/104-doTag-noIframe.html',
'http://www.dailymail.co.uk/tvshowbiz/article-2203532/Titanic-James-Cameron-explains-Jack-climb-raft-Rose.html?ito=feeds-newsxml',
'http://minnesota.cbslocal.com/2012/09/13/mcds-installs-corrected-hmong-billboards/',
'http://wal.sh/bk/tags/tests/130-mobile.html',
'http://wal.sh/bk/tags/tests/test-bk-mobile-requirejs.html',
'http://js.bizographics.com/support/partner.html',
'http://nnl2000.baseball.cbssports.com/',
'http://www.dailymail.co.uk/tvshowbiz/article-2203532/Titanic-James-Cameron-explains-Jack-climb-raft-Rose.html?ito=feeds-newsxml', // /js/bk-static.js
'http://www.shopping.hp.com/en_US/home-office/-/products/Laptops/Laptops',
'http://www.ebay.com/sch/Greek-/37906/i.html',
'http://www.zillow.com/',
'http://www.zillow.com/homes/Houses-in-Jefferson-county-_rb/',
'http://www.moneysupermarket.com/loans/',
'http://www.cyclingnews.com/',
'http://www.gamesradar.com/nhl-13-review/',
'http://www.cio.com/article/716369/CIOs_Look_Ahead_Millennials_Consumer_Tech_and_the_Future?taxonomyId=3185'
];
// use this from the command line
var uri = process.argv[2] ? process.argv[2] : uriQueue[0];
var openUri = function(uri) {
console.log('\n- ', uri);
page.open(
encodeURI(uri),
function (status) {
page.timedout = false;
if (status !== "success") {
console.log("Unable to access network");
} else {
// console.log("Load success");
var meta = page.evaluate(
function() {
delete BKTAG;
var scripts=document.getElementsByTagName('script')[0];
var s=document.createElement('script');
s.async = true;
s.src = 'http://tags.bkrtx.com/js/bk-coretag.js';
scripts.parentNode.insertBefore(s, scripts);
BKTAG.doTag(2);
return {
'title': document.getElementsByTagName('title')[0].innerHTML,
'version': BKTAG.version,
'hpversion': BKTAG.hpversion
};
});
if (meta) {
console.log('\n{code}\n', meta, '\n{code}');
}
}
});
};
openUri(uri);
var intervalPage = setInterval(
function() {
if (new Date() - page.lastRequest > timeout) {
console.log('\n- Run completed: ', new Date());
var completedScreenshot = new Date().getTime() + '.png';
page.render(completedScreenshot);
fs.readFile(
completedScreenshot,
function(err, buf){
var req = client.put(
'/sc/' + completedScreenshot,
{
'Content-Length': buf.length,
'Content-Type': 'image/png'
});
req.on('response', function(res){
if (200 == res.statusCode) {
console.log('saved to %s', req.url);
}
});
req.end(buf);
});
phantom.exit();
}
}, 100);
var intervalQueue = setInterval(
function() {
if (new Date() - page.lastRequest > timeout) {
phantom.exit();
}
}, 100);
});
|
"use strict";
var CommentBox = React.createClass({
displayName: "CommentBox",
render: function render() {
return React.createElement(
"div",
{ className: "commentBox" },
React.createElement(CommentList, null),
React.createElement(CommentForm, null)
);
}
});
var CommentList = React.createClass({
displayName: "CommentList",
render: function render() {
return React.createElement(
"div",
{ className: "commentList" },
React.createElement(
Comment,
{ author: "Mordan Walke", tel: "15311099902" },
"This is *another* comment"
),
React.createElement(
Comment,
{ author: "Pete Hunt", tel: "13011099902" },
"This is one comment",
React.createElement(
"span",
null,
"(welcome)"
)
),
React.createElement(
Comment,
{ author: "Jordan Walke", tel: "15011099902" },
React.createElement(
"div",
null,
"This is *another* comment"
)
)
);
}
});
var CommentForm = React.createClass({
displayName: "CommentForm",
render: function render() {
return React.createElement(
"form",
{ className: "commentForm" },
React.createElement("input", { type: "text", placeholder: "Your name" }),
React.createElement("input", { type: "text", placeholder: "Say something..." }),
React.createElement("input", { type: "submit", value: "Post" })
);
}
});
var Comment = React.createClass({
displayName: "Comment",
render: function render() {
return React.createElement(
"div",
{ className: "comment" },
React.createElement(
"h2",
{ className: "commentAuthor" },
this.props.author,
"-",
this.props.tel
),
this.props.children
);
}
}); |
// app/routes.js
var comment = require('./../models/comment');
var io = require('socket.io')();
module.exports = function(socket) {
// broadcast a user's message to other users
socket.on('send:message', function (data) {
var newMsg = new comment({
username: data.username,
ownerType: data.type,
description: data.message,
room: "school",
ownerId: data.username,
groupId: ""
});
//Save it to database
newMsg.save(function(err, msg){
//Send message to those connected in the room
socket.broadcast.emit('message-sent', {
description: msg.description,
created_at : msg.created_at ,
ownerType : msg.ownerType
});
});
});
socket.on('delete:message', function (data) {
//Save it to database
comment.remove({_id : data.message_id} , function(err, msg){
//Send message to those connected in the room
socket.broadcast.emit('message-deleted', {
reloadList : "true"
});
});
});
//Globals
var defaultRoom = 'school';
var rooms = ['school' , 'classroom' , 'classroom-group' , 'staff-teachers'];
//Emit the rooms array
socket.emit('setup', {
rooms: rooms
});
//Listens for new user
socket.on('new user', function(data) {
data.room = defaultRoom;
//New user joins the default room
socket.join(defaultRoom);
//Tell all those in the room that a new user joined
io.in(defaultRoom).emit('user joined', data);
});
//Listens for switch room
socket.on('switch room', function(data) {
//Handles joining and leaving rooms
//console.log(data);
socket.leave(data.oldRoom);
socket.join(data.newRoom);
io.in(data.oldRoom).emit('user left', data);
io.in(data.newRoom).emit('user joined', data);
});
//Listens for a new chat message
socket.on('new message', function(data) {
//Create message
var newMsg = new comment({
username: data.username,
type: "string",
description: data.message,
room: data.room.toLowerCase(),
ownerId: req.body.username,
groupId: ""
});
//Save it to database
newMsg.save(function(err, msg){
//Send message to those connected in the room
io.in(msg.room).emit('message created', msg);
});
});
}; |
import React from 'react'
import axios from 'axios';
import {ApiRoutes} from './../lib/constants';
import {CirclePicker} from 'react-color'
export default class ActionIconBar extends React.Component {
constructor() {
super();
this.state = {
pickerVisible: false,
noteType: false,
noteId: false
};
}
handleColorChange(color) {
this.apiPatch({"color": color['hex']})
}
circlePicker(color) {
let colors = ["#FFFFFF", "#FFC5C0", "#B7E9FF", "#CFD8DC"];
return (
<div class="color-picker-container">
<CirclePicker color={color}
colors={colors}
onChangeComplete={ this.handleColorChange.bind(this) }
/>
</div>
)
}
onEdit() {
this.props['setRootState']({
modal: true,
noteId: this.props['noteId'],
noteType: this.props['propType']
});
}
onTrash() {
this.apiPatch({"trash": "true"});
}
onUnTrash() {
this.apiPatch({"trash": "false"});
}
apiPatch(data) {
let url = ApiRoutes[this.props['noteType']] + 'id/' + this.props['noteId'] + '/';
axios.patch(url, data)
.then((response) => {
this.props['handleAction']();
})
.catch(function (error) {
console.log('apiPatch error');
});
}
apiDelete() {
let url = ApiRoutes[this.props['noteType']] + 'id/' + this.props['noteId'] + '/';
axios.delete(url)
.then((response) => {
this.props.handleAction();
})
.catch(function (error) {
console.log('apiDelete error');
});
}
regularActionBar(color) {
const onTogglePicker = () => this.setState({pickerVisible: !this.state.pickerVisible});
return (
<div class="mason-icon-bar">
<a href="#" onClick={onTogglePicker}><i class="icon icon-color"/></a>
<a href="#" onClick={() => {
this.onEdit()
}}><i class="icon icon-edit"/></a>
<a href="#" onClick={this.onTrash.bind(this)}><i class="icon icon-trash"/></a>
{ this.state.pickerVisible && this.circlePicker(color) }
</div>
)
}
urlActionBar() {
return (
<div class="mason-icon-bar">
<a href="#" onClick={() => {
this.onEdit()
}}><i class="icon icon-edit"/></a>
<a href="#" onClick={this.onTrash.bind(this)}><i class="icon icon-trash"/></a>
</div>
)
}
imageActionBar() {
return (
<div class="mason-icon-bar mason-icon-bar-url">
<a href="#" onClick={() => {
this.onEdit()
}}><i class="icon icon-edit"/></a>
<a href="#" onClick={this.onTrash.bind(this)}><i class="icon icon-trash"/></a>
</div>
)
}
trashActionBar(className) {
return (
<div class="mason-icon-bar">
<div className={className}>
<a href="#" onClick={this.onUnTrash.bind(this)} className="mason-trash-href">Send back to Notes
|</a>
<a href="#" onClick={this.apiDelete.bind(this)}
className="mason-trash-href mason-trash-red">Remove</a>
</div>
</div>
)
}
render() {
let className = '';
if (this.props['propType'] === "image") {
className = 'mason-trash-full-width'
}
if (this.props['trash'] === true) {
this.props['propType'] = "trash";
}
switch (this.props['propType']) {
case 'regular':
return this.regularActionBar(this.props['color']);
case 'url':
return this.urlActionBar();
case 'image':
return this.imageActionBar();
case 'trash':
return this.trashActionBar(className);
default:
return this.regularActionBar();
}
}
}
|
$(document).ready(function(){
$('.hide_message').click(function(){
$('#message').hide(3000);
});
$('#menu_link').dblclick(function(){
$('#menu').show();
});
}); |
app.service("DemoService", [function(){
return {
title: 'Demo',
};
}]);
|
var licznikUzytychFunkcji=0;
function myFunction(){
document.writeln(5 + 6);
licznikUzytychFunkcji+=1;
}
function onLoad(){
document.getElementById("cztery").addEventListener("click", displayDate);
let button = document.getElementById("szesc");
button.addEventListener("mousedown",tmp());
licznikUzytychFunkcji+=1;
}
function tmp(){
if (event.button == 0) {
console.log("Left button");
} else if (event.button == 1) {
console.log("Middle button");
} else if (event.button == 2) {
console.log("Right button");
}
}
function myFunction2(){
if (document.getElementById("demo").innerText=="xD"){
document.getElementById("demo").innerHTML="XD";
}else{
document.getElementById("demo").innerHTML="xD";
}
licznikUzytychFunkcji+=1;
}
function myFunction3(){
let text = prompt("Wprowadź jakiś tekst", "jakiś tekst");
window.alert("Wprowadziłeś tekst: "+text);
licznikUzytychFunkcji+=1;
}
function doAll(){
document.getElementById("parseInt").value=
parseInt(document.getElementById("parseInt").value,10);
document.getElementById("parseFloat").value=
parseInt(document.getElementById("parseFloat").value)+0.0001;
document.getElementById("losowaLiczba").innerHTML = Math.random()*100;
document.getElementById("floor").value=
Math.floor(document.getElementById("losowaLiczba").innerHTML);
licznikUzytychFunkcji+=1;
}
function displayDate() {
document.getElementById("piec").innerHTML = Date();
licznikUzytychFunkcji+=1;
}
function leep(){
let text="";
let n=document.getElementById("num").value;
let i;
for(i=1;i<=n;i+=1){
text=text+"\n OUTPUT: "+fibonacci(i);
}
window.alert(text);
licznikUzytychFunkcji+=1;
}
function leep2() {
let text="";
let n=document.getElementById("num2").value;
var i = 0;
while (i < n) {
text = text+"While ";
i+=1;
}
window.alert(text);
licznikUzytychFunkcji+=1;
}
function leep3() {
let text="";
let n=document.getElementById("num3").value;
var i = 0;
do {
text = text+"Do-While ";
i+=1;
}
while(i < n);
window.alert(text);
licznikUzytychFunkcji+=1;
}
function mySwitch() {
let day="";
switch (new Date().getDay()) {
case 0:
day = "Niedziela";
break;
case 1:
day = "Poniedzialek";
break;
case 2:
day = "Wtorek";
break;
case 3:
day = "Sroda";
break;
case 4:
day = "Czwartek";
break;
case 5:
day = "Piatek";
break;
case 6:
day = "Sobota";
}
window.alert(day);
}
function fibonacci(n) {
if (n === 0) return 0;
else if (n === 1 || n === 2)
return 1;
else if (n > 2) {
var a = 1;
var b = 1;
var c = 0;
for (var i = 0; i < n - 2; i++) {
c = a + b;
a = b;
b = c;
}
return c;
}
}
function ilefunkcji(){
licznikUzytychFunkcji+=1;
window.alert(licznikUzytychFunkcji);
}
function textarea(){
let text=document.getElementById("textarea").value;
window.alert("Bez spacji: "+letterCounter(text)+"\n"+"Ze spacjalmi: "+text.length+"\n"+"Liczba słów: "+counter(text));
}
function counter(str) {
var value = str;
var regex = /\s+/gi;
var wordCount = value.trim().replace(regex, ' ').split(' ').length;
return wordCount;
}
function letterCounter(str) {
var letters = 0;
var alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var ar = alphabet.split("");
for (var i=0; i<str.length;i++) {
if (ar.indexOf(str[i]) > -1) {
letters = letters + 1;
}
}
return letters;
} |
import React from 'react';
import { Link } from 'react-router-dom'
import { connect } from 'react-redux';
import {
Card,
CardImg,
CardHeader,
CardBody,
CardTitle,
CardText } from 'reactstrap';
import { showSource, showArticle } from '../../store'
import '../../stylesheets/newsfeed.css'
const SearchCar = ({source: {_id, img}, showSource}) => {
return(
<div className="search-card" onClick={() => showSource(_id)}>
<Link to= {{ pathname: `/source/${_id}`}}>
<img className="caro" src={img} alt="" />
</Link>
</div>
)
}
const CaroCard = ({source: {_id, img}, showSource}) => {
return(
<div onClick={() => showSource(_id)}>
<Link to= {{ pathname: `/source/${_id}`}}>
<img className="caro" src={img} alt="" />
</Link>
</div>
)
}
export const NewsCard = ({article:{ _id, author, title, category, urlToImage, description, url, source}, showArticle}) => {
let hostname
if(!source){
if (url.indexOf("//") > -1) {
hostname = url.split('/')[2];
}
else {
hostname = url.split('/')[0];
}
}
return(
<Card>
{source ?
<CardHeader tag="h3">{source.name}</CardHeader>
:
<CardHeader tag="h3">{hostname}</CardHeader>
}
<Link to={{pathname: `/article/${_id}`}}>
<CardImg top width="100%" src={urlToImage} alt="Card image cap" onClick={() => showArticle(_id)}/>
</Link>
<CardBody>
<CardTitle className="desc">{title}</CardTitle>
<CardTitle>BY: {author || "Suzie McGee"}</CardTitle>
<CardText>{description}</CardText>
</CardBody>
</Card>
)
}
const mapDispatchToCarousel = (dispatch) => {
return {
showSource: (id) => {
return dispatch(showSource(id))
}
}
}
const mapDispatchToFeed = (dispatch) => {
return {
showArticle: (id) => {
return dispatch(showArticle(id))
}
}
}
export const CarouselCard = connect (null, mapDispatchToCarousel)(CaroCard)
export const SearchCard = connect (null, mapDispatchToCarousel)(SearchCar)
export const NewsFeedCard = connect(null, mapDispatchToFeed)(NewsCard)
|
var twitterData = require('./keys.js');
var spotifyData = require('spotify');
var request = require('request');
var inquirer = require('inquirer');
var fs = require('fs');
var passingData = false;
console.log("");
inquirer.prompt([
{
type: "list",
message: 'Select a command',
choices: ['my-tweets', 'spotify-this-song', 'movie-this', 'do-what-it-says'],
name: "files",
}
]).then(function (argument) {
if (argument.files === 'my-tweets') {
selectTweets();
}
if (argument.files === 'spotify-this-song') {
selectSong(null, passingData);
}
if (argument.files === 'movie-this') {
selectMovie(null, passingData);
}
if (argument.files === 'do-what-it-says') {
fs.readFile("random.txt", "utf8", function (error, data) {
// console.log(data);
var dataArr = data.split(',');
switch (dataArr[0]) {
case 'my-tweets':
selectTweets();
break;
case 'spotify-this-song':
passingData = true;
selectSong(dataArr[1], passingData);
break;
case 'movie-this':
passingData = true;
selectMovie(dataArr[1], passingData)
break;
}
});
}
function selectTweets() {
twitterData.twitterKeys.get('statuses/user_timeline', {
count: 10
}, function (error, tweets, response) {
if (error) throw error;
// console.log(JSON.stringify(tweets, null, 3));
// console.log(tweets.length);
for (var i = 0; tweets.length > i; i++) {
console.log(tweets[i].text);
console.log('\n')
}
});
}
function selectSong(passedSong, passingData) {
if (passingData === false) {
inquirer.prompt([
{
type: "input",
message: 'Select a song data',
name: "songName",
}
]).then(function (song) {
spotifyData.search({
type: 'track',
query: song.songName,
}, function (err, data) {
if (err) {
console.log('Error occurred: ' + err);
return;
}
// console.log(JSON.stringify(data.tracks.items[0], null, 2));
// console.log(JSON.stringify(data.tracks.items[0].name));
console.log("");
console.log("Artist Name: " + data.tracks.items[0].artists[0].name);
console.log("Song Title: " + data.tracks.items[0].name);
console.log("Song Preview: " + data.tracks.items[0].preview_url);
console.log("Song Album: " + data.tracks.items[0].album.name);
console.log("");
});
})
} else {
spotifyData.search({
type: 'track',
query: passedSong,
}, function (err, data) {
if (err) {
console.log('Error occurred: ' + err);
return;
}
// console.log(JSON.stringify(data.tracks.items[0], null, 2));
// console.log(JSON.stringify(data.tracks.items[0].name));
console.log("");
console.log("Artist Name: " + data.tracks.items[0].artists[0].name);
console.log("Song Title: " + data.tracks.items[0].name);
console.log("Song Preview: " + data.tracks.items[0].preview_url);
console.log("Song Album: " + data.tracks.items[0].album.name);
console.log("");
});
}
}
function selectMovie(passingMovieName, passingData) {
if (passingData === false) {
console.log("");
inquirer.prompt([
{
type: "input",
message: 'Select a Movie',
name: "movieName",
}
]).then(function (movie) {
request.get("http://www.omdbapi.com/?t=" + movie.movieName + "+&y=&plot=short&tomatoes=true&r=json", function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Movie Name:-------- " + JSON.parse(body)["Title"] + "\n");
console.log("Movie Year: " + JSON.parse(body)["Year"] + "\n");
console.log("Movie imdbRating: " + JSON.parse(body)["imdbRating"] + "\n");
console.log("This movie was produce in: " + JSON.parse(body)["Country"] + "\n");
console.log("Movie Language: " + JSON.parse(body)["Language"] + "\n");
console.log("Plot: " + JSON.parse(body)["Plot"] + "\n");
console.log("Actors: " + JSON.parse(body)["Actors"] + "\n");
console.log("Rotten Tomato Rating: " + JSON.parse(body)["tomatoRating"] + "\n");
console.log("Rotten Tomato URL: " + JSON.parse(body)["tomatoURL"] + "\n");
}
})
})
}else{
request.get("http://www.omdbapi.com/?t=" + passingMovieName + "+&y=&plot=short&tomatoes=true&r=json", function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Movie Name:-------- " + JSON.parse(body)["Title"] + "\n");
console.log("Movie Year: " + JSON.parse(body)["Year"] + "\n");
console.log("Movie imdbRating: " + JSON.parse(body)["imdbRating"] + "\n");
console.log("This movie was produce in: " + JSON.parse(body)["Country"] + "\n");
console.log("Movie Language: " + JSON.parse(body)["Language"] + "\n");
console.log("Plot: " + JSON.parse(body)["Plot"] + "\n");
console.log("Actors: " + JSON.parse(body)["Actors"] + "\n");
console.log("Rotten Tomato Rating: " + JSON.parse(body)["tomatoRating"] + "\n");
console.log("Rotten Tomato URL: " + JSON.parse(body)["tomatoURL"] + "\n");
}
})
}
}
}) |
$(document).ready(function() {
"use strict";
var av_name = "FibTreeCON";
var av = new JSAV(av_name);
var fib = [1,1,2,3,5,8,13]
var val;
var fibtree = av.ds.tree({nodegap: 20});
// Slide 1
fibtree.root("7");
val = "7" + "<br>" + "-" ;//fib[6].toString();
fibtree.root().value(val);
fibtree.layout();
av.umsg("Let's see how the recursive process works when we compute the value for Fib(7). We will build a tree showing the recursive function calls that take place. In each node, the top half (in blue) shows the parameter values on the recursive call, while the bottom half (in red) shows the return value for the call. So, the root of the tree represents the initial call to the function with an input of 7.");
av.displayInit();
// Slide 2
fibtree.root().addChild("6");
val = "6" + "<br>" + "-" ;// fib[4].toString();
fibtree.root().child(0).value(val);
av.umsg("To compute Fib(7), the algorithm will make recursive calls to compute Fib(6) and Fib(5). We start with the first call to Fib(6).");
fibtree.layout();
av.step();
// Slide 3
fibtree.root().child(0).addChild("5");
val = "5" + "<br>" + "-" ;//fib[2].toString();
fibtree.root().child(0).child(0).value(val);
av.umsg("To compute Fib(6), we will need to calculate Fib(5) and Fib(4). We first call Fib(5).");
fibtree.layout();
av.step();
// Slide 4
av.umsg("We continue in this way making recursive calls, until we reach a base-case at Fib(2). This gets computed and returns the value 1.");
fibtree.root().child(0).child(0).addChild("4");
val = "4" + "<br>" + "-" ;//fib[3].toString();
fibtree.root().child(0).child(0).child(0).value(val);
fibtree.root().child(0).child(0).child(0).addChild("3");
val = "3" + "<br>" + "-" ;//fib[3].toString();
fibtree.root().child(0).child(0).child(0).child(0).value(val);
fibtree.root().child(0).child(0).child(0).child(0).addChild("2");
val = "2" + "<br>" + fib[1].toString();
fibtree.root().child(0).child(0).child(0).child(0).child(0).value(val);
fibtree.layout();
av.step();
// Slide 5
av.umsg("Now, to finish computing Fib(3) we have to also calculate Fib(3-2) = Fib(1) by making a recursive call. This is also a base-case with value 1");
fibtree.root().child(0).child(0).child(0).child(0).addChild("2");
val = "1" + "<br>" + fib[0].toString();
fibtree.root().child(0).child(0).child(0).child(0).child(1).value(val);
fibtree.layout();
av.step();
// Slide 6
av.umsg("At this point, the recusion process pops back up to sum the two values from the subproblems for Fib(3). We get Fib(3) = Fib(3-1) + Fib(3-2) = 1 + 1 = 2");
val = "3" + "<br>" + fib[2].toString();
fibtree.root().child(0).child(0).child(0).child(0).value(val);
fibtree.layout();
av.step();
// Slide 7
av.umsg("Now the recursion pops back to computing Fib(4). This requires making the second recursive call to Fib(4-2) = Fib(2). This will be a base-case again, which returns the value 1. But notice that we already solved this subproblem earlier!");
fibtree.root().child(0).child(0).child(0).addChild("2");
val = "2" + "<br>" + fib[1].toString();
fibtree.root().child(0).child(0).child(0).child(1).value(val);
fibtree.layout();
av.step();
// Slide 8
av.umsg("Now we have the results of both recusive calls needed to compute Fib(4), and can return the value Fib(4) = Fib(4-1) + Fib(4-2) = 2 + 1 = 3");
val = "4" + "<br>" + fib[3].toString();
fibtree.root().child(0).child(0).child(0).value(val);
fibtree.layout();
av.step();
// Slide 9
av.umsg("Popping the recursion stack, we return to computing the solution for Fib(5). To do this, we have to compute Fib(5-2) = Fib(3)... again!");
fibtree.root().child(0).child(0).addChild("3");
val = "3" + "<br>" + "-"; // fib[3].toString();
fibtree.root().child(0).child(0).child(1).value(val);
fibtree.root().child(0).child(0).child(1).addChild("2");
val = "2" + "<br>" + fib[1].toString();
fibtree.root().child(0).child(0).child(1).child(0).value(val);
fibtree.root().child(0).child(0).child(1).addChild("1");
val = "1" + "<br>" + fib[0].toString();
fibtree.root().child(0).child(0).child(1).child(1).value(val);
fibtree.layout();
val = "3" + "<br>" + fib[2].toString();
fibtree.root().child(0).child(0).child(1).value(val);
fibtree.layout();
av.step();
// Slide 10
av.umsg("Which lets us compute Fib(5) = 5.");
val = "5" + "<br>" + fib[4].toString();
fibtree.root().child(0).child(0).value(val);
fibtree.layout();
av.step();
// Slide 11
av.umsg("Now let's skip ahead to show the state of the tree after we have completed calculating Fib(6) and popped the recursion stack back to the root of the tre. Notice there are a lot of repeating numbers in blue.");
fibtree.root().child(0).addChild("4");
val = "4" + "<br>" + "-" ;//fib[2].toString();
fibtree.root().child(0).child(1).value(val);
fibtree.root().child(0).child(1).addChild("3");
val = "3" + "<br>" + "-" ;//fib[2].toString();
fibtree.root().child(0).child(1).child(0).value(val);
fibtree.root().child(0).child(1).child(0).addChild("2");
val = "2" + "<br>" + fib[1].toString();
fibtree.root().child(0).child(1).child(0).child(0).value(val);
fibtree.root().child(0).child(1).child(0).addChild("1");
val = "1" + "<br>" + fib[0].toString();
fibtree.root().child(0).child(1).child(0).child(1).value(val);
val = "3" + "<br>" + fib[2].toString();
fibtree.root().child(0).child(1).child(0).value(val);
fibtree.root().child(0).child(1).addChild("2");
val = "2" + "<br>" + fib[1].toString();
fibtree.root().child(0).child(1).child(1).value(val);
val = "4" + "<br>" + fib[3].toString();
fibtree.root().child(0).child(1).value(val);
val = "6" + "<br>" + fib[5].toString();
fibtree.root().child(0).value(val);
fibtree.layout();
av.step();
// Slide 12
av.umsg("Now we have to calculate Fib(5). Which, by the way, we have calcualted before.");
fibtree.root().addChild("5");
val = "5" + "<br>" + "-" ;// fib[4].toString();
fibtree.root().child(1).value(val);
fibtree.layout();
av.step();
// Slide 13
av.umsg("Here is the state of the recursion tree after calculating Fib(5).");
fibtree.root().child(1).addChild("4");
val = "4" + "<br>" + fib[3].toString();
fibtree.root().child(1).child(0).value(val);
fibtree.root().child(1).child(0).addChild("3");
val = "3" + "<br>" + fib[2].toString();
fibtree.root().child(1).child(0).child(0).value(val);
fibtree.root().child(1).child(0).child(0).addChild("1").addChild("0");
val = "2" + "<br>" + fib[1].toString();
fibtree.root().child(1).child(0).child(0).child(0).value(val);
val = "1" + "<br>" + fib[0].toString();
fibtree.root().child(1).child(0).child(0).child(1).value(val);
fibtree.root().child(1).child(0).addChild("2")
val = "2" + "<br>" + fib[1].toString();
fibtree.root().child(1).child(0).child(1).value(val);
fibtree.root().child(1).addChild("3");
val = "3" + "<br>" + fib[2].toString();
fibtree.root().child(1).child(1).value(val);
fibtree.root().child(1).child(1).addChild("1").addChild("1");
val = "2" + "<br>" + fib[1].toString();
fibtree.root().child(1).child(1).child(0).value(val);
val = "1" + "<br>" + fib[0].toString();
fibtree.root().child(1).child(1).child(1).value(val);
val = "5" + "<br>" + fib[4].toString();
fibtree.root().child(1).value(val);
fibtree.layout();
av.step();
// Slide 14
av.umsg("We finally have the pieces needed to compute Fib(7) = Fib(7-1) + Fib(7-2) = 8 + 5 = 13 ");
val = "7" + "<br>" + fib[6].toString();
fibtree.root().value(val);
fibtree.layout();
av.recorded();
});
|
FC.init = function() {
// a komponensek összedrótozása pubsub event-ekkel
b = FC.pubsub;
b.subscribe('init', FC.store, 'loadPersons');
b.subscribe('init', FC.ui.nav, 'renderMainMenu');
b.subscribe('init', FC.ui, 'initHandlers');
b.subscribe('main-page', FC.ui.nav, 'renderMainMenu');
b.subscribe('main-page', FC.ui.cont, 'renderSetList');
b.subscribe('persons-loaded', FC.store, 'loadSets');
b.subscribe('sets-loaded', FC.ui.cont, 'renderSetList');
b.subscribe('load-set', FC.store, 'loadSet');
b.subscribe('set-loaded', FC.ui.cont, 'renderSet');
b.subscribe('set-loaded', FC.ui.nav, 'renderSetMenu');
b.subscribe('set-list', FC.ui.cont, 'renderSetList');
b.subscribe('create-card', FC.store, 'createCard');
b.subscribe('card-created', FC.ui.cont, 'addCardToSet');
b.subscribe('delete-card', FC.store, 'deleteCard');
b.subscribe('card-deleted', FC.ui.cont, 'deleteCardFromSet');
b.subscribe('edit-card', FC.ui.cont, 'editCard');
b.subscribe('update-card', FC.store, 'updateCard');
b.subscribe('show-card', FC.ui.cont, 'showCard');
b.subscribe('new-set', FC.ui.cont, 'renderNewSet');
b.subscribe('create-set', FC.store, 'createSet');
b.publish('init');
// FC.testDelete();
};
gadgets.util.registerOnLoadHandler(FC.init);
|
/**
* @constant
* @memberof module:CustomUi
* @type {String}
* @default
*/
export const CUSTOM_UI_EVENT_PREFIX = 'ui';
/**
* @constant
* @memberof module:CustomUi
* @type {String}
* @default
*/
export const MEISTER_DATA_ID_ATTR = 'data-mstr-id';
/**
* @constant
* @memberof module:CustomUi
* @type {String}
* @default
*/
export const MEISTER_DATA_EVENTS_ATTR = 'data-mstr-events';
/**
* @constant
* @memberof module:CustomUi
* @type {String}
* @default
*/
export const MEISTER_DATA_STANDARD_ATTR = 'data-mstr-standard';
/**
* @constant
* @memberof module:CustomUi
* @type {String}
* @default
*/
export const MEISTER_DATA_DIRECTIVE_ATTR = 'data-mstr-directive';
|
'use strict';
var StandBot = require('../lib/standbot');
var schedule = require('node-schedule');
var model = require('../lib/model.js');
var moment = require('moment-timezone');
var config = require('../config.js');
var myModel = new model(config.dbName);
var listUsers = [];
var bot = new StandBot({
token: config.slack.token,
name: config.slack.botName
});
bot.run();
// Open RTM
bot.openRTM(function(server) {
console.log('Server launched');
console.log('---------------');
server.on('message', function(response) {
response = JSON.parse(response);
var doAskBot = true;
if(response.type == 'message') {
// Edited message
if(typeof response.subtype != 'undefined' && response.subtype == 'message_changed') {
for(var i = 0; i < listUsers.length; i++) {
for(var j = 0; j < listUsers[i].questions.length; j++) {
var ts = listUsers[i].questions[j].ts;
if(ts == response.previous_message.ts) {
listUsers[i].questions[j].answer = response.message.text;
// Save questions
saveAnswers(listUsers[i]);
if(listUsers[i].questions[j].posted_ts
&& listUsers[i].questions[j].posted_channel) {
updateChannelMessage(listUsers[i]);
}
}
}
}
}
// Posted new message
else {
if(listUsers.length > 0) {
for (var i = 0; i < listUsers.length; i++) {
if (listUsers[i].im_id == response.channel
&& listUsers[i].id == response.user
&& listUsers[i].waiting_answer) {
doAskBot = false;
// We receive a message from a user present in the UserList
// User is responding to an answer
var question_id = listUsers[i].waiting_answer;
for (var j = 0; j < listUsers[i].questions.length; j++) {
if (question_id == listUsers[i].questions[j].id) {
listUsers[i].questions[j].answer = response.text;
listUsers[i].questions[j].ts = response.ts;
}
}
listUsers[i].waiting_answer = false;
// Save questions
var user = listUsers[i];
saveAnswers(user, function(response) {
sendQuestion(user, function (response) {
if (!response) {
bot.sendMessage(user.id, {text: 'Merci !'});
sendToChannel(user, config.channel);
}
});
});
}
}
}
if(doAskBot) {
askBot(response);
}
}
}
});
});
// Get user when launch the script (we need to always have this users)
getUsers();
// Launch scheduled program
schedule.scheduleJob('0 ' + config.schedule.minute + ' * * * 1-5', function() {
getUsers(function() {
for(var i = 0; i < listUsers.length; i ++) {
if(config.schedule.hour == moment().tz(listUsers[i].tz).format("HH")) {
sendQuestion(listUsers[i]);
}
}
});
});
/**
* Get list Users
* @param callback
*/
function getUsers(callback) {
bot.getChannel(config.channel, function(id) {
bot.getMembersChannel(id, function(response) {
bot.getDetailUsersList(response, function(response) {
listUsers = response;
myModel.getQuestions(function(response) {
for(var i = 0; i < listUsers.length; i++) {
var questions = [];
for(var j = 0; j < response.length; j++) {
var q = new Object();
q.id = response[j].id;
q.value = response[j].value;
q.answer = null;
q.ts = null;
q.posted_ts = null;
q.posted_channel = null;
if(listUsers[i].tz !== 'undefined') {
listUsers[i].tz = 'Europe/Paris';
}
q.date = moment().tz(listUsers[i].tz).format("YYYY-MM-DD");
q.color = response[j].color;
questions.push(q);
}
listUsers[i].questions = questions;
listUsers[i].waiting_answer = false;
}
bot.getImListForUser(listUsers, function (response) {
listUsers = response;
if(typeof callback === 'function') {
callback();
}
});
});
});
});
});
}
/**
* Send next Question to user
*
* @param object user
* @param function callback
*/
function sendQuestion(user, callback) {
var askQuestion = false;
if(user.waiting_answer == false) {
var listQIds = [];
for(var i = 0; i < user.questions.length; i++) {
listQIds.push(user.questions[i].id);
}
var date = moment().tz(user.tz).format("YYYY-MM-DD");
myModel.getAnswers(
user.id,
date,
listQIds.join(),
function(answers) {
for(var i = 0; i < user.questions.length; i++) {
for(var j = 0; j < answers.length; j++) {
if(answers[j].question_id == user.questions[i].id) {
user.questions[i].answer = answers[j].answer;
user.questions[i].posted_ts = answers[j].posted_ts;
}
}
if(user.waiting_answer == false && (user.questions[i].answer == null || user.questions[i].answer == 'null')) {
user.waiting_answer = user.questions[i].id;
askQuestion = true;
var message = new Object();
message.text = user.questions[i].value;
message.attachments = null;
bot.sendMessage(user.im_id, message);
}
}
if(typeof callback === 'function') {
callback(askQuestion);
}
}
);
} else {
if(typeof callback === 'function') {
callback(askQuestion);
}
}
}
/**
* Save user answers
*
* @param object user
*/
function saveAnswers(user, callback) {
var iterator = 0;
for(var i = 0; i < user.questions.length; i++) {
myModel.saveAnswer(
user.id,
user.questions[i].id,
user.questions[i].answer,
user.questions[i].date,
user.questions[i].posted_ts,
function(response) {
iterator++;
if(iterator == user.questions.length && typeof callback === 'function') {
callback(response);
}
}
);
}
}
/**
* Send questions results to channel
*
* @param object user
* @param string channel
*/
function sendToChannel(user, channel) {
var message = generateChannelMessage(user);
bot.sendPersonnalizedMessage(channel, message, user.name, user.profile.image_48, function(response) {
for(var i = 0; i < user.questions.length; i++) {
user.questions[i].posted_ts = response.message.ts;
user.questions[i].posted_channel = response.channel;
myModel.saveAnswer(
user.id,
user.questions[i].id,
user.questions[i].answer,
user.questions[i].date,
response.message.ts
);
}
});
}
/**
* Update a message already send to a channel
*
* @param object user
* @param string channel
*/
function updateChannelMessage(user) {
var message = generateChannelMessage(user);
bot.updateMessage(user.questions[0].posted_ts, user.questions[0].posted_channel, message);
}
/**
* Generate the message to send to the channel
*
* @param object user
* @returns {Object}
*/
function generateChannelMessage(user) {
var message = new Object();
message.text = user.name + ' a posté un statut : ' + moment().tz(user.tz).format('D MMM, YYYY');
var attachments = [];
for(var i = 0; i < user.questions.length; i++) {
var attachment = new Object();
attachment.fallback = user.questions[i].value + '\n' + user.questions[i].answer;
attachment.color = user.questions[i].color;
attachment.title = user.questions[i].value;
attachment.text = user.questions[i].answer;
// To enable markdown in attachment (See https://api.slack.com/docs/message-formatting#message_formatting)
attachment.mrkdwn_in = ['text', 'pretext'];
attachments.push(attachment);
}
message.attachments = JSON.stringify(attachments);
return message;
}
/**
* check message when you ask the bot
*
* @param message
*/
function askBot(message) {
var isBot = false;
// Check if sender message is bot
if(message.user_profile) {
if(message.user_profile.name == config.slack.botName) {
isBot = true;
}
}
// asking bot
if(message.text && false === isBot) {
getBotImList(function(botImList) {
for(var i in botImList) {
if(message.channel == botImList[i].id) {
// asking resume
if (message.text.toLowerCase().indexOf('resume') > -1) {
var words = message.text.split(' ');
var users = [];
var date = null;
for (var i = 0; i < words.length; i++) {
// Check we have an user
if (words[i].indexOf('<@') == 0) {
users.push(words[i].substring(2, words[i].length - 1));
}
// Check we have a date
else if (words[i].match(/^\d{4}\-\d{2}\-\d{2}$/)) {
date = words[i];
}
}
if(date == null) {
date = moment().tz('Europe/Brussels').format("YYYY-MM-DD");
}
if(users.length == 0) {
myModel.getUsersQuestionByDate(date, function(response) {
if(response.length > 0) {
for(var i = 0; i < response.length; i++) {
doResume(response[i].user_id, date, message.channel);
}
} else {
var msg = 'Aucun utilisateur n\'a participé au stand à cette date : ' + date;
bot.sendMessage(message.channel, {text: msg});
}
});
} else {
for (var i = 0; i < users.length; i++) {
doResume(users[i], date, message.channel);
}
}
}
// Asking help
else if (message.text.toLowerCase().indexOf('help') > -1) {
var msg = 'Pour demander un résumé :\n';
msg += '- resume -> résumé de tous les utilisateurs d\'aujourd\'hui\n';
msg += '- resume @user_n1 @user_n2 -> résumé des utilisateurs 1 et 2 d\'aujourd\'hui\n';
msg += '- resume 2016-12-25 -> résumé de tous les utilisateurs au 25 Déc 2016\n';
msg += '- resume @user_n1 @user_n2 2016-12-25 -> résumé des utilisateurs 1 et 2 au 25 Déc 2016\n';
bot.sendMessage(message.channel, {text: msg});
}
// Asking manual report
else if (message.text.toLowerCase().indexOf('report') > -1) {
for(var i = 0; i < listUsers.length; i++) {
var user = listUsers[i];
if(message.user == user.id) {
sendQuestion(user, function(askUser) {
if(askUser == false) {
bot.sendMessage(message.user, {text: 'Vous avez déjà répondu pour aujourd\'hui !'});
}
});
}
}
}
}
}
});
}
}
/**
* Generate the resume report
* @param user_id
* @param date
* @param channel
*/
function doResume(user_id, date, channel) {
bot.getUserInfo(user_id, function(user) {
myModel.getQuestionsByUserAndByDate(user.id, date, function (uestions) {
var attachments = [];
if(questions.length > 0) {
var text = 'Résumé pour l\'utilisateur : ' + user.name + ' à la date du ' + date +' \n';
for(var i = 0; i < questions.length; i++) {
var attachment = new Object();
attachment.fallback = questions[i].value + '\n' + questions[i].answer;
attachment.color = questions[i].color;
attachment.title = questions[i].value;
attachment.text = questions[i].answer;
// To enable markdown in attachment (See https://api.slack.com/docs/message-formatting#message_formatting)
attachment.mrkdwn_in = ['text', 'pretext'];
attachments.push(attachment);
}
} else {
var text = 'Malheureusement je n\'ai pas répondu aux questions à la date du ' + date + '.';
}
var msg = new Object();
msg.text = text;
msg.attachments = JSON.stringify(attachments);
bot.sendPersonnalizedMessage(channel, msg, user.name, user.profile.image_48);
});
});
}
/**
* Get bot informations
*/
function getBotImList(callback) {
bot.getImList(function(response) {
if(typeof callback === 'function') {
callback(response.ims);
}
});
}
|
'use strict';
import { Platform, Dimensions } from 'react-native';
const IPHONE_X_SMALL_DIM = 812;
const WINDOW_DIM = Dimensions.get('window');
let iosStatusBarHeight = isIphoneX() ? 35 : 20;
let androidStatusBarHeight = 0;
export const STATUS_BAR_HEIGHT = isIOS() ? iosStatusBarHeight : androidStatusBarHeight;
export function isIOS() {
return (Platform.OS = 'ios');
}
export function isIphoneX() {
let { height, width } = WINDOW_DIM;
return ( isIOS() && (height === IPHONE_X_SMALL_DIM || width === IPHONE_X_SMALL_DIM) );
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.