text stringlengths 7 3.69M |
|---|
import infoPopover from 'raw!./infoPopover.html'
export default function ($scope, $element, $templateCache, $compile, $timeout) {
'ngInject'
let ctrl = this
$scope.projectList = ctrl.projectList.map((project) => {
project.coordinate = [project.investigation.location.longitude, project.investigation.location.latitude]
project.info.schedule.start_date = new Date(project.info.schedule.start_date.replace(/-/g, '/'))
project.info.schedule.end_date = new Date(project.info.schedule.end_date.replace(/-/g, '/'))
return project
})
const mapContentEl = $element[0].querySelector('.geo-info-map-content')
const map = new AMap.Map(mapContentEl, {zoom: 4})
map.plugin(['AMap.ToolBar'], () => {
map.addControl(new AMap.ToolBar({
direction: false,
offset: new AMap.Pixel(-10, 5)
}))
})
const infoWindow = new AMap.InfoWindow({
isCustom: true,
offset: new AMap.Pixel(16, -45)
})
ctrl.projectList.forEach((project) => {
const marker = new AMap.Marker({
position: project.coordinate,
map: map
})
marker.project = project
marker.on('click', markerClick)
})
function markerClick (e) {
$timeout(function () {
$scope.project = e.target.project
let linkFn = $compile(infoPopover)
let linkedContent = linkFn($scope)
infoWindow.setContent(linkedContent[0])
infoWindow.open(map, e.target.getPosition())
}, 0)
}
$scope.closeInfoWindow = function () {
map.clearInfoWindow()
}
}
|
const usuarioLogado = true;
const contapaga = false;
//0 => false
// 1 => true
//console.log(0 == false);
//console.log("" == false);
//console.log(1 == true);
//null
//underfined
let minhaVar;
let varNull = null;
console.log(minhaVar);
console.log(varNull); |
import React from 'react'
import { Link, useParams } from 'react-router-dom'
import planets from "../../data/planets"
const Planet = () => {
const planetName = useParams()
const planet = planets.find(planet => planet.name == planetName.name)
return (
<div className="planet-info-wrapper">
<Link to="/" className="back-btn">
<h6><span className="back-icon">←</span> Back</h6></Link>
<div className="planet-info">
<h2 className="planet-name-info">{planet.name}</h2>
<p><strong>Size:</strong> {planet.size}</p>
<p><strong>Co-ordinates:</strong> {planet.coordinates}</p>
<p><strong>Moons:</strong> {planet.moons}</p>
<div className={`info-planet ${planet.name}`}></div>
<p>{planet.info}</p>
</div>
</div>
)
}
export default Planet |
import { PRIMITIVE_TRISTRIP } from '../../platform/graphics/constants.js';
import { BLEND_NORMAL } from '../constants.js';
import { GraphNode } from '../graph-node.js';
import { Mesh } from '../mesh.js';
import { MeshInstance } from '../mesh-instance.js';
import { BasicMaterial } from '../materials/basic-material.js';
import { createShaderFromCode } from '../shader-lib/utils.js';
import { shaderChunks } from '../shader-lib/chunks/chunks.js';
import { ImmediateBatches } from './immediate-batches.js';
const tempPoints = [];
class Immediate {
constructor(device) {
this.device = device;
this.quadMesh = null;
this.textureShader = null;
this.depthTextureShader = null;
this.cubeLocalPos = null;
this.cubeWorldPos = null;
// map of Layer to ImmediateBatches, storing line batches for a layer
this.batchesMap = new Map();
// set of all batches that were used in the frame
this.allBatches = new Set();
// set of all layers updated during this frame
this.updatedLayers = new Set();
// line materials
this._materialDepth = null;
this._materialNoDepth = null;
// map of meshes instances added to a layer. The key is layer, the value is an array of mesh instances
this.layerMeshInstances = new Map();
}
// creates material for line rendering
createMaterial(depthTest) {
const material = new BasicMaterial();
material.vertexColors = true;
material.blendType = BLEND_NORMAL;
material.depthTest = depthTest;
material.update();
return material;
}
// material for line rendering with depth testing on
get materialDepth() {
if (!this._materialDepth) {
this._materialDepth = this.createMaterial(true);
}
return this._materialDepth;
}
// material for line rendering with depth testing off
get materialNoDepth() {
if (!this._materialNoDepth) {
this._materialNoDepth = this.createMaterial(false);
}
return this._materialNoDepth;
}
// returns a batch for rendering lines to a layer with required depth testing state
getBatch(layer, depthTest) {
// get batches for the layer
let batches = this.batchesMap.get(layer);
if (!batches) {
batches = new ImmediateBatches(this.device);
this.batchesMap.set(layer, batches);
}
// add it for rendering
this.allBatches.add(batches);
// get batch for the material
const material = depthTest ? this.materialDepth : this.materialNoDepth;
return batches.getBatch(material, layer);
}
getShader(id, fragment) {
if (!this[id]) {
// shared vertex shader for textured quad rendering
const vertex = `
attribute vec2 vertex_position;
uniform mat4 matrix_model;
varying vec2 uv0;
void main(void) {
gl_Position = matrix_model * vec4(vertex_position, 0, 1);
uv0 = vertex_position.xy + 0.5;
}
`;
this[id] = createShaderFromCode(this.device, vertex, fragment, `DebugShader:${id}`);
}
return this[id];
}
// shader used to display texture
getTextureShader() {
return this.getShader('textureShader', `
varying vec2 uv0;
uniform sampler2D colorMap;
void main (void) {
gl_FragColor = vec4(texture2D(colorMap, uv0).xyz, 1);
}
`);
}
// shader used to display infilterable texture sampled using texelFetch
getUnfilterableTextureShader() {
return this.getShader('textureShaderUnfilterable', `
varying vec2 uv0;
uniform highp sampler2D colorMap;
void main (void) {
ivec2 uv = ivec2(uv0 * textureSize(colorMap, 0));
gl_FragColor = vec4(texelFetch(colorMap, uv, 0).xyz, 1);
}
`);
}
// shader used to display depth texture
getDepthTextureShader() {
return this.getShader('depthTextureShader', `
${shaderChunks.screenDepthPS}
varying vec2 uv0;
void main() {
float depth = getLinearScreenDepth(uv0) * camera_params.x;
gl_FragColor = vec4(vec3(depth), 1.0);
}
`);
}
// creates mesh used to render a quad
getQuadMesh() {
if (!this.quadMesh) {
this.quadMesh = new Mesh(this.device);
this.quadMesh.setPositions([
-0.5, -0.5, 0,
0.5, -0.5, 0,
-0.5, 0.5, 0,
0.5, 0.5, 0
]);
this.quadMesh.update(PRIMITIVE_TRISTRIP);
}
return this.quadMesh;
}
// Draw mesh at this frame
drawMesh(material, matrix, mesh, meshInstance, layer) {
// create a mesh instance for the mesh if needed
if (!meshInstance) {
const graphNode = this.getGraphNode(matrix);
meshInstance = new MeshInstance(mesh, material, graphNode);
}
// add the mesh instance to an array per layer, they get added to layers before rendering
let layerMeshInstances = this.layerMeshInstances.get(layer);
if (!layerMeshInstances) {
layerMeshInstances = [];
this.layerMeshInstances.set(layer, layerMeshInstances);
}
layerMeshInstances.push(meshInstance);
}
drawWireAlignedBox(min, max, color, depthTest, layer) {
tempPoints.push(
min.x, min.y, min.z, min.x, max.y, min.z,
min.x, max.y, min.z, max.x, max.y, min.z,
max.x, max.y, min.z, max.x, min.y, min.z,
max.x, min.y, min.z, min.x, min.y, min.z,
min.x, min.y, max.z, min.x, max.y, max.z,
min.x, max.y, max.z, max.x, max.y, max.z,
max.x, max.y, max.z, max.x, min.y, max.z,
max.x, min.y, max.z, min.x, min.y, max.z,
min.x, min.y, min.z, min.x, min.y, max.z,
min.x, max.y, min.z, min.x, max.y, max.z,
max.x, max.y, min.z, max.x, max.y, max.z,
max.x, min.y, min.z, max.x, min.y, max.z
);
const batch = this.getBatch(layer, depthTest);
batch.addLinesArrays(tempPoints, color);
tempPoints.length = 0;
}
drawWireSphere(center, radius, color, numSegments, depthTest, layer) {
const step = 2 * Math.PI / numSegments;
let angle = 0;
for (let i = 0; i < numSegments; i++) {
const sin0 = Math.sin(angle);
const cos0 = Math.cos(angle);
angle += step;
const sin1 = Math.sin(angle);
const cos1 = Math.cos(angle);
tempPoints.push(center.x + radius * sin0, center.y, center.z + radius * cos0);
tempPoints.push(center.x + radius * sin1, center.y, center.z + radius * cos1);
tempPoints.push(center.x + radius * sin0, center.y + radius * cos0, center.z);
tempPoints.push(center.x + radius * sin1, center.y + radius * cos1, center.z);
tempPoints.push(center.x, center.y + radius * sin0, center.z + radius * cos0);
tempPoints.push(center.x, center.y + radius * sin1, center.z + radius * cos1);
}
const batch = this.getBatch(layer, depthTest);
batch.addLinesArrays(tempPoints, color);
tempPoints.length = 0;
}
getGraphNode(matrix) {
const graphNode = new GraphNode('ImmediateDebug');
graphNode.worldTransform = matrix;
graphNode._dirtyWorld = graphNode._dirtyNormal = false;
return graphNode;
}
// This is called just before the layer is rendered to allow lines for the layer to be added from inside
// the frame getting rendered
onPreRenderLayer(layer, visibleList, transparent) {
// update line batches for the specified sub-layer
this.batchesMap.forEach((batches, batchLayer) => {
if (batchLayer === layer) {
batches.onPreRender(visibleList, transparent);
}
});
// only update meshes once for each layer (they're not per sub-layer at the moment)
if (!this.updatedLayers.has(layer)) {
this.updatedLayers.add(layer);
// add mesh instances for specified layer to visible list
const meshInstances = this.layerMeshInstances.get(layer);
if (meshInstances) {
for (let i = 0; i < meshInstances.length; i++) {
visibleList.push(meshInstances[i]);
}
meshInstances.length = 0;
}
}
}
// called after the frame was rendered, clears data
onPostRender() {
// clean up line batches
this.allBatches.clear();
// all batches need updating next frame
this.updatedLayers.clear();
}
}
export { Immediate };
|
import React from 'react'
import { StyleSheet, Text, View } from 'react-native'
import Router from '../App/Router'
const index = () => {
return (
<Router />
)
}
export default index
|
import { put, call, takeEvery } from 'redux-saga/effects';
import {LOGIN_REQUEST, loginSuccess, loginError } from '../actions/auth.actions';
import {SIGNUP_REQUEST, signupSuccess, signupError } from '../actions/auth.actions';
import { loginRequest, signUpRequest } from '../api/accountsApi';
import utils from "../utils";
function* login(action){
try {
const data = yield call(loginRequest, action.payload.username, action.payload.password);
utils.saveAccessToken(data.access_token);
yield put(loginSuccess(data));
} catch (error) {
yield put(loginError(error));
}
}
function* signup(action){
try {
const data = yield call(signUpRequest, action.username, action.password, action.name);
utils.saveAccessToken(data.access_token);
yield put(signupSuccess(data.access_token));
} catch (error) {
yield put(signupError(error));
}
}
function* authSagas(){
yield takeEvery(LOGIN_REQUEST, login);
yield takeEvery(SIGNUP_REQUEST, signup);
}
export { authSagas } |
import dotenv from 'dotenv';
dotenv.config();
const { env } = process;
export const { APP_PORT } = env;
export const DB_CONFIG = {
host: env.DB_HOST,
port: env.DB_PORT,
user: env.DB_USERNAME,
database: env.DB_NAME,
password: env.DB_PASSWORD,
};
|
function readText(){
let input_text = document.getElementById("text_inputtext").value;
let input_question = document.getElementById("question_field").value;
document.getElementById("predicted_answers").innerText = "Running the neural net to get your answer...\n";
runQnaModel(input_question, input_text, printAnswer);
}
function setMockQuestion(){
document.getElementById("question_field").innerText = "Who helped with the breeding of Scottish Fold cats?";
}
function setMockText(){
input_text = `The original Scottish Fold was a white barn cat named Susie, who was found at a farm near Coupar Angus in Perthshire, Scotland, in 1961. Susie's ears had an unusual fold in their middle, making her resemble an owl. When Susie had kittens, two of them were born with folded ears, and one was acquired by William Ross, a neighbouring farmer and cat-fancier. Ross registered the breed with the Governing Council of the Cat Fancy (GCCF) in the United Kingdom in 1966 and started to breed Scottish Fold kittens with the help of geneticist Pat Turner. The breeding program produced 76 kittens in the first three years — 42 with folded ears and 34 with straight ears. The conclusion from this was that the ear mutation is due to a simple dominant gene.`;
document.getElementById("text_inputtext").innerText = input_text;
}
function printAnswer(answers, startTime){
all_answers_concat = "Predicted answers:<br><br>";
let scores = [];
for (let i = 0; i < answers.length; i++){
all_answers_concat += String(i+1).bold() + ". Answer: ".bold() + "\"" + answers[i].text + "\", " + "score: ".bold() + answers[i].score.toFixed(2) + "<br>";
scores.push(answers[i].score.toFixed(2));
}
let finishTime = performance.now();
time = ((finishTime - startTime) / 1000).toFixed(2);
all_answers_concat += "<br>Finished running in " + time + " seconds.";
document.getElementById("predicted_answers").innerHTML = all_answers_concat;
drawHistogramPlot(scores);
}
function runQnaModel(question, text, printAnswer) {
let startTime = performance.now();
qna.load().then((model) => {
model.findAnswers(question, text).then(answers => {
printAnswer(answers, startTime);
});
});
}
setMockQuestion();
setMockText();
|
'use strict';
let express = require('express');
let router = express.Router();
let db = require('../database/model');
let util = require('./routerUtil');
/**
* 餐单管理页面
*/
router.get('/menu', function (req, res) {
if (!util.authentication(req, res)) return;
let userName = req.session.user.username;
let menu = {
creatorName: userName,
isDeleted: false
};
db.menuModel.find(menu, function (err, result) {
if (err) {
res.send({
success: false,
message: '请求失败'
});
return false;
}
res.render('menu', {
title: '餐单页',
username: userName,
menuList: result,
nav: 'menu'
});
});
});
//创建餐单
router.route('/menu/add').get(function (req, res) {
if (!util.authentication(req, res)) return;
res.render('menu-info', {
title: '餐单-创建餐单',
username: req.session.user.username,
nav: 'menu'
});
}).post(function (req, res) {
if (!util.authentication(req, res)) return;
let userName = req.session.user.username;
let menuObj = {
menuName: req.body.menuName,
dishes: req.body.dishes,
isDeleted: false,
creatorName: userName,
createTime: new Date(),
updaterName: userName,
updateTime: new Date()
};
let menuId = req.body.menuId;
if (menuId) {
db.menuModel.update({_id: menuId, isDeleted: false}, {
$set: {
menuName: req.body.menuName,
dishes: req.body.dishes,
updaterName: userName,
updateTime: new Date()
}
}, (err) => {
if (err) {
res.send({
success: false,
message: '更新餐单失败,请稍后重试!'
});
return false;
}
res.send({
success: true,
message: '更新成功!'
});
});
} else {
new db.menuModel(menuObj).save(function (err, data) {
if (err) {
res.send({
success: false,
message: '创建餐单失败,请稍后重试!'
});
return false;
}
res.send({
success: true,
message: '餐单“' + req.body.menuName + '”创建成功!'
});
});
}
});
//编辑餐单
router.get('/menu/edit', (req, res) => {
if (!util.authentication(req, res)) return;
let queryObj = {
_id: req.query.menuId, isDeleted: false
};
let outObj = {
menuName: 1,
dishes: 1
};
db.menuModel.find(queryObj, outObj, (err, result) => {
if (err) {
res.send({
success: false,
message: '操作失败'
});
return false;
}
res.render('menu-info', {
title: '餐单-编辑餐单',
username: req.session.user.username,
nav: 'menu',
menuInfo: result[0]
});
});
});
//删除餐单
router.post('/menu/del', (req, res) => {
if (!util.authentication(req, res)) return;
let menuId = req.body.menuId;
//首先判断,如果该餐单已经被未删除的团队引用,则该餐单不能删除
db.teamModel.find({ 'menus.menuId': menuId, isDeleted: false }, (error, result) => {
if (error) {
res.send({ success: false, message: '操作失败' });
return false;
}
if (result.length > 0) {
res.send({ success: false, message: '该餐单有关联团队,不能删除' });
return false;
}
db.menuModel.update({_id: menuId}, {$set: {isDeleted: true}}, (err) => {
res.send({
success: !err,
message: !err ? '操作成功' : '操作失败'
});
});
});
});
module.exports = router; |
/* eslint-disable no-underscore-dangle */
/* eslint-disable no-restricted-syntax */
import firebase from 'firebase/app';
import 'firebase/storage';
import axios from 'axios';
import { db, updateAlgolia } from '@/auth';
import { slugify } from '@/mixins';
import {
UPDATE_ITEM,
CREATE_ITEM,
UPDATE_MAIN_IMAGE,
MUTATE_MAIN_IMAGE,
GET_ITEM_DATA_BY_DOC_ID,
MUTATE_ITEM,
SET_ITEM_DETAILS,
GET_ITEM_DATA_BY_NAME,
} from '../types';
const handleSecondaryImages = (otherImages) => {
const imagesObject = {};
for (const photo of otherImages) {
imagesObject.otherImages.push(`${photo.lastModified}-${photo.size}-${photo.name}`);
imagesObject.child(`${photo.lastModified}-${photo.size}-${photo.name}`).put(photo);
}
return imagesObject;
};
export default {
[UPDATE_ITEM]: ({}, item) => {
const storageRef = firebase.storage().ref();
const itemToPublish = { ...item };
// set up tags
itemToPublish.tags = {};
for (const tag of item.tagsSearchbale) {
itemToPublish.tags[tag] = true;
}
// create slug
if (!itemToPublish.slug) {
itemToPublish.slug = slugify.sanitizeTitle(`${itemToPublish.name} ${itemToPublish.city} ${itemToPublish.state}`);
}
if (item.mainImage) {
if (item.mainImage.constructor === FileList) {
// mainImage has changed, we need to upload it
const mainImage = item.mainImage[0];
itemToPublish.mainImage = `${mainImage.lastModified}-${mainImage.size}-${mainImage.name}`;
storageRef.child(`${mainImage.lastModified}-${mainImage.size}-${mainImage.name}`).put(mainImage);
}
}
if (item.otherImages) {
item.otherImages.forEach((photo, index) => {
if (photo.constructor === FileList) {
const photoDetails = photo[0];
itemToPublish.otherImages[index] = `${photoDetails.lastModified}-${photoDetails.size}-${photoDetails.name}`;
storageRef.child(`${photoDetails.lastModified}-${photoDetails.size}-${photoDetails.name}`).put(photo[0]);
}
});
}
if (!itemToPublish._geoloc) {
axios.get(`https://open.mapquestapi.com/nominatim/v1/search.php?key=WWoKqSLir2hzGkpTBhbJbFXeyC8Gz96S&format=json&q=${itemToPublish.streetAddress} ${itemToPublish.city}, ${itemToPublish.state}`)
.then((res) => {
itemToPublish._geoloc = {
lat: parseFloat(res.data[0].lat),
lng: parseFloat(res.data[0].lon),
};
db.collection('items').doc(itemToPublish.ID)
.update(itemToPublish).then(() => {
itemToPublish.objectID = itemToPublish.ID;
updateAlgolia(itemToPublish);
});
});
} else {
db.collection('items').doc(itemToPublish.ID)
.update(itemToPublish).then(() => {
itemToPublish.objectID = itemToPublish.ID;
updateAlgolia(itemToPublish);
});
}
},
// Create a new item
[CREATE_ITEM]: ({ getters }, item) => {
// Upload images to firestore
const storageRef = firebase.storage().ref();
// copy item object so we can reassign some values
const itemToPublish = { ...item };
// set the user to the userID we get from our getters
itemToPublish.user = getters.userId;
// clear out otherImages as we'll reassigning them with just the name value
itemToPublish.otherImages = [];
// Main image First
if (item.mainImage) {
const mainImage = item.mainImage[0];
itemToPublish.mainImage = `${mainImage.lastModified}-${mainImage.size}-${mainImage.name}`;
storageRef.child(`${mainImage.lastModified}-${mainImage.size}-${mainImage.name}`).put(mainImage);
}
// Secondary Images
if (item.otherImages) {
/* for (const photo of item.otherImages) {
itemToPublish.otherImages.push(`${photo.lastModified}-${photo.size}-${photo.name}`);
storageRef.child(`${photo.lastModified}-${photo.size}-${photo.name}`).put(photo);
} */
itemToPublish.otherImages = handleSecondaryImages(item.otherImages);
}
// set up tags
if (item.tagsSearchbale) {
itemToPublish.tags = {};
for (const tag of item.tagsSearchbale) {
itemToPublish.tags[tag] = true;
}
}
// create slug
itemToPublish.slug = slugify.sanitizeTitle(`${itemToPublish.name} ${itemToPublish.city} ${itemToPublish.state}`);
axios.get(`https://open.mapquestapi.com/nominatim/v1/search.php?key=WWoKqSLir2hzGkpTBhbJbFXeyC8Gz96S&format=json&q=${itemToPublish.streetAddress} ${itemToPublish.city}, ${itemToPublish.state}`)
.then((response) => {
itemToPublish._geoloc = {
lat: parseFloat(response.data[0].lat),
lng: parseFloat(response.data[0].lon),
};
// push to firestore
db.collection('items').add(itemToPublish)
.then((res) => {
// res.id has the id to add to user's item array
db.collection('users').doc(itemToPublish.user)
.update({
items: firebase.firestore.FieldValue.arrayUnion(res.id),
});
// update algolia
itemToPublish.objectID = itemToPublish.ID;
updateAlgolia(itemToPublish);
});
});
},
// Update main image on item page
// Used for switching between thumbnails
[UPDATE_MAIN_IMAGE]: ({ commit }, payload) => {
commit(MUTATE_MAIN_IMAGE, payload);
},
// Sync curItem in store to item from Firebase
[GET_ITEM_DATA_BY_DOC_ID]: ({ commit }, itemRef) => new Promise((resolve) => {
// After sync, set the item's main image into separate mainIMage var in store
db.collection('items').doc(itemRef).get()
.then((doc) => {
commit(MUTATE_ITEM, doc.data());
commit(MUTATE_MAIN_IMAGE, doc.data().mainImage);
resolve(doc.data());
});
}),
[SET_ITEM_DETAILS]: ({ commit }, item) => {
commit(MUTATE_ITEM, item);
},
// Search for item in collection by slug
// This is used when someone directly accesses an item page rather than coming via a
// link that includes the doc ID (such as the tags list or search list)
[GET_ITEM_DATA_BY_NAME]: ({ dispatch }, itemRef) => new Promise((resolve) => {
db.collection('items').where('slug', '==', itemRef).limit(1).get()
.then((doc) => {
// id of item we need is doc.docs[0].id
dispatch(GET_ITEM_DATA_BY_DOC_ID, doc.docs[0].id).then((res) => {
resolve(res);
});
});
}),
};
|
const fs = require('fs')
module.exports = {
afterEnd: function (runner) {
const coverage = runner.page.evaluate(function () { return window.__coverage__ }),
path = '.nyc_output/coverage.json'
if (coverage) {
console.log('Writing coverage to: ' + path)
fs.write(path, JSON.stringify(coverage), 'w')
} else {
console.log('No coverage data generated')
}
}
} |
var selectionsort = require("../selectionsort");
var chai = require("chai");
var expect = chai.expect;
describe ("selectionsort", function(){
it("empty array", function(){
expect(selectionsort([])).to.equal("Empty Array");
});
it("simple array", function(){
expect(selectionsort([3,2,1])).to.eql([1,2,3]);
expect(selectionsort([3,2,1,8,7,0,5,4,6])).to.eql([0,1,2,3,4,5,6,7,8]);
});
}); |
import React, { Component } from 'react';
import { connect } from 'react-redux';
class Details extends Component {
render() {
if(!this.props.car){
return(<p>Please,choose the auto! </p>);
}
return (
<div>
<h2>{this.props.car.car}</h2>
<p>{this.props.car.speed}</p>
</div>
)
}
}
let mapStateToProps = (state) => ({
car: state.active
})
export default connect(mapStateToProps)(Details); |
require('./globals_dev.js');
require('./globals.js');
CliMgr.show();
|
'use strict';
const gulp = require('gulp');
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const sourcemaps = require('gulp-sourcemaps');
const lost = require('lost');
const browser = require('browser-sync');
var sassPaths = [
// For using with foundation / bootstrap etc
// Point this towards any folder that contains scss files and they will be
// included...
];
gulp.task('css', () => {
var processors = [
autoprefixer({browsers: ['last 3 versions']}),
cssnano(),
lost(),
];
return gulp.src('./assets/scss/app.scss')
.pipe(sourcemaps.init())
.pipe(sass(
// includePaths: sassPaths,
).on('error', sass.logError))
.pipe(postcss(processors))
.pipe(gulp.dest('./build/css'))
.pipe(browser.stream());
});
|
import { responsiveStateReducer } from 'redux-responsive'
import { combineReducers } from 'redux'
import responsiveDrawer from 'material-ui-responsive-drawer/lib/store/reducer'
import formReducer from 'redux-form/lib/reducer.js'
import persistentValues from './persistentValues/reducer'
import simpleValues from './simpleValues/reducer'
import dialogs from './dialogs/reducer'
import locale from './locale/reducer'
import theme from './theme/reducer'
import firekitReducers from 'firekit'
import filterReducer from 'material-ui-filter/lib/store/reducer'
import initState from './init'
import * as authTypes from './auth/types'
const appReducer = combineReducers({
browser: responsiveStateReducer,
responsiveDrawer,
form: formReducer,
dialogs,
persistentValues,
simpleValues,
locale,
theme,
...firekitReducers,
filters: filterReducer
})
const rootReducer = (state, action) => {
if (action.type === authTypes.USER_LOGOUT) {
state = initState
}
return appReducer(state, action)
}
export default rootReducer
|
import { Pagination } from "antd";
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { FILTER_BY_PAGE } from "../../constants/filterContants";
import { PRODUCT_PAGINATION_PAGE } from "../../constants/productConstants";
import "./styles.scss";
function Paginate(props) {
const dispatch = useDispatch();
const productList = useSelector((state) => state.productList);
const { page, totalRows } = productList;
const onChange = (page) => {
dispatch({ type: PRODUCT_PAGINATION_PAGE, payload: page });
dispatch({ type: FILTER_BY_PAGE, payload: page });
};
return (
<div className="paginate">
<Pagination
current={page}
onChange={onChange}
total={totalRows}
pageSize={16}
/>
</div>
);
}
export default Paginate;
|
// lang form
var langForm = {};
// get btn
langForm.getBtn = function () {
return zForm.currentAjaxForm.find ( 'input[type="submit"]' );
};
// init
langForm.init = function () {
// lang form init
zForm.addAjaxHandler ({
_selector: 'form.lang', // optional
// action before sending a request
_before: function () { // optional
var btn = langForm.getBtn();
btn.addClass ( 'transparent' );
},
// action after receiving a response
_preResponse: function () { // optional
var btn = langForm.getBtn();
btn.removeClass ( 'transparent' );
},
// results
ok: function () {
window.location.reload();
}
});
};
// autorun
if ( $( '#langs' ).length > 0 ) {
langForm.init();
} |
/**
* @module ref.js
*
*/
/**
* Class pour une référence. Une référence est une instance qui permet de gérer
* à la volée les références à d'autres fiches qui sont faites dans des textes
* (ou plus rarement des titres). Une référence possède une fiche-cible ({Fiche})
* qui correspond à l'instance {Fiche} visée par la référence (comprendre :
* “l'instance {Ref} fait référence à la cible {Fiche}).
*
* L'instance {Ref} peut posséder également une “porteuse”, qui est la fiche dans
* laquelle cette référence est insérée. Elle est définie principalement lorsque
* le texte de la porteuse doit être formaté pour affichage "humain".
*
* L'instance {Ref} est capable de gérer toutes les situations, celle où la cible
* n'est pas encore une fiche chargée, où la fichier porteuse de la référence
* n'appartient pas au même livre que la fiche-cible de référence, etc.
*
* Notes
* -----
* * Bien que l'instance {Ref} ne soit pas une {Fiche}, ses propriétés `id` et
* `type` sont les mêmes que sa fiche-cible. Mais pour la clarté, l'instance {Ref}
* possède les propriétés `cible_id` et `cible_type` qui sont des alias.
*
* @class Ref
* @constructor
* @param {String} rid Identifiant de la référence correspondant à `<type>-<id>`
* de la cible.
*/
window.Ref = function(rid)
{
var did = rid.split('-')
if(did.length == 2 /* ancienne référence */)
{
F.error("La référence `"+rid+"` est obsolète. Il faut l'actualiser (avec le livre). Je mets 0 en attendant mais ça risque de produire des erreurs.")
did.unshift("0")
}
/**
* Class de la référence
* @property {String} class
* @static
*/
this.class = "Ref"
/**
* Book de la référence
* @note Cette propriété permet d'aller plus vite, au cours de la
* publication du livre, pour savoir si la fiche appartient au même
* livre.
*/
this.book_id = did[0]
/**
* Type de la cible de la référence ('book', 'page', etc.)
* @property {String} type
* @final
*/
this.type = this.cible_type = did[1]
/**
* Identifiant de la cible de la référence
* @property {Number|String} id
* @final
*/
this.id = this.cible_id = did[2]
/**
* La fiche porteuse de la référence, c'est-à-dire qui la possède dans
* son texte. La plupart du temps, c'est un {Paragraph} de page.
* Notes
* -----
* * Noter que cette propriété est dynamique elle change en fonction de
* la référence à écrire.
*
* @property {Fiche} porteuse
*/
this.porteuse = null
REFS.list[rid] = this
}
$.extend(Ref.prototype,{
/**
* Formate la balise pour affichage
*
* Notes
* -----
* * Le formatage de la balise dépend de :
* * Si la cible est chargée ou non
* * Si la cible appartient au même livre ou non
* * Si le chargement de la cible peut se faire ou non
*
* @method formate
* @param {Fiche} porteuse La fiche qui doit recevoir la référence formatée
* @param {Array} default_title Le titre par défaut contenu dans la balise.
* @param {Boolean} skip_loading
* Pour le moment, ce paramètre n'est pas pris en compte : on ne
* tente jamais de charger la fiche d'une référence inexistante
* pour éviter les problèmes (vu que le formatage est un flux sur)
* un ensemble de paragraphes.
* @return {String} La balise formatée pour affichage.
*/
formate:function(porteuse, default_title, skip_loading)
{
this.porteuse = porteuse
this.default_title = default_title
if(this.type=='para') this.default_title = '<span class="small">'+this.default_title+' […]</span>'
this['titres_for_'+(this.cible?'':'non_')+'loaded_cible']()
return this.to_html
},
/**
* Formatage du titre pour une cible chargée
* La méthode définit les valeurs `titre_same_book` et `titre_hors_book` de
* la référence
*
* @method titres_for_loaded_cible
*
*/
titres_for_loaded_cible:function()
{
this.titre_same_book = this.human_type + " “"+this.titre_cible+"”"
this.titre_hors_book = this.titre_same_book + this.mark_book
},
/**
* Définit les titres pour une cible non chargée (simple)
* Notes
* -----
* * La cible n'étant pas chargée, on ne peut rien savoir d'elle, on met
* donc le même texte simple dans les deux propriétés `titre_same_book`
* et `titre_hors_book`.
*
* @method titres_for_non_loaded_cible
*/
titres_for_non_loaded_cible:function()
{
var titre = "[# " + this.human_type + " “" + this.default_title + "” #]"
this.titre_same_book = titre
this.titre_hors_book = titre
},
})
Object.defineProperties(Ref.prototype, {
/* ---------------------------------------------------------------------
* MÉTHODES D'ÉCRITURE
*/
/**
* Retourne la balise [ref:...] à écrire dans le code du texte/titre
* @property {String} to_balise
* @final
* @example
* jq.append(ref.to_balise)
* // Where `jq` is a DOMElement
* // And `ref` is a Ref Instance
*/
"to_balise":{
get:function(){
if(undefined == this._to_balise) this._to_balise = get_fiche(this.id).to_balise
return this._to_balise
}
},
/**
* Retourne la balise HTML pour la référence
* Notes
* -----
* * C'est une propriété complexe, l'appeler sans parenthèses
* * Le titre (le contenu) de la balise doit avoir été construit avant
* d'appeler cette méthode
* @method balise_html
* @return {String} La balise à écrire dans le texte.
*/
"to_html":{
get:function(){
return '<ref' +
' class="'+this.classcss + '"'+
' onclick="FICHES.show('+this.id+', \''+this.type+'\', event)"'+
'>' +
this.titre_for_porteuse +
'</ref>'
}
},
/**
* Appelée pour updater l'affichage de toutes les références lorsque la
* fiche-cible est chargée.
* Notes
* -----
* * Propriété complexe => appeler sans parenthèses
*
* @method update
*/
"update":{
get:function(){
this.titres_for_loaded_cible()
}
},
/* ---------------------------------------------------------------------
* MÉTHODES DE DONNÉES
*/
/**
* Instance Fiche de la cible de la référence
*
* Notes
* -----
* * WARNING: Cette propriété est mise à NULL même si l'instance Fiche
* existe, mais qu'elle n'est pas encore chargée.
* * Pour obtenir vraiment la fiche, utiliser la propriété `fiche`
* @property {Fiche} cible
*
*/
"cible":{
get:function(){
if(undefined == this._cible && FICHES.list[this.cible_id]){
this._cible = get_fiche(this.cible_id)
if(!this._cible.loaded) this._cible = null
}
return this._cible
}
},
"fiche":{
get:function(){
return get_fiche(this.cible_id)
}
},
/**
* Titre pour la fiche-porteuse (pour la composition de son texte affiché)
* Notes
* -----
* * Ce titre varie en fonction du fait que cible et porteuse se trouvent
* ou non dans le même livre.
*
* @property {String} titre_for_porteuse
*
*/
"titre_for_porteuse":{
get:function(){
return this['titre_'+(this.same_book?'same':'hors')+'_book']
}
},
/**
* Retourne le titre pour la cible
* Notes
* -----
* * Ce titre dépend du type de la fiche. Pour un book, on prend son titre
* réel (`real_titre`), pour un paragraphe, on prend ses 50 premiers signes,
* et on prend le titre normal pour les chapitres et les pages.
* * Cette propriété ne doit être utilisée que pour une fiche-cible chargée.
*
* @property {String} titre_cible
* @static
*/
"titre_cible":{
get:function(){
if(undefined == this._titre_cible) this._titre_cible = this.fiche.titre_for_ref
return this._titre_cible
}
},
/**
* Marque pour le livre à ajouter dans le titre hors book (quand la cible et
* la fiche porteuse n'appartienne pas au même livre ou que l'une des deux fiches
* n'est pas dans un livre)
* @property {String} mark_book
* @final
*/
"mark_book":{
get:function(){
if(undefined == this._mark_book)
{
if(this.book) this._mark_book = " (livre “"+(this.book.real_titre||this.book.titre)+"”)"
else this._mark_book = ""
}
return this._mark_book
}
},
/**
* Renvoie true si la cible de la référence appartient au même livre que la
* fiche porteuse (this.porteuse).
*
* Notes
* -----
* * C'est une propriété complexe qui est recalculée à chaque nouvelle porteuse.
* * @rappel: this.porteuse est une instanceof {Fiche}
* * Si la cible de la référence courante n'est pas encore chargée, on ne peut
* pas déterminer son livre. La propriété est alors mise à false.
*
* @property {Boolean} same_book
*
*/
"same_book":{
get:function(){
if(undefined == this.porteuse)
{
var err = "La porteuse de la référence devrait être définie… Je ne peux rien faire."
F.error(err)
throw err
}
if(!this.cible || !this.cible.loaded) return false
else return this.book == this.porteuse.book_id
}
},
/**
* Retourne la class pour la balise `ref` en tenant compte du fait que la
* référence appartient ou non au même livre que la fiche porteuse contenant
* la référence.
* Notes
* -----
* * C'est une propriété complexe car la valeur est redéfini à chaque nouvelle
* insertion dans le texte demandée.
* @property {String} class
*/
"classcss":{
get:function(){
return this['classcss_'+(this.same_book?'same':'hors')+'_book']
}
},
/**
* Retourne la class pour la balise ref dans le cas d'une référence qui
* appartient au même livre que la porteuse.
* Notes
* -----
* * C'est une propriété complexe qui redéfinit la valeur à chaque nouvelle
* fiche porteuse (paragraphe)
* @property {String} class_same_book
*/
"classcss_same_book":{
get:function(){
return this.type+"-"+this.id+"-in"
}
},
/**
* Retourne la class pour la balise ref dans le cas d'une référence qui
* N'appartient PAS au même livre que la porteuse.
* Notes
* -----
* * C'est une propriété complexe qui redéfinit la valeur à chaque nouvelle
* fiche porteuse (paragraphe)
* @property {String} class_hors_book
*/
"classcss_hors_book":{
get:function(){
return this.type+"-"+this.id+"-out"
}
},
/**
* Titre construit pour la référence, tel qu'il apparaitra dans le texte.
* Il dépend de l'état de chargement de la cible de la référence et de l'appartenance
* ou non au même book que la porteuse.
* Notes
* -----
* * C'est une propriété complexe car sa (re)-définition peut faire varier
* toutes les balises références de la même référence.
*
* @property {String} titre
*/
"titre_same_book":{
get:function(){
return this._titre_same_book // doit avoir été défini avant
},
set:function(titre){
this._titre_same_book = titre
// On doit modifier toutes les références qu'on trouve
$('ref.'+this.class_same_book).html( titre )
}
},
/**
* Propriété similaire à la précédente, mais pour une référence n'appartenant
* pas au livre de la porteuse.
* @property {String} titre_hors_book
*/
"titre_hors_book":{
get:function(){
return this._titre_hors_book // doit avoir été défini avant
},
set:function(titre){
this._titre_hors_book = titre
// On doit modifier toutes les références qu'on trouve
$('ref.'+this.class_hors_book).html( titre )
}
},
/**
* Type humain de la référence (par exemple "livre" pour le type 'book')
* Notes
* -----
* * La valeur est sans capitale, pour pouvoir s'insérer dans le flux du texte
* ou entre parenthèses.
* @property {String} human_type
* @final
*/
"human_type":{
get:function(){
if(undefined == this._human_type) this._human_type = FICHES.datatype[this.type].hname;
return this._human_type
}
},
/**
* Retourne l'instance {Fiche} de la référence courante
*
* Notes
* -----
* * Pour obtenir cette information, il faut obligatoirement que
* la cible de la référence soit chargée.
*
* @property {Fiche} book
*
*/
"book":{
get:function(){
if(undefined == this._book) this._book = get_fiche(this.book_id)
return this._book
}
},
}) |
/// <reference path="viewHeaders.ts" />
/// <reference path="../../core/plugins/fbsdk.d.ts" />
|
let getId = x => document.getElementById(x);
let rightBtn = getId('rightBtn');
let leftBtn = getId('leftBtn');
let slider = getId('slider');
let playBtn = getId('playBtn');
let form = document.forms['sliderDots'];
let start = 0;
let direction;
let sliderImg = document.getElementsByClassName('sliderImg');
function moveLeft(){
sliderImg[start].classList.remove('showing');
start = (++start) % sliderImg.length;
sliderImg[start].classList.add('showing');
form.point[start].checked = true;
}
rightBtn.addEventListener("click", moveLeft);
leftBtn.addEventListener("click", function () {
if (start == 0) {
sliderImg[start].classList.remove('showing');
start = sliderImg.length-1;
sliderImg[start].classList.add('showing');
form.point[start].checked = true;
}
else{
sliderImg[start].classList.remove('showing');
start = (--start) % sliderImg.length;
sliderImg[start].classList.add('showing');
console.log(start);
form.point[start].checked = true;
}
})
///////////////////////////////////////////////////////SET INTERVAL
let check = true;
let mySlider;
playBtn.addEventListener('click', function () {
if (check) {
playBtn.value = `pause`;
mySlider = setInterval(moveLeft, 2000);
check = false;
}
else {
playBtn.value = `play`;
check = true;
clearInterval(mySlider);
}
})
///////////////////////////////////////////////////////RADIO BTN
for (let i = 0; i < form.point.length; i++) {
form.point[i].index = i;
form.point[i].addEventListener('click', function () {
sliderImg[start].classList.remove('showing');
sliderImg[event.target.index].classList.add('showing');
start = event.target.index;
start = event.target.index;
})
}
///////////////////////////////////////////////////////MPUSEOVER SLIDE
let label = document.getElementsByTagName('label');
console.log(label);
for(let i = 0; i<label.length; i++) {
label[i].addEventListener('mouseover', function(){
label[i].index = i;
over.classList.add('dspBlock');
let attr = sliderImg[label[i].index].getAttribute("src");
console.log(attr);
over.style.background = `url(${attr})`;
over.style.backgroundSize = `100% 100%`;
over.style.backgroundRepeat = `no-repeat`;
})
label[i].addEventListener('mouseout', function () {
over.classList.remove('dspBlock');
})
} |
import Taro, { Component } from '@tarojs/taro';
import { View, Image } from '@tarojs/components';
import { AtList, AtListItem } from "taro-ui"
import { connect } from '@tarojs/redux';
import './index.scss';
import message_img from '../../assets/images/user/message.png';
@connect(({ login }) => ({
login
}))
export default class User extends Component {
config = {
navigationBarTitleText: '我的',
};
goPage = (e) => {
if (e.currentTarget.dataset.url == '/pages/login/index' && this.props.access_token) {
return;
}
Taro.navigateTo({
url: e.currentTarget.dataset.url,
})
}
goToPage = (url) => {
if (url === '/pages/userMgmt/index') {
const userInfo = Taro.getStorageSync('userInfo')
if (userInfo.roleLevel < 499) {
Taro.showToast({title: '无权访问', icon: 'none'})
return
}
}
(/pages/i).test(url) ? Taro.navigateTo({ url }) : null
}
getUserinfo = () => {
const { userName } = this.props.login;
if (userName) {
return this.props.login;
} else {
return Taro.getStorageSync('userInfo')
}
}
render() {
const userinfo = this.getUserinfo();
const { mobile, avatar, userName } = this.props.login;
return (
<View className='user-page'>
<View className='not-login'>
<View className='to-login' data-url='/pages/login/index' onClick={this.goPage}>
<View className='left'>
<View className={mobile ? 'name black' : 'name '}>{userName || userinfo && userinfo.userName }</View>
<View>
<View className='msg' data-url='/pages/message/index' onClick={this.goToPage}>
<Image mode='widthFix' src={message_img} />
</View>
<View className='msg' onClick={this.outLogin}>
<Image mode='widthFix' src='http://static-r.msparis.com/uploads/9/a/9a00ce9a5953a6813a03ee3324cbad2a.png' />
</View>
</View>
</View>
<View className='avatar-container'>
<Image className='avatar' src={avatar} />
</View>
</View>
</View>
<View className='nav-list'>
<AtList>
<AtListItem
title='系统设置'
arrow='right'
onClick={this.goToPage.bind(this, '/pages/about/index')}
iconInfo={{
size: 28, color: '#2bb2a7', value: 'settings',
}}
/>
<AtListItem
title='用户管理'
arrow='right'
data-url='/pages/about/index'
onClick={this.goToPage.bind(this, '/pages/userMgmt/index')}
iconInfo={{
size: 28, color: '#2bb2a7', value: 'user',
}}
/>
<AtListItem
title='关于我们'
arrow='right'
data-url='/pages/about/index'
onClick={this.goToPage.bind(this, '/pages/about/index')}
iconInfo={{
size: 28, color: '#2bb2a7', value: 'alert-circle',
}}
/>
</AtList>
</View>
</View>
)
}
}
|
//= require_tree ./admin/utilities
//= require ./admin/modules/base_module
//= require_tree ./admin/modules
//= require ./admin/plugins/base_plugin
//= require_tree ./admin/plugins
//= require ./admin/editors/base_editor
//= require_tree ./admin/editors
//= require ./admin/models/resource
//= require_tree ./admin/models
|
import React from 'react';
import {Grid, Container, Header, Divider, Segment, Button, Icon} from 'semantic-ui-react'
class Home extends React.Component{
render(){
return(
<Segment
textAlign='center'
style={{ minHeight: 700, padding: '1em 0em' }}
vertical
inverted
>
<Container text>
<Header
as='h1'
content='Imagine-a-Company'
inverted
style={{
//fontSize: mobile ? '2em' : '4em',
fontSize: '4em',
fontWeight: 'normal',
marginBottom: 0,
marginTop: '3em',
//marginTop: mobile ? '1.5em' : '3em',
}}
/>
<Header
as='h2'
content='Do whatever you want when you want to.'
inverted
style={{
//fontSize: mobile ? '1.5em' : '1.7em',
fontWeight: 'normal',
// marginTop: mobile ? '0.5em' : '1.5em',
}}
/>
<Button primary size='huge'>
Get Started
<Icon name='right arrow' />
</Button>
</Container>
</Segment>
)
}
}
export default Home; |
import React, { Fragment, useState } from "react";
const EditQuiz = ({ quiz }) => {
const [title, setTitle] = useState(quiz.title);
//edit quiz
const updateQuiz = async (e) => {
e.preventDefault();
try {
const body = { title };
const response = await fetch(`http://localhost:3000/quiz/${quiz.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
console.log(response);
} catch (error) {
console.error(error.message);
}
};
return (
<Fragment>
<button
type="button"
className="btn btn-warning"
data-toggle="modal"
data-target={`#id${quiz.id}`}
>
Edit
</button>
<div
className="modal"
id={`id${quiz.id}`}
onClick={() => setTitle(quiz.title)}
>
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h4 className="modal-title">Edit Quiz</h4>
<button
type="button"
className="close"
data-dismiss="modal"
onClick={() => setTitle(quiz.title)}
>
×
</button>
</div>
<div className="modal-body">
<input
type="text"
className="form-control"
value={title}
onChange={(e) => setTitle(e.target.value)}
></input>
</div>
<div className="modal-footer">
<button
type="button"
className="btn btn-warning"
data-dismiss="modal"
onClick={(e) => updateQuiz(e)}
>
Edit
</button>
<button
type="button"
className="btn btn-danger"
data-dismiss="modal"
onClick={() => setTitle(quiz.title)}
>
Close
</button>
</div>
</div>
</div>
</div>
</Fragment>
);
};
export default EditQuiz;
|
module.exports = {
getBody: (event) => {
if (Array.isArray(event.Records) && event.Records.length) {
const { data } = JSON.parse(event.Records[0].body);
return data;
}
return JSON.parse(event.body);
}
}
|
import React, { useContext, useState } from 'react';
import { useParams, useHistory } from 'react-router-dom';
import Header from '../commons/Header';
import styled from 'styled-components/macro';
import GameContext from '../../context/GameContext';
import Input from '../commons/Input';
import { Button } from '../commons/Button';
export default function SignInPage() {
const { gameid } = useParams();
const history = useHistory();
const [name, setName] = useState('');
const [signInFailed, setSignInFailed] = useState('');
const { signInGame } = useContext(GameContext);
return (
<>
<Header>Schaetzmeisterin </Header>
<main>
<FormStyled onSubmit={handleSubmit}>
<LabelStyled>
Please enter your name to sign into{' '}
{gameid ? 'game ' + gameid : 'a new game'}.
<Input value={name} onChange={handleNameChange} />
</LabelStyled>
<Button>Sign in</Button>
{signInFailed && <p>{signInFailed}</p>}
</FormStyled>
</main>
</>
);
function handleNameChange(event) {
setName(event.target.value);
}
function handleSubmit(event) {
event.preventDefault();
signInGame(gameid, name)
.catch(() => {
setSignInFailed('Sign in failed, please try again');
})
.then((game) => history.push('/game/' + game?.id));
}
}
const FormStyled = styled.form`
display: grid;
gap: var(--size-m);
grid-auto-rows: min-content;
grid-template-columns: 1fr;
padding: var(--size-m);
input {
}
`;
const LabelStyled = styled.label`
display: grid;
grid-gap: var(--size-xs);
grid-auto-rows: min-content;
`;
|
/** @jsx jsx */
import { css, jsx } from "@emotion/core";
import { useMemo, useCallback } from "react";
import BorderRadiusInput from "./BorderRadiusInput";
const BorderRadiusSettingRow = ({
name,
borderRadius,
baseWidth,
onChange,
}) => {
const hName = `${name}H`;
const vName = `${name}V`;
const horizontalRadius = borderRadius[hName];
const verticalRadius = borderRadius[vName];
const changeBorderRadius = useCallback(
({ name, value }) => {
onChange(
Object.assign({}, borderRadius, {
[name]: value,
})
);
},
[borderRadius, onChange]
);
const formattedName = useMemo(() => {
return name.replace(/([a-z0-9]|(?=[A-Z]))([A-Z])/g, "$1-$2").toLowerCase();
}, [name]);
const sectionStyle = css`
margin-bottom: 1rem;
`;
return (
<article>
<h3>{`border-${formattedName}-radius`}</h3>
<section css={sectionStyle}>
<BorderRadiusInput
label="Horizontal Radius"
name={hName}
radius={horizontalRadius}
baseWidth={baseWidth}
onChange={changeBorderRadius}
/>
</section>
<section css={sectionStyle}>
<BorderRadiusInput
label="Vertical Radius"
name={vName}
radius={verticalRadius}
baseWidth={baseWidth}
onChange={changeBorderRadius}
/>
</section>
</article>
);
};
export default ({ baseWidth, borderRadius, onChange }) => {
return (
<div
css={css`
display: grid;
grid-template-columns: repeat(2, auto);
justify-content: center;
grid-column-gap: 4rem;
`}
>
{["topLeft", "topRight", "bottomLeft", "bottomRight"].map((name) => (
<BorderRadiusSettingRow
key={name}
name={name}
baseWidth={baseWidth}
borderRadius={borderRadius}
onChange={onChange}
/>
))}
</div>
);
};
|
import React, {Component} from 'react';
import './WeatherIcon.css';
class WeatherIcon extends Component {
render() {
return (<div className="WeatherIcon">
<span data-icon="B" id="weather-icon"></span>
</div>);
}
}
export default WeatherIcon;
|
import { all } from 'redux-saga/effects';
import loginSaga from './login.saga';
import registrationSaga from './registration.saga';
import userSaga from './user.saga';
import shelfSaga from './shelf.saga';
import deleteSaga from './delete.saga';
// rootSaga is the primary saga.
// It bundles up all of the other sagas so our project can use them.
// This is imported in index.js as rootSaga
// some sagas trigger other sagas, as an example
// the registration triggers a login
// and login triggers setting the user
function* rootSaga() {
yield all([
loginSaga(), // login saga is now registered
registrationSaga(),
userSaga(),
deleteSaga(),
shelfSaga(), //include it in rootSaga as well! Remember this!
]);
}
export default rootSaga;
|
(function () {
'use strict';
angular.module('ShoppingListCheckOff', [])
.controller('ToBuyController', ToBuyController)
.controller('AlreadyBoughtController', AlreadyBoughtController)
.service('ShoppingListCheckOffService', ShoppingListCheckOffService);
function ShoppingListCheckOffService() {
var service = this;
service.itemsToBuy = [
{
name : "cookies",
quantity: 10
},
{
name : "candy bars",
quantity: 5
},
{
name : "apples",
quantity: 100
},
{
name : "oranges",
quantity: 30
},
{
name : "bananas",
quantity: 50
}
];
service.itemsBought = [];
service.buyItem = function(index) {
var itemBought = service.itemsToBuy[index];
service.itemsToBuy.splice(index,1)
service.itemsBought.push(itemBought);
};
}
ToBuyController.$inject = ['ShoppingListCheckOffService'];
function ToBuyController(ShoppingListCheckOffService) {
var buyList = this;
buyList.itemsToBuy = ShoppingListCheckOffService.itemsToBuy;
buyList.buyItem = function(index) {
ShoppingListCheckOffService.buyItem(index)
}
}
AlreadyBoughtController.$inject = ['ShoppingListCheckOffService'];
function AlreadyBoughtController(ShoppingListCheckOffService) {
var boughtList = this;
boughtList.itemsBought = ShoppingListCheckOffService.itemsBought;
}
})(); |
const gulp = require('gulp');
const { task } = require('gulp');
const sass = require('gulp-sass');
function style() {
// 1. where is my scss files
return gulp.src('./src/*.scss')
// 2. pass that file through sass compiler
.pipe(sass())
// 3. where do I save the compiled css?
.pipe(gulp.dest('./dist/css'))
}
exports.style = style; |
import React from 'react'
import {
getStorage,
get,
Link,
LOGIN_STATUS,
noop,
post,
RESUME_ID,
setStorage,
withRouter,
formatDateToPast, addCommaToInt
} from '~utils'
import TextField from '~/components/TextField'
import Button from '~/components/Button'
import {
pick,
} from '~utils'
import api from '~api'
import {
MainConsumer,
MainContext,
} from '~/modules/Context'
import style from './admin.scss'
class Admin extends React.Component {
state = {
username: '',
password: '',
isLoading: false,
hasValidated: false,
visitors: []
}
componentDidMount() {
this.tryGetVisitors()
}
tryGetVisitors = () => {
if (getStorage(LOGIN_STATUS) === true) {
get(api.GET_VISITORS)
.then((res) => {
this.setState({
isLoading: true,
visitors: res.visitors
})
})
.catch(noop)
.finally(() => {
this.setState({
isLoading: false,
})
})
}
}
onClickLogin = () => {
this.setState({
hasValidated: true,
isLoading: true,
})
post(api.LOGIN, pick(this.state, ['username', 'password']))
.then(() => {
this.context.markLogin()
this.tryGetVisitors()
})
.catch(noop)
.finally(() => {
this.setState({
isLoading: false,
})
})
}
onCancelLogin = () => {
this.props.history.goBack()
}
onClickLogout = () => {
this.setState({
hasValidated: true,
isLoading: true,
})
post(api.LOGOUT)
.then(() => {
this.context.markLogout()
})
.catch(noop)
.finally(() => {
this.setState({
isLoading: false,
})
})
}
getSetStateMethod = stateKey => evt => {
this.setState({
[stateKey]: evt.target.value
})
}
renderLogin = () => {
if (this.context.hasLoggedIn) {
return null
}
return (
<div className={'login-area'}>
<TextField
className={'username'}
label={'用户名'}
value={this.state.username}
onChange={this.getSetStateMethod('username')}
width={'100%'}
maxLength={16}
validatorRegExp={/^\d{2,16}$/}
disabled={this.state.isLoading}
/>
<TextField
className={'password'}
type={'password'}
label={'密码'}
value={this.state.password}
onChange={this.getSetStateMethod('password')}
width={'100%'}
maxLength={20}
validatorRegExp={/^.{6,20}$/}
disabled={this.state.isLoading}
/>
<Button
className={'submit'}
type={'primary'}
onClick={this.onClickLogin}
disabled={this.state.isLoading}
>
登录
</Button>
<Button
className={'cancel'}
onClick={this.onCancelLogin}
disabled={this.state.isLoading}
>
取消
</Button>
</div>
)
}
renderAdmin = () => {
if (!this.context.hasLoggedIn) {
return null
}
return (
<div className={'admin-area'}>
<Button
className={'new-article'}
type={'primary'}
disabled={this.state.isLoading}
onClick={() => this.props.history.push(`/editor`)}
>
新建笔记
</Button>
<Button
className={'edit-resume'}
disabled={this.state.isLoading}
onClick={() => this.props.history.push(`/editor?id=${RESUME_ID}`)}
>
编辑简历
</Button>
<Button
className={'edit-resume'}
disabled={this.state.isLoading}
onClick={() => this.props.history.push(`/article?id=${RESUME_ID}`)}
>
查看简历
</Button>
<Button
className={'cancel'}
onClick={this.onClickLogout}
type={'secondary'}
disabled={this.state.isLoading}
>
退出登录
</Button>
</div>
)
}
renderVisitors = () => {
if (!this.context.hasLoggedIn) {
return null
}
return (
<>
<p className={'sum'}>
访问 10 次以上的设备总计:
<span className={'num'}>
{this.state.visitors.length}
</span>
</p>
<div className={'visitors-wrap rhaego-responsive'}>
<table className={'visitors'}>
<thead>
<tr>
<th>IP</th>
<th>今日剩余请求次数</th>
<th>上次访问</th>
<th>禁用</th>
<th>访问次数</th>
</tr>
</thead>
<tbody>
{
this.state.visitors.map(item => (
<tr key={item._id}>
<td>
{item.clientIp}
</td>
<td align={'right'}>
{item.dailyAttempts}
</td>
<td>
{formatDateToPast(item.lastVisited)}
</td>
<td align={'center'}>
{item.restricted === true ? '是' : '否'}
</td>
<td align={'right'}>
{addCommaToInt(item.visitCount)}
</td>
</tr>
))
}
</tbody>
</table>
</div>
</>
)
}
componentWillUnmount() {
}
render() {
return (
<div className={'rhaego-admin content-pop-in'}>
{this.renderAdmin()}
{this.renderLogin()}
{this.renderVisitors()}
</div>
)
}
}
Admin.contextType = MainContext
export default withRouter(Admin)
|
var compose_8c =
[
[ "ComposeRedrawData", "structComposeRedrawData.html", "structComposeRedrawData" ],
[ "MAX_ADDR_ROWS", "compose_8c.html#ae0a35f3369b4cd706f92571c89a99b34", null ],
[ "MAX_USER_HDR_ROWS", "compose_8c.html#a5d9bfff8fe9b32f6ffa8df2576ef0e88", null ],
[ "CHECK_COUNT", "compose_8c.html#a3ab795b188471453ebe6cdb5fb15ab41", null ],
[ "CUR_ATTACH", "compose_8c.html#a3de3b86ab6b21aee74c81d3b6d93cf45", null ],
[ "ALTS_TAG", "compose_8c.html#a09885d2cb5854aa82240411a1708abf7", null ],
[ "LINGUAL_TAG", "compose_8c.html#afba239d7867db7919ad4e4bc8e20283f", null ],
[ "HeaderField", "compose_8c.html#adaffad40d353965ad6b52804bc72afef", [
[ "HDR_FROM", "compose_8c.html#adaffad40d353965ad6b52804bc72afefae991ac64da53a06212cdfe54d66a43bf", null ],
[ "HDR_TO", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa75f62356b04e1e2f84c7a5d7ac9871fb", null ],
[ "HDR_CC", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa5d6974e738d6caaa531c2f71bcf91818", null ],
[ "HDR_BCC", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa874d952c2b2d2e5352db258e87507b02", null ],
[ "HDR_SUBJECT", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa050cfc849276a9e72a54c0035c867593", null ],
[ "HDR_REPLYTO", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa1f4a6698e7ff2a6b492f1b92e8c3620f", null ],
[ "HDR_FCC", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa39910162978e49562d0647a81fbb1e3d", null ],
[ "HDR_MIX", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa62728120899d075ec6494f9d63581a77", null ],
[ "HDR_CRYPT", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa523859c2fa6df34616951b86d1a5b799", null ],
[ "HDR_CRYPTINFO", "compose_8c.html#adaffad40d353965ad6b52804bc72afefae14d5f70a401bba6b13710ba5770a747", null ],
[ "HDR_AUTOCRYPT", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa26271ff4de69905731ba0156d7585460", null ],
[ "HDR_NEWSGROUPS", "compose_8c.html#adaffad40d353965ad6b52804bc72afefac1c0836c481768b0029d6726172713fa", null ],
[ "HDR_FOLLOWUPTO", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa899d1ee4207e6c72ffb51a80dfd2096d", null ],
[ "HDR_XCOMMENTTO", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa94aacb3c16ece8df6abc9f1bf5b4ac4e", null ],
[ "HDR_CUSTOM_HEADERS", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa88ca78afc66383536a30e479eff87184", null ],
[ "HDR_ATTACH_TITLE", "compose_8c.html#adaffad40d353965ad6b52804bc72afefa43f7afec0cc5209a2b68bea401ec20f2", null ]
] ],
[ "compose_status_line", "compose_8c.html#a1531d785d4faa4bc82cd8c43ff6e9f04", null ],
[ "calc_header_width_padding", "compose_8c.html#aef0c67b5c00c17dd35738a4fdc6b65a3", null ],
[ "init_header_padding", "compose_8c.html#afc34fec9cb024fbc4c2e4d1b72e90ac5", null ],
[ "snd_make_entry", "compose_8c.html#a7cd542de4349c167dd99566a9ce04a85", null ],
[ "autocrypt_compose_menu", "compose_8c.html#ae51515965703068c13b684e949b0963b", null ],
[ "draw_floating", "compose_8c.html#a3a2628773125cc354856c45fbffbb224", null ],
[ "draw_header", "compose_8c.html#a1c8ed66a5996c5748a22515f6915d559", null ],
[ "draw_header_content", "compose_8c.html#ac4f2268c759c82af60b1be3013ca29a1", null ],
[ "calc_address", "compose_8c.html#ad673e390566335a4a5a342573121d571", null ],
[ "calc_security", "compose_8c.html#ad8a877791bfe53ca05c98d5fb6446618", null ],
[ "calc_user_hdrs", "compose_8c.html#ad733535fb06b49e9cb6e55e865d6ca08", null ],
[ "calc_envelope", "compose_8c.html#a260eba8ce50a7b007ccd1e42df97bd4f", null ],
[ "redraw_crypt_lines", "compose_8c.html#a4d1badace8a605f05e3094d32837b3ab", null ],
[ "update_crypt_info", "compose_8c.html#a5ce2f7dfd6942654a9610af1c19a5f21", null ],
[ "redraw_mix_line", "compose_8c.html#a390ced109c2d496e6a6661db461d3f50", null ],
[ "check_attachments", "compose_8c.html#ab888d10bda8b3f792707eb614bc9d7b1", null ],
[ "draw_envelope_addr", "compose_8c.html#a094c42d2adc33086bf5e51684819cd24", null ],
[ "draw_envelope_user_hdrs", "compose_8c.html#a2fa8cea9616d3eeb400aa36f9ff1034c", null ],
[ "draw_envelope", "compose_8c.html#aafa46e29920afd47903620b3d77ac45f", null ],
[ "edit_address_list", "compose_8c.html#a995fe70fb321e85b2799e74e3e3322f0", null ],
[ "delete_attachment", "compose_8c.html#a81116139e0a71a3bd2b6967f7dcaa71b", null ],
[ "mutt_gen_compose_attach_list", "compose_8c.html#ac4f967e1fde0b8096af8be64a5ecbb95", null ],
[ "mutt_update_compose_menu", "compose_8c.html#aec953e61fa82157673592462a732b8c0", null ],
[ "update_idx", "compose_8c.html#a6d6517aa9ace035c5e1449dd0bbcdeed", null ],
[ "compose_custom_redraw", "compose_8c.html#a8faee93bf8b76d2c9fd2fa1f99aa73e7", null ],
[ "compose_attach_swap", "compose_8c.html#a06eaad0402e7c6919916f45932477419", null ],
[ "cum_attachs_size", "compose_8c.html#a10fb95e2265c7801f3cc2dcb92c3b836", null ],
[ "compose_format_str", "compose_8c.html#ac48dc934e7245d47d1a4feb8459ccb81", null ],
[ "compose_config_observer", "compose_8c.html#a82dc12838cf57973070cdd4e9c554d41", null ],
[ "compose_header_observer", "compose_8c.html#aeb0d87aee0853ff188ec505c7f3bb20c", null ],
[ "mutt_compose_menu", "compose_8c.html#acbb0d4100be90b597c9229f13cd7ef2b", null ],
[ "There_are_no_attachments", "compose_8c.html#ad560832702dd29552851dc3cc4b7e619", null ],
[ "HeaderPadding", "compose_8c.html#a2dc7f233f069332ab5fd13ebb6a32934", null ],
[ "MaxHeaderWidth", "compose_8c.html#aa57902c74e4b99785680a0bc4e263029", null ],
[ "Prompts", "compose_8c.html#a577b891ac761db94d93ff7d31e9670bb", null ],
[ "ComposeHelp", "compose_8c.html#a785f04ab170c17ce970ceea7d2615150", null ],
[ "ComposeNewsHelp", "compose_8c.html#aa5d7e91e9396582befc17198ad78464c", null ],
[ "AutocryptRecUiFlags", "compose_8c.html#acf023820a2a75f370be7bc00634502d6", null ]
]; |
import React, { Component } from 'react';
import ReactTable from 'react-table'
import CheckboxParent from './CheckboxParent.js'
let expandedGroups = {};
export default class TurnerReactTable extends Component {
constructor(props){
super(props)
this.state = {
searchBrand: '',
searchLocation:'',
searchCategory:'',
expanded: {},
isCheckedBrandName:[]
}
this.handleCheckCompany = this.handleCheckCompany.bind(this);
this.handleCheckBrand = this.handleCheckBrand.bind(this);
}
// Search Handelers
handleBrandSearch(e){
this.setState({
searchBrand: e.target.value,
expanded: expandedGroups
});
}
handleLocationSearch(e){
this.setState({
searchLocation: e.target.value,
expanded: expandedGroups
}, ()=>{console.log('this.state.searchLocation', this.state.searchLocation, expandedGroups)});
}
handleCategorySearch(e){
this.setState({
searchLocation: '',
searchBrand: '',
searchCategory: e.target.value
});
}
//checkboxHandelers
// Select All
handleCheckCompany(e, props){
// is id set to company name
let selectedCompany = e.target.id
console.log('props', props)
// find the company that matches the selected company
let company = props.original
// get all brand names from selected company
let brandNames = company.brands.map((brand) => {
return brand.brandName
});
// if checkbox is checked add brandNames to existing state of isCheckedBrandName
if (e.target.checked){
// make new array from existing state and new brand names
let newBrandArray = [...this.state.isCheckedBrandName, ...brandNames];
this.setState({
// set new state to existing state plus new brands with no duplicates
isCheckedBrandName: Array.from(new Set(newBrandArray))
}, ()=>{console.log('state selected names',this.state.isCheckedBrandName)})
} else {
// if checkbox is unchecked remove from isCheckedBrandName all the brands associated with selected company
let removeBrands = this.state.isCheckedBrandName.filter((brand) => {
// why does this work?
return brandNames.includes(brand) === false;
});
this.setState({
isCheckedBrandName: removeBrands,
},()=>{console.log('state selected names removed company',this.state.isCheckedBrandName)});
}
};
// Select One *** should this be based on if checked or not?
handleCheckBrand(e) {
// id is set to brand name
let brandName = e.target.id;
// if the checked brand state does not include the selected brand, add it.
if (e.target.checked === true && this.state.isCheckedBrandName.includes(brandName) === false) {
this.setState({
isCheckedBrandName: [...this.state.isCheckedBrandName, brandName]
},() => {console.log('checked Brands',this.state.isCheckedBrandName)});
} else if (e.target.checked === false) {
// if the checked brand state does not include the selected brand, remove it.
let filterExistingBrandName = this.state.isCheckedBrandName.filter((b) => {
return b !== brandName;
})
this.setState({
isCheckedBrandName: filterExistingBrandName
},()=>{console.log('checked Brands', this.state.isCheckedBrandName)});
}
}
// When all brands are selected check company, when company is selected but a brand is delecected, deselect company
areBrandsChecked(props){
let brandNames = props.original.brands.map((brand) => {return brand.brandName;})
return brandNames.every((brandName)=>{
return this.state.isCheckedBrandName.includes(brandName)
});
}
// fires when expaner arrow is clicked
handleRowExpanded(newExpanded, index, event) {
// make a new object of existing values of expanded state
let expandedTables = Object.assign({}, this.state.expanded);
// if expandedTable is not expanded, expand it.
if (expandedTables[index] === false || expandedTables[index] === undefined ) {
expandedTables[index] = true;
} else {
// if expanded tables are expanded collapse them
expandedTables[index] = false;
}
this.setState({
expanded: expandedTables
});
}
render() {
let data = [].concat(this.props.data);
//let expandedGroups = this.state.expanded;
// Search by Company/Brand names
if(this.state.searchBrand){
// get company names that match searchString with name and/or brandNames
data = data.filter((company, index) => {
// check if search is in company name
let companyMatches = company.name.toLowerCase().includes(this.state.searchBrand.toLowerCase());
// check if search is in brands of a particular company
let filteredBrands = company.brands.filter((brand) => {
return brand.brandName.toLowerCase().includes(this.state.searchBrand.toLowerCase())
});
// if search string is in company name or brand name return true
if(companyMatches || filteredBrands.length > 0){
return true;
}
return false;
}).map((company, index) => {
const companyClone = Object.assign({}, company);
// check if search is in brands of a particular company
companyClone.brands = company.brands.filter((brand) => {
return brand.brandName.toLowerCase().includes(this.state.searchBrand.toLowerCase())
});
return companyClone;
});
expandedGroups = data.map((element, index)=>{
return expandedGroups[index] = true;
});
} else if (this.state.searchBrand === '' && this.state.searchLocation === ''){
expandedGroups = data.map((element, index)=>{
return expandedGroups[index] = false;
});
data = [].concat(this.props.data)
}
// Search by Location
if(this.state.searchLocation){
data = data.filter((company) => {
let companyMatches = company.location.toLowerCase().includes(this.state.searchLocation.toLowerCase());
let filteredLocation = company.brands.filter((brand) => {
return brand.brandName.toLowerCase().includes(this.state.searchLocation.toLowerCase())
});
if (companyMatches || filteredLocation.length > 0){
return true;
}
return false;
}).map((company)=>{
const companyClone = Object.assign({},company);
companyClone.brands = company.brands.filter((brand)=>{
return brand.brandName.toLowerCase().includes(this.state.searchLocation.toLowerCase());
});
return companyClone;
});
expandedGroups = data.map((element, index)=>{
return expandedGroups[index] = true;
});
}else if (this.state.searchBrand === '' && this.state.searchLocation === ''){
expandedGroups = data.map((element, index)=>{
return expandedGroups[index] = false;
});
data = [].concat(this.props.data);
}
// Search by Category ***** FIND OUT WHAT WE ARE REALLY FILTERING HERE ********
if(this.state.searchCategory){
data = this.props.data.filter((company) => {
let companyMatches = company.category.toLowerCase().includes(this.state.searchCategory.toLowerCase());
let filteredCategory = company.brands.filter((brand) => {
return brand.category.toLowerCase().includes(this.state.searchCategory.toLowerCase())
});
if (companyMatches || filteredCategory.length > 0){
return true;
}
return false;
}).map((company)=>{
const companyClone = Object.assign({},company);
companyClone.brands = company.brands.filter((brand)=>{
return brand.category.toLowerCase().includes(this.state.searchCategory.toLowerCase());
});
return companyClone;
});
};
// Company Columns
const companyColumns = [{
expander: true,
width: 50
}, {
Header: 'Name',
accessor: 'name', // String-based value accessors!
Cell: (props) => {
let index = props.index;
let checked = this.areBrandsChecked(props);
return(
<span className='number'>
<input
type="checkbox"
id={props.value}
value={props.value}
checked={checked}
onChange={(e)=>{this.handleCheckCompany(e, props)}}/>
<label htmlFor={props.value}> {props.value} </label>
</span>
)},
width: 500,
}, {
Header: 'Type',
accessor: 'type',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false
}, {
Header: 'Location',
accessor: 'location',
Cell: props => <span className='number'>{props.value}</span>,
sortable: false // Custom cell components!
}, {
Header: 'Version',
accessor: 'version',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
Header: 'Category',
accessor: 'category',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
Header: 'Published',
accessor: 'published', // Custom value accessors!
},{
width: 65,
filterable: false,
sortable: false
}]
// Brand Columns
const brandColumns = [{
width: 50
}, {
accessor: 'brandName', // String-based value accessors!
Cell: (props) => {
let checked = false;
if (this.state.isCheckedBrandName.includes(props.original.brandName)){
checked = true;
} else {
checked = false
};
return (
<span style={{ paddingLeft: "20px" }} className='number'>
<input
type="checkbox"
id={props.value}
value={props.value}
checked={checked}
onChange={(e)=>{this.handleCheckBrand(e)}}/>
<label htmlFor={props.value}> {props.value} </label></span>
)},
width: 500,
sortable: false
}, {
accessor: 'type',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
accessor: 'countryName',
Cell: props => <span className='number'>{props.value}</span>,
sortable: false, // Custom cell components!
}, {
accessor: 'version',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
accessor: 'category',
Cell: props => <span className='number'>{props.value}</span>, // Custom cell components!
filterable: false,
sortable: false
}, {
accessor: 'published', // Custom value accessors!
}, {
expander: true,
width: 65,
Expander: ({ isExpanded, ...rest }) =>
<div>
{isExpanded
? <span>⊙</span>
: <span>⊕</span>}
</div>,
style: {
cursor: "pointer",
fontSize: 25,
padding: "0",
textAlign: "center",
userSelect: "none"
}
}]
return (
<div>
<div>
<input
value={this.state.searchBrand}
onChange={(e)=>{this.handleBrandSearch(e)}}
placeholder="Search Brands"
style={{height: "30px", width: "200px", fontSize:"1em"}}
/>
<select
value={this.state.searchLocation}
onChange={(e)=>{this.handleLocationSearch(e)}}
style={{height: "30px", width: "200px", fontSize:"1em"}}>
<option value="">Worldwide</option>
<option value="USA">USA</option>
<option value="France">France</option>
<option value="Japan">Japan</option>
</select>
<select
style={{height: "30px", width: "200px", fontSize:"1em"}}
onChange={(e)=>{this.handleCategorySearch(e)}}>
<option value="all">All Categories</option>
<option value="Company">Company</option>
<option value="Brand">Brand</option>
</select>
</div>
<ReactTable
defaultPageSize={10}
data={data}
columns={companyColumns}
resizable={false}
expanded={this.state.expanded}
onExpandedChange={(newExpanded, index, event) => {this.handleRowExpanded(newExpanded, index, event)}}
SubComponent={(row) => {
console.log('row brands', row.original.brands)
return (
<ReactTable
showPaginationBottom={false}
defaultPageSize={row.original.brands.length}
data={row.original.brands}
columns={brandColumns}
resizale={false}
SubComponent={(row) => {
//console.log('row', row)
return (
<div style={{padding: "20px 20px 20px 50px", border:"solid black 1px",}}>
Run new affinio report on @{row.original.brandName}
</div>
)}}/>
)}}/>
</div>
)
}
}
|
// Menu Toggle
$("#menu-toggle").click(function(e) {
e.preventDefault();
$("#wrapper").toggleClass("toggled");
});
// Slide Dropdown
$('.dropdown').on('show.bs.dropdown', function(e){
$(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
});
$('.dropdown').on('hide.bs.dropdown', function(e){
$(this).find('.dropdown-menu').first().stop(true, true).slideUp(300);
}); |
/*
Should synced to client
*/
module.exports = {
CARD_STATE : {
hidden: -1,
open : 0,
closed: 1
},
GAME_TYPES : {
SINGLE : 0,
MULTIPLAYER : 1
},
GAMESTATE : {
boardNotready : -2,
waitForOpponent : -1,
play : 0,
won : 1,
lost : 2,
draw : 3
},
GAME_VARIANTS : {
normal : 0,
moreAndMore : 1,
multiplayer : 2
}
};
|
import React from "react"
import { Box, InputBase } from "@material-ui/core"
import { makeStyles } from "@material-ui/core/styles"
const useStyles = makeStyles(theme => ({
root: {
backgroundColor: theme.palette.common.white,
borderRadius: "3px",
padding: ".75rem 1.25rem",
},
}))
const TextInput = () => {
const classes = useStyles()
return (
<InputBase
classes={{ root: classes.root }}
fullWidth
placeholder="Loan amount"
/>
)
}
export default TextInput
|
(function() {
(function(root) {
(root.tome != null ? root.tome : root.tome = {}).version = '0.0.1';
module.exports = root.tome;
})(typeof global !== "undefined" && global !== null ? global : window);
}).call(this);
(function() {
tome.Event = (function() {
function Event(options) {
var _ref, _ref1, _ref2;
if (options == null) {
options = {};
}
this.type = (_ref = options.type) != null ? _ref : 'UNKNOWN';
this.data = (_ref1 = options.data) != null ? _ref1 : {};
this.source = (_ref2 = options.source) != null ? _ref2 : {};
this.stopped = false;
}
Event.prototype.stopPropagation = function() {
this.stopped = true;
return this;
};
return Event;
})();
}).call(this);
(function() {
var callEventHandlers,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
tome.EventSource = (function() {
function EventSource() {
this.trigger = __bind(this.trigger, this);
this.off = __bind(this.off, this);
this.on = __bind(this.on, this);
this.handlers = {};
}
EventSource.prototype.on = function(event_type, handler) {
var _base;
(_base = this.handlers)[event_type] || (_base[event_type] = collection([]));
this.handlers[event_type].add(handler);
return this;
};
EventSource.prototype.off = function(event_type, handler) {
var _ref;
if (handler == null) {
handler = false;
}
if (handler) {
this.handlers[event_type] = this.handlers[event_type].without(handler);
}
if (!handler || ((_ref = this.handlers[event_type]) != null ? _ref.isEmpty() : void 0)) {
delete this.handlers[event_type];
}
return this;
};
EventSource.prototype.trigger = function(event_type, data) {
var event;
if (data == null) {
data = {};
}
event = new tome.Event({
type: event_type,
data: data,
source: this
});
if (this.handlers[event_type]) {
callEventHandlers(event, this.handlers[event_type]);
}
return event;
};
return EventSource;
})();
callEventHandlers = function(event, handlers) {
var handler, _i, _len, _ref;
_ref = handlers.array();
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
handler = _ref[_i];
if (event.stopped) {
return;
}
handler.call(event.source, event);
}
};
}).call(this);
(function() {
var _, _s,
__slice = [].slice;
_ = require('lodash');
_s = require('underscore.string');
tome.Collection = (function() {
var _this = this;
function Collection(items) {
var item, _i, _len;
if (items == null) {
items = [];
}
this.items = [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (item) {
this.add(item);
}
}
}
Collection.prototype.add = function() {
var item, items, _i, _len;
items = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
for (_i = 0, _len = items.length; _i < _len; _i++) {
item = items[_i];
if (item) {
this.items.push(item);
}
}
this.length = this.items.length;
return this;
};
Collection.prototype.array = function() {
var item, _i, _len, _ref, _results;
_ref = this.items;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
item = _ref[_i];
_results.push(item);
}
return _results;
};
Collection.LODASH_METHODS = _s.words("all any at each first last rest compact map reduce reduceRight find isEmpty pluck filter select reject size sample difference uniq intersection where without remove");
Collection.LODASH_METHODS.forEach(function(method) {
return Collection.prototype[method] = function() {
var args, results;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
args.unshift(this.items);
results = _[method].apply(_, args);
if (_.isArray(results)) {
return new Collection(results);
} else {
return results;
}
};
});
return Collection;
}).call(this);
}).call(this);
(function() {
var uuid,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
uuid = require('node-uuid');
tome.Entity = (function(_super) {
__extends(Entity, _super);
function Entity(options) {
var _ref, _ref1;
if (options == null) {
options = {};
}
this.has = __bind(this.has, this);
this.get = __bind(this.get, this);
this.add = __bind(this.add, this);
this.id = (_ref = options.id) != null ? _ref : uuid.v4();
this.current_components = {};
if ((_ref1 = options.components) != null) {
_ref1.forEach(this.add);
}
}
Entity.prototype.add = function(component) {
return this.current_components[component.name] = component;
};
Entity.prototype.components = function() {
return this.current_components;
};
Entity.prototype.get = function(component_name) {
return this.current_components[component_name];
};
Entity.prototype.has = function(component_name) {
var _ref;
return (_ref = this.get(component_name)) !== null && _ref !== (void 0);
};
Entity.prototype.is = Entity.prototype.has;
return Entity;
})(tome.EventSource);
}).call(this);
(function() {
var getName, setAttribute, _, _s,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
_ = require('lodash');
_s = require('underscore.string');
tome.EntityComponent = (function(_super) {
__extends(EntityComponent, _super);
function EntityComponent(options) {
var attr, v, _ref, _ref1, _ref2, _ref3;
if (options == null) {
options = {};
}
this.attrs = {};
_ref2 = (_ref = (_ref1 = options.attributes) != null ? _ref1 : options.attrs) != null ? _ref : {};
for (attr in _ref2) {
v = _ref2[attr];
this.set(attr, v);
}
this.name = (_ref3 = options.name) != null ? _ref3 : getName(this);
if (this.accessible_attrs != null) {
this.make_accessible(this.accessible_attrs);
}
}
EntityComponent.prototype.attributes = function() {
return this.attrs;
};
EntityComponent.prototype.entity = function(entity) {
if (entity) {
return this.entity = entity;
} else {
return entity;
}
};
EntityComponent.prototype.get = function(attr_name) {
return this.attrs[attr_name];
};
EntityComponent.prototype.has = function(attr_name) {
var _ref;
return (_ref = this.get(attr_name)) !== null && _ref !== (void 0);
};
EntityComponent.prototype.is = EntityComponent.prototype.has;
EntityComponent.prototype.json = function() {
return {
name: this.name,
attributes: this.attrs
};
};
EntityComponent.prototype.jsonString = function() {
return JSON.stringify(this.json());
};
EntityComponent.prototype.make_accessible = function(attr_names) {
var _ref,
_this = this;
attr_names = (_ref = typeof attr_names.split === "function" ? attr_names.split(' ') : void 0) != null ? _ref : attr_names;
return attr_names.forEach(function(attr_name) {
return _this.constructor.prototype[attr_name] = function(value) {
if (value) {
_this.set(attr_name, value);
return _this;
} else {
return _this.get(attr_name);
}
};
});
};
EntityComponent.prototype.readOnly = function() {
return new EntityComponent({
attributes: _.cloneDeep(this.attrs)
}).set({
readonly: true
});
};
EntityComponent.prototype.set = function(attr, val) {
var attr_name;
if (val == null) {
val = null;
}
if (_.isObject(attr)) {
for (attr_name in attr) {
val = attr[attr_name];
setAttribute(this.attrs, attr_name, val);
}
} else {
setAttribute(this.attrs, attr, val);
}
return this;
};
return EntityComponent;
})(tome.EventSource);
getName = function(component) {
return _s.underscored(component.constructor.name.replace(/component/i, ''));
};
setAttribute = function(attrs, attr, val) {
if (attrs.readonly === true) {
throw exception("Attempting to set " + attr + " for read-only component");
}
if (_.isFunction(val)) {
val = typeof val === "function" ? val() : void 0;
}
if (val === (void 0) || val === null) {
return delete attrs[attr];
} else {
return attrs[attr] = val;
}
};
}).call(this);
(function() {
tome.EntityController = (function() {
function EntityController() {}
EntityController.prototype.update = function(entities, update_stats, game_state) {};
EntityController.prototype.render = function(entities, update_stats, game_state) {};
return EntityController;
})();
}).call(this);
(function() {
var _, _s,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
_ = require('lodash');
_s = require('underscore.string');
tome.Game = (function() {
var addState, setCurrentState;
Game.prototype.states = {};
Game.prototype.current_state = null;
Game.prototype.stopped = true;
function Game(states) {
var name, options;
if (states == null) {
states = {};
}
this.update = __bind(this.update, this);
this.render = __bind(this.render, this);
for (name in states) {
options = states[name];
addState(this, name, options);
if (!this.current_state) {
setCurrentState(this, name);
}
}
}
Game.prototype.currentState = function() {
return this.current_state;
};
Game.prototype.start = function() {
if (_.isEmpty(this.states)) {
throw Error("No game states defined");
}
this.stopped = false;
this.update();
this.render();
return this;
};
Game.prototype.stop = function() {
this.stopped = true;
return this;
};
Game.prototype.render = function(timestamp) {
if ((typeof requestAnimationFrame !== "undefined" && requestAnimationFrame !== null) && !this.stopped) {
this.current_state.render(timestamp);
requestAnimationFrame(this.render);
}
};
Game.prototype.update = function() {
if (!this.stopped) {
this.current_state.update();
schedule(tome.GameFrameStats.DEFAULT_STEP_DELTA, this.update);
}
};
addState = function(game, state_name, state_options) {
if (state_options == null) {
state_options = {};
}
state_options.name = state_name;
return game.states[state_name] = new tome.GameState(state_options);
};
setCurrentState = function(game, name) {
game.current_state = game.states[name];
return this;
};
return Game;
})();
}).call(this);
(function() {
tome.GameFrameStats = (function() {
GameFrameStats.DEFAULT_STEP_DELTA = 1000 / 60;
GameFrameStats.prototype.current_frame_time = null;
GameFrameStats.prototype.last_frame_time = null;
GameFrameStats.prototype.last_frame_duration = null;
GameFrameStats.prototype.frames_per_second = 0;
GameFrameStats.prototype.frame_count = 0;
function GameFrameStats() {
this.current_frame_time = +new Date();
}
GameFrameStats.prototype.step = function(timestamp) {
if (timestamp == null) {
timestamp = +new Date();
}
this.last_frame_time = this.current_frame_time;
this.current_frame_time = timestamp;
this.last_frame_duration = this.current_frame_time - this.last_frame_time;
this.frames_per_second = Math.floor(this.last_frame_duration / 1000.0);
this.frame_count++;
};
GameFrameStats.prototype.fps = function() {
return this.frames_per_second;
};
GameFrameStats.prototype.stepDelta = function() {
return this.last_frame_duration || GameFrameStats.DEFAULT_STEP_DELTA;
};
return GameFrameStats;
})();
}).call(this);
(function() {
var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
tome.GameState = (function() {
function GameState(options) {
var _ref, _ref1;
if (options == null) {
options = {};
}
this.render = __bind(this.render, this);
this.update = __bind(this.update, this);
if (options.name != null) {
this.name = options.name;
} else {
throw new Error("game states require a name");
}
this.frame_update_stats = new tome.GameFrameStats;
this.frame_render_stats = new tome.GameFrameStats;
this.controllers = (_ref = options.controllers) != null ? _ref : [];
this.entities = (_ref1 = options.entities) != null ? _ref1 : [];
}
GameState.prototype.update = function(timestamp) {
var _this = this;
this.frame_update_stats.step(timestamp);
this.controllers.forEach(function(controller) {
return typeof controller.update === "function" ? controller.update(_this.entities, _this.frame_update_stats, _this) : void 0;
});
};
GameState.prototype.render = function(timestamp) {
var _this = this;
this.frame_render_stats.step(timestamp);
this.controllers.forEach(function(controller) {
return typeof controller.render === "function" ? controller.render(_this.entities, _this.frame_render_stats, _this) : void 0;
});
};
return GameState;
})();
}).call(this);
(function() {
(function(root) {
root.findClass = function(name, suffix, strict) {
var class_name, clazz, suffixed_name, _ref, _ref1, _ref2;
if (suffix == null) {
suffix = '';
}
if (strict == null) {
strict = false;
}
if (!/([A-Z0-9][a-z0-9]+)+/.test(class_name)) {
class_name = _.str.classify("" + class_name);
}
suffixed_name = "" + class_name + suffix;
clazz = (_ref = (_ref1 = (_ref2 = tome[class_name]) != null ? _ref2 : tome[suffixed_name]) != null ? _ref1 : root[class_name]) != null ? _ref : root[suffixed_name];
if (strict && !_.isFunction(clazz)) {
throw exception("Can't find class " + class_name);
}
return clazz;
};
root.collection = function(items) {
if (items == null) {
items = [];
}
if (items instanceof tome.Collection) {
return items;
}
if (items.constructor.name !== 'Array') {
items = arguments;
}
return new tome.Collection(items);
};
root.entity = function(components) {
if (components == null) {
components = [];
}
if (arguments.length > 1) {
components = arguments;
}
return new tome.Entity({
components: components
});
};
root.component = function(name, attrs) {
var _ref;
if (attrs == null) {
attrs = {};
}
return new ((_ref = findClass(name)) != null ? _ref : tome.EntityComponent)({
attributes: attrs
});
};
root.controller = function(name) {
var _ref;
return new ((_ref = findClass(name)) != null ? _ref : tome.EntityController)({
attributes: attrs
});
};
return root.components = function(components) {
var attrs, name;
if (components == null) {
components = {};
}
return collection((function() {
var _results;
_results = [];
for (name in components) {
attrs = components[name];
_results.push(component(name, attrs));
}
return _results;
})());
};
})(typeof global !== "undefined" && global !== null ? global : window);
}).call(this);
(function() {
(function(root) {
root.schedule = function(ms, fn) {
return setTimeout(fn, ms);
};
root.unschedule = function(timeout_id) {
return clearTimeout(timeout_id);
};
return root.async = function(fn) {
return schedule(0, fn);
};
})(typeof global !== "undefined" && global !== null ? global : window);
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
tome.AccountComponent = (function(_super) {
__extends(AccountComponent, _super);
function AccountComponent() {
_ref = AccountComponent.__super__.constructor.apply(this, arguments);
return _ref;
}
AccountComponent.prototype.accessible_attrs = 'token connectedAt';
return AccountComponent;
})(tome.EntityComponent);
}).call(this);
(function() {
}).call(this);
(function() {
var _ref,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
tome.PositionComponent = (function(_super) {
__extends(PositionComponent, _super);
function PositionComponent() {
_ref = PositionComponent.__super__.constructor.apply(this, arguments);
return _ref;
}
PositionComponent.prototype.accessible_attrs = 'x y z';
PositionComponent.prototype.distance = function(position) {
var x, y, z;
(x = position.x() - this.x()) * x;
(y = position.y() - this.y()) * y;
(z = position.z() - this.z()) * z;
return Math.sqrt(x + y + z);
};
return PositionComponent;
})(tome.EntityComponent);
}).call(this);
|
import React from 'react'
import img from "../img1.jpg"
import { MDBMask, MDBView, MDBCol } from "mdbreact";
export default function Home() {
return (
<MDBCol sm="15" >
<MDBView hover zoom>
<img
src={img}
className="img-fluid"
alt=""
/>
<MDBMask className="flex-center">
<p className="white-text">mal7oog</p>
</MDBMask>
</MDBView>
</MDBCol>
)
}
|
import React from 'react';
import { Root } from 'native-base'
import { StyleSheet } from 'react-native';
import { Container, Header, Content, Body, Text, Title, Icon, ActionSheet, Form, Item, Label, Input, Button, Right } from 'native-base';
import DatePicker from 'react-native-datepicker'
import TaskProvider from '../Providers/TaskProvider'
import CategoryProvider from '../Providers/CategoryProvider'
export default class TaskInformation extends React.Component {
constructor(props) {
super(props);
this.state = state = {
data: null,
saveState: "Saved",
taskTitle: '',
taskDescription: '',
taskDate: '',
taskCategory: '',
date: '',
TaskData: TaskProvider.getInstance(),
categoriesList: [],
categorysToDisplay: [],
CategoryData: CategoryProvider.getInstance(),
currentCategory: '',
oldCategory: ''
}
const { navigation } = this.props;
this.state.data = navigation.getParam('data', 'Default');
this.state.categoriesList = navigation.getParam('categoriesList', 'Default');
this.populateCategoryNames();
this.state.taskTitle = this.state.data.taskTitle;
this.state.taskDescription = this.state.data.taskDescription;
this.state.taskDate = this.state.data.taskDate;
this.state.taskCategory = this.state.data.taskCategory;
this.setState ({ oldCategory : this.state.taskCategory})
this.state.oldCategory = this.state.taskCategory
}
populateCategoryNames() {
this.setState({ categoriesList: [] })
for (let i = 0; i < this.state.categoriesList.length; i++) {
this.state.categorysToDisplay.push(this.state.categoriesList[i].categoryName);
}
}
unsave() {
//alert(this.state.taskCategory)
this.setState({ saveState: "Save" })
}
updateTask() {
this.setState({ saveState: "Saved" });
this.state.TaskData.updateTask(this.state.taskTitle,
this.state.taskDescription,
this.state.taskDate,
this.state.taskCategory,
this.state.data,
);
//Update categories
if (this.state.taskCategory != this.state.oldCategory) {
this.state.CategoryData.updateCategoryCount(
this.state.categoriesList,
this.state.oldCategory,
'minus'
);
this.state.CategoryData.updateCategoryCount(
this.state.categoriesList,
this.state.taskCategory,
'plus'
);
this.state.oldCategory = this.state.taskCategory
}
this.props.navigation.navigate('HomeScreen')
}
render() {
return (
<Root>
<Container style={styles.container}>
<Content>
<Header style={styles.header}>
<Body>
<Title style={styles.title}>Edit: {this.state.taskTitle}</Title>
</Body>
<Right>
<Button transparent onPress={() => this.props.navigation.navigate('HomeScreen')}>
<Icon name='close' />
</Button>
</Right>
</Header>
<Form>
<Item floatingLabel>
<Label>Title</Label>
<Input
autoCorrect={false}
autoCapitalize="none"
onChangeText={taskTitle =>
this.setState({ taskTitle },
this.unsave()
)}
value={this.state.taskTitle}
/>
</Item>
<Item floatingLabel>
<Label>Details</Label>
<Input
multiline={true}
numberOfLines={5}
onChangeText={taskDescription =>
this.setState({ taskDescription },
this.unsave()
)}
value={this.state.taskDescription}
style={styles.textArea}
/>
</Item>
</Form>
<DatePicker
style={styles.date}
date={this.state.taskDate}
mode="date"
placeholder="Event Date"
format="DD-MM-YYYY"
minDate="01-01-2001"
maxDate="31-12-2030"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
showIcon={false}
hideText={false}
customStyles={{
dateInput: {
borderLeftWidth: 0,
borderRightWidth: 0,
borderTopWidth: 0,
padding: 5,
alignItems: 'flex-start',
},
placeholderText: {
color: '#234456'
}
}}
onDateChange={(date) => {
this.setState({ taskDate: date }),
this.unsave()
}} />
<Button full transparent dark style={styles.categoryButton} onPress={() =>
ActionSheet.show(
{
options: this.state.categorysToDisplay,
cancelButtonIndex: this.state.categorysToDisplay.indexOf('Default'),
title: "Choose a category"
},
(buttonIndex) => {
this.setState({ taskCategory: this.state.categorysToDisplay[buttonIndex] },
this.unsave()
);
}
)}
>
<Text>{this.state.taskCategory}</Text>
</Button>
<Button style={styles.buttonStyle}
full
rounded
onPress={this.updateTask.bind(this)}
>
<Text style={{ color: 'white' }}> {this.state.saveState}</Text>
</Button>
</Content>
</Container>
</Root>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
taskText: {
textDecorationLine: 'line-through',
color: 'black',
marginLeft: 10,
marginRight: 10
},
text: {
color: 'grey',
marginLeft: 10,
marginRight: 10
},
header: {
backgroundColor: '#445df7',
fontWeight: 'bold',
},
title: {
fontWeight: 'bold',
},
buttonStyle: {
backgroundColor: "#445df7",
margin: 10,
},
textArea: {
height: 200,
marginLeft: 10,
marginRight: 10,
marginTop: 10,
textAlignVertical: "top"
},
date: {
width: '100%',
marginLeft: 15,
marginTop: 10,
marginRight: 15,
color: 'black'
},
categoryButton: {
borderWidth: 0.5,
borderColor: 'black',
margin: 10,
borderLeftWidth: 0,
borderRightWidth: 0,
borderTopWidth: 0,
justifyContent: "flex-start"
}
}) |
var express = require('express');
var router = express.Router();
const loggedIn = require('../middleware/loggedIn');
const postsController = require('../controllers/postsController');
const commentsController = require('../controllers/commentsController');
const votesController = require('../controllers/votesController');
router
.route('')
.get(postsController.getPosts)
.post(loggedIn, postsController.createPost)
.put(loggedIn, postsController.updatePost)
.delete(loggedIn, postsController.deletePost);
router
.route('/vote')
.post(loggedIn, votesController.addVote)
.delete(loggedIn, votesController.removeVote);
router
.route('/comments')
.get(commentsController.getComments)
.post(loggedIn, commentsController.addComment)
.delete(loggedIn, commentsController.deleteComment);
module.exports = router;
|
var estiloPopup = {'maxWidth': '200','maxHeigth':'200'};
var sitios=[];
var radio;
var mark_pos = L.icon({
iconUrl: 'img/marcador-de-posicion.png',
iconSize: [35, 35],
iconAnchor: [28, 28],
popupAnchor: [-6,-20]
});
for (var i = 0; i < app.length; i++) {
L.marker([app[i]['coordenadax'],app[i]['coordenaday']],{icon:mark_pos,draggable: false})
.bindPopup("<h3 style='text-align:center;'>"+app[i]['nombre']+"</h3><p><img style='width:100%;' src='img/"+app[i]['img']+"'></p>",estiloPopup).addTo(map);
}
map.on(L.Draw.Event.CREATED, function (e) {
drawnItems.clearLayers();
sitios=[];
var layer = e.layer;
drawnItems.addLayer(layer);
//obtener el radio
var a=(layer.getRadius()/1E3);
var latLngs = layer.getLatLng();
var lat=latLngs['lat'];
var lon=latLngs['lng'];
for (var i = 0; i < app.length; i++) {
var km=(getKilometros(lat,lon,app[i]['coordenadax'],app[i]['coordenaday']));
if(km<=a){
sitios.push(app[i]['id_poi']);
}
}
});
map.on(L.Draw.Event.EDITRESIZE, function(event) {
if (L.Browser.mobile) {
map.gestureHandling.disable();
}
var layer = event.layer;
var a=(layer.getRadius()/1E3);
var latLngs = layer.getLatLng();
var lat=latLngs['lat'];
var lon=latLngs['lng'];
sitios=[];
for (var i = 0; i < app.length; i++) {
if((getKilometros(lat,lon,app[i]['coordenadax'],app[i]['coordenaday']))<= a){
sitios.push(app[i]['id_poi']);
}
radio=a;
}
});
map.on(L.Draw.Event.EDITMOVE, function(event) {
if (L.Browser.mobile) {
map.gestureHandling.disable();
}
var layer = event.layer;
var a=(layer.getRadius()/1E3);
var latLngs = layer.getLatLng();
var lat=latLngs['lat'];
var lon=latLngs['lng'];
sitios=[];
console.clear();
for (var i = 0; i < app.length; i++) {
if((getKilometros(lat,lon,app[i]['coordenadax'],app[i]['coordenaday']))<= a){
sitios.push(app[i]['id_poi']);
}
radio=a;
}
});
map.on(L.Draw.Event.EDITED, function(event) {
if (L.Browser.mobile) {
map.gestureHandling.enable();
}
var layers = event.layers;
layers.eachLayer(function(layer) {
var a=(layer.getRadius()/1E3);
var latLngs = layer.getLatLng();
var lat=latLngs['lat'];
var lon=latLngs['lng'];
sitios=[];
for (var i = 0; i < app.length; i++) {
if((getKilometros(lat,lon,app[i]['coordenadax'],app[i]['coordenaday']))<=a){
sitios.push(app[i]['id_poi']);
}
} radio=a;
});
});
getKilometros = function(lat1,lon1,lat2,lon2)
{
rad = function(x) {return x*Math.PI/180;}
var R = 6378.137;
var dLat = rad( lat2 - lat1 );
var dLong = rad( lon2 - lon1 );
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.cos(rad(lat1)) * Math.cos(rad(lat2)) * Math.sin(dLong/2) * Math.sin(dLong/2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
var d = R * c;
return d;
}
L.easyButton('<img src="img/enviar.png" style="width:15px;">', function(btn, map){
$('#pois').val(sitios);
if(sitios.length > 1){
document.formulario.submit();
}else{
alert('Para la crear una ruta debe seleccionar mas de un punto de interes');
}
}).addTo(map);
|
//var pElt = document.querySelector('p');
//pElt.style.color = 'red';
//pElt.style.margin = '50px';
//pElt.style.backgroundColor = 'blue';
var stylePara =
getComputedStyle(document.getElementById('para'));
console.log(stylePara.fontStyle);
console.log(stylePara.color);
|
let a = document.querySelector('.old')
a.classList.add('new') //COLOR CHANGES TO BLUE. |
import React, { Component } from 'react'
import { StyleSheet } from 'quantum'
import { Button } from 'bypass/ui/button'
import { ColumnLayout, RowLayout, Layout } from 'bypass/ui/layout'
import { Input } from 'bypass/ui/input'
import { Text } from 'bypass/ui/text'
import Toolbar from './Toolbar'
import Price from './Price'
const styles = StyleSheet.create({
self: {
transition: 'all 0.3s',
border: '2px solid #9e9e9e',
borderRadius: '5px',
background: '#ffffff',
width: '100%',
display: 'flex',
},
})
class UpdatePrice extends Component {
static defaultProps = {
prices: [],
}
constructor(props, context) {
super(props, context)
this.state = {
prices: props.prices,
price: '',
}
}
componentWillReceiveProps(nextProps) {
if (nextProps.prices !== this.props.prices) {
this.setState({ prices: nextProps.prices })
}
}
onSelectPrice = (price) => {
const { prices } = this.state
this.setState({
prices: prices.map(item => {
if (item === price) {
return {
...item,
selected: !item.selected,
}
}
return item
}),
})
}
onChangePrice = ({ target }) => {
this.setState({ price: target.value })
}
onUpdate = () => {
const { onUpdate } = this.props
const { price, prices } = this.state
const selected = prices.filter(item => item.selected)
if (onUpdate) {
onUpdate(selected, price)
}
this.setState({ price: '' })
}
onRemove = () => {
const { onRemove } = this.props
const { prices } = this.state
const selected = prices.filter(item => item.selected)
if (onRemove) {
onRemove(selected)
}
}
renderTopTollbar() {
return (
<Text size={14}>
{__i18n('SELLER.PRICING.CURRENT')}
</Text>
)
}
renderPrices() {
const { prices } = this.state
return (
<div style={{ width: '100%' }}>
{prices.map((price, index) => (
<Price
key={index}
price={price}
onSelect={this.onSelectPrice}
/>
))}
</div>
)
}
renderBottomToolbar() {
const { price, prices } = this.state
const selected = prices.filter(item => item.selected)
return (
<ColumnLayout align='center'>
<Layout basis='230px' shrink={1}>
<Input
value={price}
disabled={!selected.length}
placeholder={__i18n('SELLER.PRICING.PRICE')}
onChange={this.onChangePrice}
/>
</Layout>
<Layout grow={1} />
<Layout basis='10px' />
<Layout>
<Button
size='small'
disabled={!(selected.length && price.length)}
onClick={this.onUpdate}
>
{__i18n('SELLER.PRICING.UPDATE')}
</Button>
</Layout>
<Layout basis='10px' />
<Layout>
<Button
size='small'
disabled={!selected.length}
onClick={this.onRemove}
>
{__i18n('LANG.BUTTONS.DELETE')}
</Button>
</Layout>
</ColumnLayout>
)
}
render() {
return (
<div className={styles()}>
<RowLayout>
<Layout>
<Toolbar>
{this.renderTopTollbar()}
</Toolbar>
</Layout>
<Layout grow={1}>
{this.renderPrices()}
</Layout>
<Layout>
<Toolbar>
{this.renderBottomToolbar()}
</Toolbar>
</Layout>
</RowLayout>
</div>
)
}
}
export default UpdatePrice
|
import React from 'react'
import PropTypes from 'proptypes'
const ShopCard = (props) => {
return (
<li className="ShopCard" key={props.name}>
<div className="ShopPhoto" style={{ backgroundImage: `url(${props.photoUrl})`}}></div>
<h3>{props.name}</h3>
<p>{props.address1}<br/>{props.city}, {props.state}</p>
</li>
)
}
ShopCard.propTypes = {
name: PropTypes.string.isRequired,
address1: PropTypes.string.isRequired,
city: PropTypes.string.isRequired,
state: PropTypes.string.isRequired,
photoUrl: PropTypes.string.isRequired
}
export default ShopCard
|
'use strict';
let fs = require('fs');
/**
* Adds two numbers together.
* @param {string} file The path to the file relative to test/res.
* @return {string} The file's contents.
*/
export function readResFile(file) {
const relFilePath = 'test/res/' + file;
let data = fs.readFileSync(relFilePath, 'utf8');
return data;
}
export default {
readResFile,
};
|
/* If we don’t sleep enough, we accumulate sleep debt. In this project we’ll calculate if you’re getting enough sleep each week using a sleep debt calculator.
The program will determine the actual and ideal hours of sleep for each night of the last week.
Finally, it will calculate, in hours, how far you are from your weekly sleep goal. */
// determining how many hours of sleep you got each night of the week
const getSleepHours = day => {
switch (day) {
case 'monday':
return 8;
break;
case 'teusday':
return 6;
break;
case 'wednesday':
return 5;
break;
case 'thursday':
return 7;
break;
case 'friday':
return 5;
break;
case 'saturday':
return 8;
break;
case 'sunday':
return 9;
break;
}
}
// Now we calculate the total sleep hours that you actually slept
const getActualSleepHours = () =>
getSleepHours('monday') +
getSleepHours('teusday') +
getSleepHours('wednesday') +
getSleepHours('thursday') +
getSleepHours('friday') +
getSleepHours('saturday') +
getSleepHours('sunday');
// Get the ideal sleep hours that you prefer
const getIdealSleepHours = () => {
idealHours = 8
return idealHours * 7 // multiplying by 7 to get the total hours prefered in a week
}
// Calculate the sleep debt, if any.
const calculateSleepDebt = () => {
actualSleepHours = getActualSleepHours();
idealSleepHours = getIdealSleepHours();
if (actualSleepHours === idealHours) {
console.log( 'You got the perfect amount of sleep.')
} else if (actualSleepHours > idealSleepHours) {
console.log(`You got ${actualSleepHours - idealSleepHours} hours more sleep than needed.`)
} else {
console.log(`You got ${actualSleepHours - idealSleepHours} hours less sleep than required. You should sleep more.`)
}
}
calculateSleepDebt() |
// console.log('hello worldjkfksdjkafjkfhk')
// const http = require('http');
// const server = http.createServer((req, res)=>{
// res.setHeader('Content-Type', 'text/html')
// res.end('<h1>hello browser<h1/>')
// res.end('more data...')
// })
// server.listen(3000)
//express
// const exp = require('express')
// const bp = require('body-parser')
// const app = exp()
// app.use(bp.urlencoded({ extended: false }))
// // parse application/json
// app.use(bp.json())
// app.use('/',exp.static(__dirname+'/public'))
// app.post('/login', (req,res)=>{
// console.log(req.query)
// console.log(req.body.u)
// const data = {
// message: 'ok',
// user
// }
// res.send(data)
// console.log(req.query)
// const user = req.query.username;
// res.send('get data firm you' + user)
// const user = {
// name: ' eli'
// }
// res.send(user)
// })
// app.listen(3000)
/*
const exp = require('express');
const bp = require('body-parser');
const app = exp();
// parse application/x-www-form-urlencoded
app.use(bp.urlencoded({ extended: false }))
// parse application/json
app.use(bp.json())
// app.set('port',9000);
// console.log(__dirname);
app.use('/',exp.static(__dirname+'/public'));
app.route('/login')
.get( (req,res)=> {
console.log(req.query);
const user = req.query.username;
console.log(user);
const pass = req.query.p;
const data = {
message: 'Welcome',
user
}
console.log(data);
res.send(data)
})
.post( (req,res) => {
console.log(req.body);
let user = req.body.username;
let pass = req.body.password;
const data = {
message: 'Welcome',
user,
pass
}
console.log('POST',data);
res.send(data)
})
app.get('/user/:ziv',(req,res)=>{
console.log(req.params);
res.send('bla bla')
})
app.listen(3000);
// app.listen(app.get('port'), ()=>{
// console.log('listen on port 9000');
// })
*/
//exersize 1
// const http = require('http');
// const server = http.createServer((req, res)=>{
// res.setHeader('Content-Type', 'text/html')
// res.end('<h1>This is my first response<h1/><br><h3>This is my second response</h3><br><h4>This is my third response</h4>')
// })
// server.listen(3000)
//exersize 2
// const http = require('http');
// const server = http.createServer((req, res)=>{
// res.setHeader('Content-Type', 'application/json')
// let obj = {
// name: 'eli'
// }
// res.end(JSON.stringify(obj))
// })
// server.listen(3000)
//exersize 3
// const exp = require('express')
// const app = exp()
// app.get('/', (req, res)=>{
// let obj = {
// name: 'eli'
// }
// res.send(obj)
// })
// app.listen(8080);
//exersize xp 2
//1
const exp = require('express')
const app = exp()
app.get('/public', (req, res)=>{
let obj = {
name: 'eli'
}
res.send(obj)
})
app.listen(3000);
|
/*
* Copyright (C) 2021 Radix IoT LLC. All rights reserved.
*/
import dataPointTagKeySelectTemplate from './dataPointTagKeySelect.html';
import './dataPointTagKeySelect.css';
/**
* @ngdoc directive
* @name ngMango.directive:maDataPointTagKeySelect
* @restrict 'E'
* @scope
*
* @description Displays a drop down list of tag keys.
*
* @param {expression} ng-model Assignable expression to output the selected tag key. Output will be a string.
*
* @usage
* <ma-data-point-tag-key-select ng-model="tagKey"></ma-data-point-tag-key-select>
*
**/
class DataPointTagKeySelectController {
static get $$ngIsClass() { return true; }
static get $inject() { return ['maDataPointTags', 'maTranslate']; }
constructor(maDataPointTags, maTranslate) {
this.maDataPointTags = maDataPointTags;
this.maTranslate = maTranslate;
this.queryOnOpen = true;
}
$onInit() {
this.ngModelCtrl.$render = () => {
this.selected = this.ngModelCtrl.$viewValue;
};
this.updatePlaceholder();
this.updateDisabledOptions();
this.updateExcludeTags();
}
$onChanges(changes) {
if (changes.editMode && !changes.editMode.isFirstChange()) {
this.updatePlaceholder();
}
if (changes.disabledOptions && !changes.disabledOptions.isFirstChange()) {
this.updateDisabledOptions();
}
if (changes.excludeTags && !changes.excludeTags.isFirstChange()) {
this.updateExcludeTags();
}
}
updatePlaceholder() {
this.filterPlaceholder = this.maTranslate.trSync(this.editMode ? 'ui.components.filterOrAddTagKey' : 'ui.app.filter');
}
onOpen() {
this.dropDownOpen = true;
}
onClose() {
this.dropDownOpen = false;
// delete the query promise so the API request is issued on next open
if (this.queryOnOpen) {
delete this.queryPromise;
}
}
doQuery(filter) {
if (!this.queryPromise) {
this.queryPromise = this.maDataPointTags.keys();
if (this.onQuery) {
this.onQuery({$promise: this.queryPromise});
}
}
return this.queryPromise.then(values => {
if (this.editMode) {
values = this.addSelectedOptions(values);
if (filter && !values.includes(filter)) {
this.addNewValue = filter;
} else {
delete this.addNewValue;
}
}
return values
.filter(v => !filter || typeof v === 'string' && v.toLowerCase().includes(filter.toLowerCase()))
.sort();
});
}
inputChanged() {
this.ngModelCtrl.$setViewValue(this.selected);
}
updateDisabledOptions() {
this.disabledOptionsMap = {};
if (Array.isArray(this.disabledOptions)) {
for (const key of this.disabledOptions) {
this.disabledOptionsMap[key] = true;
}
}
}
updateExcludeTags() {
this.excludeTagsMap = {};
if (Array.isArray(this.excludeTags)) {
for (const key of this.excludeTags) {
this.excludeTagsMap[key] = true;
}
}
}
/**
* Ensures all currently selected tags are available in the list when using edit mode.
* @param {string[]} values
* @returns {string[]}
*/
addSelectedOptions(values) {
const valueSet = new Set(values);
if (this.multiple && Array.isArray(this.selected)) {
this.selected.forEach(v => valueSet.add(v));
} else if (!this.multiple && this.selected != null) {
valueSet.add(this.selected)
}
return Array.from(valueSet);
}
}
export default {
bindings: {
disabledOptions: '<?',
multiple: '<?selectMultiple',
selectedText: '<?',
excludeTags: '<?',
noFloat: '<?',
onQuery: '&?',
queryOnOpen: '<?',
editMode: '<?',
labelText: '@?',
required: '<?ngRequired',
disabled: '<?ngDisabled'
},
require: {
ngModelCtrl: 'ngModel'
},
transclude: {
label: '?maLabel'
},
template: dataPointTagKeySelectTemplate,
controller: DataPointTagKeySelectController,
designerInfo: {
translation: 'ui.components.maDataPointTagKeySelect',
icon: 'label'
}
};
|
var $=jQuery.noConflict();
(function($){
"use strict";
$(function(){
/*------------------------------------*\
#GLOBAL
\*------------------------------------*/
$(window).ready(function(){
footerBottom();
$('.carousel').carousel({
interval:false
});
//finalConcurso();
if ( $("#concurso-terminado").length > 0 ) {
$('#concurso-terminado').modal('show');
}
if(window.location.href.indexOf("album/?cat=") > -1) {
$( ".carousel-control" ).addClass('hidden');
};
if ( $('.box-raking').length > 0 && $('.js-current-user').length > 0 ){
$('.box-raking').scrollTo(".js-current-user", 2000);
}
});
$(window).on('resize', function(){
footerBottom();
});
$('.image-perfil').on('click', function(event){
event.preventDefault();
//Cuando ya hay un perfil seleccionado previamente
$( ".image-perfil div.perfil-selected" ).removeClass('perfil-selected');
$( ".image-perfil div.perfil-selected" ).addClass('perfil-unselected');
$(this).find('div').addClass('perfil-selected');
//console.log('perfil seleccionado');
if( $('.image-perfil div.perfil-selected').hasClass('perfil-unselected') ){
$( ".image-perfil div.perfil-selected" ).removeClass('perfil-unselected');
}
var id = $(this).data('id');
$('#avatar-participante').val(id);
});
// CARGAR MEDALLA
if (document.getElementById('gifCargando')) {
var $img = $('#gifCargando');
$img.show(0);
$('#imgMedalla').hide(0);
setTimeout(function() {
$img.attr('src', $img.attr('src'));
}, 0);
setTimeout(function() {
$('#imgMedalla').show(0);
}, 3200);
setTimeout(function() {
$img.hide(0);
$('.formCargaMedalla').addClass('hidden');
$('#textoCargaExitosa').removeClass('hidden');
}, 3700);
}
});
})(jQuery);
//Footer fixed
function footerBottom(){
var alturaFooter = getFooterHeight();
$('.main').css('padding-bottom', alturaFooter );
}
function getHeaderHeight(){
return $('.js-header').outerHeight();
}
function getFooterHeight(){
return $('footer').outerHeight();
}
//Show controls video
$('video').hover(function toggleControls() {
if (this.hasAttribute("controls")) {
this.removeAttribute("controls")
} else {
this.setAttribute("controls", "controls")
}
});
//Display de medalla cargada
$("#medalla-cargada").delay(3000).queue(function(){
$(this).removeClass("hidden").dequeue();
$(this).addClass("block").dequeue();
});
function setCookie(cname,cvalue,exdays) {
var d = new Date();
alert(d);
d.setTime(d.getTime() + (exdays*1*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
//Open Modal
function finalConcurso(){
$today = new Date().getTime();
$endDate = new Date('5 Jan 2017 19:00:00 GMT').getTime() //5hrs. de diferencia
if ( $endDate > $today ){
//console.log('aún no pasa');
} else{
//console.log('ya pasó');
var $limiteCookie = getCookie("Concurso");
//console.log( $limiteCookie );
if ($limiteCookie == '') {
$('#concurso-terminado').modal('show');
$('#ranking-cerrado').removeClass('hidden');
$('#ranking-abierto').addClass('hidden');
document.cookie="Concurso=acabo; expires=Thu, 30 Sep 2018 00:06:40 GMT";
}
}
}
jQuery.fn.scrollTo = function(elem, speed) {
$(this).animate({
scrollTop: $(this).scrollTop() - $(this).offset().top + $(elem).offset().top
}, speed == undefined ? 1000 : speed);
return this;
}; |
import React from 'react';
import {Alert, Platform, StyleSheet, Text, View, Image, TextInput, Button, ToastAndroid} from 'react-native';
import Bananas from './utils/Bananas';
import ErrorMessage from './utils/ErrorMessage';
import firebase from 'firebase';
import LinearGradient from 'react-native-linear-gradient';
export default class DonateScreen extends React.Component {
constructor(props) {
super(props);
this.cuser = JSON.parse(JSON.stringify(this.props.navigation.getParam('user')));
this.cuser = this.cuser[Object.keys(this.cuser)[0]];
this.state = {units: 0, lat: 0, lng: 0, errorMessage: '', disabled: false};
}
static navigationOptions = () => ({
headerTintColor: 'white',
headerStyle: {
backgroundColor: 'black'
},
});
componentDidMount = () => {
navigator.geolocation.getCurrentPosition(
position => {
this.setState({lat : JSON.stringify(position.coords.latitude) , lng: JSON.stringify(position.coords.longitude)});
},
error => alert(JSON.stringify(error)),
{ enableHighAccuracy: true, timeout: 20000 }
);
};
donate() {
this.setState({disabled: true});
firebase.database().ref('distributors').limitToFirst(1).once('value')
.then((cdistributor) => {
cdistributor = JSON.parse(JSON.stringify(cdistributor));
cdistributor = cdistributor[Object.keys(cdistributor)[0]];
firebase.database().ref('donations').push({
foodUnits: this.state.units,
donorLat: this.state.lat,
donorLng: this.state.lng,
donorPhoneno: this.cuser.phoneno,
distLat: cdistributor.latitude,
distLng: cdistributor.longitude,
distPhoneno: cdistributor.phoneno,
})
.then(() => { ToastAndroid.show(this.state.units+' units donated!', ToastAndroid.SHORT); this.setState({disabled: false})} )
.catch(error => { this.setState({disabled: false, errorMessage: error.message}); });
})
.catch(error => { this.setState({disabled: false, errorMessage: error.message}); });
}
render() {
const {navigate} = this.props.navigation;
const cuser = JSON.parse(JSON.stringify(this.props.navigation.getParam('user')));
return (
<LinearGradient
colors={['#000428', '#004e92']}
start={{x: 0.0, y: 1.0}} end={{x: 1.0, y: 0.0}}
style={styles.container}>
<View style={styles.card}>
<Text style={styles.show}>How many units of food would you like to donate?</Text>
<View style={styles.inputContainer}>
<TextInput
placeholder='Units'
onChangeText={(unitss) => this.setState({units: unitss})}
/>
</View>
<View style={styles.btnContainer}>
<Button
title="Donate"
color='#111EC6'
disabled={this.state.disabled}
onPress={() => this.donate()}
/>
</View>
<ErrorMessage errorMessage={this.state.errorMessage}></ErrorMessage>
</View>
</LinearGradient>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: '#F5FCFF',
},
field: {
fontSize:20,
color: '#841584',
},
btnContainer: {
margin: 20,
width: 200,
},
card:{
padding:30,
width: '80%',
marginTop:100,
marginBottom:100,
backgroundColor: '#DDDDDD',
borderRadius:20,
borderWidth: 3,
borderColor: '#222222',
flex: 1,
alignItems: 'center',
flexDirection: 'column',
justifyContent: 'center',
},
show:{
fontSize:20,
color: '#222222',
},
inputContainer: {
margin: 6,
width: 100,
borderBottomWidth: 1,
borderColor: 'black',
},
});
|
import React from 'react';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { userActions } from '../_actions';
class SocialAuthLandingPage extends React.Component {
constructor(props) {
super(props);
this.state = {
data : this.props.socialUser
};
}
componentWillMount() {
const { dispatch } = this.props;
var params = (new URL(document.location)).searchParams;
var id = params.get("facebookId");
dispatch(userActions.getSocialLoginData(id));
//this.renderMyData();
}
renderMyData(){
var params = (new URL(document.location)).searchParams;
var id = params.get("facebookId");
fetch('http://localhost:3000/user/fetch/'+id)
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
this.setState({ data : responseJson })
})
.catch((error) => {
console.error(error);
});
}
render() {
return (
<div >
{this.props.socialUser != null ?
<div>
<h2> Welcome {this.props.socialUser.first_name} </h2>
<img src={'https://graph.facebook.com/'+this.props.socialUser.id+'/picture?type=large&width=150&height=150'} alt="Profile Picture" style={{float: 'left'}}/>
<h4 > Your email id is: <br/><b>{this.props.socialUser.email} </b></h4>
</div>
: null}
<Link style={{marginTop: '88px'}}to="/login" className="btn btn-link">Log out</Link>
</div>
);
}
}
function mapStateToProps(state) {
const { socialUser } = state.authentication;
return {
socialUser
};
}
const connectedSocialAuthLandingPage = connect(mapStateToProps)(SocialAuthLandingPage);
export { connectedSocialAuthLandingPage as SocialAuthLandingPage };
|
import React from "react";
//import any components needed
//Import your array data to from the provided data file
import { operators } from "../../../data";
const Operators = ({symbol, value}) => {
// STEP 2 - add the imported data to state
const operatorButton = "opButton";
const operatorButtonCon = "opButtonCon";
// function symbolKeys(){
// if (symbol === "/" || symbol === "x" || symbol === "-" || symbol === "+" || symbol === "=") {
// return () => symbol
// }
// }
// function valueKeys() {
// if (value === "/" || "*" || "-" || "+" || "=") {
// return () => value
// }
// }
return (
<div className={operatorButtonCon}>
{/* STEP 3 - Use .map() to iterate over your array data and return a button
component matching the name on the provided file. Pass
it any props needed by the child component*/
operators.map((chars, index) =>
<div key={index}
symbol={chars.char}
value={chars.value}
className={operatorButton}>
{chars.char}</div>
)
}
</div>
);
};
export default Operators; |
import React from 'react';
import { makeStyles, createStyles, Grid } from '@material-ui/core'
import "./Footer.css";
const useStyles = makeStyles((theme) =>
createStyles({
gridContainer: {
margin: 'auto'
},
gridEl: {
justifyContent: 'left'
}
})
);
function Footer() {
const classes = useStyles();
return (
<div className="footerBg">
<Grid
container
direction="row"
justifyContent="space-evenly"
className={classes.gridContainer}
>
<Grid
container
direction="column"
item xs={6} sm={6} md={4} lg={6} xl={6}
className={classes.gridEl}
>
<h5 className="footTitle">Our Company</h5>
<ul className="footList">
<a href="About" target="_blank" rel="noreferrer"><li>About Wayo</li></a>
<a href="Careers" target="_blank" rel="noreferrer"><li>Careers</li></a>
<a href="Legal" target="_blank" rel="noreferrer"><li>Legal</li></a>
<a href="Privacy" target="_blank" rel="noreferrer"><li>Privacy & Cookies</li></a>
<a href="Corporate" target="_blank" rel="noreferrer"><li>Corporate Info</li></a>
</ul>
</Grid>
<Grid
container
direction="column"
item xs={6} sm={6} md={6} lg={6} xl={6}
>
<h5 className="footTitle">Find Us On</h5>
<ul className="footList">
<a href="https://github.com/imjord/wayo-clothing-brand-.01" target="_blank" rel="noreferrer"><li>Github</li></a>
<a href="https://discord.com/" target="_blank" rel="noreferrer"><li>Discord</li></a>
<a href="https://facebook.com/" target="_blank" rel="noreferrer"><li>Facebook</li></a>
<a href="https://twitter.com/" target="_blank" rel="noreferrer"><li>Twitter</li></a>
<a href="https://instagram.com/" target="_blank" rel="noreferrer"><li>Instagram</li></a>
<a href="https://youtube.com/" target="_blank" rel="noreferrer"><li>YouTube</li></a>
</ul>
</Grid>
<Grid
container
direction="column"
>
<h5 className="footTitle">Sign up for Wayo Updates</h5>
<p className="footPara">By entering your email address below, you consent to receiving our
newsletter with access to our latest collections, events and initiatives.
More details on this are provided in our Privacy Policy
</p>
<form>
<input
className='nes-input'
placeholder='Your email'
name='email'
type='email'
id='email'
/>
<button className='nes-btn is-primary' type='submit'>
Submit
</button>
</form>
</Grid>
</Grid>
<div>
<h6 className="rights">© 2021 Wayo Clothing Brand LLC. All rights reserved.</h6>
</div>
</div>
);
};
export default Footer; |
"use strict";
/**
Here's the list of the OS, software, and libraries I'm using
Software on Macbook Pro 17-inch, Mid 2009
-----------------------------------------
Mac OSX: 10.9.4
Node.js: 0.10.31
MongoDB: 2.6.4
Node.js libraries from package.json
-----------------------------------
async: ^0.9.0
bcrypt-nodejs: 0.0.3
mongodb: ^1.4.18
mongoose: ^3.8.16
**/
// Import async.js - utility library for handlng asynchronous calls
var async = require('async');
// URL to connect to a local MongoDB with database test.
// Change this to fit your running MongoDB instance
var databaseURL = 'mongodb://dbuser:Emerson123@ds163681.mlab.com:63681/meetingstandupnotes';
// Import native MongoDB client for Node.js
var MongoClient = require('mongodb').MongoClient;
// Import mongoose.js to define our schema and interact with MongoDB
var mongoose = require('mongoose');
// Define Book schema model with 3 fields: user, email, password
var bookSchema = new mongoose.Schema({
title: {
type: String
},
author: {type: String},
genre: {type: String},
read: {type: Boolean, default: false}
});
var Book = mongoose.model('Book', bookSchema);
// Async series method to make sure asynchronous calls below run sequentially
async.series([
// First function - connect to MongoDB, then drop the database
function(callback) {
// Originally, I wanted to use mongoose to drop the database
// but the code below doesn't drop the database, only clears
// all documents. Refer to:
//
//https://github.com/LearnBoost/mongoose/issues/1654
/*
mongoose.connection.on('open', function() {
mongoose.connection.db.dropDatabase(function(err) {
if (err) console.log(err);
mongoose.connection.close(function(err) {
callback(null, 'Dropped database');
});
});
});
*/
MongoClient.connect(databaseURL, function(err, db) {
if(err){
throw err;
}
// Drop database which is an asynchronous call
db.dropDatabase(function(err, result) {
// After successfully dropping database, force close database which is another asynchronous call
db.close(true, function(err, result) {
// Close successful so execute callback so second function in async.serial gets called
callback(null, 'SUCCESS - dropped database');
});
});
});
},
// Second function - connect to MongoDB using mongoose, which is an asynchronous call
function(callback) {
// Open connection to MongoDB
mongoose.connect(databaseURL);
// Need to listen to 'connected' event then execute callback method
// to call the next set of code in the async.serial array
mongoose.connection.on('connected', function(){
console.log('db connected via mongoose');
// Execute callback now we have a successful connection to the DB
// and move on to the third function below in async.series
callback(null, 'SUCCESS - Connected to mongodb');
});
},
// Third function - use Mongoose to create a User model and save it to database
function(callback) {
// BEGIN SEED DATABASE
// Use an array to store a list of User model objects to save to the database
var books = [];
var testBookCount = 20;
for (var i = 0; i < testBookCount; i++) {
var book = new Book({
title: i,
author: i + '@' + i + '.com',
genre: i + '@' + i + '.com'
});
// Add newly create User model to 'users' array
books.push(book);
}
console.log("Populating database with %s books", books.length);
// Use 'async.eachSeries' to loop through the 'users' array to make
// sure each asnychronous call to save the user into the database
// completes before moving to the next User model item in the array
async.eachSeries(
// 1st parameter is the 'users' array to iterate over
books,
// 2nd parameter is a function takes each user in the 'users' array
// as an argument and a callback function that needs to be executed
// when the asynchronous call complete.
// Note there is another 'callback' method here called 'userSavedCallBack'.
// 'userSavedCallBack' needs to be called to inform async.eachSeries to
// move on to the next user object in the 'users' array. Do not mistakenly
// call 'callback' defined in line 130.
function(book, bookSavedCallBack){
// There is no need to make a call to create the 'test' database.
// Saving a model will automatically create the database
book.save(function(err) {
if(err) {
// Send JSON response to console for errors
console.dir(err);
}
// Print out which user we are saving
console.log("Saving book #%s out of %s", book.name, testBookCount);
// Call 'userSavedCallBack' and NOT 'callback' to ensure that the next
// 'user' item in the 'users' array gets called to be saved to the database
bookSavedCallBack();
});
},
// 3rd parameter is a function to call when all users in 'users' array have
// completed their asynchronous user.save function
function(err){
if (err) {
console.dir(err);
}
console.log("Finished aysnc.each in seeding db");
// Execute callback function from line 130 to signal to async.series that
// all asynchronous calls are now done
callback(null, 'SUCCESS - Seed database');
}
);
// END SEED DATABASE
}
],
// This function executes when everything above is done
function(err, results){
console.log("\n\n--- Database seed progam completed ---");
if(err) {
console.log("Errors = ");
console.dir(err);
} else {
console.log("Results = ");
console.log(results);
}
console.log("\n\n--- Exiting database seed progam ---");
// Exit the process to get back to terrminal console
process.exit(0);
}); |
// Import Major Dependencies
import React, { Component } from 'react'
import { ethers } from 'ethers';
import { Input, Form, Button, Loader } from 'semantic-ui-react'
// Import CSS Files
import './limitorder.css'
class LimitOrder extends Component {
constructor(props) {
super(props);
this.state = {
loading: false,
sidetext: "LOADING...",
init: false,
error: false,
success: false,
price: '',
amount_0: '',
ui_amount_0: '',
amount_1: '',
ui_amount_1: '',
bignumbers: [],
last_price: ''
};
this.handleSubmit = this.handleSubmit.bind(this);
this.flashSuccess = this.flashSuccess.bind(this);
this.flashError = this.flashError.bind(this);
}
componentDidMount() {
this.generateBigNumbers();
}
// Generates and stores BigNumber integers for easy math later
generateBigNumbers() {
let bignumbers = {};
for(let i = 0; i <= 10; i++) {
const key = i;
bignumbers[key] = ethers.utils.bigNumberify(key);
}
this.setState({ bignumbers });
}
// Main function that interfaces and writes to the blockchain.
// This is the most important function here.
async handleSubmit(type) {
// Set loading to true to update UI
let sidetext;
if(type === "BUY") {
sidetext = "BUYING..."
} else if(type === "SELL") {
sidetext = "SELLING..."
} else {
sidetext = "LOADING..."
}
this.setState({loading: true, sidetext, error: false, success: false});
const { currencies, options } = this.props;
// Get the important info for the transaction
const amount_0 = this.state.amount_0;
const amount_1 = this.state.amount_1;
const curr_gem_0 = options.contracts[currencies[0]].address;
const curr_gem_1 = options.contracts[currencies[1]].address;
let data = {};
// Set data to the correct value depending on if the order is a BUY or SELL
// Basically you just flip the currency 0 and currency 1
if(type === "BUY") {
data = {
pay_amt: amount_1,
pay_gem: curr_gem_1,
buy_amt: amount_0,
buy_gem: curr_gem_0
};
} else if(type === "SELL") {
data = {
pay_amt: amount_0,
pay_gem: curr_gem_0,
buy_amt: amount_1,
buy_gem: curr_gem_1
};
} else {
return;
}
console.log(data);
try {
const tx = await options.contracts.Market.offer(data.pay_amt, data.pay_gem, data.buy_amt, data.buy_gem, 1, { gasLimit: 500000, gasPrice: options.gasPrice });
await tx.wait();
this.flashSuccess();
} catch (error) {
console.log(error);
this.flashError();
}
}
// Function to flash Success on the button when a order has gone thru
flashSuccess() {
this.setState({ success : true, loading: false });
setTimeout(() => this.setState({ success: false, price: '', amount_0: '0', ui_amount_0: '', amount_1: '0', ui_amount_1: '' }), 1500);
}
// Function to flash Error on the button when a order has failed
flashError() {
this.setState({ error: true, loading: false });
setTimeout(() => this.setState({ error: false }), 1500);
}
// Handler for changes in price in the UI
handlePriceChange(value) {
if(/\S/.test(value) && this.state.ui_amount_0 !== "") {
const price = value;
const ui_amount_1 = this.state.ui_amount_0 * price;
const amount_1_bn = ethers.utils.parseUnits(ui_amount_1.toString(), 'ether');
this.setState({ price: price, amount_1: amount_1_bn.toString(), ui_amount_1: ui_amount_1.toString() });
} else {
this.setState({ price: value, amount_1: '0', ui_amount_1: '' });
}
}
// Handler for changes in amount to be traded in the UI
handleAmountChange(index, value) {
if(/\S/.test(value) && this.state.price !== "") {
const price = this.state.price;
let ui_amount_0 = null;
let ui_amount_1 = null;
let amount_0_bn = null;
let amount_1_bn = null;
// All math is done in BigNumber arithmetic using wei
if(index === 0) {
ui_amount_0 = value;
amount_0_bn = ethers.utils.bigNumberify(ethers.utils.parseUnits(ui_amount_0.toString(), 'ether'));
ui_amount_1 = ui_amount_0 * price;
amount_1_bn = ethers.utils.bigNumberify(ethers.utils.parseUnits(ui_amount_1.toString(), 'ether'));
} else if(index === 1) {
ui_amount_1 = value;
amount_1_bn = ethers.utils.bigNumberify(ethers.utils.parseUnits(ui_amount_1.toString(), 'ether'));
ui_amount_0 = ui_amount_1 / price;
amount_0_bn = ethers.utils.bigNumberify(ethers.utils.parseUnits(ui_amount_0.toString(), 'ether'));
} else {
return;
}
this.setState({
amount_0: amount_0_bn.toString(),
ui_amount_0: ui_amount_0,
amount_1: amount_1_bn.toString(),
ui_amount_1: ui_amount_1,
});
} else {
this.setState({
amount_0: '0',
ui_amount_0: '',
amount_1: '0',
ui_amount_1: ''
});
}
}
// Handler for changes in amount using the percentage tools
handleAmountPercentageChange(index, value) {
const price = this.state.price;
// All arithmetic is done using BigNumber and wei
let ui_amount_0 = null;
let ui_amount_1 = null;
let amount_0_bn = null;
let amount_1_bn = null;
const price_bn = ethers.utils.bigNumberify(ethers.utils.parseUnits(price.toString(), 'ether'));
const one_bn = ethers.utils.bigNumberify(ethers.utils.parseUnits('1'), 'ether');
if(index === 0) {
amount_0_bn = value;
amount_1_bn = amount_0_bn.mul(price_bn).div(one_bn);
} else if(index === 1) {
amount_1_bn = value;
amount_0_bn = amount_1_bn.mul(one_bn).div(price_bn);
} else {
return;
}
// Try catch to stop any type of input that is invalid with a valid response
try {
ui_amount_0 = ethers.utils.formatUnits(amount_0_bn.toString(), 'ether');
} catch(err) {
console.log(err);
ui_amount_0 = ethers.utils.formatUnits("0", 'ether');
}
try {
ui_amount_1 = ethers.utils.formatUnits(amount_1_bn.toString(), 'ether');
} catch(err) {
console.log(err);
ui_amount_1 = ethers.utils.formatUnits("0", 'ether');
}
this.setState({
amount_0: amount_0_bn.toString(),
ui_amount_0: ui_amount_0,
amount_1: amount_1_bn.toString(),
ui_amount_1: ui_amount_1
});
}
render() {
const { price, amount_0, amount_1, ui_amount_0, ui_amount_1, bignumbers, loading, success, error, sidetext } = this.state;
const { currencies, last_price, balances, options } = this.props;
// Set flags that set whether a buy/sell is logically possible
let can_buy = false;
let can_sell = false;
const curr_0_balance = ethers.utils.bigNumberify(balances[0]);
const curr_1_balance = ethers.utils.bigNumberify(balances[1]);
const amount_0_bn = ethers.utils.bigNumberify(amount_0);
const amount_1_bn = ethers.utils.bigNumberify(amount_1);
if(price !== "" && curr_0_balance.gte(amount_0_bn) && amount_0_bn.gt(ethers.utils.bigNumberify("1000"))) {
can_sell = true;
}
if(price !== "" && curr_1_balance.gte(amount_1_bn) && amount_1_bn.gt(ethers.utils.bigNumberify("1000"))) {
can_buy = true;
}
// Set the sidetext (text next to the button) depending on the situation context
let side_text = "";
if(loading) {
side_text = (<span className="LimitOrder-color"><Loader active inline size="small"/> {sidetext} </span>);
}
if(error) {
side_text = (<span className="red LimitOrder-color">FAILED</span>);
}
if(success) {
side_text = (<span className="green LimitOrder-color">SUCCESS</span>);
}
return (
<div className="LimitOrder">
<Form size='tiny'>
<div className="LimitOrder-headers">Price</div>
<Form.Field id="LimitOrder-price">
<Input
label={{ basic: true, content: currencies[1] + " / " + currencies[0] }}
labelPosition='right'
placeholder='Enter Price...'
value={price}
onChange={(e) => { this.handlePriceChange(e.target.value) }}
disabled={options.readOnly}
/>
<span className="LimitOrder-currentPrice" onClick={() => this.handlePriceChange(last_price) } >Current Market Price</span>
</Form.Field>
<hr />
<div className="LimitOrder-headers" id="LimitOrder-amount-header">Amounts</div>
<Form.Field>
<Input
label={{ basic: true, content: currencies[0] }}
labelPosition='right'
placeholder='Enter Amount...'
disabled={price === '' || options.readOnly}
value={ui_amount_0}
onChange={(e) => { this.handleAmountChange(0, e.target.value) }}
className="LimitOrder-amount-input"
/>
<Button.Group className="LimitOrder-mini-buttons" size='mini' basic inverted>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountChange(1, '') } >0%</Button>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountPercentageChange(0, curr_0_balance.div(bignumbers[4]))} >25%</Button>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountPercentageChange(0, curr_0_balance.div(bignumbers[2]))} >50%</Button>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountPercentageChange(0, curr_0_balance.mul(bignumbers[3]).div(bignumbers[4]))} >75%</Button>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountPercentageChange(0, curr_0_balance) } >100%</Button>
</Button.Group>
</Form.Field>
<Form.Field>
<Input
label={{ basic: true, content: currencies[1] }}
labelPosition='right'
placeholder='Enter Amount...'
disabled={price === '' || options.readOnly}
value={ui_amount_1}
onChange={(e) => { this.handleAmountChange(1, e.target.value) }}
className="LimitOrder-amount-input"
/>
<Button.Group className="LimitOrder-mini-buttons" size='mini' basic inverted>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountChange(1, '') } >0%</Button>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountPercentageChange(1, curr_1_balance.div(bignumbers[4]))} >25%</Button>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountPercentageChange(1, curr_1_balance.div(bignumbers[2]))} >50%</Button>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountPercentageChange(1, curr_1_balance.mul(bignumbers[3]).div(bignumbers[4]))} >75%</Button>
<Button disabled={price === "" || options.readOnly} onClick={() => this.handleAmountPercentageChange(1, curr_1_balance) } >100%</Button>
</Button.Group>
</Form.Field>
<Button className="LimitOrder-button" color='green' disabled={!can_buy || loading || options.readOnly} onClick={() => this.handleSubmit("BUY")} >BUY {currencies[0]}</Button>
<Button className="LimitOrder-button" color='red' disabled={!can_sell || loading || options.readOnly} onClick={() => this.handleSubmit("SELL")} >SELL {currencies[0]}</Button>
{side_text}
</Form>
</div>
);
}
}
export default LimitOrder |
/**
* Created by Bhanu on 27/03/2016.
*/
"use strict";
(function () {
angular
.module("profileApp")
.config(function ($routeProvider, $httpProvider, ChartJsProvider) {
$routeProvider
.when('/', {
controller: 'HomeController',
controllerAs: "model",
templateUrl: 'views/home/home.view.html'
})
.otherwise({
redirectTo: '/'
});
});
})(); |
import {Cell} from "./Cell.js";
export class CellBox3 {
constructor(cellMap, state, offsetX = 0, offsetY = 0) {
if (cellMap.length !== 9) {
throw 'CellBox3 map must be 9 cells.'
}
this._cellMap = cellMap;
this._state = state;
this._offsetX = offsetX;
this._offsetY = offsetY;
}
getCells() {
let cells = [];
for (let x = 1; x <= 3; x++) {
for (let y = 1; y <= 3; y++) {
if (this._cellMap[((y - 1) * 3) + (x - 1)] === 1) {
cells.push(new Cell(x + this._offsetX, y + this._offsetY, this._state));
}
}
}
return cells;
}
/**
* There is probably some math to do this, but the transformation
* is just:
*
* 0 1 2 6 3 0
* 3 4 5 ==> 7 4 1
* 6 7 8 8 5 2
*/
rotate() {
let c = this._cellMap;
return new CellBox3(
[
c[6], c[3], c[0],
c[7], c[4], c[1],
c[8], c[5], c[2],
],
this._state,
this._offsetX,
this._offsetY
);
}
translate(x, y) {
return new CellBox3(
this._cellMap,
this._state,
this._offsetX + x,
this._offsetY + y
);
}
}
|
//[COMMENTS]
/*
Instructions
Add the less than or equal to operator to the indicated lines so that the return statements make sense.
testLessOrEqual(0) should return "Smaller Than or Equal to 12"
testLessOrEqual(11) should return "Smaller Than or Equal to 12"
testLessOrEqual(12) should return "Smaller Than or Equal to 12"
testLessOrEqual(23) should return "Smaller Than or Equal to 24"
testLessOrEqual(24) should return "Smaller Than or Equal to 24"
testLessOrEqual(25) should return "25 or More"
testLessOrEqual(55) should return "25 or More"
You should use the <= operator at least twice
*/
//[COMMENTS]
function testLessOrEqual(val) {
if (val <= 12) { // Change this line
return "Smaller Than or Equal to 12";
}
if (val <= 24) { // Change this line
return "Smaller Than or Equal to 24";
}
return "25 or More";
}
// Change this value to test
testLessOrEqual(10);
|
export const fa = {
nomNote: 'Fa',
nomNoteAng: 'F',
positionGraveCorde1: 1,
toutesPositions: {
noteSurCorde1: [1, 13],
noteSurCorde2: [8, 20],
noteSurCorde3: [3, 15],
noteSurCorde4: [10, 22],
noteSurCorde5: [6, 18],
noteSurCorde6: [1, 13],
}
};
export const faDiese = {
nomNote: 'Fa#',
nomNoteAng: 'F#',
positionGraveCorde1: 2,
toutesPositions: {
noteSurCorde1: [2, 14],
noteSurCorde2: [9, 21],
noteSurCorde3: [4, 16],
noteSurCorde4: [11],
noteSurCorde5: [7, 19],
noteSurCorde6: [2, 14],
}
};
export const sol = {
nomNote: 'Sol',
nomNoteAng: 'G',
positionGraveCorde1: 3,
toutesPositions: {
noteSurCorde1: [3, 15],
noteSurCorde2: [10, 22],
noteSurCorde3: [5, 17],
noteSurCorde4: [12],
noteSurCorde5: [8, 20],
noteSurCorde6: [3, 15],
}
};
export const solDiese = {
nomNote: 'Sol#',
nomNoteAng: 'G#',
positionGraveCorde1: 4,
toutesPositions: {
noteSurCorde1: [4, 16],
noteSurCorde2: [11],
noteSurCorde3: [6, 18],
noteSurCorde4: [1, 13],
noteSurCorde5: [9, 21],
noteSurCorde6: [4, 16],
}
};
export const la = {
nomNote: 'La',
nomNoteAng: 'A',
positionGraveCorde1: 5,
toutesPositions: {
noteSurCorde1: [5, 17],
noteSurCorde2: [12],
noteSurCorde3: [7, 19],
noteSurCorde4: [2, 14],
noteSurCorde5: [10, 22],
noteSurCorde6: [5, 17],
}
};
export const siBemol = {
nomNote: 'Si♭',
nomNoteAng: 'B♭',
positionGraveCorde1: 6,
toutesPositions: {
noteSurCorde1: [6, 18],
noteSurCorde2: [1, 13],
noteSurCorde3: [8, 20],
noteSurCorde4: [3, 15],
noteSurCorde5: [11],
noteSurCorde6: [6, 18],
}
};
export const si = {
nomNote: 'Si',
nomNoteAng: 'B',
positionGraveCorde1: 7,
toutesPositions: {
noteSurCorde1: [7, 19],
noteSurCorde2: [2, 14],
noteSurCorde3: [9, 21],
noteSurCorde4: [4, 16],
noteSurCorde5: [12],
noteSurCorde6: [7, 19],
}
};
// on a bien écrit "doo" et nom pas "do" (nom réservé)
export const doo = {
nomNote: 'Do',
nomNoteAng: 'C',
positionGraveCorde1: 8,
toutesPositions: {
noteSurCorde1: [8, 20],
noteSurCorde2: [3, 15],
noteSurCorde3: [10, 22],
noteSurCorde4: [5, 17],
noteSurCorde5: [1, 13],
noteSurCorde6: [8, 20],
}
};
export const doDiese = {
nomNote: 'Do#',
nomNoteAng: 'C#',
positionGraveCorde1: 9,
toutesPositions: {
noteSurCorde1: [9, 21],
noteSurCorde2: [4, 16],
noteSurCorde3: [11],
noteSurCorde4: [6, 18],
noteSurCorde5: [2, 14],
noteSurCorde6: [9, 21],
}
};
export const re = {
nomNote: 'Ré',
nomNoteAng: 'D',
positionGraveCorde1: 10,
toutesPositions: {
noteSurCorde1: [10, 22],
noteSurCorde2: [5, 17],
noteSurCorde3: [12],
noteSurCorde4: [7, 19],
noteSurCorde5: [3, 15],
noteSurCorde6: [10, 22],
}
};
export const miBemol = {
nomNote: 'Mi♭',
nomNoteAng: 'E♭',
positionGraveCorde1: 11,
toutesPositions: {
noteSurCorde1: [11],
noteSurCorde2: [6, 18],
noteSurCorde3: [1, 13],
noteSurCorde4: [8, 20],
noteSurCorde5: [4, 16],
noteSurCorde6: [10, 22],
}
};
export const mi = {
nomNote: 'Mi',
nomNoteAng: 'E',
positionGraveCorde1: 12,
toutesPositions: {
noteSurCorde1: [12],
noteSurCorde2: [7, 19],
noteSurCorde3: [2, 14],
noteSurCorde4: [9, 21],
noteSurCorde5: [5, 17],
noteSurCorde6: [11],
}
};
|
export default function isUndefined(x) {
return x === undefined;
};
|
'use strict';
var docomo = require('./docomo.js');
var fs = require('fs');
var buf = fs.readFileSync('sample1.png');
console.log(buf);
console.log("Read picture");
docomo.storeImg("Droid", "Sample1.png", buf, function(data, response){
console.log("Stored picture");
console.log(data);
console.log(response);
docomo.getPictures(function(data, response){
console.log("Get memory");
console.log(data);
docomo.createDataSet("1", function(data, response){
console.log("Created Data set");
console.log(data);
console.log(response.status);
var id = data.creatingTmpImageDataSetJobId;
docomo.getDataSets(id, function(data, response){
console.log("Got data sets");
console.log(data);
});
});
});
});
|
import React from 'react';
import Map from '../components/Map';
import Form from '../components/Form';
import Grid from "@material-ui/core/Grid";
const Contact = () => {
return (
<div className='Contact'>
<Grid container>
<Grid item sm={12} md={6} className="top-left">
<Form />
</Grid>
<Grid item sm={12} md={6} className="top-right">
<Map />
</Grid>
</Grid>
</div>
)
}
export default Contact; |
function init(){
var tbody = d3.select("tbody");
dataSet.forEach((sighting) => {
var row = tbody.append("tr");
Object.entries(sighting).forEach(([key, value]) => {
var cell = tbody.append("td");
cell.text(value);
});
});
}
var reset = d3.select("#reset_btn");
var search = d3.select("#search_btn");
//working code
/*
submit.on("click", function() {
// Prevent the page from refreshing
d3.event.preventDefault();
var inputDate = d3.select("#date").property("value");
var inputCity = d3.select("#city").property("value");
var inputState = d3.select("#state").property("value");
var inputCountry = d3.select("#country").property("value");
var inputShape = d3.select("#shape").property("value");
var inputDuration = d3.select("#duration").property("value");
var inputDescription = d3.select("#description").property("value");
var toWrite = {
datetime: inputDate,
city: inputCity,
state:inputState,
country:inputCountry,
shape:inputShape,
duration:inputDuration,
comments:inputDescription
};
dataSet.push(toWrite);
});
*/
reset.on("click", function(){
init();
});
search.on("click", function() {
d3.event.preventDefault();
var tbl = document.getElementById("main_table");
tbl.innerHTML="";
// Prevent the page from refreshing
var tbody = d3.select("tbody");
dataSet.forEach((sighting) => {
var row = tbody.append("tr");
if(sighting.datetime == d3.select("#date").property("value")){
Object.entries(sighting).forEach(([key, value]) => {
var cell = tbody.append("td");
cell.text(value);
});
}
});
document.getElementById('date').value = '';
});
init(); |
export default ({
shops:[],
foodtype:[],
userinfo:[],
cartgoods:[],
shopinfo:[]
})
|
(function () {
'use strict'
window.GOVUK = window.GOVUK || {}
function WordsToAvoidHighlighter (wordsToAvoidRegexps, options) {
var $el = $(options.el)
var textareaHighlightSelector = 'span.highlight'
$.map($el, function (textarea) {
$(textarea).highlightTextarea({
color: '#FFB040',
caseSensitive: false,
words: wordsToAvoidRegexps
})
})
var disable = function () {
$.map($el, function (textarea) {
$(textarea).highlightTextarea('disable')
})
$(textareaHighlightSelector).hide()
}
$(document).bind('govuk.WordsToAvoidGuide.disable', disable)
var enable = function () {
$.map($el, function (textarea) {
$(textarea).highlightTextarea('highlight')
})
$(textareaHighlightSelector).show()
}
$(document).bind('govuk.WordsToAvoidGuide.enable', enable)
}
GOVUK.WordsToAvoidHighlighter = WordsToAvoidHighlighter
}())
|
import { createActions } from 'redux-actions'
import { getUserName } from '../auth'
import { getGameName } from '../game'
import { Guesses } from '../collections'
const { receiveGuess } = createActions({
RECEIVE_GUESS: guess => guess
})
const makeGuess = guess => (dispatch, getState) =>
Guesses.child(getGameName(getState())).create({
text: guess,
user: getUserName(getState()) || 'renan',
madeAt: (new Date()).getTime(),
})
const listenForGuesses = () => (dispatch, getState) =>
Guesses.child(getGameName(getState())).listenFor(
'child_added',
guess => guess && dispatch(receiveGuess(guess))
)
export {
receiveGuess,
makeGuess,
listenForGuesses,
}
|
import Page from "components/Page";
export default () => {
const title = "macrame";
return (
<Page title={title}>
<h2 className="entry-title">{title}</h2>
</Page>
);
};
|
/* @flow */
import Bcrypt from 'bcrypt';
let CoBcrypt : Object = {};
CoBcrypt.genSalt = (rounds : number, seedLength : number) =>
(done : Function) => {
Bcrypt.genSalt(rounds, seedLength, done);
};
CoBcrypt.hash = (str : string, salt : string) =>
(done : Function) => {
Bcrypt.hash(str, salt, done);
};
CoBcrypt.compare = (str : String, hash : String) =>
(done : Function) => {
Bcrypt.compare(str, hash, done);
};
export default CoBcrypt;
|
class DiceRoll {
constructor(quantity, successValue, reroll, valueToReRoll, failures, diceSides) {
this.quantity = quantity;
this.successValue = successValue;
this.reroll = reroll;
this.valueToReRoll = valueToReRoll;
this.failures = failures;
this.diceSides = diceSides;
}
static castObjectToDiceRoll(obj) {
return Object.assign(this, obj)
}
}
export default DiceRoll; |
app.factory('efService', [function () {
return {
employee: {
fullname: 'nguyen van nam',
notes: 'laptrinhvien javascript',
department: 'administrator',
perkCard: true,
perkStock: false,
perkSixWeek: true,
payrollType: "none"
}
};
}]) |
const Neo4jWrapper = require('simple-neo4j-wrapper');
const async = require('async');
const { NEO4J_URL, NEO4J_USERNAME, NEO4J_PASSWORD } = require('../config');
const neo4j = new Neo4jWrapper(NEO4J_URL, NEO4J_USERNAME, NEO4J_PASSWORD);
class ContentController {}
ContentController.executeQueryAndFetchResults = (query, cb) => {
neo4j.queryExecutor(query, (err, result) => {
if (!err) {
const records = result.records.map(record => record._fields[0].properties);
cb(null, records);
} else {
cb(err, null);
}
});
};
ContentController.fetchAllContents = (options, cb) => {
const skip = (options.page - 1) * options.limit;
const query = `MATCH (n:content) return n ORDER BY n.mediaContentId SKIP ${skip} LIMIT ${options.limit}`;
ContentController.executeQueryAndFetchResults(query, cb);
};
ContentController.fetchContentById = (contentId, options, cb) => {
const skip = (options.page - 1) * options.limit;
const query = `MATCH (n:content {mediaContentId: '${contentId}'}) return n ORDER BY n.name SKIP ${skip} LIMIT ${options.limit}`;
ContentController.executeQueryAndFetchResults(query, cb);
};
ContentController.fetchRelatedConcepts = (contentId, options, cb) => {
const skip = (options.page - 1) * options.limit;
const queryToFetchConceptsDirectly = `MATCH \
(m:content {mediaContentId: '${contentId}'})-[:explains]->(n:concept) \
return DISTINCT n ORDER BY n.name SKIP ${skip} LIMIT ${options.limit}`;
const queryToFetchConceptsThroughResource = `MATCH \
(m:content {mediaContentId: '${contentId}'})<-[:aggregates]-(:resource)-[:explains]->(n:concept) \
return DISTINCT n ORDER BY n.name SKIP ${skip} LIMIT ${options.limit}`;
async.parallel([
ContentController
.executeQueryAndFetchResults
.bind(null, queryToFetchConceptsDirectly),
ContentController
.executeQueryAndFetchResults
.bind(null, queryToFetchConceptsThroughResource),
], (err, results) => {
let mergedResults;
if (!err) {
mergedResults = [].concat(...results);
}
cb(err, mergedResults);
});
};
ContentController.fetchRelatedCourses = (contentId, options, cb) => {
const skip = (options.page - 1) * options.limit;
const query = `MATCH (m:content {mediaContentId: '${contentId}'})<-[:aggregates]-(:resource)-[:usedIn]->(n:course) return DISTINCT n ORDER BY n.courseId SKIP ${skip} LIMIT ${options.limit}`;
ContentController.executeQueryAndFetchResults(query, cb);
};
ContentController.fetchAllRelatedItems = (contentId, options, cb) => {
async.parallel([
ContentController.fetchContentById.bind(null, contentId, options),
ContentController.fetchRelatedConcepts.bind(null, contentId, options),
ContentController.fetchRelatedCourses.bind(null, contentId, options),
], (err, results) => {
if (!err) {
const [contents, concepts, courses] = results;
const relatedConcepts = concepts.map(concept => ({
entityId: concept.identifier,
entityType: 'concepts',
entityName: concept.displayName,
}));
const relatedCourses = courses.map(course => ({
entityId: course.courseId,
entityType: 'courses',
entityName: course.displayName,
}));
const [contentAndItsRelatedEntities] = contents.map(content => ({
entityId: content.mediaContentId,
entityType: 'contents',
entityName: content.displayName,
relatedGroups: [
{
name: 'concepts',
entities: relatedConcepts,
},
{
name: 'courses',
entities: relatedCourses,
},
],
}));
cb(null, contentAndItsRelatedEntities);
} else {
cb(err, null);
}
});
};
module.exports = ContentController;
|
import Skill from '../../models/Skills';
export const DELETE_SKILL = 'DELETE_SKILL';
export const CREATE_SKILL = 'CREATE_SKILL';
export const UPDATE_SKILL = 'UPDATE_SKILL';
export const SET_SKILLS = 'SET_SKILLS';
export const fetchSkills = () => {
return async (dispatch, getState) => {
// any async code you want!
const userId = getState().auth.userId;
try {
const response = await fetch(
`https://resume-maker-143-default-rtdb.firebaseio.com/${userId}/skills.json`
);
if (!response.ok) {
throw new Error('Something went wrong!');
}
const resData = await response.json();
const loadedSkills = [];
// console.log(resData,'res data');
for (const key in resData) {
console.log(resData[key].value)
loadedSkills.push(
new Skill(
key,
resData[key].name,
resData[key].value
)
);
}
// console.log(loadedSkills,'loaded skills')
dispatch({
type: SET_SKILLS,
skills: loadedSkills,
});
} catch (err) {
// send to custom analytics server
console.log(err)
throw err;
}
};
};
export const deleteSkill = skillId => {
return async (dispatch, getState) => {
const userId = getState().auth.userId;
const response = await fetch(
`https://resume-maker-143-default-rtdb.firebaseio.com/${userId}/skills/${skillId}.json`,
{
method: 'DELETE'
}
);
if (!response.ok) {
throw new Error('Something went wrong!');
}
dispatch({ type: DELETE_SKILL, pid: skillId });
};
};
export const createSkill = (name, value) => {
return async (dispatch, getState) => {
// any async code you want!
const userId = getState().auth.userId;
// console.log(userId,'user id')
const response = await fetch(
`https://resume-maker-143-default-rtdb.firebaseio.com/${userId}/skills.json`,
{
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name,
value,
})
}
);
const resData = await response.json();
dispatch({
type: CREATE_SKILL,
skillData: {
id: resData.name,
name,
value,
}
});
};
};
export const updateSkill = (id, name, value) => {
return async (dispatch, getState) => {
const userId = getState().auth.userId;
const response = await fetch(
`https://resume-maker-143-default-rtdb.firebaseio.com/${userId}/skills/${id}.json`,
{
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
name,
value
})
}
);
if (!response.ok) {
throw new Error('Something went wrong!');
}
dispatch({
type: UPDATE_SKILL,
pid: id,
skillData: {
name,
value
}
});
};
};
|
/**
* Created by user on 24.03.15.
*/
'use strict';
angular.module('crm')
.controller('EditProcessorCtrl',function($scope, data, close, ProcessorSetup, DataStorage, Notification, $rootScope) {
$scope.modalTitle = data.modalTitle;
$scope.fieldOptions = ProcessorSetup.processorCreateEditFormFields();
if (data.rowData) {
$scope.fields = {
monthlyLimitTxtValue: data.rowData.MonthlyLimit ? parseInt(data.rowData.MonthlyLimit) : '',
passwordTxtValue: data.rowData.Password ? data.rowData.Password : '',
processorIdTxtValue: data.rowData.Processor_Id ? data.rowData.Processor_Id : '',
processorNameTxtValue: data.rowData.ProcessorName ? data.rowData.ProcessorName : '',
usernameTxtValue: data.rowData.Username ? data.rowData.Username : '',
Processor_Id: data.rowData.Processor_Id
};
$scope.fieldOptions.currencyRLOptions.defaultID = $scope.fieldOptions.currencyRLOptions.data.filter(function (item) {
return data.rowData.CurrencyKey === item.name;
})[0].id;
$scope.fieldOptions.stickyRLOptions.defaultID = data.rowData.IsSticky ? 23 : 24;
$scope.fieldOptions.activeRLOptions.defaultID = data.rowData.IsActive ? 25 : 26;
}
$scope.save = function() {
$scope.$broadcast('show-errors-check-validity');
if ($scope.editProcessorForm.$invalid) return false;
var saveObj = {};
saveObj.ProcessorID = data.rowData.ProcessorID;
// This proc id never used, but required
saveObj.Processor_Id = $scope.fields.processorIdTxtValue;
saveObj.Username = $scope.fields.usernameTxtValue || '';
saveObj.Password = $scope.fields.passwordTxtValue || '';
saveObj.ProcessorName = $scope.fields.processorNameTxtValue || '';
saveObj.MonthlyLimit = $scope.fields.monthlyLimitTxtValue || '0';
// Add CurrencyKey
saveObj.CurrencyKey = $scope.fields.currencyRLValue ? $scope.fields.currencyRLValue.name : 'USD';
saveObj.IsSticky = $scope.fields.stickyRLValue.name == 'Yes';
saveObj.IsActive = $scope.fields.activeRLValue.name == 'Yes';
var serverAction = 'editprocessor';
var server = DataStorage.processorAnyApi(serverAction).post(saveObj).$promise;
$scope.saving = true;
server.then(
function (result) {
$scope.saving = false;
if (result.Status) {
close(false, 500);
}else{
Notification.success({message: $rootScope.translate('modals.campaigns.processor.editprocessor.processor-updated', {value: saveObj.ProcessorID}), delay: 5000})
close(result, 500);
}
},
function (error) {
close(false, 500);
}
);
};
// when you need to close the modal, call close
$scope.close = function(result) {
close(result, 500); // close, but give 500ms for bootstrap to animate
};
});
|
import React, { Component } from "react";
import {
View,
StyleSheet,
StatusBar,
ScrollView,
Switch,
Text,
TouchableOpacity,
TextInput,
Image,
FlatList,
AsyncStorage,
ActivityIndicator,
PanResponder,
Alert,
Dimensions
} from "react-native";
import { withNavigation, DrawerActions } from "react-navigation";
import { ScrollableTabView } from "@valdio/react-native-scrollable-tabview";
import CustomHeader from "../Header/CustomHeader";
import AntIcon from "react-native-vector-icons/AntDesign";
import MultiSelect from "react-native-multiple-select";
import { RadioGroup } from "react-native-btr";
import * as CONSTANT from "../Constants/Constant";
import axios from "axios";
import Moment from "moment";
import RBSheet from "react-native-raw-bottom-sheet";
import TimePicker from "react-native-simple-time-picker";
import {
Collapse,
CollapseHeader,
CollapseBody
} from "accordion-collapse-react-native";
import HTML from "react-native-render-html";
const Entities = require("html-entities").XmlEntities;
const entities = new Entities();
class AddSetting extends Component {
//To store data within component
constructor(props) {
super(props);
this.state = {
projectHospitalKnown: "",
projectIntervalKnown: "",
projectDurationKnown: "",
projectSlotsKnown: "",
projectDaysKnown: "",
projectSelectedServiceKnown: "",
projectprojectEndTimeKnown: "",
projectprojectStartTimeKnown: "",
selectedHours: 0,
selectedMinutes: 0,
fee: "",
customSpaces: "",
service: [],
isLoading: true,
radioButtonsforStartAs: [
{
label: "1",
value: "1",
checked: true,
color: "#323232",
disabled: false,
width: "33.33%",
size: 6
},
{
label: "2",
value: "2",
checked: false,
color: "#323232",
disabled: false,
width: "33.33%",
size: 6
},
{
label: "Other",
value: "other",
checked: false,
color: "#323232",
disabled: false,
width: "33.33%",
size: 6
}
]
};
}
//calls when component load
componentDidMount() {
this.ProjectHospitalSpinner();
}
// To get hospital list
ProjectHospitalSpinner = async () => {
const { params } = this.props.navigation.state;
return fetch(
CONSTANT.BaseUrl +
"taxonomies/get_posts_by_post_type?post_type=hospitals",
{
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
}
)
.then(response => response.json())
.then(responseJson => {
let projectHospital = responseJson;
this.setState(
{
projectHospital
},
this.ProjectIntervalSpinner
);
})
.catch(error => {
console.error(error);
});
};
// To get all Intervals
ProjectIntervalSpinner = async () => {
const { params } = this.props.navigation.state;
return fetch(CONSTANT.BaseUrl + "taxonomies/get_list?list=intervals", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseJson => {
let projectInterval = responseJson;
this.setState({ projectInterval }, this.ProjectDurationSpinner);
})
.catch(error => {
console.error(error);
});
};
// To get duration list
ProjectDurationSpinner = async () => {
const { params } = this.props.navigation.state;
return fetch(CONSTANT.BaseUrl + "taxonomies/get_list?list=durations", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseJson => {
let projectDuration = responseJson;
this.setState(
{
projectDuration
},
this.ProjectStartTimeSpinner
);
})
.catch(error => {
console.error(error);
});
};
// To get all slots list
ProjectStartTimeSpinner = async () => {
const { params } = this.props.navigation.state;
return fetch(CONSTANT.BaseUrl + "taxonomies/get_list?list=time", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseJson => {
let projectStartTime = responseJson;
this.setState(
{
projectStartTime
},
this.ProjectEndTimeSpinner
);
})
.catch(error => {
console.error(error);
});
};
// To get all slots list
ProjectEndTimeSpinner = async () => {
const { params } = this.props.navigation.state;
return fetch(CONSTANT.BaseUrl + "taxonomies/get_list?list=time", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseJson => {
let projectEndTime = responseJson;
this.setState(
{
projectEndTime,
isLoading: false
},
this.ProjectServicesSpinner
);
})
.catch(error => {
console.error(error);
this.setState({
isLoading: false
});
});
};
ProjectServicesSpinner = async () => {
const id = await AsyncStorage.getItem("projectProfileId");
const {
projectHospitalKnown,
projectServices,
projectSpecialityServices
} = this.state;
const response = await fetch(
CONSTANT.BaseUrl + "taxonomies/get_list?list=services&profile_id=" + id
);
const json = await response.json();
console.log("Data", JSON.stringify(json));
console.log(json);
if (Array.isArray(json) && json && json.type && json.type === "error") {
this.setState({ projectServices: [] }, this.ProjectDaysSpinner); // empty data set
} else {
this.setState({ projectServices: json }, this.ProjectDaysSpinner);
}
};
// To get all days list
ProjectDaysSpinner = async () => {
const { params } = this.props.navigation.state;
return fetch(CONSTANT.BaseUrl + "taxonomies/get_list?list=week_days", {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(responseJson => {
let projectDays = responseJson;
this.setState({
projectDays
});
})
.catch(error => {
console.error(error);
});
};
createRequiredArray = index => {
this.state.service[index] = this.state.projectSelectedServiceKnown;
var array = this.state.service;
var filtered = array.filter(function(el) {
return el != null;
});
};
PostLocationData = async () => {
let selectedItemforStartAs = this.state.radioButtonsforStartAs.find(
e => e.checked == true
);
selectedItemforStartAs = selectedItemforStartAs
? selectedItemforStartAs.value
: this.state.radioButtonsforStartAs[0].value;
const Uid = await AsyncStorage.getItem("projectUid");
const {
title,
desc,
base64_string,
articleCategoryKnown,
name,
type,
path,
customSpaces,
fee,
service
} = this.state;
var array = this.state.service;
console.log(
"Data:",
" id " +
Uid +
" projectDaysKnown " +
this.state.projectDaysKnown +
" selectedItemforStartAs " +
selectedItemforStartAs +
" projectSelectedServiceKnown " +
this.state.projectSelectedServiceKnown +
" projectHospitalKnown " +
this.state.projectHospitalKnown +
" projectIntervalKnown " +
this.state.projectIntervalKnown +
" projectDurationKnown " +
this.state.projectDurationKnown +
" projectprojectStartTimeKnown " +
this.state.projectprojectStartTimeKnown +
" projectprojectEndTimeKnown " +
this.state.projectprojectEndTimeKnown
);
axios
.post(CONSTANT.BaseUrl + "appointments/appointment_settings", {
hospital_id: this.state.projectHospitalKnown.toString(),
start_time: this.state.projectprojectStartTimeKnown.toString(),
end_time: this.state.projectprojectEndTimeKnown.toString(),
intervals: this.state.projectIntervalKnown.toString(),
durations: this.state.projectDurationKnown.toString(),
service: array,
spaces: selectedItemforStartAs,
week_days: this.state.projectDaysKnown,
custom_spaces: customSpaces,
doctor_id: Uid,
consultant_fee: fee
})
.then(async response => {
if (response.status === 200) {
this.setState({ isUpdatingLoader: false });
Alert.alert("Actualizado con éxito", response.data.message);
console.log(response);
this.setState({
isLoading: false
});
} else if (response.status === 203) {
Alert.alert("Error", response.data.message);
console.log(response);
this.setState({
isLoading: false
});
}
})
.catch(error => {
Alert.alert(error);
console.log(error);
});
};
calculateEndTime = () => {};
// openTimePicker = () =>{
// const { selectedHours, selectedMinutes } = this.state;
// return(
// Alert.alert("hello" , <TimePicker
// selectedHours={selectedHours}
// selectedMinutes={selectedMinutes}
// onChange={(hours, minutes) => this.setState({ selectedHours: hours, selectedMinutes: minutes })}
// />)
// );
// }
AddLocation = () => {
const {
projectHospitalKnown,
projectIntervalKnown,
projectDurationKnown,
projectSlotsKnown,
projectDaysKnown
} = this.state;
};
render() {
let selectedItemforStartAs = this.state.radioButtonsforStartAs.find(
e => e.checked == true
);
selectedItemforStartAs = selectedItemforStartAs
? selectedItemforStartAs.value
: this.state.radioButtonsforStartAs[0].value;
const { selectedHours, selectedMinutes, isLoading } = this.state;
return (
<View style={styles.container}>
{isLoading ? (
<View style={{ justifyContent: "center", height: "100%" }}>
<ActivityIndicator
size="small"
color={CONSTANT.primaryColor}
style={{
height: 30,
width: 30,
borderRadius: 60,
alignContent: "center",
alignSelf: "center",
justifyContent: "center",
backgroundColor: "#fff",
elevation: 5
}}
/>
</View>
) : null}
<ScrollView
showsVerticalScrollIndicator={false}
style={{ backgroundColor: "#fff", borderRadius: 5, margin: 10 }}
>
<Text
style={{
color: "#3d4461",
width: "70%",
fontSize: 20,
fontFamily:CONSTANT.PoppinsBold,
marginBottom: 15,
marginLeft: 10,
marginTop: 10
}}
>
Add New Location
</Text>
<View
style={{
marginLeft: 10,
marginRight: 10,
marginBottom: 10,
marginTop: 10
}}
>
<MultiSelect
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={value =>
this.setState({
projectHospitalKnown: value
})
}
uniqueKey="id"
items={this.state.projectHospital}
selectedItems={this.state.projectHospitalKnown}
borderBottomWidth={0}
single={true}
searchInputPlaceholderText="Pick Hospital..."
selectText="Pick Hospital"
styleMainWrapper={{
backgroundColor: "#fff",
borderRadius: 4,
marginTop: 10
}}
styleDropdownMenuSubsection={{
backgroundColor: "#fff",
paddingRight: -7,
height: 60,
paddingLeft: 10,
borderWidth: 0.6,
borderColor: "#fff",
borderColor: "#dddddd",
borderRadius: 4
}}
displayKey="name"
submitButtonText="Submit"
/>
</View>
<View style={{ marginLeft: 10, marginRight: 10, marginBottom: 10 }}>
<MultiSelect
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={value =>
this.setState({
projectIntervalKnown: value
})
}
uniqueKey="key"
items={this.state.projectInterval}
selectedItems={this.state.projectIntervalKnown}
borderBottomWidth={0}
single={true}
searchInputPlaceholderText="Pick Interval..."
selectText="Pick Interval"
styleMainWrapper={{
backgroundColor: "#fff",
borderRadius: 4,
marginTop: 10
}}
styleDropdownMenuSubsection={{
backgroundColor: "#fff",
paddingRight: -7,
height: 60,
paddingLeft: 10,
borderWidth: 0.6,
borderColor: "#fff",
borderColor: "#dddddd",
borderRadius: 4
}}
displayKey="val"
submitButtonText="Submit"
/>
</View>
<View style={{ marginLeft: 10, marginRight: 10, marginBottom: 10 }}>
<MultiSelect
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={value =>
this.setState({
projectDurationKnown: value
})
}
uniqueKey="key"
items={this.state.projectDuration}
selectedItems={this.state.projectDurationKnown}
borderBottomWidth={0}
single={true}
searchInputPlaceholderText="Pick Duration..."
selectText="Pick Duration"
styleMainWrapper={{
backgroundColor: "#fff",
borderRadius: 4,
marginTop: 10
}}
styleDropdownMenuSubsection={{
backgroundColor: "#fff",
paddingRight: -7,
height: 60,
paddingLeft: 10,
borderWidth: 0.6,
borderColor: "#fff",
borderColor: "#dddddd",
borderRadius: 4
}}
displayKey="val"
submitButtonText="Submit"
/>
</View>
<View style={{ marginLeft: 10, marginRight: 10, marginBottom: 10 }}>
<MultiSelect
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={value =>
this.setState({
projectprojectStartTimeKnown: value
})
}
uniqueKey="key"
items={this.state.projectStartTime}
selectedItems={this.state.projectprojectStartTimeKnown}
borderBottomWidth={0}
single={true}
searchInputPlaceholderText="Pick Start Time..."
selectText="Pick Start Time"
styleMainWrapper={{
backgroundColor: "#fff",
borderRadius: 4,
marginTop: 10
}}
styleDropdownMenuSubsection={{
backgroundColor: "#fff",
paddingRight: -7,
height: 60,
paddingLeft: 10,
borderWidth: 0.6,
borderColor: "#fff",
borderColor: "#dddddd",
borderRadius: 4
}}
displayKey="val"
submitButtonText="Submit"
/>
</View>
<View style={{ marginLeft: 10, marginRight: 10, marginBottom: 10 }}>
<MultiSelect
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={value =>
this.setState({
projectprojectEndTimeKnown: value
})
}
uniqueKey="key"
items={this.state.projectEndTime}
selectedItems={this.state.projectprojectEndTimeKnown}
borderBottomWidth={0}
single={true}
searchInputPlaceholderText="Pick End Time..."
selectText="Pick End Time"
styleMainWrapper={{
backgroundColor: "#fff",
borderRadius: 4,
marginTop: 10
}}
styleDropdownMenuSubsection={{
backgroundColor: "#fff",
paddingRight: -7,
height: 60,
paddingLeft: 10,
borderWidth: 0.6,
borderColor: "#fff",
borderColor: "#dddddd",
borderRadius: 4
}}
displayKey="val"
submitButtonText="Submit"
/>
</View>
{this.state.projectServices && (
<View>
<Text
style={{
color: "#3d4461",
width: "70%",
fontSize: 20,
fontFamily:CONSTANT.PoppinsBold,
marginBottom: 15,
marginLeft: 10,
marginTop: 10
}}
>
Available Services:
</Text>
<FlatList
style={{ paddingLeft: 5, marginBottom: 10 }}
data={this.state.projectServices}
extraData={this.state}
renderItem={({ item, index }) => (
<Collapse>
<CollapseHeader
style={{ height: 70, marginTop: 10, marginBottom: 15 }}
>
<View
style={{
backgroundColor: "#ffffff",
elevation: 3,
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
shadowColor: "#000",
marginRight: 10,
marginTop: 10,
marginLeft: 3,
marginBottom: 10,
borderRadius: 4,
height: 70
}}
>
<TouchableOpacity>
<View style={styles.mainLayoutServices}>
<Image
resizeMode="cover"
style={styles.ImageStyle}
source={{ uri: item.logo }}
/>
<View
style={{
borderLeftColor: "#dddddd",
borderLeftWidth: 0.6,
paddingTop: 20
}}
/>
{/* <Text
numberOfLines={1}
style={styles.mainServiceName}>
{item.title}
</Text> */}
<HTML
numberOfLines={1}
html={item.title}
containerStyle={styles.mainServiceName}
imagesMaxWidth={Dimensions.get("window").width}
/>
</View>
</TouchableOpacity>
<AntIcon
name="down"
color={"#484848"}
size={17}
style={{
alignSelf: "flex-end",
marginTop: -62,
padding: 20
}}
/>
</View>
</CollapseHeader>
<CollapseBody>
<View>
<View
style={{
marginLeft: 10,
marginRight: 10,
marginTop: 10,
marginBottom: 10
}}
>
<MultiSelect
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={value =>
this.setState(
{
projectSelectedServiceKnown: value
},
this.createRequiredArray(
this.state.projectServices[index].id
)
)
}
uniqueKey="service_id"
items={this.state.projectServices[index].services}
selectedItems={
this.state.projectSelectedServiceKnown
}
borderBottomWidth={0}
searchInputPlaceholderText="Pick Service..."
selectText="Pick Service"
styleMainWrapper={{
backgroundColor: "#fff",
borderRadius: 4,
marginTop: 10
}}
styleDropdownMenuSubsection={{
backgroundColor: "#fff",
paddingRight: -7,
height: 60,
paddingLeft: 10,
borderWidth: 0.6,
borderColor: "#fff",
borderColor: "#dddddd",
borderRadius: 4
}}
displayKey="title"
submitButtonText="Submit"
/>
</View>
</View>
</CollapseBody>
</Collapse>
)}
/>
</View>
)}
<Text
style={{
color: "#3d4461",
width: "70%",
fontSize: 20,
fontFamily:CONSTANT.PoppinsBold,
marginBottom: 15,
marginLeft: 10,
marginTop: 10
}}
>
Assign Appointment Spaces:
</Text>
<RadioGroup
color={CONSTANT.primaryColor}
labelStyle={{ fontSize: 14 }}
radioButtons={this.state.radioButtonsforStartAs}
onPress={radioButtons => this.setState({ radioButtons })}
style={{
paddingTop: 0,
flexDirection: "row",
marginBottom: 10,
marginTop: 0,
marginLeft: 25,
display: "flex",
width: "100%",
alignSelf: "center",
alignContent: "center",
textAlign: "center"
}}
/>
{selectedItemforStartAs == "other" && (
<TextInput
underlineColorAndroid="transparent"
placeholderTextColor="#7F7F7F"
placeholder="Other Value"
style={styles.TextInputLayout}
onChangeText={customSpaces => this.setState({ customSpaces })}
/>
)}
<Text
style={{
color: "#3d4461",
width: "70%",
fontSize: 20,
fontFamily:CONSTANT.PoppinsBold,
marginBottom: 15,
marginLeft: 10,
marginTop: 10
}}
>
Days I Offer My Services:
</Text>
<View style={{ marginLeft: 10, marginRight: 10, marginBottom: 10 }}>
<MultiSelect
ref={component => {
this.multiSelect = component;
}}
onSelectedItemsChange={value =>
this.setState({
projectDaysKnown: value
})
}
uniqueKey="key"
items={this.state.projectDays}
selectedItems={this.state.projectDaysKnown}
borderBottomWidth={0}
searchInputPlaceholderText="Pick Days..."
selectText="Pick Days"
styleMainWrapper={{
backgroundColor: "#fff",
borderRadius: 4,
marginTop: 10
}}
styleDropdownMenuSubsection={{
backgroundColor: "#fff",
paddingRight: -7,
height: 60,
paddingLeft: 10,
borderWidth: 0.6,
borderColor: "#fff",
borderColor: "#dddddd",
borderRadius: 4
}}
displayKey="val"
submitButtonText="Submit"
/>
</View>
<TextInput
underlineColorAndroid="transparent"
placeholderTextColor="#7F7F7F"
placeholder="Consultancy Fee"
style={styles.TextInputLayout}
onChangeText={fee => this.setState({ fee })}
/>
<TouchableOpacity
onPress={this.PostLocationData}
style={{
alignItems: "center",
height: 40,
margin: 10,
borderRadius: 4,
width: "50%",
alignSelf: "center",
backgroundColor: CONSTANT.primaryColor
}}
>
<Text
style={{
alignSelf: "center",
alignItems: "center",
textAlign: "center",
color: "#fff",
paddingTop: 10,
fontFamily:CONSTANT.PoppinsMedium,
}}
>
Save & Update
</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
}
export default withNavigation(AddSetting);
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#f7f7f7"
},
TextInputLayout: {
minHeight: 45,
color: "#323232",
paddingLeft: 10,
paddingRight: 10,
borderRadius: 2,
borderWidth: 0.6,
borderColor: "#dddddd",
marginLeft: 10,
marginRight: 10,
marginBottom: 10,
fontFamily:CONSTANT.PoppinsMedium,
},
mainServiceName: {
color: "#484848",
fontSize: 15,
margin: 24,
fontFamily:CONSTANT.PoppinsMedium,
},
ImageStyle: {
margin: 15,
width: 35,
height: 35
},
mainLayoutServices: {
flexDirection: "row",
height: 70
}
});
|
import React, {Component} from 'react';
import ChatBar from './ChatBar.jsx';
import MessageList from './MessageList.jsx';
import Message from './Message.jsx';
import Navbar from './Navbar.jsx';
/* Parent class state modified to delete old messages and user count */
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: {name: 'Anon'},
messages: [],
users: 0
};
// sets new web socket for each instance of App
this.connection = new WebSocket('ws://localhost:3001');
}
componentDidMount() {
/*on load - sends welcome notification w/ brief instruction for
optimal way to begin chat*/
setTimeout(() => {
const newMessage = {
type: 'incomingNotification',
username: this.state.currentUser.name,
content: 'Welcome to ChattyApp! Type your name below then TAB and say hello'
};
const messages = this.state.messages.concat(newMessage)
this.setState({messages: messages})
}, 500);
// sets event listener on messages from server
this.connection.onopen = () => {
console.log('we have something going on')
};
// recieves messages -- produces new object
this.connection.onmessage = (event) => {
const incomingEvent = JSON.parse(event.data);
/* checks if message contains user count sets state of user count ...
otherwise updates [{messages}] with chat messages and/or notifications ...
sets state for [{messages}]*/
if (incomingEvent.type === 'activeUsers') {
this.setState( {users: incomingEvent.count} )
} else {
const oldMessages = this.state.messages;
const newMessages = [
...oldMessages,
incomingEvent
]
this.setState({messages: newMessages});
}
}
}
/* updates state IF user changes name (default is anon) ...
send notification to all users who have connections of name change
... reset to 'Anon' if empty ... now allows almostr any user anme including fales or 0*/
changeName = (event) => {
let lastUsername = this.state.currentUser.name;
let newUsername = event.target.value === '' ? 'Anon' : event.target.value;
console.log('past if', this.state.currentUser)
if (lastUsername === newUsername) return;
this.setState({currentUser: {name: newUsername}}, () => {
let newJSONContent = {
type: 'postNotification',
content: `${lastUsername} changed their username to ${newUsername}`
}
this.connection.send(JSON.stringify(newJSONContent));
})
}
/* updates state WHEN user adds a chat message (content) ...
sends their name and content to all users who have connection ...
will do nothing if chatbar-message is blank*/
postChat = (event) => {
const userInput = event.target
if (event.key === 'Enter' && userInput.value) {
let newJSONContent = {
type: 'postMessage',
username: this.state.currentUser.name,
content: userInput.value
}
this.connection.send(JSON.stringify(newJSONContent));
userInput.value = '';
}
}
/* sends props and/or function s to children ...
renders all elements tio single page app*/
render() {
return (
<div>
<Navbar
userCount={this.state.users}
/>
<MessageList
messages={this.state.messages}
/>
<Message />
<ChatBar
currentUser={this.state.currentUser}
postChat={this.postChat}
changeName={this.changeName}
/>
</div>
);
}
}
export default App;
|
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import './assets/styles/common.css'
// 处理axios的三个问题
import axios from 'axios'
// 问题1
axios.defaults.baseURL = 'http://localhost:8888/api/private/v1/'
// 问题2
// Vue.prototype.$axios = axios // 以后组组件内 this.$axios
Vue.prototype.$axios = axios
// 问题3 : 请求拦截器
axios.interceptors.request.use(
function (config) {
config.headers.Authorization = localStorage.getItem('token')
return config
},
function (error) {
// Do something with request error
return Promise.reject(error)
}
)
Vue.config.productionTip = false
Vue.use(ElementUI)
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
|
function randomNumber(min, max) {
return Math.random() * (max - min) + min;
}
function berry(id, by, x, y) {
this.class = 'Food'
this.isdead = false;
this.id = id;
this.radius = randomNumber(10, 15)
this.isbiome = false;
this.type = 20; //object type (animal. hill bush)
this.collideable = false
this.xp = randomNumber(1, 3)
this.water = 0
this.energy = 0
this.spawned = true
this.isloaded = false
this.spawnedby = by
this.spawnedby2 = by
this.biome = 0
this.movable = true
this.speed = 10
this.killerid = 0
this.isinvisible = false
this.x = x
this.y = y
this.isinquadtree = false
this.lowestrespawnsec = 25
this.bigestrespawnsec = 50
this.veloX = 0
this.veloY = 0
this.deathtime = 80
this.spawnedtime = Date.now();
};
berry.prototype = {
};
berry.prototype.customdatawriteoncreate = function (buf, off) {
}
berry.prototype.customdatawriteonupdate = function (buf, off) {
}
module.exports = berry; |
require('dotenv').config();
const express = require('express');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const usersDb = require('../data/helpers/usersHelper.js');
const notesDb = require('../data/helpers/notesHelper.js');
const logoutDb = require('../data/helpers/logoutHelper.js');
const protected = require('../middleware/protected.js');
const userIdVerify = require('../middleware/userIdVerification.js');
const router = express.Router();
// generates jwt
const generateToken = user => {
const payload = {
subject: user.id,
username: user.username
};
const secret = process.env.JWT_SECRET;
const options = {
expiresIn: '12h',
};
return jwt.sign(payload, secret, options);
};
// [GET] /api/users/protectedTest
router.get('/protectedTest', protected, (req, res) => {
res.status(418).json({ message: 'You must be logged in!' })
});
// [POST] /api/users/availableUsername
router.post('/availableUsername', async (req, res) => {
const username = req.body.username;
try {
const result = await usersDb.availableUsername(username);
res.status(200).send(result);
} catch (err) {
res.status(500).json({ code: 3, message: 'Error registering user' });
}
});
// [GET] /api/users
router.get('', (req, res) => {
usersDb.getUsers()
.then(users => {
if (users.length) {
res.status(200).json(users);
} else {
res.status(404).json({ code: 9, message: 'No users in database' });
}
})
.catch(err => {
res.status(500).json({ code: 3, message: 'Error retrieving users' });
});
});
// [GET] /api/users/:id
router.get('/:id', (req, res) => {
const userId = req.params.id;
usersDb.getUser(userId)
.then(user => {
if (user.length) {
res.status(200).json(user);
} else {
res.status(404).json({ code: 4, message: 'User does not exist' });
}
})
.catch(err => {
res.status(500).json({ code: 3, message: 'Error retrieving user' });
})
});
// [GET] /api/users/:token/notes
router.get('/:token/notes', protected, userIdVerify, async (req, res) => {
const user_id = req.id;
try {
const notes = await notesDb.getNotes(user_id);
if (notes.length) {
res.status(200).json(notes);
} else {
const checkUser = await usersDb.getUser(user_id);
if (checkUser.length) {
res.status(200).json({ code: 1, message: 'No notes in database' });
} else {
res.status(404).json({ code: 4, message: 'User does not exist' });
}
}
} catch (err) {
res.status(500).json({ code: 3, message: 'Error retrieving notes' });
};
});
// [POST] /api/users/register
router.post('/register', (req, res) => {
const newUser = req.body;
if (typeof newUser.username === 'string' && typeof newUser.password === 'string') {
if (usersDb.availableUsername(newUser.username)) {
usersDb.registerUser(newUser)
.then(id => {
res.status(201).json(id);
})
.catch(err => {
if (err.code === "23505") {
res.status(409).json({ code: 10, message: 'Username already exists' });
} else {
res.status(500).json({ code: 3, message: 'Error registering new user' });
}
})
} else {
res.status(409).json({ code: 10, message: 'Username already exists' })
}
} else {
res.status(400).json({ code: 5, message: 'Request formatted incorrectly' });
}
});
// [POST] /api/users/login
router.post('/login', (req, res) => {
const creds = req.body;
creds.username = creds.username.toLowerCase();
usersDb.getUserByUsername(creds.username)
.then(user => {
if (user && bcrypt.compareSync(creds.password, user.password)) {
const token = generateToken(user);
res.status(200).json({ code: 12, message: 'Successful login', token });
} else {
res.status(401).json({ code: 11, message: 'Failed login' });
}
})
.catch(err => {
res.status(500).json({ code: 3, message: 'Error occurred during login' });
});
});
// [POST] /api/users/:id/newNote
router.post('/newNote', protected, userIdVerify, (req, res) => {
const user_id = req.id;
console.log(user_id);
const newNote = req.body;
let valid = true;
// validate post request format
Object.getOwnPropertyNames(newNote).forEach(key => {
switch (key) {
case 'title':
if (typeof newNote[key] !== 'string' || newNote[key] === '') {
valid = false;
};
break;
case 'textBody':
if (typeof newNote[key] !== 'string') {
valid = false;
};
break;
case 'tags':
if (!Array.isArray(newNote[key])) {
valid = false;
break;
} else {
if (!newNote[key].every(element => typeof element === 'string' || typeof element === 'number')) {
valid = false;
break;
};
newNote.tags = newNote.tags.join(',');
break;
}
default:
break;
}
});
if (valid) {
notesDb.addNote(newNote, user_id)
.then(id => {
res.status(201).json(id);
})
.catch(err => {
if (err.errno === 19 && err.code === 'SQLITE_CONSTRAINT') {
res.status(404).json({ code: 4, message: 'User not found' });
} else {
res.status(500).json({ code: 3, message: 'Error creating note' });
}
});
} else {
res.status(400).json({ code: 5, message: 'Request formatted incorrectly' });
}
});
// [POST] /api/users/logout
router.post('/logout', protected, (req, res) => {
if (req.body.token) {
if (typeof req.body.token === 'string') {
const invalidToken = { invalidToken: req.body.token };
logoutDb.invalidateToken(invalidToken)
.then(id => {
if (id) {
res.status(200).json({ code: 15, message: 'Successful logout' })
};
})
.catch(err => {
if (err.errno === 19 && err.code === 'SQLITE_CONSTRAINT') {
res.status(404).json({ code: 16, message: 'Token already invalidated' });
} else {
res.status(500).json({ code: 3, message: 'Error logging out' });
}
});
} else {
res.status(400).json({ code: 13, message: 'Invalid token' });
}
} else {
res.status(400).json({ code: 14, message: 'No token provided' });
}
});
module.exports = router; |
import React from "react";
import { connect } from "react-redux";
import $ from "jquery"
import "./Kuserissue.scss";
class Kuserissue extends React.Component {
constructor(props) {
super(props);
this.state = {
tab:[{
text:"我发布的",
title:"我的",
id:1
},{
text:"点赞的话题",
title:"点赞",
id:2
},{
text:"收藏的话题",
title:"收藏",
url:"https://www.easy-mock.com/mock/5993f32f059b9c566dbf4430/frent/label",
id:3
},{
text:"关注人话题",
title:"关注",
id:4
}],
tabId : 1,
data:[]
}
this.tab = this.tab.bind(this);
}
tab(e){
this.setState({tabId:e.target.dataset.id},function(){
});
}
componentDidMount(){
this.setState({tabId:this.props.match.params.id})
var self = this;
axios.get("https://www.easy-mock.com/mock/5993f32f059b9c566dbf4430/frent/label").then(function (response) {
self.setState({data:response.data},function(){
// console.log(this.state.data)
})
})
}
render() {
return (
<div className="Kuserissue">
<div className="KuserissueHead">
<span><a href="#/user">返回</a></span>
<p>{
this.state.tab.map((item)=>{
if(item.id==this.state.tabId){
return item.text;
}
})
}</p>
<span></span>
</div>
<div className="Kuserissue-tab">
{
this.state.tab.map((item)=>{
return <div onClick={this.tab} data-id={item.id} key={item.id} className={this.state.tabId == item.id?"Kuserissue-tab-active":""}>{item.title}</div>
})
}
</div>
<div className="KuserissueBody">
<div className="mu-card-header">
<div className="mu-avatar">
<div className="mu-avatar-inner">
<img src="http://placeimg.com/80/80/any?id=6" />
</div>
</div>
<div className="mu-card-header-title">
<div className="mu-card-title">
蒋娟 | #室友
</div>
<div className="mu-card-sub-title">
1988-11-21 21:27:30
</div>
</div>
</div>
<div className="mu-card-text">
件来争形单高便律义布划革口以一社。
<div className="mu-badge-container demo-badge-content">#女室友 <em className="mu-badge mu-badge-float"></em>
</div>
</div>
<div className="mu-flexbox mu-flex-row">
<div className="mu-flexbox-item flex-demo" style={{marginLeft:" 8px", flex: "1 1 auto", order: "0"}}>
<img zdepth="1" className="mu-col-img" src="http://placeimg.com/244/132/any?id=8" lazy="loaded"/>
</div>
<div className="mu-flexbox-item flex-demo" style={{marginLeft: "8px",flex: "1 1 auto", order: "0"}}>
<img zdepth="1" className="mu-col-img" src="http://placeimg.com/244/132/any?type=8" lazy="loaded"/>
</div>
</div>
</div>
</div>
)
}
}
export default connect((state) => {
return state
})(Kuserissue)
|
module.exports = angular
.module('torrents')
.factory('Torrents', function (njrtLog, Restangular, Socket, Notification, $state, SessionService) {
var logger = njrtLog.getInstance('torrents.Torrents');
logger.debug('Torrents loaded.');
var Torrents = {};
Torrents.torrents = [];
Socket.on('connect', function() {
logger.debug('Connected to socket.');
});
Socket.on('connecting', function() {
logger.debug('Connecting to socket.');
});
Socket.on('connect_failed', function() {
logger.error('Connection to socket failed');
Notification.add('danger', 'Failed to connect to server via web sockets');
});
Socket.on('error', function(err) {
if (err === 'handshake unauthorized') {
Notification.add('danger', 'Handshake unauthorized. Please login.');
// Clear session
SessionService.clearSession();
// Redirect to login
$state.go('login');
}
logger.error(err);
});
Socket.on('torrents', function(data) {
Torrents.torrents = data;
});
Torrents.getTorrents = function () {
logger.debug('Getting torrents');
// Initial REST call to get torrents on resolve.
}
/**
* Start a torent given a specified torrent hash.
* @param {String} hash Hash of the torrent.
* @return {Promise} Promise with success string.
*/
Torrents.start = function (hash) {
logger.debug('Starting torrent from hash', hash);
return Restangular
.one('torrents', hash)
.post('start', {})
.then(function () {
return Notification.add('success', 'Torrent started.');
}, function () {
return Notification.add('danger', 'Torrent failed to start.');
});
}
/**
* Pause a torrent given a specified torrent hash.
* @param {String} hash Hash of the torrent.
* @return {Promise} Promise with success string.
*/
Torrents.pause = function (hash) {
logger.debug('Pausing torrent from hash', hash);
return Restangular
.one('torrents', hash)
.post('pause', {})
.then(function () {
return Notification.add('success', 'Torrent paused.');
}, function () {
return Notification.add('danger', 'Torrent failed to pause.');
});
}
/**
* Stop a torrent given a specified torrent hash.
* @param {String} hash Hash of the torrent
* @return {Promise} Promise with success string.
*/
Torrents.stop = function (hash) {
logger.debug('Stopping torrent from hash', hash);
return Restangular
.one('torrents', hash)
.post('stop', {})
.then(function () {
return Notification.add('success', 'Torrent stopped.');
}, function () {
return Notification.add('danger', 'Torrent failed to stop.');
});
}
/**
* Remove a torrent given a specified torrent hash.
* @param {String} hash Hash of the torrent
* @return {Promise} Promise with success string.
*/
Torrents.remove = function (hash) {
logger.debug('Removing torrent from hash', hash);
return Restangular
.one('torrents', hash)
.post('remove', {})
.then(function () {
return Notification.add('success', 'Torrent removed.');
}, function () {
return Notification.add('danger', 'Torrent could not be removed.');
});
}
/**
* Delete torrent data given a specified torrent hash.
* @param {String} hash Hash of the torrent
* @return {Promise} Promise with success string.
*/
Torrents.deleteData = function (hash) {
logger.debug('Deleting torrent data from hash', hash);
return Restangular
.one('torrents', hash)
.post('delete_data', {})
.then(function () {
return Notification.add('success', 'Torrent data deleted.');
}, function () {
return Notification.add('danger', 'Torrent could not be deleted.');
});
}
/**
* Load a torrent given a url string of the torrent file or magnet link.
* @param {String} url Url of the torrent file or magnet link.
* @return {Promise} Promise with success string.
*/
Torrents.load = function (url) {
logger.debug('Loading torrent from url', url);
return Restangular
.all('torrents')
.customPOST({
'url': url
}, 'load')
.then(function () {
return Notification.add('success', 'Torrent loaded.');
}, function () {
return Notification.add('danger', 'Torrent failed to load.');
});
}
/**
* Set the throttle channel for the specified torrent hash.
* @param {String} hash Hash of the torrent.
* @param {String} channel Channel name (specified by the server).
* @return {Promise} Promise with success string.
*/
Torrents.setChannel = function (hash, channel) {
logger.debug('Setting channel for hash', hash, 'and channel', channel);
return Restangular
.one('torrents', hash)
.post('channel', {
'channel': channel
})
.then(function () {
return Notification.add('success', 'Torrent throttle channel set.');
}, function () {
return Notification.add('danger', 'Torrent could not be throttled.');
});
}
return Torrents;
}); |
const puppeteer = require('puppeteer')
const notifier = require('node-notifier')
;(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setViewport({
width: 2000,
height: 2000,
deviceScaleFactor: 1
})
const lat = 15.02198;
const lng = 104.797501;
const line = 9;
// const position = '15.02198,104.838501'
for(i=-1;i<0;i++){
const position = `${lat-(line*0.031)},${lng+(i*0.041)}`
await page.goto(
`https://www.google.co.th/maps/place/%E0%B8%AD%E0%B8%B3%E0%B9%80%E0%B8%A0%E0%B8%AD+%E0%B9%80%E0%B8%94%E0%B8%8A%E0%B8%AD%E0%B8%B8%E0%B8%94%E0%B8%A1+%E0%B8%AD%E0%B8%B8%E0%B8%9A%E0%B8%A5%E0%B8%A3%E0%B8%B2%E0%B8%8A%E0%B8%98%E0%B8%B2%E0%B8%99%E0%B8%B5/@${position},4011m/data=!3m1!1e3!4m5!3m4!1s0x31141e1be7696775:0x302b54113606010!8m2!3d14.8548457!4d105.0791228?hl=th`
)
await page.waitFor(20000)
await page.click('.widget-pane-toggle-button-container button')
await page.screenshot({path: `line${line}/${i}.png`})
await console.log(`saved : line ${line}-${i}`)
await notifier.notify(`saved : line ${line}-${i}`)
}
await browser.close()
})()
|
import React from 'react'
import documentsData from '../data/documents'
import SingleDocument from './SingleDocument'
import GoBack from '../components/GoBack'
const DocumentsContainer = (props) => {
return (
<div id="documentsContainer">
<GoBack backButton={props.backButton} />
{documentsData.map((document) => {
return <SingleDocument key={document.id} document={document} />
})}
</div>
)
}
export default DocumentsContainer
|
/**
* Created by sungmin on 11/13/16.
*/
/*
* NAME - Object constructor function
* @param _parentElement -- HTML element in which to draw the visualization
* @param _data -- ???
*/
NAME = function(_parentElement, _data) {
this.parentElement = _parentElement;
this.data = _data;
this.initVis();
}
/*
* Initialize visualization (static content, e.g. SVG area or axes)
*/
NAME.prototype.initVis = function() {
var vis = this;
vis.wrangleData();
}
/*
* Data wrangling
*/
NAME.prototype.wrangleData = function() {
var vis = this;
// Currently no data wrangling/filtering needed
// vis.displayData = vis.data;
// Update the visualization
vis.updateVis();
}
/*
* The drawing function
*/
NAME.prototype.updateVis = function() {
var vis = this;
}
|
import Vue from 'vue'
/* mixin to add boolean when component is mounted, which can be used alongside with vuetify */
export const mountedMixin = {
data () {
return {
isComponentMounted: false
}
},
mounted () {
this.isComponentMounted = true
}
}
Vue.mixin(mountedMixin)
|
import I18n from "react-native-i18n";
import en from "../locales/en";
import fi from "../locales/fi"
I18n.fallbacks=true;
I18n.translations={
en:en,
fi:fi
}
I18n.locale="en"
export default I18n; |
import sedans from "./images/icon-sedans.svg";
import suvs from "./images/icon-suvs.svg";
import luxury from "./images/icon-luxury.svg";
function App() {
return (
<div className="app-container">
<div className={"column-card-container"}>
<div className={"column-card-item"} id={"sedans"}>
<div className={"column-card-item-car-pic"}>
<img src={sedans} />
</div>
<div className={"column-card-item-text"} >
<div className={"column-card-item-h1"} >
<h1>SEDANS</h1>
</div>
<div className={"column-card-item-p"}>
<p>Choose a sedan for its affordability and excellent fuel economy. Ideal for cruising in the city or on your next road trip.</p>
</div>
</div>
<div className={"column-card-item-button"}>
<button>Learn More</button>
</div>
</div>
<div className={"column-card-item"} id={"suvs"}>
<div className={"column-card-item-car-pic"}>
<img src={suvs} />
</div>
<div className={"column-card-item-text"}>
<div className={"column-card-item-h1"}>
<h1>SUVS</h1>
</div>
<div className={"column-card-item-p"}>
<p>Take an SUV for its spacious interior, power, and versatility. Perfect for your next family vacation and off-road adventures.</p>
</div>
</div>
<div className={"column-card-item-button"}>
<button>Learn More</button>
</div>
</div>
<div className={"column-card-item"} id={"luxury"}>
<div className={"column-card-item-car-pic"}>
<img src={luxury} />
</div>
<div className={"column-card-item-text"}>
<div className={"column-card-item-h1"}>
<h1>LUXURY</h1>
</div>
<div className={"column-card-item-p"}>
<p>Cruise in the best car brands without the bloated prices. Enjoy the enchanced comfort of a luxury rental and arrive in style.</p>
</div>
</div>
<div className={"column-card-item-button"}>
<button>Learn More</button>
</div>
</div>
</div>
</div>
);
}
export default App;
|
import clamp from "lodash/clamp";
import keys from "lodash/keys";
import omit from "lodash/omit";
import { simpleMemoize } from "./utils/generalUtils";
// COLORS
export const COLORS = {
orange: "#ee6a29",
green: "#26632d",
yellow: "#e7ea08",
red: "#a51d1a",
lightBrown: "#c4bc9d",
blue: "#57abef",
lightGreen: "#4be34d",
purple: "#9251fb",
brown: "#4d3d2f",
background: "#fbf6ea"
};
export const BLOCK_COLORS = keys(omit(COLORS, ["background", "brown"]));
// GAME LOGIC
export const NUM_COLUMNS = 10;
export const MAX_ROWS = 14;
export const STARTING_ROWS = 5;
export const CHANCE_OF_WALL_FOR_ROW = 0.35;
export const MAX_WALLS = 5;
export const BLOCKS_BEFORE_NEXT_CHILI = 50;
const STARTING_COLORS = 5;
const STARTING_BLOCKS_PER_LEVEL = 120;
const LEVEL_TO_START_DECREASING = 11;
const BLOCKS_PER_LEVEL_DECREASE = 10;
const MINIMUM_BLOCKS_PER_LEVEL = 60;
export const NUM_COLORS = level =>
Math.min(STARTING_COLORS + level - 1, BLOCK_COLORS.length);
export const BLOCKS_TO_CLEAR_LEVEL = level =>
Math.max(
STARTING_BLOCKS_PER_LEVEL -
Math.max(level + 1 - LEVEL_TO_START_DECREASING, 0) *
BLOCKS_PER_LEVEL_DECREASE,
MINIMUM_BLOCKS_PER_LEVEL
);
const STARTING_INTERVAL = 15000;
const INTERVAL_DECAY = 0.9;
export const NEW_ROW_INTERVAL = level =>
Math.round(
STARTING_INTERVAL *
INTERVAL_DECAY **
Math.max(level - 1 - BLOCK_COLORS.length + STARTING_COLORS, 0)
);
// SCORING
export const POINTS_PER_BLOCK = 10;
export const POINTS_FOR_CLEARING_BOARD = 1000;
export const POINTS_FOR_CLEARING_LEVEL = 2000;
// TIMING
export const BLOCK_MOVE_DURATION = 70;
export const REMOVAL_DELAY = BLOCK_MOVE_DURATION + 10;
export const BLOCK_APPEAR_DURATION = 200;
export const BLOCK_DISAPPEAR_DURATION = 500;
export const BLOCK_DISAPPEAR_BLINK_COUNT = 2;
// GAME DIMENSIONS
export const GUTTER = 1;
export const MINIMUM_SCREEN_PADDING = 8;
export const GAME_AREA_BORDER = 2;
export const BLOCK_BORDER_WIDTH = 2;
export const TIMER_HEIGHT = 3;
export const BLOCK_HEIGHT = simpleMemoize(
(blockWidth, gameHeight) =>
Math.floor(
(gameHeight -
2 * GAME_AREA_BORDER -
2 * GUTTER -
CHARACTER_HOLD_POSITION(blockWidth)) /
(MAX_ROWS + 0.2)
) - GUTTER
);
// CHARACTER DIMENSIONS
export const CHARACTER_SIZE = simpleMemoize(blockWidth =>
clamp(blockWidth, 50, 140)
);
export const CHARACTER_VERTICAL_OFFSET = simpleMemoize(
blockWidth => -Math.round(5 / 64 * CHARACTER_SIZE(blockWidth))
);
export const CHARACTER_HOLD_POSITION = simpleMemoize(
blockWidth =>
Math.round(34 / 64 * CHARACTER_SIZE(blockWidth)) +
CHARACTER_VERTICAL_OFFSET(blockWidth)
);
|
const TIM = require('tim-wx-sdk');
const COS = require('cos-wx-sdk-v5');
const { seatLog } = require('./request');
class IM {
constructor({sdkAppId, userID, userSig, receivedEventCb,getMessageListCb, errorEventCb, to}) {
this.tim = null;
this.sdkAppId = sdkAppId;
this.userID = userID;
this.userSig = userSig;
this.to = to;
this.getMessageListCb = getMessageListCb;
this.receivedEventCb = receivedEventCb;
this.errorEventCb = errorEventCb;
}
create() {
console.log('im: create');
this.tim = TIM.create({
SDKAppID: this.sdkAppId
});
this.tim.registerPlugin({'cos-wx-sdk': COS});
this.initEvents();
}
login() {
console.log('im: login');
this.tim.login({
userID: this.userID,
userSig: this.userSig
}).then(res => {
console.log('im login success', res);
}).catch(err => {
console.error('im login fail', err);
wx.showToast({
title: '登录错误,请重试',
success: () => {
setTimeout(() => wx.navigateBack(), 2000);
}
})
})
}
logout() {
console.log('im: logout');
this.tim.logout();
this.removeEvents();
}
initEvents() {
console.log('im: init events');
this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.imReceivedEvent, this);
this.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.imListUpdateEvent, this);
this.tim.on(TIM.EVENT.KICKED_OUT, this.imKickedOutEvent, this);
this.tim.on(TIM.EVENT.ERROR, this.imErrorEvent, this);
this.tim.on(TIM.EVENT.SDK_READY, this.imReadyEvent, this);
this.tim.on(TIM.EVENT.SDK_NOT_READY, this.imNotReadyEvent, this);
}
removeEvents() {
console.log('im: remove events');
this.tim.off(TIM.EVENT.MESSAGE_RECEIVED, this.imReceivedEvent, this);
this.tim.off(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.imListUpdateEvent, this);
this.tim.off(TIM.EVENT.KICKED_OUT, this.imKickedOutEvent, this);
this.tim.off(TIM.EVENT.ERROR, this.imErrorEvent, this);
this.tim.off(TIM.EVENT.SDK_READY, this.imReadyEvent, this);
this.tim.off(TIM.EVENT.SDK_NOT_READY, this.imNotReadyEvent, this);
}
imReceivedEvent(e) {
this.receivedEventCb(e);
}
imListUpdateEvent(e) {
console.log(TIM.EVENT.CONVERSATION_LIST_UPDATED, e);
}
imKickedOutEvent(e) {
console.log(TIM.EVENT.KICKED_OUT, e);
wx.showToast({
title: '重复登录,请重试',
success: () => {
setTimeout(() => {
wx.navigateBack()
}, 2000)
}
})
}
imErrorEvent(e) {
console.error(TIM.EVENT.ERROR, e);
// seatLog(e);
this.errorEventCb(e);
}
imReadyEvent(e) {
console.log('im: ready', TIM.EVENT.SDK_READY, e);
// console.log()
this.getMessageListCb(this.getMessageList())
// this.cb();
}
imNotReadyEvent(e) {
console.log(TIM.EVENT.SDK_NOT_READY, e);
}
createCustomMessage(message) {
console.log(this.to);
return this.tim.createCustomMessage({
to: this.to,
conversationType: TIM.TYPES.CONV_GROUP,
payload: {
data: JSON.stringify(message)
}
})
}
createTextMessage(message) {
console.log(this.to);
return this.tim.createTextMessage({
to: this.to,
conversationType: TIM.TYPES.CONV_GROUP,
payload: {
text: message
}
})
}
createImageMessage(image) {
return this.tim.createImageMessage({
to: this.to,
conversationType: TIM.TYPES.CONV_GROUP,
payload: {
file: image
},
onProgress: event => console.log('image upload progress ', event)
})
}
sendIvrConfirmMessage() {
const app = getApp()
const message = this.tim.createCustomMessage({
to: this.to,
conversationType: TIM.TYPES.CONV_GROUP,
payload: {
data: JSON.stringify({
src: "2",
ivrId: app.globalData.ivrId
})
}
});
return this.tim.sendMessage(message);
}
sendMessage(message) {
return this.sendIvrConfirmMessage()
.then(res => {
console.log('im: ivr confirm success', res);
})
.catch(err => {
console.warn('im: ivr confirm fail', err);
seatLog(JSON.stringify({err}));
return Promise.resolve()
})
.then(() => {
console.log('im: after ivr confirm');
return this.tim.sendMessage(message);
})
}
reSendMessage(message) {
return this.tim.resendMessage(message);
}
getMessageList() {
return new Promise((resolve, reject) => {
this.tim.getMessageList({
conversationID: 'GROUP' + this.to
}).then(res => {
console.log('拉取消息记录ID', 'GROUP' + this.to)
console.log('拉取消息记录', res)
this.setMessageRead();
res.data.messageList = res.data.messageList.filter(message => {
return message.payload.data !== '{"src":"2","ivrId":"90"}' // 过滤ivr信息
});
resolve(res);
}).catch(err => {
reject(err);
})
})
}
setMessageRead() {
this.tim.setMessageRead({conversationID: this.to})
.then()
.catch(err => {
console.error('im: setMessageRead fail', err)
})
}
}
module.exports = IM;
|
const Discord = require("discord.js");
const bot = new Discord.Client();
bot.on("ready", () => {
console.log(`Bot has started, with ${bot.users.size} users, in ${bot.channels.size} channels of ${bot.guilds.size} guilds.`);
bot.guilds.forEach((guild) => { //for each guild the bot is in
let defaultChannel = "";
guild.channels.forEach((channel) => {
if(channel.type == "text" && defaultChannel == "") {
if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
defaultChannel = channel;
}
}
})
setInterval (function () {
defaultChannel.send({embed: {
color: 3447003,
author: {
name: bot.user.username,
icon_url: bot.user.avatarURL
},
title: "👍 UPDATE LOG! 👍",
url: "http://google.com",
description:"This is an update log.",
fields: [{
name: "#1 Updated create",
value:"Now you can just set up the giveaways by using ?create"
},
{
name: "Kim updated",//wait l'm sending an update log //what is it?
value:"more cell added"
},
{
name: "#3 Cmds added",
value: "Some more cmds have been added as well!"
},
{
name:"#4 system upgraded!",
value:"updated system worker"//hold on
},
{
name:"#5 Bugs fixes",
value:"Fixes some bugs"
},
{
name:"Feedback",
value:"you can join us by clicking [here](https://discord.gg/ZY7DbYJ) also you can vote for the bot here to keep it update and make kim online [vote](https://discordbots.org/bot/447044725820620810/vote)"
},
{
name:"Add me to your server!",
value:"Add me to your server using this [link.](https://discordapp.com/api/oauth2/authorize?client_id=447044725820620810&permissions=8&scope=bot)"
},
{
name: "We love the community!",
value:"make sure to show the teams some love by joining our [Server.](https://discord.gg/ZY7DbYJ)"
}
],
timestamp: new Date(),
footer: {
icon_url: bot.user.avatarURL,
text: "© By Community Of People Developers"
}
}
})
}
)
})
});
bot.login("") |
exports.seed = function(knex, Promise) {
// Deletes ALL existing entries
return knex('actions')
.truncate()
.then(function() {
// Inserts seed entries
return knex('actions').insert([
{
description: 'Inital setup',
notes: 'Add dependencies etc.',
completed: true,
project_id: 1,
},
{
description: 'Migrate database',
notes: 'Use that migrate stuff',
completed: false,
project_id: 1,
},
{
description: 'Get some coffee',
notes: 'Got to get the work juice flowing',
completed: true,
project_id: 3,
},
]);
});
};
|
import React, { useEffect } from "react";
import { useLocation } from "react-router-dom";
import { connect } from "react-redux";
import { setIsRoomHost } from "../store/actions";
import JoinRoomTitle from "./JoinRoomTitle";
import JoinRoomContent from "./JoinRoomContent";
import "./JoinRoomPage.css";
const JoinRoomPage = (props) => {
const { setIsRoomHostAction, isRoomHost } = props;
const search = useLocation().search;
useEffect(() => {
const isRoomHost = new URLSearchParams(search).get("host");
if (isRoomHost) {
setIsRoomHostAction(true);
}
}, []);
return (
<div className="join_room_page_container">
<div className="join_room_page_panel">
<JoinRoomTitle isRoomHost={isRoomHost} />
<JoinRoomContent />
</div>
</div>
);
};
const mapStoreStateToProps = (state) => {
return {
...state,
};
};
const mapActionsToProps = (dispatch) => {
return {
setIsRoomHostAction: (isRoomHost) => dispatch(setIsRoomHost(isRoomHost)),
};
};
export default connect(mapStoreStateToProps, mapActionsToProps)(JoinRoomPage);
|
// The overview is the first page which we see when loading up the application.
// It's based on the current default landing page for LASE. This component uses
// hooks, so read carefully.
// Imports
import React, { useContext, useReducer, useState, useEffect } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, ScrollView, TouchableOpacity } from 'react-native';
import Publication from '../../Publications/Publication.js';
import Footer from '../Footer';
import { BASE_URL } from '../../../constants/API.js';
import { Entypo, MaterialCommunityIcons } from '@expo/vector-icons';
import { LightStyles, DarkStyles, Colors} from '../../../constants/globalStyle';
import KeyContext from '../../../KeyContext';
import { LinkOpener } from '../../../constants/SimpleFunctions';
export default function Publications(props) {
const { key, dark } = useContext(KeyContext);
const [styles, updateStyles] = useReducer(() => StyleSheet.create({...(dark ? DarkStyles : LightStyles), ...LocalStyles}), {});
useEffect(updateStyles, [dark]);
const [pubs, setPubs] = useState({loaded: false, items: []});
useEffect(() => {
let get = async () => {
let items = [], page = 0;
while(true) {
let resp_items = await fetch(`${BASE_URL}/publications?page=${page}`, {
method: "GET",
headers: { "x-api-key": key }
}).then(r => r.json());
items = items.concat(resp_items.publications);
page++;
if(resp_items.publications.length < 100) break;
}
let sorter = (a, b) => {
let aYear = parseInt(a.year) || 0, bYear = parseInt(b.year) || 0;
let aMonth = parseInt(a.month) || 0, bMonth = parseInt(b.month) || 0;
let aDay = parseInt(a.day) || 0, bDay = parseInt(b.day) || 0;
return aYear === bYear ? aMonth === bMonth ? aDay === bDay ? 0 : bDay - aDay : bMonth - aMonth : bYear - aYear;
}
setPubs({loaded: true, items: items.sort(sorter)})
}
get();
}, []);
return (
<View style={styles.componentBackground}>
{pubs.loaded ? (
<ScrollView style={{padding: 15}}>
<Text style={[styles.lblPrimaryHeading, styles.bold]}>Showing {pubs.items.length} publications</Text>
<View>
{pubs.items.map(pub => (
<View key={pub.id}
style={styles.horiztonalItemWrapper}>
<Publication
key={pub.id}
data={pub}
dark={dark}
/>
{pub.file ? (
<TouchableOpacity
style={[styles.horiztonalItemWrapper, {margin: 5}]}
onPress={LinkOpener(`https://lase.mer.utexas.edu/documents/library/${pub.file.indexOf(":") > -1 ? pub.file.substring(0, pub.file.indexOf(":")) : pub.file}`)}>
<Entypo name="link" size={24} color="blue" />
<Text style={styles.lblColorized}>PDF</Text>
</TouchableOpacity>
) : (<View/>)}
{pub.url ? (
<TouchableOpacity
style={styles.horiztonalItemWrapper}
onPress={LinkOpener(pub.url)}>
<MaterialCommunityIcons name="file-document-box-check-outline" size={24} color="blue" />
<Text style={styles.lblColorized}>DOI</Text>
</TouchableOpacity>
) : (<View/>)}
</View>
))}
</View>
<Footer />
</ScrollView>
) : (
<ActivityIndicator style={{margin: 25}}/>
)}
</View>
);
}
const LocalStyles = {}
|
/// <reference types="cypress" />
describe("Post Request", () => {
let titleOfPosts = new Array();
let randomTitle = Math.random().toString(36).substring(1) + Math.random().toString(36).substring(1);
it("Create a new post via /posts api", () => {
cy.request({
method: "POST",
url: "http://localhost:3000/posts",
body: {
title: randomTitle,
author: "Sarah Jones"
}
}).then(response => {
expect(response.status).to.eql(201)
})
});
it("Validate title of latest post", () => {
cy.request({
method: "GET",
url: "http://localhost:3000/posts",
headers: {
accept: "application/json"
}
}).then(response => {
let body = JSON.parse(JSON.stringify(response.body));
body.forEach(function(item) {
titleOfPosts.push(item["title"]);
})
}).then(() => {
var latestPost = titleOfPosts[titleOfPosts.length-1]
expect(latestPost).to.eq(randomTitle);
})
})
}); |
/*
* This file runs screenshot comparison tasks for the homepage
*
* @package: Blueacorn hpScreenshotCompare.js
* @version: 1.0
* @Author: Blue Acorn, Inc. <code@blueacorn.com>
* @Copyright: Copyright 2015-06-26 08:11:00 Blue Acorn, Inc.
*/
//relative files paths for local testing
//import js files
phantom.page.injectJs('../../data/Constants.js');
phantom.page.injectJs('../../utilities/Start.js');
phantom.page.injectJs('../../utilities/Run.js');
phantom.page.injectJs('../../utilities/Screenshot.js');
phantom.page.injectJs('../../utilities/CommonTests.js');
phantom.page.injectJs('../../utilities/InitializePhantomCss.js')
phantom.page.injectJs('../../objects/HomePage.js');
/*
Quick screenshot test to make sure National Wholesale is up and running
*/
//casper.userAgent('Mozilla/5.0(Macintosh; Intel Mac OS X)');
/*
Require and initialise PhantomCSS module
Paths are relative to CasperJs directory
*/
var start = new Start();
var run = new Run();
var screenshot = new Screenshot();
var ct = new CommonTests();
var phcss = new InitializePhantomCss();
var hp = new HomePage();
casper.test.begin('PhantomCSS Test', 13, function(test) {
casper.options.viewportSize = {width:1440, height:950};
var x = require('casper').selectXPath;
var fs = require( 'fs' );
var delay = 20;
var hide = '';
phcss.startPhantomCss();
start.start('http://staging.shopnational.com', 'nat', 'pass4nat');
ct.testHttpStatus();
casper.then(function() {
//take screenshots with phantomcss
phcss.takePhantomScreenshot(hp.getHeroImagePath(), delay, hide, '1heroImage');
phcss.takePhantomScreenshot(hp.getBlock1ImagePath(), delay, hide, '2block1');
phcss.takePhantomScreenshot(hp.getBlock1ButtonPath(), delay, hide, '2block1Button');
phcss.takePhantomScreenshot(hp.getBlock2ImagePath(), delay, hide, '3block2');
phcss.takePhantomScreenshot(hp.getBlock2ButtonPath(), delay, hide, '3block2Button');
phcss.takePhantomScreenshot(hp.getBlock3ImagePath(), delay, hide, '4block3');
phcss.takePhantomScreenshot(hp.getBlock3ButtonPath(), delay, hide, '4block3Button');
phcss.takePhantomScreenshot(hp.getBlock4ImagePath(), delay, hide, '5block4');
phcss.takePhantomScreenshot(hp.getBlock4ButtonPath(), delay, hide, '5block4Button');
phcss.takePhantomScreenshot(hp.getBlock5ImagePath(), delay, hide, '6block5');
phcss.takePhantomScreenshot(hp.getBlock5ButtonPath(), delay, hide, '6block5Button');
});
//test hover states of all buttons
casper.then(function() {
this.mouse.move(hp.getHeroImageButtonPath());
phcss.takePhantomScreenshot(hp.getHeroImageButtonPath(), delay, hide, '7heroImageButtonHover');
});
//for some reason, the hero image is the only button that I can actually see the hover state on
//the rest of the tests below do not provide accurate results
/*
casper.then(function() {
this.mouse.move(hp.getBlock1ButtonPath());
phcss.takePhantomScreenshot(hp.getBlock1ButtonPath(), delay, hide, '8Block1ButtonHover');
});
casper.then(function() {
this.mouse.move(hp.getBlock2ButtonPath());
phcss.takePhantomScreenshot(hp.getBlock2ButtonPath(), delay, hide, '9Block2ButtonHover');
});
casper.then(function() {
this.mouse.move(hp.getBlock3ButtonPath());
phcss.takePhantomScreenshot(hp.getBlock3ButtonPath(), delay, hide, '10Block3ButtonHover');
});
casper.then(function() {
this.mouse.move(hp.getBlock4ButtonPath());
phcss.takePhantomScreenshot(hp.getBlock4ButtonPath(), delay, hide, '11Block4ButtonHover');
});
casper.then(function() {
this.mouse.move(hp.getBlock5ButtonPath());
phcss.takePhantomScreenshot(hp.getBlock5ButtonPath(), delay, hide, '12Block5ButtonHover');
});
//tested out casper.on event to see if that would activate the hover state on buttons
casper.on('mouse.move', function() {
phcss.takePhantomScreenshot(hp.getBlock5ButtonPath(), delay, hide, '13Block1ButtonHover');
});
*/
casper.then(function() {
phcss.phantomCompareSession();
});
run.run();
});
|
import React from "react";
import {Link} from "react-router-dom";
import PropTypes from "prop-types";
import {offerTypes} from "../../mocks/offers.proptypes";
const PlaceCard = (props) => {
const {properties, images, price, ratingStars, features, isFavoritesList} = props.card;
const type = props.type;
const imageSize = (type === `favorites__card`)
? {width: 150, height: 110}
: {width: 260, height: 200};
return (
<article className={`${type} place-card`} onMouseEnter={()=>props.moveHandler(props.card)}>
{(properties.mark) ?
<div className="place-card__mark">
<span>{properties.mark}</span>
</div>
: null}
<div className={`${type.split(`__`)[0]}__image-wrapper place-card__image-wrapper`}>
<Link to="/offer/2">
<img className="place-card__image" src={images[0]}
width={imageSize.width}
height={imageSize.height}
alt="Place image"/>
</Link>
</div>
<div className={(isFavoritesList) ? `favorites__card-info place-card__info` : `place-card__info`}>
<div className="place-card__price-wrapper">
<div className="place-card__price">
<b className="place-card__price-value">{price.currency}{price.value} </b>
<span className="place-card__price-text">/ {price.period}</span>
</div>
<button className={`place-card__bookmark-button ` + ((properties.isBookmark) ? `place-card__bookmark-button--active ` : ``) + `button`} type="button">
<svg className="place-card__bookmark-icon" width="18" height="19">
<use xlinkHref="#icon-bookmark" />
</svg>
<span className="visually-hidden">{(properties.isBookmark) ? `In bookmarks` : `To bookmarks`}</span>
</button>
</div>
<div className="place-card__rating rating">
<div className="place-card__stars rating__stars">
<span style={{width: `${Math.round(ratingStars * 20)}%`}}/>
<span className="visually-hidden">Rating</span>
</div>
</div>
<h2 className="place-card__name">
<Link to="/offer/4">{properties.name}</Link>
</h2>
<p className="place-card__type">{features.entire}</p>
</div>
</article>
);
};
PlaceCard.propTypes = {
card: offerTypes,
moveHandler: PropTypes.func.isRequired,
type: PropTypes.string.isRequired
};
export default PlaceCard;
|
import styled from "styled-components";
export const Main = styled.main`
width: 100vw;
height: 80vh;
background-color: #000011;
`;
export const Container = styled.div`
width: 100vw;
height: 80vh;
display: flex;
flex-direction: column;
align-items: flex-end;
`;
export const Trip = styled.div`
width: 98vw;
height: 15vh;
padding-right: 2vw;
margin-top: 3vh;
background-color: #7f8c8dfb;
display: flex;
justify-content: flex-end;
`;
|
import { app, BrowserWindow } from 'electron';
import { autoUpdater } from 'electron-updater';
import logger from 'electron-log';
import { notify } from './notification.js';
logger.transports.file.level = 'warn';
autoUpdater.logger = logger;
let window;
const gotTheLock = app.requestSingleInstanceLock();
if (!gotTheLock)
app.quit()
app.on('second-instance', () => {
if (!window)
return;
if (window.isMinimized())
window.restore();
window.focus();
});
app.on('ready', async () => {
window = new BrowserWindow({ width: 800, height: 600 });
window.loadURL('https://github.com')
autoUpdater.checkForUpdatesAndNotify();
});
setTimeout(() => notify({ title: 'Test', body: 'this is a test!', icon: '../assets/logo.jpg' }), 2000); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.