text
stringlengths 7
3.69M
|
|---|
import React, { Component } from 'react';
import { View, Text, StyleSheet } from 'react-native';
import styles from './styles/allStyles';
import strings from '../res/strings';
import { SimpleCard } from './CommonComp';
/** Component to just show coming soon text for other new resume options */
export default class ComingSoonScene extends Component {
renderBody() {
return (
<Text>Stay tuned!!</Text>
);
}
render() {
return (
<View style={styles.sceneBase}>
<SimpleCard title={strings.comingSoon} cardBody={this.renderBody()}/>
</View>
);
}
}
|
import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Link } from 'react-router-dom';
// import '..src/App.css';
import Header from './components/Header';
import Home from './components/pages/Home';
import Registration from './components/pages/Registration';
import Login from './components/pages/Login';
import AddItem from './components/pages/AddItem';
import Cart from './components/pages/Cart';
function App() {
return (
<Router>
<div className="App">
<Header />
<Route exact path ='/' component = {Home} />
<Route exact path ='/login' component = {Login} />
<Route exact path ='/registration' component = {Registration} />
<Route exact path ='/AddItem' component = {AddItem} />
<Route exact path ='/Cart' component = {Cart} />
</div>
</Router>
);
}
export default App;
|
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import * as actions from '../actions';
import TodoList from '../components/TodoList';
import FetchError from '../components/FetchError';
import {getVisibleTodos, getIsFetching, getErrorMessage} from '../reducers';
class VisibleTodoList extends Component {
componentDidMount() {
this.fetchTodos();
}
componentDidUpdate(prevProps) {
const {filter} = this.props;
if (prevProps.filter !== filter) {
this.fetchTodos();
}
}
fetchTodos() {
const {fetchTodos, filter} = this.props;
fetchTodos(filter).then(() => console.log('done!'));
}
render() {
const {toggleTodo, isFetching, errorMessage, todos} = this.props;
if (isFetching && !todos.length) {
return <p>Loading...</p>
}
if (errorMessage && !todos.length) {
return (
<FetchError
message={errorMessage}
onRetry={() => this.fetchTodos()}
/>
);
}
return (
<TodoList
onTodoClick={toggleTodo}
todos={todos}
/>
);
}
}
const mapStateToProps = (state, {match}) => {
const filter = match.params.filter || 'all';
return {
isFetching: getIsFetching(state, filter),
todos: getVisibleTodos(state, filter),
errorMessage: getErrorMessage(state, filter),
filter,
};
};
VisibleTodoList = withRouter(connect(
mapStateToProps,
actions
)(VisibleTodoList));
export default VisibleTodoList;
|
import React, { Component } from 'react'
import { app as firebase } from '../config/firebase'
export default (WrappedComponent) => {
class RequireAuth extends Component {
state = {
isLogin : null
}
componentDidMount(){
firebase.auth().onAuthStateChanged((user)=>{
console.log(user);
if (user) {
// User is signed in.
this.setState({
isLogin : true
})
} else {
this.props.history.push({
pathname: '/login'
});
// No user is signed in.
}
});
}
render(){
const {isLogin} = this.state
if (isLogin) {
return <WrappedComponent {...this.props} />
}else{
return (
<div>Loading</div>
)
}
}
}
return RequireAuth
}
|
const AlfaToken = artifacts.require("./AlfaToken.sol");
const AlfaTokenOffering = artifacts.require("./AlfaTokenOffering.sol");
const AlfaPayments = artifacts.require("./AlfaPayments.sol");
module.exports = function (deployer, network, accounts) {
console.log(`Accounts: ${accounts}`);
let alfaToken = null;
let alfaOffering = null;
let alfaPayments = null;
const owner = accounts[0];
const admin = accounts[1];
return deployer.deploy(
AlfaToken, admin, { from: owner }
).then(() => {
return AlfaToken.deployed().then(instance => {
alfaToken = instance;
console.log(`AlfaToken deployed at \x1b[36m${instance.address}\x1b[0m`)
});
}).then(() => {
const rate = 5000;
const beneficiary = accounts[1];
const baseCap = 10**17;
return deployer.deploy(
AlfaTokenOffering, rate, beneficiary, baseCap, alfaToken.address, { from: owner }
).then(() => {
return AlfaTokenOffering.deployed().then(instance => {
alfaOffering = instance;
console.log(`AlfaTokenOffering deployed at \x1b[36m${instance.address}\x1b[0m`)
alfaToken.setTokenOffering(instance.address, 0);
});
})
}).then(() => {
const arbitrationAddress = accounts[1];
const arbitrationFee = 10;
return deployer.deploy(
AlfaPayments, arbitrationAddress, arbitrationFee, { from: owner }
).then(() => {
return AlfaPayments.deployed().then(instance => {
alfaPayments = instance;
console.log(`AlfaPayments deployed at \x1b[36m${instance.address}\x1b[0m`)
})
})
});
};
|
angular.module('gt-gamers-guild.auth-ctrl', [])
.controller('AuthCtrl', function($scope) {
$scope.hello = 'hello';
});
|
(function() {
'use strict';
angular
.module('app')
.controller('CustomerAdminController', CustomerAdminController);
CustomerAdminController.$inject = ['customerFactory', '$state', '$stateParams'];
/* @ngInject */
function CustomerAdminController(customerFactory, $state, $stateParams) {
var vm = this;
vm.title = 'CustomerAdminController';
//Properties
vm.customers = [];
vm.customerSelected = [];
vm.newCustomer = {
firstName: '',
lastName: '',
business: '',
phone: '',
email: '',
streetAddress: '',
city: '',
state: '',
zipCode: '',
note: ''
}
//Functions
vm.getCustomer = getCustomer;
vm.addCustomer = addCustomer;
vm.updateCustomer = updateCustomer;
vm.deleteCustomer = deleteCustomer;
//vm.populateCustomerData = populateCustomerData;
vm.getSelectedCustomer = getSelectedCustomer;
activate();
////////////////
function activate() {
getCustomer();
getSelectedCustomer()
}
function getCustomer() {
customerFactory
.getAll()
.then(function(response) {
vm.customers = response.data;
})
}
function getSelectedCustomer() {
customerFactory
.getById($stateParams.CustomerId)
.then(function(response) {
vm.customerSelected = response.data;
})
.catch(function(error) {
})
}
function addCustomer() {
customerFactory
.create(vm.newCustomer)
.then(function(response) {
vm.customers.push(response.data);
swal('Sucess!!', vm.newCustomer.firstName + ' ' + vm.newCustomer.lastName + ' has been saved', 'success');
//clears form so you can add another customer
vm.newCustomer = {
firstName: '',
lastName: '',
business: '',
phone: '',
email: '',
streetAddress: '',
city: '',
state: '',
zipCode: '',
note: ''
}
})
.catch(function(error) {
swal('Error!', 'Customer was not added, please try again.', 'error');
});
}
//this is an attempt to populate the customer form to be edited
// function populateCustomerData(customer) {
// vm.newCustomer.business = customer.business;
// vm.newCustomer.firstName = customer.firstName;
// vm.newCustomer.lastName = customer.lastName;
// vm.newCustomer.phone = customer.phone;
// vm.newCustomer.email = customer.email;
// vm.newCustomer.streetAddress = customer.streetAddress;
// vm.newCustomer.city = customer.city;
// vm.newCustomer.state = customer.state;
// vm.newCustomer.zipCode = customer.zipCode;
// vm.newCustomer.note = customer.note;
// }
//not sure if this update method is working properly at this time
function updateCustomer(customerId) {
customerFactory
.update(customerId)
.then(function(response) {
vm.customers.push(response.data);
swal('Sucess!!', vm.newCustomer.firstName + ' ' + vm.newCustomer.lastName + ' has been saved', 'success');
})
.catch(function(error) {
swal('Error!', 'Customer record was not updated, please try again.', 'error');
});
}
function deleteCustomer(customerID) {
swal({
title: "Are you sure?",
text: "Your will not be able to recover this customer's record!",
type: "warning",
showCancelButton: true,
confirmButtonColor: "#DD6B55",
confirmButtonText: "Yes, delete it!",
closeOnConfirm: false
},
function() {
customerFactory
.remove(customerID)
.then(function(response) {
swal('Sucess!!', 'The customer\'s record has been deleted', 'success');
//pushs the response to the page without refreshing
activate();
}).catch(function(error) {
swal('Error!', 'The customer\'s record was not deleted', 'error');
});
});
}
}
})();
|
function splitAndMerge(str, sp) {
return str.split(' ').map(function(word) {
return word.split('').join(sp);
}).join(' ');
};
function convert(object) {
return Object.keys(object).map(function(i) {
return [i, object[i]]
});
};
function toCamelCase(str) {
newString = str.replace(/(\_|\-)[A-z]/g, function(string) {
return string[1].toUpperCase();
});
return newString;
};
function reverseWords(str){
var splitArray = str.split(' ');
var newSring = splitArray[0].split('').reverse().join('')+ " ";
for(var item = 1 in splitArray){
newSring = newSring + splitArray[item].split('').reverse().join('')+ " ";
}
return newSring;
};
function stringExpansion(str){
return newSring = str.replace(/(\d)+[A-z]/g,function(word){
var num = parseInt(word[word.length-2]);
var character = word[word.length-1];
return new Array(num+1).join(character);
})
}
function largest(){
var largest = arguments[0];
for(var item =1 in arguments){
if (arguments[item]>largest)
largest = arguments[item];
}
return largest;
};
function smallest(){
var smallest = arguments[0];
for(var item =1 in arguments){
if (arguments[item]<smallest)
smallest = arguments[item];
}
return smallest;
};
function transform(arr) {
return arr.map(function(item) {
return function() {
return item;
};
});
};
function sum(){
var sum=0;
for(var i=0 in arguments){
sum =sum+ arguments[i];
}
return sum;
};
function countDown(num){
while(num>=0){
console.log(num);
num--;
}
};
Function.prototype.myBind = function(context) {
var f = this;
var prev = [].slice.call(arguments, 1);
return function() {
var cur = [].slice.call(arguments);
var all = [].concat(prev, cur);
return f.apply(context, all);
};
};
console.log("IN: "+ " toCamelCase('the-stealth-warrior') "+ "OUT: " + toCamelCase("the-stealth-warrior") );
console.log("IN: "+ " toCamelCase('The_Stealth_Warrior') "+ "OUT: " + toCamelCase("The_Stealth_Warrior") );
console.log("IN: "+ " reverseWords(' A fun little challenge! ')"+ "OUT: " + reverseWords(" A fun little challenge! ") );
console.log("IN: "+ " stringExpansion('3D2a5d2f')"+ "OUT: " + stringExpansion('3D2a5d2f') );
console.log("IN: "+ " stringExpansion('3d332f2a')"+ "OUT: " + stringExpansion('3d332f2a') );
console.log("IN: "+ " stringExpansion('abcde')"+ "OUT: " + stringExpansion('abcde') );
console.log("IN: "+ " largest(2, 0.1, -5, 100, 3) "+ "OUT: " + largest(2, 0.1, -5, 100, 3));
console.log("IN: "+ " smallest(2, 0.1, -5, 100, 3) "+ "OUT: " + smallest(2, 0.1, -5, 100, 3));
console.log("IN: "+ " transform([10, 20, 30, 40, 50])[3]() "+ "OUT: " + transform([10, 20, 30, 40, 50])[3]() );
console.log("IN: "+ " sum(1,3,5,7) "+ "OUT: " + sum(1,3,5,7) );
function addPropToNumber(number) {
return this.prop + number;
};
var bound = addPropToNumber.myBind({ prop: 9 });
console.log(bound(1));
|
import React from 'react'
import HomeOutlinedIcon from '@material-ui/icons/HomeOutlined';
import './styles.css'
export default class Navbar extends React.Component{
render(){
return(
<div className="homeIcon">
<a href="/#/home"><HomeOutlinedIcon/></a>
</div>
);
}
}
|
/**
* Test for debugger; keyword used in various contexts (in a function, in an
* dynamically evaluated functions, etc.)
*
* The test also verifies Issue 3082: Disable "debugger;" statements by converting
* them to conditional breakpoints.
*/
function runTest()
{
// Load test case page
FBTest.openNewTab(basePath + "script/debuggerKeyword/testPage.html", function(testWindow)
{
FBTest.clearCache();
FBTest.enablePanels(["script", "console"], function(win)
{
var doc = win.document;
// List of tasks for this test.
var taskList = new FBTest.TaskList();
taskList.push(executeTest, doc, "debuggerSimple", 33, true);
taskList.push(executeTest, doc, "debuggerShallow", 39, true);
taskList.push(executeTest, doc, "debuggerDeep", 65, true);
taskList.push(executeTest, doc, "debuggerInXHR", 14, false); // Disable is not supported for XHR.
taskList.push(executeTest, doc, "debuggerInScript", 16, true);
// Start all async tasks.
taskList.run(function() {
FBTest.testDone();
});
});
});
}
/**
* This function check behavior of a debugger keyword.
* The logic is as follows:
* 1) Verify that debugger is resumed.
* 2) Click specified test button (testId)
* 3) Verify that debugger halted at specified line (lineNo)
* 4) Press 'Disable' in the balloon dialog.
* 5) Click specified test button again.
* 6) Nothing should happen, the debugger must be resumed.
* 7) Remove a breakpoint that has been created in step #4.
*/
function executeTest(callback, doc, testId, lineNo, disable)
{
FBTest.progress("TEST: " + testId + " should stop on " + lineNo);
if (!testResumeState())
return;
var chrome = FW.Firebug.chrome;
FBTest.waitForBreakInDebugger(chrome, lineNo, false, function(row)
{
// Don't disable if the test says so.
if (!disable)
{
FBTest.clickContinueButton();
callback();
return;
}
// Clicking on the 'Disable' button resumes the debugger.
clickDisableButton(function()
{
if (testResumeState())
{
FW.Firebug.Debugger.clearAllBreakpoints(null);
callback();
}
})
});
// Execute a method with debuggger; keyword in it. This is done
// asynchronously since it stops the execution context.
FBTest.click(doc.getElementById(testId));
}
function testResumeState()
{
var chrome = FW.Firebug.chrome;
var stopped = chrome.getGlobalAttribute("fbDebuggerButtons", "stopped");
if (!FBTest.compare("false", stopped, "The debugger must be resumed by now"))
{
FBTest.testDone("debuggerKeyword.FAIL; stopped=" + stopped);
return false;
}
return true;
}
function clickDisableButton(callback)
{
var panel = FBTest.getPanel("script");
var button = panel.panelNode.querySelector(".notificationButton.skipButton");
if (!FBTest.ok(button, "There must be a balloon with 'Disable' button."))
{
FBTest.testDone();
// Will fail on timeout since the callback will never be executed.
return;
}
FBTest.waitForDebuggerResume(function()
{
callback();
});
FBTest.click(button);
}
|
/*
* C.Layer.Tile.TileSchema //TODO description
*/
'use strict';
C.Layer.Tile.yAxis = {
NORMAL: 0,
INVERTED: 1
};
C.Layer.Tile.TileSchema = C.Utils.Inherit(function (base, option) {
this._extent = option.extent;
this._tileWidth = option.tileWidth;
this._tileHeight = option.tileHeight;
this._resolutions = option.resolutions;
this._yAxis = option.yAxis;
this._originX = option.originX;
this._originY = option.originY;
this._bounds = [];
this._resolution = 0;
this.calculateBounds();
/*
** Tile hashmap
*/
this._unchangedTiles = {};
this._removedTiles = {};
this._addedTiles = {};
}, EventEmitter, 'C.Layer.Tile.TileSchema');
C.Layer.Tile.TileSchema.prototype.register = function () {
this.emit('register');
};
C.Layer.Tile.TileSchema.prototype.unregister = function () {
this.emit('unregister');
};
C.Layer.Tile.TileSchema.prototype.tileToWorld = function (tileIndex, resolutionId) {
throw 'Not implemented';
};
C.Layer.Tile.TileSchema.prototype.worldToTile = function (world, resolutionId) {
throw 'Not implemented';
};
C.Layer.Tile.TileSchema.prototype.calculateBounds = function () {
for (var i = 0; i < this._resolutions.length; ++i) {
this._bounds[i] = 1 << i;
}
};
C.Layer.Tile.TileSchema.prototype.getZoomLevel = function (resolution) {
for (var i = 0; i < this._resolutions.length; ++i) {
var res = this._resolutions[i];
if (resolution > res && !C.Utils.Comparison.Equals(resolution, res)) {
i = (i > 0) ? (i - 1) : (0);
return (i);
}
}
return (this._resolutions.length - 1);
};
C.Layer.Tile.TileSchema.prototype.fitToBounds = function (point, bound, floor) {
if (floor) {
point._x = Math.floor(point._x);
point._y = Math.floor(point._y);
}
if (point._x < 0) { point._x = 0; }
if (point._y < 0) { point._y = 0; }
if (point._x > bound) { point._x = bound; }
if (point._y > bound) { point._y = bound; }
};
C.Layer.Tile.TileSchema.prototype._mergeTiles = function () {
for (var key in this._addedTiles) {
this._unchangedTiles[key] = this._addedTiles[key];
}
};
C.Layer.Tile.TileSchema.prototype.getCurrentTiles = function () {
var result = {};
for (var key in this._unchangedTiles) {
result[key] = this._unchangedTiles[key];
}
for (var key in this._addedTiles) {
result[key] = this._addedTiles[key];
}
return (result);
};
C.Layer.Tile.TileSchema.prototype.isTileInView = function (tileIndex) {
if (tileIndex._BId in this._unchangedTiles ||
tileIndex._BId in this._addedTiles)
{
return (true);
}
return (false);
};
C.Layer.Tile.TileSchema.prototype.tileToPoly = function (tile, resolution, size, rotation) {
//TODO: use yAxis
var x = Math.floor(tile._x);
var y = Math.floor(tile._y);
var tcenter = this.tileToWorld(new C.Layer.Tile.TileIndex(x + 0.5,
y + 0.5,
tile._z,
tile._BId),
resolution,
size);
var half = (size / 2) * resolution;
return ([
[tcenter.X - half, tcenter.Y + half],
[tcenter.X + half, tcenter.Y + half],
[tcenter.X - half, tcenter.Y - half],
[tcenter.X + half, tcenter.Y - half]
]);
};
C.Layer.Tile.TileSchema.prototype.computeTiles = function (viewport) {
if (!C.Utils.Comparison.Equals(viewport._rotation, 0)) { // Compute tile with rotation
var resolution = viewport._resolution;
var rotation = viewport._rotation;
var zoom = this.getZoomLevel(resolution);
this._resolution = this._resolutions[zoom];
var size = this._resolution / resolution * this._tileWidth;
var bound = this._bounds[zoom];
var center = this.worldToTile(viewport._origin, resolution, size);
center._x = Math.floor(center._x);
center._y = Math.floor(center._y);
var polyBox = [
[ viewport._bbox._topLeft.X, viewport._bbox._topLeft.Y ],
[ viewport._bbox._topRight.X, viewport._bbox._topRight.Y ],
[ viewport._bbox._bottomRight.X, viewport._bbox._bottomRight.Y ],
[ viewport._bbox._bottomLeft.X, viewport._bbox._bottomLeft.Y ]
];
var self = this;
var explored = {};
var cost = 0;
var tiles = {};
this._mergeTiles();
var addedTilesCount = 0;
this._addedTiles = {}; // reset added tiles
var removedTilesCount = 0;
this._removedTiles = {}; // reset removed tiles
(function rSearch(tile) {
explored[tile._BId] = 1;
var tilePoly = self.tileToPoly(tile, resolution, size, rotation);
if (C.Helpers.IntersectionHelper.polygonContainsPolygon(polyBox, tilePoly)) {
// tile is in bbox
if (tile._x >= 0 && tile._x < bound && tile._y >= 0 && tile._y < bound) {
// this is a valid tile in view
tiles[tile._BId] = tile;
if (!(tile._BId in self._unchangedTiles)) { // this is a new tile
self._addedTiles[tile._BId] = tile;
++addedTilesCount;
}
}
var x = Math.floor(tile._x);
var y = Math.floor(tile._y);
var neighbours = [
C.Layer.Tile.TileIndex.fromXYZ(x - 1, y , tile._z),
C.Layer.Tile.TileIndex.fromXYZ(x + 1, y , tile._z),
C.Layer.Tile.TileIndex.fromXYZ(x , y - 1 , tile._z),
C.Layer.Tile.TileIndex.fromXYZ(x , y + 1 , tile._z)
];
for (var i = 0; i < 4; ++i) {
if (!(neighbours[i]._BId in explored))
rSearch(neighbours[i]);
}
}
})(center);
/** Compute removed tiles **/
for (var key in this._unchangedTiles) {
if (!(key in tiles)) { // this is a removed tile
this._removedTiles[key] = this._unchangedTiles[key];
delete this._unchangedTiles[key];
++removedTilesCount;
}
}
if (removedTilesCount > 0) {
this.emit('removedTiles', this._removedTiles, viewport);
}
if (addedTilesCount > 0) {
this.emit('addedTiles', this._addedTiles, viewport);
}
} else {
var zoom = this.getZoomLevel(viewport._resolution);
this._resolution = this._resolutions[zoom];
var size = this._resolution / viewport._resolution * this._tileWidth;
var topLeft = this.worldToTile(viewport._bbox._topLeft, viewport._resolution, size);
var topRight = this.worldToTile(viewport._bbox._topRight, viewport._resolution, size);
var bottomLeft = this.worldToTile(viewport._bbox._bottomLeft, viewport._resolution, size);
var bound = this._bounds[zoom];
this.fitToBounds(topLeft, bound, true);
this.fitToBounds(topRight, bound);
this.fitToBounds(bottomLeft, bound);
var tiles = {};
this._mergeTiles();
var addedTilesCount = 0;
var removedTilesCount = 0;
this._addedTiles = {}; // reset added tiles
this._removedTiles = {}; // reset removed tiles
for (var y = topLeft._y; y < bottomLeft._y; ++y) {
for (var x = topLeft._x; x < topRight._x; ++x) {
var tile = C.Layer.Tile.TileIndex.fromXYZ(x, y, zoom);
tiles[tile._BId] = tile;
if (!(tile._BId in this._unchangedTiles)) { // this is a new tile
this._addedTiles[tile._BId] = tile;
++addedTilesCount;
}
}
}
/** Compute removed tiles **/
for (var key in this._unchangedTiles) {
if (!(key in tiles)) { // this is a removed tile
this._removedTiles[key] = this._unchangedTiles[key];
delete this._unchangedTiles[key];
++removedTilesCount;
}
}
if (removedTilesCount > 0) {
this.emit('removedTiles', this._removedTiles, viewport);
}
if (addedTilesCount > 0) {
this.emit('addedTiles', this._addedTiles, viewport);
}
}
};
|
var express = require('express');
var app = express();
var bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// parse application/json
app.use(bodyParser.json())
app.use(express.static(__dirname + '../../app'));
app.get('/', function(req, res){
res.redirect('index.html');
});
// app.post('/api/search', function(res, req){
// // console.log(req.body);
// res.redirect('index.html');
// });
module.exports = app;
|
import { configure } from '@storybook/react';
function loadStories() {
require('../src/common/dropdown-toggle-select/index.story.js');
require('../src/navbar/index.story.js');
require('../src/editor/index.story.js');
require('../src/editor/toolbar/index.story.js');
require('../src/editor/toolbar/font-dropdown/index.story.js');
require('../src/editor/toolbar/size-dropdown/index.story.js');
require('../src/editor/toolbar/theme-dropdown/index.story.js');
require('../src/editor/document/index.story.js');
require('../src/heart/index.story.js');
require('../src/not-found/index.story.js');
}
configure(loadStories, module);
|
import React, { Component } from 'react';
import Card from './Card';
import Info from './Info';
import WinningScreen from './WinningScreen';
class Board extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
cardData: [],
gameStatus: "stopped"
};
this.flippedCards = [];
this.count = 0;
this.moves = 0;
this.cards = 36;
this.solvedCards = 0;
this.incrementer = 0;
this.createCard = this.createCard.bind(this);
this.flipCard = this.flipCard.bind(this);
this.resetCards = this.resetCards.bind(this);
this.shuffle = this.shuffle.bind(this);
this.checkMatch = this.checkMatch.bind(this);
this.setupGame = this.setupGame.bind(this);
}
componentDidMount() {
this.setupGame();
}
setupGame() {
var cardArray = [];
var itemCount = 0;
var emojis = [0x1F600, 0x1F604, 0x1F34A, 0x1F344, 0x1F37F, 0x1F363, 0x1F370, 0x1F355,
0x1F354, 0x1F35F, 0x1F6C0, 0x1F48E, 0x1F5FA, 0x23F0, 0x1F579, 0x1F4DA,
0x1F431, 0x1F42A, 0x1F439, 0x1F424];
for (var i = 0; i < this.cards; i++) {
//
// This is done to give two array items the same value
//
if (i % 2 === 0) {
itemCount++;
}
cardArray.push({
flipped: false,
content: String.fromCodePoint(emojis[itemCount]),
id: i,
solved: false,
key: "card" + i
});
}
//
// Shuffles the contents of our array that maps to a
// shuffled collection of cards
//
cardArray = this.shuffle(cardArray);
// reset the state to a good starting value
this.setState({
cardData: cardArray,
showWinningScreen: false,
gameStatus: "stopped"
});
this.moves = 0;
this.count = 0;
this.solvedCards = 0;
}
flipCard(id) {
// ensure game is running to start the timer
this.setState({
gameStatus: "running"
})
// open cards and check if they match or not!
var cardArray = this.state.cardData;
for (var i = 0; i < cardArray.length; i++) {
var tempCard = cardArray[i];
// identify the card we clicked on
if (tempCard.id === id) {
// have opened two cards yet?
if (this.count < 2) {
this.count++;
tempCard.flipped = true;
this.flippedCards.push(tempCard);
this.checkMatch();
} else {
// if two cards are already open, close them and
// start over with this card
this.resetCards();
tempCard.flipped = true;
this.flippedCards.push(tempCard);
this.checkMatch();
this.count++;
}
}
}
// which cards are open and which aren't are all
// stored in cardData
this.setState({
cardData: cardArray
});
}
checkMatch() {
// Check if the two opened cards match!
if (this.flippedCards.length === 2) {
var cardA = this.flippedCards[0];
var cardB = this.flippedCards[1];
if (cardA.content === cardB.content) {
cardA.solved = true;
cardB.solved = true;
// update our internal representation
// of the cards in play and so on
this.flippedCards = [];
this.count = 0;
this.solvedCards++;
this.moves++;
// check if the game has ended
if (this.solvedCards === this.cards / 2) {
this.setState({
gameStatus: "victory"
});
}
}
}
}
//
// Shuffle an array using the Fisher-Yates method:
// https://www.kirupa.com/html5/shuffling_array_js.htm
//
shuffle(cards) {
var input = cards;
for (var i = input.length - 1; i >= 0; i--) {
var randomIndex = Math.floor(Math.random() * (i + 1));
var itemAtIndex = input[randomIndex];
input[randomIndex] = input[i];
input[i] = itemAtIndex;
}
return input;
}
//
// Flip back all unsolved cards
//
resetCards() {
var cardArray = this.state.cardData;
cardArray.map((item) => {
if (item.solved === false) {
item.flipped = false;
} else {
item.flipped = true;
}
return true;
});
this.count = 0;
this.flippedCards = [];
this.moves++;
}
//
// Helper function to create the JSX for each card
//
createCard(item) {
return <Card flipHelper={this.flipCard}
flipped={item.flipped}
content={item.content}
id={item.id}
solved={item.solved}
key={item.key}/>;
}
render() {
var cardItems = this.state.cardData;
var cards = cardItems.map(this.createCard);
// Display the winning screen only when the game has ended
var winningScreen;
if (this.state.gameStatus === "victory") {
winningScreen = <WinningScreen resetGame={this.setupGame}/>;
}
return (
<div>
{winningScreen}
{cards}
<Info moves={this.moves} gameState={this.state.gameStatus}/>
</div>
);
}
};
export default Board;
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
View,
StyleSheet,
} from 'react-native';
import {
Text,
Card,
} from 'react-native-elements';
import propTypes from 'prop-types';
import BoardStatus from './board-status';
import Planning from './planning';
import Jour from './jour';
import Mois from './mois';
import Semaine from './semaine';
class BoardContent extends Component {
constructor() {
super();
this.state = {
status: "planning",
};
}
static getDerivedStateFromProps(nextProps, prevState) {
return {
status: nextProps.status,
};
}
renderContent() {
const { vw, vh, isLandScape, isTablet, openPlaning } = this.props;
const { status } = this.state;
switch(status) {
case 'jour':
return (
<Jour vw={vw} vh={vh}
isTablet={isTablet}
isLandScape={isLandScape}
openPlaning={openPlaning} />
)
case 'planning':
return (
<Planning vw={vw} vh={vh}
isTablet={isTablet}
isLandScape={isLandScape}
openPlaning={openPlaning} />
)
case 'semaine':
return (
<Semaine vw={vw} vh={vh}
isTablet={isTablet}
isLandScape={isLandScape}
openPlaning={openPlaning} />
)
case 'mois':
return (
<Mois vw={vw} vh={vh}
isTablet={isTablet}
isLandScape={isLandScape}
openPlaning={openPlaning} />
)
default:
return (
<Text>In Progress</Text>
)
}
}
render() {
const { vw, vh, isLandScape, isTablet } = this.props;
const fv = isLandScape ? vh : vw;
return (
<View style={[
styles.container,
{
marginTop: 1*vh,
paddingHorizontal: isLandScape ? 0 : 2 * fv,
}
]}>
<Card containerStyle={{
marginTop: 0,
marginHorizontal: 0,
borderRadius: 10,
padding: 0,
height: '100%',
}} >
{!isLandScape && <BoardStatus vw={vw} vh={vh} isTablet={isTablet} isLandScape={isLandScape} />}
{this.renderContent()}
</Card>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: '100%',
justifyContent: 'flex-start',
alignItems: 'center',
},
});
BoardContent.propTypes = {
vw: propTypes.number,
vh: propTypes.number,
isLandScape: propTypes.bool,
isTablet: propTypes.bool,
openPlaning: propTypes.func,
};
const mapStateToProps = (state, ownProps) => {
return {
...state.uiCalendar.toJS(),
};
};
export default connect(mapStateToProps)(BoardContent);
|
import styled from 'styled-components'
const Wrapper = styled.div`
width: 25%;
height: 300px;
float: left;
border: none;
`;
export default Wrapper;
|
module.exports = () => {
const jwt = require('jsonwebtoken');
const { appConfig } = require('../src/setup')();
async function generateAuthToken(user) {
const payload = {
exp: Math.floor(Date.now() / 1000) + 24 * 60 * 60, //24hour
_id: user._id,
email: user.email,
};
const token = jwt.sign(payload, appConfig.session.secret);
return token;
}
return {
generateAuthToken,
};
};
|
String.prototype.camelCase = function() {
// @todo - Tokenise with delim ' ' - Start every word with lower case and then remove white spaces
// concat all words to one string.
return this.charAt(0).toUpperCase() + this.toLowerCase().slice(1);
}
String.prototype.removeWhiteSpace = function() {
return this.replace(/\s/g, "");
}
String.prototype.removeTags = function() {
return this.replace(/(<([^>]+)>)/ig, "");
}
function validateInput(input, fname = 'fieldname', limit = 32) {
if (input.length <= 0 || input.length > limit) {
throw Error("Size of field '" + fname + "' not within limits - 1 to " + limit + ' chars');
}
return input;
}
function validateFormText(inputTag) {
return validateInput(inputTag.value, inputTag.name, inputTag.size);
}
function validateToDoForm(formValidate) {
formValidate.todo.value = formValidate.todo.value.trim().removeTags();
try {
if (formValidate.todo.value.length == 0) {
return false;
} else {
formValidate.todo.value = validateFormText(formValidate.todo);
return true;
}
} catch (e) {
alert(e);
return false;
}
}
|
import React, { Component } from 'react';
import { Spin, Modal, Radio, Table, Input, Icon, Button, Popconfirm, Form, Checkbox, message, Row, Col, DatePicker, TimePicker, Select } from 'antd';
import {Link} from 'react-router';
import moment from 'moment';
const RadioGroup = Radio.Group;
const { TextArea } = Input;
const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;
const Option = Select.Option;
import './css/supervision.css';
import AddgysName from './AddgysName';
import { ECHILD } from 'constants';
// import { on } from 'cluster';
function handleChange(value) {
console.log(`selected ${value}`);
}
//form表单初始布局
const formItemLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 16 },
};
const formTailLayout = {
labelCol: { span: 4 },
wrapperCol: { span: 8, offset: 4 },
};
const rangeConfig = {
rules: [{ type: 'array', required: true, message: '请选择时间' }],
};
class AddSupervisionPlanNew extends Component {
constructor(props) {
super(props);
this.state = {
ModalText: 'Content of the modal',
confirmLoading: false, //加载状态
value: 1,
checkNick: false,
names: '',
stateFunEdit: null,
modalKey: 0,
datas: [],
datasGYS:null,
gysFlag:false,//供应商名称列表显示隐藏标识
spinFlag:false,//加载中图案显示隐藏标识
loading:false,
columns:null,
dataSource:null,
datass:null,
cities: {},
secondCity: [],
cascadeLeft:[],
initDept:'tom',
}
this.tableData = null;
this.cascadeLeft=[];
this.auditGroup={};
this.datas=[{
key: 1,
dept:'',
NAME:'',
labor:'',
remark:'',
}];
this.columns = [{
title: '部门',
dataIndex: 'dept',
key: 'dept',
render: (text, record) => {
// console.log(record)
const provinceOptions = this.state.cascadeLeft.map(province => <Option key={province.EAF_ID1} value={JSON.stringify(province)}>{province.EAF_NAME}</Option>);
return (
<div style={{float:'left'}}>
<Select style={{ width: 190 }} onChange={(e)=>this.handleProvinceChange(e,record.key)}>
{provinceOptions}
</Select>
</div>
)
}
}, {
title: '姓名',
dataIndex:'NAME',
key: 'NAME',
width:'110px',
render: (text, record) => {
// console.log(record)
// console.log(text)
const { getFieldDecorator } = this.props.form;
console.log(this.state.cities);
const cityOptions = this.state.cities[record.key]&&this.state.cities[record.key].map(city => <Option key={city.EAF_ID} value={JSON.stringify(city)}>{city.EAF_NAME}</Option>);
return (
<div id="nameItem">
<FormItem label="">
{getFieldDecorator('peoples'+[record.key], {
rules: [{
required: false,
message: '',
}],
})(
<Select style={{ width: 110 }} onChange={(e)=>this.onSecondCityChange(e,record.key)}>
{cityOptions}
</Select>
)}
</FormItem>
</div>
)
}
}, {
title: '分工',
dataIndex: 'labor',
key: 'labor',
width:'35%',
render: (text, record) => {
return(
//<Input defaultValue={text} onBlur={(e)=>this.handleEdit(e,record,'labor')}/>
<TextArea autosize autosize={{ maxRows: 6 }} style={{minHeight:32}} defaultValue={text} onBlur={(e)=>this.handleEdit(e,record,'labor')}/>
)
},
}, {
title: '备注',
dataIndex: 'remark',
key: 'remark',
width:'25%',
render: (text, record) => {
return(
// <Input defaultValue={text} onBlur={(e)=>this.handleEdit(e,record,'remark')}/>
<TextArea autosize autosize={{ maxRows: 6 }} style={{minHeight:32}} defaultValue={text} onBlur={(e)=>this.handleEdit(e,record,'remark')}/>
)
},
}, {
title: '操作',
dataIndex: 'action',
width:'10%',
render: (text, record) => (
<a href="javascript:;" onClick={() => this.deleteData(record)}>删除</a>
),
}
];
}
componentDidMount = () => {
const _this = this;
ajax({
url:"/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.selectAuditGroupAndMember&colname=json_ajax&colname1={%27dataform%27:%27eui_datagrid_data%27,%27tablename%27:%27detail0%27}",
dataType:"json",
success:function(res){
console.log(res);
_this.setState({cascadeLeft:res.rows});
_this.cascadeLeft=res.rows;
// res&&res.rows.length>0&&res.rows.map((item,index)=>{
// _this.cascadeLeft.push(item.EAF_NAME)
// })
},
error: function (res) {
message.error(res.EAF_ERROR);
}
})
// 初始化经办和编制部门
ajax({
url: "/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.initLoginInspaction&colname=json&colname1={'dataform':'eui_form_data'}",
dataType: "json",
type: "GET",
success: function (result) {
if(result.EAF_ERROR) {
message.error(result.EAF_ERROR);
return;
}
_this.props.form.setFieldsValue({
agent:result.login_User.loginUserName,
bzbm: result.login_User.deptName,
});
},
error: function (res) {
message.error(res.EAF_ERROR);
}
});
ajax({
url:"/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.initAuditGroupAndMember&colname=json&refresh=eval(Math.random())&colname1={'dataform':'eui_form_data'}",
type:'get',
success:function(res){
// console.log(111);
// console.log(res);
if(res){
const columns = [{
title: '部门',
dataIndex: 'dept',
key: 'dept',
}, {
title: '姓名',
dataIndex:'NAME',
key: 'NAME',
width:'20%'
}, {
title: '分工',
dataIndex: 'labor',
key: 'labor',
render: (text, record) => {
return(
<Input defaultValue={text} onBlur={(e)=>_this.handleEdit(e,record,'labor')}/>
)
},
}, {
title: '备注',
dataIndex: 'remark',
key: 'remark',
render: (text, record) => {
return(
<Input defaultValue={text} onBlur={(e)=>_this.handleEdit(e,record,'remark')}/>
)
},
}
];
const dataSource = res.auditAndMemberList?res.auditAndMemberList:'';
_this.setState({dataSource:dataSource,columns:columns});
}
},
error:function(res){
message.error(res.EAF_ERROR)
}
})
}
addData = () =>{
let datas = JSON.parse(JSON.stringify(this.datas));
let length = 0;
if(this.datas.length>0){
length = this.datas?this.datas[this.datas.length-1].key+1:0;
}else{
length = 0;
}
this.datas.push({
key: length + 1,
dept:'',
NAME:'',
labor:'',
remark:'',
})
this.setState({datas:this.datas})
}
handleEdit = (e,record,key)=>{
let datas = JSON.parse(JSON.stringify(this.datas));
datas.map((item,index)=>{
if(item.key == record.key){
datas[index][key]=e.target.value;
this.setState({datas:datas})
this.datas=datas
}
})
console.log(datas)
}
deleteData = (record) =>{
const datas = JSON.parse(JSON.stringify(this.datas));
const datass = datas.filter((item, index) => item.key != record.key)
this.setState({datas:datass})
this.datas=datass
console.log(datas)
console.log(datass)
}
//新增分类
showModal = () => {
this.props.showModal();
this.props.clearData();
}
//新增/编辑 保存modal内容请求
handleOk = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
console.log("submit's value is :", values);
if (!err) {
console.log(this.datas);
let obj = {};
this.setState({loading:true});
const _this = this;
obj.sup_id = this.state.datasGYS.EAF_ID?this.state.datasGYS.EAF_ID:'';
obj.supplier_code = this.state.datasGYS.MDM_CODE?this.state.datasGYS.MDM_CODE:'';
obj.sup_name = values.first;//供应商名称
obj.address = values.second;//供应商地址
obj.inspection_scope = values.third;//督查范围
obj.inspection_start_time = values.rangePicker[0].format("YYYY-MM-DD");//开始时间
obj.inspection_end_time = values.rangePicker[1].format("YYYY-MM-DD");//结束时间
obj.supervision_purpose = values.note;//督查目的
// obj.auditGroup = this.state.dataSource;
console.log(_this.datas)
obj.auditGroup = _this.datas;
let flagDept = true;
if(_this.datas&&_this.datas.length==0){
message.error('部门不能为空')
return
}
_this.datas.map((item,index)=>{
if(flagDept&&!item.dept){
flagDept = false;
message.error('部门不能为空');
return;
}
flagDept&&_this.datas.map((items,indexs)=>{
if(index!==indexs&&flagDept&&item.dept_id==items.dept_id){
flagDept = false;
message.error('同一个部门不能重复添加');
return;
}
})
})
flagDept&&ajax({
url: "/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.addInspaction&colname=json&colname1={'dataform':'eui_form_data'}",
dataType: "json",
data: { "insertObject": JSON.stringify(obj) },
success: function (result) {
if(result.EAF_ERROR) {
message.error(result.EAF_ERROR);
return;
}
_this.setState({loading:false});
if(result.SUCCESS=="true"){
message.success("提交成功");
window.location.href = "#Supervision";
}
},
error: function (res) {
message.error(res.EAF_ERROR)
}
})
}
});
}
onChange = (e) => {
this.setState({
value: e.target.value,
});
}
handleTableData = (data) => {
this.tableData = check(JSON.stringify(data));
}
// 点击时供应商名称表格的显示隐藏
listToggle = () => {
this.setState({
gysFlag:!this.state.gysFlag
});
}
// 失焦时供应商名称表格隐藏
listHide = () => {
this.setState({
gysFlag:false
});
}
//新增监督计划 - 物料供应商名称
addmCont = (data) => {
// date:点击行的数据
this.setState({ datasGYS: data,gysFlag:false});
this.props.form.setFieldsValue({
first:data.COMPANY_NAME,//供应商名称
// second: data.ALL_MAT_NAME,//拟供物料名称
second: data.REGISTERD_ADDRESS,
});
}
saveTabelData = (data,hang,lie)=>{
console.log('00')
console.log(data)
console.log(this.datas)
this.datas.map((item,index)=>{
if(item.key==hang){
if(lie=='dept'){
this.datas[index][lie]=data.EAF_NAME;
this.datas[index].dept_id=data.EAF_ID1;
this.datas[index].labor=data.labor?data.labor:"";
this.datas[index].remark=data.remark?data.remark:"";
}else if(lie=='NAME'){
this.datas[index][lie]=data.EAF_NAME;
this.datas[index].user_id=data.EAF_ID;
}else{
this.datas[index][lie]=data;
}
}
})
console.log(this.datas)
}
handleProvinceChange = (value,key) => {
console.log(value);
let id = JSON.parse(value).EAF_ID1;
// let name = JSON.parse(value).EAF_NAME;
this.saveTabelData(JSON.parse(value),key,'dept');
const _this = this;
ajax({
url:"/txieasyui?taskFramePN=supplierInspactionDao&command=supplierInspactionDao.selectUserByDeptId&colname=json_ajax&colname1={%27dataform%27:%27eui_datagrid_data%27,%27tablename%27:%27detail0%27}",
dataType:"json",
data:{"deptId":id},
success:function(res){
if(res.EAF_ERROR){
message.error(res.EAF_ERROR);
return;
}
console.log(res)
let obj = _this.state.cities;
obj[key] = res.rows;
_this.setState({cities:obj})
_this.props.form.setFieldsValue({
['peoples'+key]: res.rows[0].EAF_NAME,
});
_this.saveTabelData(res.rows[0],key,'NAME');
console.log(res.rows[0])
console.log(_this.state.cities)
},
error: function (res) {
message.error(res.EAF_ERROR);
}
})
// this.setState({
// cities: cityData[value],
// secondCity: cityData[value][0],
// });
}
onSecondCityChange = (value,key) => {
console.log(value);
this.saveTabelData(JSON.parse(value),key,'NAME');
// console.log(value)
// this.setState({
// secondCity: value,
// });
}
render() {
const funEdit = this.props.funEdit;
const { getFieldDecorator } = this.props.form;
return (
<div className="new">
{/* <Spin size="large" style={{display:this.state.spinFlag?"block":"none",position: "absolute",left: "50%",top: "40%",zIndex: 999}}/> */}
<h2 style={{textAlign:"center",fontWeight:"bolder"}}>中车株洲电机有限公司<br/>供应商监督审核计划</h2>
<div id="gysName">
<FormItem {...formItemLayout} label="供应商名称">
{getFieldDecorator('first', {
// initialValue:this.state.datas?this.state.datas.rowName:null,
rules: [{
required: true,
message: '请选择供应商名称',
}],
})(
<Input onClick={this.listToggle} placeholder="" maxLength={0} />
)}
</FormItem>
<FormItem {...formItemLayout} label="" style={{position:'absolute',width:"100%",display:this.state.gysFlag ? "block":"none"}}>
{getFieldDecorator('gysTableData', {
//initialValue: this.state.datas ? this.state.datas.rownName : null,
rules: [],
})(
<div className="gysList" style={{width:"100%"}}>
<AddgysName addmCont={this.addmCont} data={this.state.gysTableData}/>
</div>
)}
</FormItem>
</div>
<FormItem {...formItemLayout} label="供应商地址">
{getFieldDecorator('second', {
//initialValue: this.state.datas ? this.state.datas.rownName : null,
rules: [{
required: true,
message: '请选择供应商地址',
}],
})(
<TextArea maxLength={200} placeholder=""/>
)}
</FormItem>
<FormItem {...formItemLayout} label="督察范围">
{getFieldDecorator('third', {
initialValue: funEdit ? funEdit.ORDER_NO : '',
rules: [{
required: true,
message: '请输入督察范围',
}],
})(
<TextArea maxLength={500} autosize={{ minRows: 2, maxRows: 6 }} />
)}
</FormItem>
<FormItem {...formItemLayout} label="督察时间">
{getFieldDecorator('rangePicker', rangeConfig)(
<RangePicker />
)}
</FormItem>
<FormItem {...formItemLayout} label="督察目的">
{getFieldDecorator('note', {
initialValue: funEdit ? funEdit.REMARK : '',
rules: [{
required: true,
message: '请输入督察目的 ',
}],
})(
<TextArea maxLength={200} autosize={{ minRows: 2, maxRows: 6 }} />
)}
</FormItem>
<FormItem {...formItemLayout} label="经办">
{getFieldDecorator('agent', {
initialValue: this.props.users ? this.props.users : '',
rules: [{
required: true,
message: '请输入经办人',
}],
})(
<Input placeholder="" disabled={true}/>
)}
</FormItem>
<FormItem {...formItemLayout} label="编制部门">
{getFieldDecorator('bzbm', {
initialValue: this.props.department ? this.props.department : '',
rules: [{
required: true,
message: '请输入编制部门',
}],
})(
<Input placeholder="" disabled={true}/>
)}
</FormItem>
{/*
<p className="p-box" style={{ textAlign: 'center' }}>
<lable className="lab" style={{ float: 'none',fontSize: '18px', }}>审核组成员及分工</lable>
</p>
<p className="p-box">
<div style={{width:"75%",marginLeft:"10%"}}>
<Table loading={!this.state.dataSource} pagination={false} bordered={true} columns={this.state.columns} dataSource={this.state.dataSource} />
</div>
</p>
*/}
<p className="p-box" style={{ textAlign: 'center',marginBottom:'20' }}>
<lable className="lab" style={{ float: 'none',fontSize: '17px' }}>审核组成员及分工</lable>
</p>
<div id="teams">
<FormItem label="">
{getFieldDecorator('teams', {
initialValue: this.props.department ? this.props.department : '',
rules: [{
required: false,
message: '审核组成员及分工不能为空',
}],
})(
<div style={{width:"75%",marginLeft:"10%"}}>
<Table style={{ position: 'relative', zIndex: 2 }} columns={this.columns} pagination={false} dataSource={this.datas} />
<div className='addLine' style={{marginLeft:'40%',width:'120px'}}><span className='topEmpty' onClick={this.addData}>增加一行</span></div>
</div>
)}
</FormItem>
</div>
{/*
<p className="p-box" style={{ textAlign: 'center',marginBottom:'20' }}>
<lable className="lab" style={{ float: 'none',fontSize: '17px' }}>审核组成员及分工</lable>
</p>
<p className="p-box">
<div style={{width:"75%",marginLeft:"10%"}}>
<Table style={{ position: 'relative', zIndex: 2 }} columns={this.columns} pagination={false} dataSource={this.datas} />
<div className='addLine' style={{marginLeft:'40%',width:'120px'}}><span className='topEmpty' onClick={this.addData}>增加一行</span></div>
</div>
</p>
*/}
{/*
<p className="p-box">
<div style={{width:"75%",marginLeft:"10%",position:"relative",overflow:"hidden"}}>
<div style={{float:'left'}}>
<Select defaultValue={this.cascadeLeft.length>0&&this.cascadeLeft[0].EAF_NAME} style={{ width: 190 }} onChange={this.handleProvinceChange}>
{provinceOptions}
</Select>
</div>
<div style={{float:'left'}}>
<FormItem label="">
{getFieldDecorator('peoples', {
// initialValue: this.props.department ? this.props.department : '',
rules: [{
required: false,
message: '请输入编制部门',
}],
})(
<Select style={{ width: 190 }} onChange={this.onSecondCityChange}>
{cityOptions}
</Select>
)}
</FormItem>
</div>
</div>
</p>
*/}
<div style={{textAlign:"center",marginTop:20}}>
<Button type="primary" onClick={this.handleOk}>
发起
</Button>
<Link to="Supervision">
<Button style={{marginLeft:30}} type="default">
返回
</Button>
</Link>
</div>
</div>
)
}
}
const AddSupervisionPlanNews = Form.create()(AddSupervisionPlanNew);
export default AddSupervisionPlanNews;
|
const connection = require('../database/connection');
module.exports = {
async index(req, res) {
const enterprise_id = req.userIdToken;
if (!enterprise_id) {
return res.status(400).json({ error: 'Enterprise authorization required.' });
}
const services = await connection('services').where('enterprise_id', enterprise_id).select('*');
console.log("servicesProfile: ", services);
return res.json(services);
}
}
|
import React, { useState } from 'react';
import PropTypes from 'prop-types';
const Searchbar = ({
fetchPokemonByType
}) => {
const [ input, setInput ] = useState('')
const handleSubmit = event => {
event.preventDefault();
fetchPokemonByType(input);
setInput('');
}
return (
<form
className="flex"
onSubmit={event => handleSubmit(event)}
>
<div className="flex-auto mr-2">
<input
className="py-1 px-2 w-full border-2 border-gray-500 focus:border-black"
type="text"
placeholder="Search by type"
onChange={event => setInput(event.target.value)}
/>
</div>
<div className="ml-2">
<button
className="py-1 px-2 border-2 border-gray-500 hover:border-black hover:bg-black hover:text-white transition-all duration-75"
>
Submit
</button>
</div>
</form>
)
}
Searchbar.propTypes = {
fetchPokemonByType: PropTypes.func.isRequired,
}
export default Searchbar;
|
// import { baseURL } from '../urls';
// import sendPushMsg from '../services/sendNotification';
// export default function getUserPushToken(id, title, message) {
// const headers = new Headers();
// headers.append('Accept', 'application/json');
// fetch(`${baseURL}/retrieveToken/${id}`, { method: 'POST', headers })
// .then((a) => a.json())
// .then((result) => {
// // console.log('User push token below...');
// // console.log(result);
// const token = result?.data?.push_token[0]?.push_token;
// sendPushMsg(token, title, message);
// })
// .catch((error) => {
// console.log(error);
// });
// }
|
import React, { Component } from 'react';
export default class Responsive extends Component {
render() {
return (
<section className="responsive">
<div className="container">
<div>
<img src="./assets/images/section4-macbook.png" alt="Macbook"/>
</div>
<div>
<h4>New design</h4>
<h2>Responsive design, just needs your tap <span className="elipsis">....</span></h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras et ornare nulla. Pellentesque nec turpis vel turpis eleifend convallis.
Etiam ac commodo urna. Aenean dapibus imperdiet pellentesque. Nullam quis lacus eleifend, consequat orci eleifend, vehicula velit.
Etiam ultrices enim et diam dignissim dapibus. Morbi ipsum ipsum, malesuada nec diam in, suscipit condimentum ipsum. Nullam interdum ante dolor,
porttitor fermentum tortor feugiat vel. Morbi non sapien nisl. Maecenas id vehicula erat. Donec eros nisi, maximus in ornare nec,
efficitur eu ante.
</p>
</div>
</div>
</section>
);
}
}
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { text } from '@storybook/addon-knobs';
import Card from '../_storybookWrappers/Card';
import Notices from './index';
import { notice } from '../../events';
const stories = storiesOf('Components|Notices', module).addParameters({
component: Notices,
componentSubtitle: 'Displays a select component',
});
const NoticesLog = ({ customText }) => (
<>
<Card>
<button onClick={() => notice.showError(customText)}>Create notice error</button>
<button onClick={() => notice.showSuccess(customText)}>Create notice success</button>
<button onClick={() => notice.showInfo(customText)}>Create notice info</button>
<button onClick={() => notice.showWarning(customText)}>Create notice warning</button>
</Card>
<Notices />
</>
);
stories.add('default', () => {
const customText = text('custom text', 'Example of custom text');
return <NoticesLog customText={customText} />;
});
|
import Const from '../Constants';
import defaultUser from 'Assets/defaultUser';
export const initialState = {
authenticated: null,
iaaAuth: null,
iaacheck: '',
groupName: '',
subgroups: [],
users: [],
loading: { users: false, subgroups: false },
registrationToken: false,
privGrpVis: true,
privGrpVisTimeout: 5,
netidAllowed: false,
tokenTTL: 180,
confidential: false,
notifications: []
};
export const RootReducer = (state = initialState, action) => {
switch (action.type) {
case Const.RECEIVE_GROUP_NAME:
return { ...state, groupName: action.groupName };
case Const.LOADING_SUBGROUPS:
return { ...state, loading: { ...state.loading, subgroups: true } };
case Const.RECEIVE_SUBGROUPS:
return { ...state, subgroups: action.subgroups, loading: { ...state.loading, subgroups: false } };
case Const.DELETE_SUBGROUP:
let subgroups = state.subgroups.filter(sg => sg.name !== action.subgroup);
return { ...state, subgroups };
case Const.LOADING_USERS:
return { ...state, loading: { ...state.loading, users: true } };
case Const.RECEIVE_USERS:
case Const.CLEAR_USERS:
return { ...state, users: action.users, loading: { ...state.loading, users: false } };
case Const.ADD_DUMMY_USER:
return { ...state, users: [{ displayId: action.displayId, UWRegID: action.displayId, Base64Image: defaultUser, loading: true }, ...state.users] };
case Const.FAILED_DUMMY_USER:
return { ...state, users: state.users.filter(u => u.displayId !== action.displayId) };
case Const.UPDATE_USERS:
let newUsers = state.users.map(u => {
return u.displayId && u.displayId === action.user.displayId ? action.user : u;
});
return { ...state, users: newUsers };
case Const.MARK_USER_FOR_DELETION:
let users = state.users.map(u => {
if (u.UWNetID === action.identifier) {
u.deleting = true;
}
return u;
});
return { ...state, users };
case Const.REMOVE_USER:
return { ...state, users: state.users.filter(u => u.UWNetID !== action.user) };
case Const.USER_AUTHENTICATION:
return { ...state, authenticated: action.authenticated, iaaAuth: action.iaaAuth, iaacheck: action.iaacheck };
case Const.STORE_REGISTRATION_TOKEN:
return { ...state, registrationToken: action.token };
case Const.STORE_PRIVATE_GROUP_VISIBILITY:
return { ...state, privGrpVis: action.enabled };
case Const.STORE_PRIVATE_GROUP_VISIBILITY_TIMEOUT:
return { ...state, privGrpVisTimeout: action.timeout };
case Const.STORE_NETID_ALLOWED:
return { ...state, netidAllowed: action.netidAllowed };
case Const.STORE_TOKEN_TTL:
return { ...state, tokenTTL: action.tokenTTL };
case Const.ADD_NOTIFICATION:
return { ...state, notifications: [...state.notifications, action.notification] };
case Const.REMOVE_NOTIFICATION:
return { ...state, notifications: state.notifications.filter(n => n.messageId != action.messageId) };
case Const.PRIVATE_GROUP:
return { ...state, confidential: action.confidential };
case Const.RESET_STATE:
return initialState;
case Const.STORE_SETTINGS:
return { ...state, ...action.settings };
default:
return state;
}
};
|
angular.module('ngApp.directBooking').controller('DirectBookingCollectionDateTimeController', function ($scope, $uibModal, $uibModalInstance, $translate, PackageLength, toaster, ShipFromCountryId, DirectBookingService, $rootScope) {
$scope.closePopUp = function () {
$scope.PlaceBookingObj.Type = "Close";
$scope.PlaceBookingObj.BookingStatus = 'Current';
$scope.PlaceBookingObj.CollectionDate = $scope.CollectionDate;
$scope.PlaceBookingObj.CollectionTime = $scope.CollectionTime;
if ($scope.IsCollection === true) {
$scope.PlaceBookingObj.IsCollection = $scope.IsCollection;
}
$uibModalInstance.close($scope.PlaceBookingObj);
};
var setModalOptions = function () {
$translate(['FrayteWarning', 'CollectionTime_Required', 'CollectionDate_Required']).then(function (translations) {
$scope.Frayte_Warning = translations.FrayteWarning;
$scope.CollectionTimeRequired = translations.CollectionTime_Required;
$scope.CollectionDateRequired = translations.CollectionDate_Required;
$scope.CountryCurrentDateTime();
});
};
$scope.CountryCurrentDateTime = function () {
DirectBookingService.GetCountryCurrentDateTime($scope.FromCountryId).then(function (response) {
if (response.data !== undefined && response.data !== null && response.data !== '') {
$scope.CurrentDate = response.data.CurrentDate;
$scope.CurrentTime = response.data.CurrentTime;
}
else {
$scope.CurrentDate = "";
$scope.CurrentTime = "";
}
});
};
$scope.OpenCalender = function ($event) {
$scope.status.opened = true;
};
$scope.PlaceBooking = function (directBookingForm, IsValid, directBooking) {
if ($scope.IsCollection !== undefined && $scope.IsCollection !== null && $scope.IsCollection !== '' && $scope.IsCollection === true) {
if (($scope.CollectionTime === undefined || $scope.CollectionTime === '' || $scope.CollectionTime === null)) {
toaster.pop({
type: 'warning',
title: $scope.Frayte_Warning,
body: $scope.CollectionTimeRequired,
showCloseButton: true
});
}
else {
$scope.PlaceBookingObj.Type = "Confirm";
$scope.PlaceBookingObj.BookingStatus = 'Current';
$scope.PlaceBookingObj.CollectionDate = $scope.CollectionDate;
$scope.PlaceBookingObj.CollectionTime = $scope.CollectionTime;
if ($scope.IsCollection === true) {
$scope.PlaceBookingObj.IsCollection = $scope.IsCollection;
}
$scope.PlaceBookingObj.Message = $scope.Message;
$uibModalInstance.close($scope.PlaceBookingObj);
}
}
else {
$scope.PlaceBookingObj.Type = "Confirm";
$scope.PlaceBookingObj.BookingStatus = 'Current';
$scope.PlaceBookingObj.CollectionDate = $scope.CollectionDate;
$scope.PlaceBookingObj.CollectionTime = $scope.CollectionTime;
if ($scope.IsCollection === true) {
$scope.PlaceBookingObj.IsCollection = $scope.IsCollection;
}
$scope.PlaceBookingObj.Message = $scope.Message;
$uibModalInstance.close($scope.PlaceBookingObj);
}
};
$scope.GetDateDay = function (CollectionDate) {
var date = CollectionDate;
if (date !== undefined && date !== null && date !== '') {
if (date.getDay() === 6) {
$scope.Message = true;
}
else {
$scope.Message = false;
}
}
var todayDate = new Date();
var colleDate = new Date(CollectionDate);
if (todayDate < colleDate) {
$scope.IsCollectionDateTime = true;
}
else {
$scope.IsCollectionDateTime = false;
}
};
function init() {
$scope.IsCollectionDateTime = false;
$scope.IsCollection = false;
$scope.PlaceBookingObj = {
directBookingForm: {},
BookingStatus: "",
isValid: false,
CollectionTime: "",
CollectionDate: new Date(),
Type: "",
IsCollection: false
};
$scope.FromCountryId = ShipFromCountryId;
$scope.status = {
opened: false
};
$scope.dateOptions = {
formatYear: 'yy',
startingDay: 1,
minDate: new Date(),
dateDisabled: function (data) {
var date = data.date,
mode = data.mode;
return mode === 'day' && (date.getDay() === 0);
}
};
//|| date.getDay() === 6
$scope.IsShowColleDateMsg = false;
$scope.CollectionDate = new Date();
setModalOptions();
}
init();
});
|
import moment from 'moment';
const AERIS_CLIENT_ID = '0eMxRAeeo9ePYk9HdurS7';
const AERIS_CLIENT_SECRET = 'E57wbnHxx1Ebkq81ClFh1U6DoN2ZzQfEUJ8xMj2V';
export function getForecastForCity(city) {
return fetch('https://api.aerisapi.com/forecasts/'+city+'?client_id='+AERIS_CLIENT_ID+'&client_secret='+AERIS_CLIENT_SECRET)
.then(response => response.json())
.then(responseJson => {
if (responseJson.success) {
return {
error: false,
city: city,
forecast: parseForecast(responseJson.response[0].periods),
};
}
else {
return {
error: true,
};
}
});
}
function parseForecast(periods) {
var forecasts = [];
for (var i = 0; i < periods.length; i++) {
// Get the forecast for period "i"
var forecastReceived = periods[i];
var date = convertTimestampToDate(forecastReceived.validTime);
var myForecast = {
description: forecastReceived.weather,
date: date,
averageTemp: forecastReceived.avgTempF,
maximumTemp: forecastReceived.maxTempF,
minimumTemp: forecastReceived.minTempF,
precipitation: forecastReceived.precipIN,
humidity: forecastReceived.humidity,
feelsLikeTemp: forecastReceived.feelslikeF,
windSpeed: forecastReceived.windSpeedMPH,
windDirection: forecastReceived.windDir,
};
forecasts.push(myForecast);
}
return forecasts;
}
function convertTimestampToDate(timestamp) {
// Convert the timestamp for this period into a date/time
var myMomentObject = moment(timestamp);
var date = myMomentObject.format('dddd, MMM Do');
return date;
}
|
'use strict';
var express = require('express');
var router = express.Router();
var Message = require('../models/message');
//route for message
router.get('/', (req, res) => {
Message.findAll(function(err, messages){
if(err){
return res.status(400).send(err);
}
console.log(messages);
res.render('message',{ messages: messages});
// res.send();
});
});
router.post('/', (req,res) => {
Message.create(req.body, (err,x) => {
if(err){
res.send(err);
}
res.send(x);
});
});
router.delete('/:id', (req,res) => {
console.log(req.params.id);
Message.delete(req.params.id, (err, x) => {
if(err){
res.send(err);
}
console.log(x);
res.send(x);
});
});
// router.put('/:id', (req, res) => {
// Message.edit(req.params.id, err => {
// if(err){
// res.send(err);
// }
// res.send();
// });
// });
module.exports = router;
|
window.onload = _ => {
let canvas_ref = document.getElementById("canvas").getContext("2d");
canvas_ref.canvas.addEventListener("mousemove", function(event) {
let x = event.clientX - canvas_ref.canvas.offsetLeft;
let y = event.clientY - canvas_ref.canvas.offsetTop;
document.getElementById("mouse_position_tracker").innerHTML = "x: " + x + " | y" + y;
});
}
|
import classTemplates from './classTemplates';
export default class CharacterClass {
constructor(key) {
this.key = key;
const classTemplate = _.findWhere(classTemplates, {key: key});
this.label = classTemplate.label;
}
}
|
const SERVER_URL = 'http://localhost:5000';
const loggedin = localStorage.getItem('isAuthenticated');
const user = localStorage.getItem('user');
const deviceId = localStorage.getItem('deviceID')
if (!loggedin) {
const path = window.location.pathname;
if (path !== '/login' && path !== '/registration') {
location.href = '/login';
}
}
$(document).ready(() => {
document.getElementById("title").textContent = `Switch ${deviceId} Info Page`;
$.get(`${SERVER_URL}/device` , {deviceId} ).then((res) => {
//console.log(res.switch.colour)
c = []
c.push(res.switch.colour.red)
c.push(res.switch.colour.green)
c.push(res.switch.colour.blue)
var b = c.map(function(x){ //For each array element
x = parseInt(x).toString(16); //Convert to a base16 string
return (x.length==1) ? "0"+x : x; //Add zero if we get only one character
})
b = "#"+b.join("");
document.getElementById("ID").textContent = deviceId
let _state = (res.switch.state) ? "On" : "Off";
let brightness = res.switch.brightness * 100
document.getElementById("state").textContent = _state
document.getElementById("brightness").textContent = `${brightness}%`
document.getElementById("colour").style.backgroundColor = b
res.switch.lightsIDs.forEach(id => {
var li = document.createElement('li');
li.innerHTML = id;
document.getElementById("list").appendChild(li);
});
})
})
$('#statebtn').on('click', () =>{
$.get(`${SERVER_URL}/device` , {deviceId} ).then((res) => {
let _state = (!res.switch.state) ? "On" : "Off";
document.getElementById("state").textContent = _state
let brightness = (!res.switch.state) ? 1 : 0;
let _switch = {
ID: deviceId,
state: !res.switch.state,
brightness:brightness,
colour:{red:0,green:0,blue:0},
lightsIDs:res.switch.lightsIDs
}
brightness = _switch.brightness * 100
document.getElementById("brightness").textContent = `${brightness}%`
let client = true
_switch.lightsIDs.forEach(id => {
light = {
'ID': id,
'state': _switch.state,
'brightness': _switch.brightness,
'colour': {'red': _switch.colour.red, 'green': _switch.colour.green, 'blue': _switch.colour.blue}
}
$.post(`${SERVER_URL}/updateLight`, { light, client}).then(res => {
console.log(`statusCode: ${res.status}`)
}).catch(error => {
console.error(error)
})
});
$.post(`${SERVER_URL}/updateSwitch`, {_switch, client}).then(res => {
console.log(`statusCode: ${res.status}`)
})
.catch(error => {
console.error(error)
})
});
})
|
/*global ODSA */
$(document).ready(function() {
"use strict";
var av_name = "LazyLists7CON"; // Illustrate and develop the is.map function
var av = new JSAV(av_name);
var code = ODSA.UTILS.loadConfig({av_name: av_name}).code;
var pseudo = av.code(code[0]).show();
var n = 31;
// var arrValues = ["F", "F", "T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T","T", "T"];
// var arrValues = [".", ".", ".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".",".", "."];
var arrValues = [" ", " ", " "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ", " "];
var arr = av.ds.array(arrValues, {indexed: true});
var p_label = av.label("p = 2", {left: 20, top: 60}).hide();
// var p = av.variable(2, {label: "p = ", relativeTo:arr, anchor:'right top',
// myAnchor:'left top',
// left: 20,
// top: 70});
// Slide 1
av.umsg("Suppose n = 30. Trace through the pseudocode below.");
for (var i = 0; i < n; i++) arr.addClass(i, "narrow");
pseudo.addClass([1,2,3,4,5,6,7,8], "extrawidth");
p_label.addClass("emphasize");
pseudo.setCurrentLine(1);
av.displayInit();
// S 2
pseudo.setCurrentLine(2);
arr.value(0,"F");
arr.value(1,"F");
for (i = 2; i < n; i++) { arr.value(i,"T");arr.highlight(i); }
av.step();
// S 3
pseudo.setCurrentLine(3);
p_label.show();
av.step();
// S 4
pseudo.setCurrentLine(4);
for (i = 4; i < n; i= i + 2) { arr.value(i,"F");arr.unhighlight(i); }
av.step();
// S 5
p_label.text("p = 3");
pseudo.setCurrentLine(5);
av.step();
// S 6
pseudo.setCurrentLine(7);
av.step();
// S 7
pseudo.setCurrentLine(4);
for (i = 6; i < n; i= i + 3) { arr.value(i,"F");arr.unhighlight(i); }
av.step();
// S 8
p_label.text("p = 5");
pseudo.setCurrentLine(5);
av.step();
// S 9
pseudo.setCurrentLine(7);
av.step();
// S 10
pseudo.setCurrentLine(4);
for (i = 10; i < n; i= i + 5) { arr.value(i,"F");arr.unhighlight(i); }
av.step();
// S11
p_label.text("No such p");
pseudo.setCurrentLine(5);
av.step();
//S12
p_label.hide();
pseudo.setCurrentLine(6);
av.step();
//S13
pseudo.setCurrentLine(8);
av.step();
av.recorded();
});
|
/**
* Common JavaScript
*/
$(document).ready(function() {
$(".autoHidePane .autoHidePaneDelete").click(function(){
$(this).parents(".autoHidePane").animate({ opacity: "hide" }, "fast");
});
// Show auto hide message if it contains something
if (($('#autoHideMessage').text() != '')) {
$('.autoHidePane').css('display', 'inline');
// Set hiding if autoHide contains something
setTimeout('$(".autoHidePane").animate({ opacity: "hide" }, "slow"); ', 3000);
}
// Numeric entry
$('.numericEntry').keypress(function(event){
var allowKeys = Array(
48, 49, 50, 51, 52, 53, 54, 55, 56, 57,
35, 36, 37, 39,
46, 8,
9
);
var keyp = [event.keyCode||event.which];
for (var i in allowKeys) {
if (allowKeys[i] == keyp) {
return true;
}
}
event.preventDefault? event.preventDefault() : event.returnValue = false;
});
$('.numericEntry').focus(function(){
this.select();
});
$('.telephone').attr('maxlength', 14).attr('size', 14);
$('.telephone').keypress(function(event){
return telephoneKeyPress(event, this);
});
// Set onclick action of info which display on hover of "?"
$('.info').click(function(){
return false;
});
// Set href value to '#'
$('.info').attr('href', '#');
tooltip();
// Call autohide message if there's a message on session
if (autoHideTitle) {
showMessage(autoHideTitle, autoHideMessage, 0, true, true);
}
});
/**
* Processes class telephone keypress event
*/
function telephoneKeyPress(event, element)
{
var keyp = [event.keyCode||event.which];
//var strFormat = '(###) ###-####';
var strFormat = '0#-##-##-##-##';
var ctrlKeys = Array(
35, 36, 37, 39,
46, 8,
9
);
for (var i in ctrlKeys) {
if (ctrlKeys[i] == keyp) {
return true;
}
}
var allowKeys = Array(
48, 49, 50, 51, 52, 53, 54, 55, 56, 57, // numeric
40, 41, 45, 32 // (, ), -, space
);
var invalidKey = true;
for (var i in allowKeys) {
if (allowKeys[i] == keyp) {
invalidKey = false;
break;
}
}
if (invalidKey) {
return false;
}
for (i = 0; i < 14; i++) {
if (strFormat.charAt(i) == "#") {
// The current character must be a digit.
if(element.value.length > i ) {
if(isNaN(element.value.charAt(i)) || element.value.charAt(i) == " ") {
// if its not a number, it's erased and the loop is set back one
element.value = element.value.substring(0,i) + element.value.substring(i + 1,element.value.length)
i--;
}
}
} else if (strFormat.charAt(i) == "a") {
// The current character must be a letter (case insensitive).
if(element.value.length > i ) {
// if its not a letter, it's erased
if(element.value.charAt(i).toUpperCase() < "A" || element.value.charAt(i).toUpperCase() > "Z" ) {
element.value = element.value.substring(0,i) + element.value.substring(i + 1,element.value.length)
i--;
}
}
} else if (strFormat.charAt(i) == "A") {
// The current character must be an uppercase letter.
if(element.value.length > i ) {
// if its not a letter, it's removed
if(element.value.charAt(i).toUpperCase() < "A" || element.value.charAt(i).toUpperCase() > "Z" ) {
element.value = element.value.substring(0,i) + element.value.substring(i + 1,element.value.length)
i--;
} else {
// otherwise, it is set to uppercase
element.value = element.value.substring(0,i) + element.value.charAt(i).toUpperCase() + element.value.substring(i + 1,element.value.length)
}
}
} else {
// The current character must be the same as the one in the format string.
if(element.value.length > i ) {
// if it isn't already the correct character, insert the character
if(element.value.charAt(i) != strFormat.charAt(i)) {
element.value = element.value.substring(0,i) + strFormat.charAt(i) + element.value.substring(i,element.value.length)
}
}
}
}
}
/**
* Show the message
*/
function showMessage(title, message, pos, withCloseControl, manageAutoHide)
{
if (pos == 'middle') {
$('.autoHidePane').css('top', '200px');
$('.autoHidePaneDelete').css('display', 'none');
} else if (pos == 'top') {
$('.autoHidePane').css('top', '0px');
$('.autoHidePaneDelete').css('display', 'inline').css('top', '10px');
} else {
$('.autoHidePane').css('top', pos + 'px');
if (typeof withCloseControl == 'undefined') {
$('.autoHidePaneDelete').hide();
} else {
$('.autoHidePaneDelete').show();
}
}
$('#autoHideTitle').html(title);
$('#autoHideMessage').html(message);
if (title == 'Failure' || title == 'Echec') {
$('.autoHidePane').css({
display:"inline",
backgroundColor:"#FFC4C4",
border:"1px solid #FF6363",
borderTop:"solid 2px #FF6363"
});
$('.autoHidePaneDelete').show();
} else {
$('.autoHidePane').css({
display:"inline",
backgroundColor:"#edf5e1",
border:"1px solid #c4df9b",
borderTop:"solid 2px #c4df9b"
});
if (manageAutoHide == true) {
setTimeout('hideMessage("slow");', 3000);
}
}
return false;
}
/**
* Hide the message
*/
function hideMessage(strSpeed)
{
if (typeof strSpeed == "undefined") {
$(".autoHidePane").hide();
} else {
$(".autoHidePane").animate({ opacity: "hide" }, strSpeed);
}
return false;
}
/**
* Use this function to toggle the attribute: checked
* Sample calls:
$("input[@type='checkbox']").check();
$("input[@type='checkbox']").check('on');
$("input[@type='checkbox']").check('off');
$("input[@type='checkbox']").check('toggle');
*/
$.fn.check = function(mode) {
var mode = mode || 'on'; // if mode is undefined, use 'on' as default
return this.each(function() {
switch(mode) {
case 'on':
this.checked = true;
break;
case 'off':
this.checked = false;
break;
case 'toggle':
this.checked = !this.checked;
break;
}
});
};
/**
* This function will replace instances of searchTerm with replaceWith in str. Pass ignoreCase if needed.
*/
function replaceAll( str, searchTerm, replaceWith, ignoreCase )
{
var regex = "/"+searchTerm+"/g";
if( ignoreCase ) regex += "i";
return str.replace( eval(regex), replaceWith );
}
/**
* Tooltip script
* powered by jQuery (http://www.jquery.com)
* written by Alen Grakalic (http://cssglobe.com)
* for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
*/
this.tooltip = function(){
/* CONFIG */
xOffset = -15;
yOffset = 14;
// these 2 variable determine popup's distance from the cursor
// you might want to adjust to get the right result
/* END CONFIG */
$("a.tooltip").hover(function(e){
this.t = this.title;
this.title = "";
$("body").append("<p id='tooltip'>"+ this.t +"</p>");
$("#tooltip")
.css("top",(e.pageY - xOffset) + "px")
.css("left",(e.pageX + yOffset) + "px")
.fadeIn("fast");
},
function(){
this.title = this.t;
$("#tooltip").remove();
});
$("a.tooltip").mousemove(function(e){
$("#tooltip")
.css("top",(e.pageY - xOffset) + "px")
.css("left",(e.pageX + yOffset) + "px");
});
};
/**
* Check for valid numeric strings
*/
function isNumeric(strString)
{
var strValidChars = "0123456789";
var strChar;
var blnResult = true;
if (strString.length == 0) return false;
// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++) {
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1) {
blnResult = false;
}
}
return blnResult;
}
/**
* This will format 0123456789 to 01-23-45-67-89
*/
function intToPhoneFormat(intPhone) {
if (isNumeric(intPhone) == false) {
// If not entirely numeric, don't alter it.
return intPhone;
}
if (intPhone.length > 10) {
// Too long, don't alter it.
return intPhone;
} else if (intPhone.length < 9) {
// Too short, don't alter it.
return intPhone;
} else if (intPhone.length == 9) {
// Add '0' as phone prefix.
intPhone = '0' + intPhone;
}
return intPhone.substring(0, 2)
+ '-' + intPhone.substring(2, 4)
+ '-' + intPhone.substring(4, 6)
+ '-' + intPhone.substring(6, 8)
+ '-' + intPhone.substring(8, 10);
}
// eof
|
import React, { useState } from 'react';
import './style.css';
export const Card = (props) => {
const [display, setDisplay] = useState(false);
const handleClick = () => {
setDisplay(!display);
};
return (
<div className="card">
<div className="container">
<div className="container__left-side">
<h2 className="card-title__mobile">{props.title}</h2>
<img className="container__photo" src={props.photo} alt={props.alt} />
</div>
<div className="container__right-side">
<h2 className="card-title__large">{props.title}</h2>
<p>{props.text}</p>
<button className="button--card" onClick={handleClick}>
{display === true ? 'Zavřít' : 'Vstoupit'}
</button>
</div>
</div>
<div
className={display !== true ? 'object-no-display' : 'object-display'}
>
{props.children}
</div>
</div>
);
};
|
/**
* Created by Administrator on 2015/12/10 0010.
*/
/*
使用方法:
<div id="operation-infosel" class=" patientlist_infosel">
<p>筛选方式<i></i></p>
<ul>
<li><a href="#">编辑</a></li>
<li><a href="#">删除</a></li>
<li><a href="#">添加</a></li>
<li><a href="#">登陆</a></li>
<li><a href="#">退出</a></li>
</ul>
</div>
*/
/*下拉列表开始*/
$("#operation-infosel p").bind("click",function(){
var ul = $("#operation-infosel ul");
$("#operation-infosel p i").addClass("current");
if (ul.css("display")=="none"){
ul.slideDown("fast");
}else{
ul.slideUp("fast");
};
});
$("#operation-infosel ul li a").bind("click",function(){
var txt=$(this).text();
$("#operation-infosel p").html(txt+"<i></i>");
$("#operation-infosel ul").hide();
});
/*
|
var searchData=
[
['nbmots',['nbMots',['../structSolution.html#a60e0881a49e593091d2210dd49f2f51a',1,'Solution']]]
];
|
import {
buildProgressWindowDiv,
buildHeaderWrapperDiv,
buildProgressSummaryParagraph,
buildLoadedSoFarParagraph,
buildParsedSoFarParagraph,
buildUserInfoParagraph,
buildUserWarningParagraph,
buildHeaderFieldsWrapper,
} from "./../../../src/js/helpers/progressWindowHelpers";
import { expect } from "chai";
import jsdom from "jsdom";
const { JSDOM } = jsdom;
function mockGlobalDocument() {
global.window = new JSDOM("<body></body>").window;
global.document = window.document;
}
mockGlobalDocument();
describe("Progress Window Helper", () => {
describe("#buildProgressWindowDiv", () => {
it("returns a proper DIV element scaled according to passed parameters", () => {
const progressWindowDiv = buildProgressWindowDiv(300, 150);
expect(progressWindowDiv).to.exist;
expect(progressWindowDiv.style.width).to.eq("300px");
expect(progressWindowDiv.style.left).to.eq("150px");
expect(progressWindowDiv.outerHTML).to.eq(`<div id="progressWindowDiv" style="display: flex; flex-direction: column; width: 300px; position: fixed; top: 100px; left: 150px; z-index: 1000; background-color: rgb(255, 255, 255); overflow: hidden;"></div>`); // eslint-disable-line quotes
});
});
describe("#buildHeaderWrapperDiv", () => {
it("returns a proper header wrapping DIV element", () => {
const headerWrapperDiv = buildHeaderWrapperDiv();
expect(headerWrapperDiv).to.exist;
expect(headerWrapperDiv.outerHTML).to.eq(`<div id="headerWrapperDiv" style="background-color: rgb(255, 255, 255);"></div>`); // eslint-disable-line quotes
});
});
describe("#buildProgressSummaryParagraph", () => {
it("returns 'Progress Summary' paragraph", () => {
const progressSummaryP = buildProgressSummaryParagraph();
expect(progressSummaryP).to.exist;
expect(progressSummaryP.outerHTML).to.eq(`<p style="padding: 10px 20px; font-weight: 800; font-size: 14px;">Progress summary</p>`); // eslint-disable-line quotes
});
});
describe("#buildLoadedSoFarParagraph", () => {
it("returns 'Loaded So Far' paragraph", async () => {
const loadedSoFarP = await buildLoadedSoFarParagraph();
expect(loadedSoFarP).to.exist;
expect(loadedSoFarP.outerHTML).to.eq(`<p id="loadedSoFar" style="padding-left: 20px; margin-top: 8px; margin-bottom: 20px; font-weight: 500;">Posts loaded: undefined</p>`); // eslint-disable-line quotes
});
});
describe("#buildParsedSoFarParagraph", () => {
it("returns 'Parsed So Far' paragraph", () => {
const parsedSoFarP = buildParsedSoFarParagraph();
expect(parsedSoFarP).to.exist;
expect(parsedSoFarP.outerHTML).to.eq(`<p id="parsedSoFar" style="padding-left: 20px; margin-top: 8px; margin-bottom: 20px; font-weight: 500;">Posts processed: 0</p>`); // eslint-disable-line quotes
});
});
describe("#buildUserInfoParagraph", () => {
it("returns 'User Info' paragraph", () => {
const userInfoP = buildUserInfoParagraph();
expect(userInfoP).to.exist;
expect(userInfoP.outerHTML).to.eq(`<p id="userInfo" style="padding-left: 20px; margin-top: 8px; margin-bottom: 20px; font-size: 10px;">Please don't manipulate the website while scraper is working. If you see no progress in the number of posts parsed for a long time, please restart the scraper.</p>`); // eslint-disable-line quotes
});
});
describe("#buildUserWarningParagraph", () => {
it("returns 'User Warning' paragraph", () => {
const userWarningP = buildUserWarningParagraph();
expect(userWarningP).to.exist;
expect(userWarningP.outerHTML).to.eq(`<p id="userWarning" style="padding-left: 20px; margin-top: 8px; margin-bottom: 20px; font-style: italic; font-size: 10px; color: rgb(255, 0, 0);">This browser tab has to stay ACTIVE during this process</p>`); // eslint-disable-line quotes
});
});
describe("#buildUserWarningParagraph", () => {
it("returns 'User Warning' paragraph", () => {
const userWarningP = buildUserWarningParagraph();
expect(userWarningP).to.exist;
expect(userWarningP.outerHTML).to.eq(`<p id="userWarning" style="padding-left: 20px; margin-top: 8px; margin-bottom: 20px; font-style: italic; font-size: 10px; color: rgb(255, 0, 0);">This browser tab has to stay ACTIVE during this process</p>`); // eslint-disable-line quotes
});
});
describe("#buildHeaderFieldsWrapper", () => {
it("returns proper Header Fields Wrapper DIV element", () => {
const headerFieldsWrapper = buildHeaderFieldsWrapper();
expect(headerFieldsWrapper).to.exist;
expect(headerFieldsWrapper.outerHTML).to.eq(`<div id="headerFieldsWrapper" style="display: flex; flex-direction: row;"></div>`); // eslint-disable-line quotes
});
});
});
|
/* global jQuery */
(function elementorAnchor($) {
// Fixes missing anchor on elementor widget pagination.
// https://github.com/elementor/elementor/issues/4703
$(document).ready(() => {
const $widget = $('.elementor-widget-woocommerce-products');
if (!$widget.attr('id')) {
$widget.attr('id', $widget.attr('data-id'));
}
$('.elementor-widget-woocommerce-products .page-numbers a').each((i, a) => {
$(a).attr('href', `${$(a).attr('href')}#${$(a).closest($widget).attr('id')}`);
// Remove event listeners to prevent Elementor from treating links as anchor target links.
$(a).off('click').on('click', (e) => e.stopImmediatePropagation());
});
});
}(jQuery));
|
import React from 'react';
import _ from 'lodash';
import { Link } from 'react-router-dom';
import ItemCard from './ItemCard';
import DashboardBtn from './DashboardBtn';
const OrderItems = props => {
return (
<div>
<div className='order-items-header'>
<h4>Your upcoming order:</h4>
<Link to='/subscribe'>
<DashboardBtn ctaText={'Update Subscription'} />
</Link>
</div>
{_.map(props.orderItems, (item, key) => (
<ItemCard item={item} key={key} />
))}
</div>
);
};
export default OrderItems;
|
//Agregar, Editar y Eliminar Carrera
function agregarCarrera() {
alert("Carrera Agregada Existosamente");
header("Location: carreras.html");
}
function editarCarrera(codigo) {
$("#edit").val(codigo);
$('#formularioEditarCarrera').submit();
}
function eliminarCarrera(codigo) {
var r = confirm("¿Esta Seguro que desea eliminar esta Carrera?");
if (r == true) {
$("#id").val(codigo);
$('#formularioCarrera').submit();
}
else {
header("Location: carreras.html");
}
}
//Agregar, Editar y Eliminar Estudiante
function agregarEstudiante() {
alert("Estudiante Agregado Existosamente");
header("Location: estudiantes.html");
}
function editarEstudiante(id) {
$("#edit").val(id);
$('#formularioEditarEstudiante').submit();
}
function eliminarEstudiante(cedula) {
var r = confirm("¿Esta Seguro que desea eliminar este Estudiante?");
if (r == true) {
$("#id").val(cedula);
$('#formularioEstudiante').submit();
}
else {
header("Location: estudiante.php");
}
}
//Agregar, Editar y Eliminar Usuario
function agregarUsuario() {
alert("Usuario Agregado Existosamente");
header("Location: usuarios.html");
}
function editarUsuario(id) {
$("#editid").val(id);
$('#formularioEditarUsuario').submit();
}
function eliminarUsuario(id) {
var r = confirm("¿Esta Seguro que desea eliminar este Usuario?");
if (r == true) {
$("#id").val(id);
$('#formularioUsuario').submit();
}
else {
header("Location: usuarios.html");
}
}
|
// 자바스크립트에서 array에 추가하는 방법은 array.push(), array[index] = value 방법이 있다
// 주의점은 append함수는 지원하지 않는다.
let foods = ['a', 'b', 'c'];
foods.push('d')
foods[4] = 'e'
console.log(foods);
console.log('-----------------------------------------')
// 배열 중복 제거
const arr = [1,1,3,4,5,1,4,2]
const newArr = [...new Set(arr)]
console.log(newArr)
console.log('--------------------------------------------')
// 배열 유니크한 원소 뽑아내기
const arr1 = [1,2,3,4,4,2,1,5]
// 중복되지 않는 값 가져오기(중복되는값 필터링)
const newArr1 = arr1.filter(val => arr1.indexOf(val) === arr1.lastIndexOf(val))
console.log(newArr1)
console.log('---------------------------------------------')
// 배열 특정 인덱스 요소 제거
const arr2 = [1,2,3,4,5]
// slice(start, end) end의 요소는 적용안됨
const newArr2 = [...arr2.slice(0,2), ...arr2.slice(3)]
//원본유지
console.log(arr2)
console.log(newArr2)
// 원본 훼손
// splice(start, number) start 인덱스부터 number개의 인덱스를 삭제
console.log(arr2.splice(2, 2))
console.log('------------------------------------------')
// 배열에 규칙적인 연속된 값 할당하기
const arr3 = Array(5).fill(1)
console.log(arr3)
const arr4 = Array(5).fill(1).map((value, index) => value + index)
console.log(arr4)
|
(function() {
/* Start angularLocalStorage */
'use strict';
var penguinGame = angular.module('milan.world.factory', ['penguin.LocalStorageService','pascalprecht.translate']);
penguinGame.factory('worldFactory', function($http, localStorageService, $translate, $sce, $location) {
var BASE = DEBUG_PENGUIN ? 12 : 12;
var MAX_TEST_PER_VISITS = {'sentences':2,'test':3,crosswords:0, quiz: 0}
var NUM_WORDS_FOR_UNLOCK_INFO = 5;
var self = this;
self.game = null;
var placesInWorld = null;
var placesInWorldIds = null;
var cachedPlacesForInfo = {};
function setup(learnLang, nativeLang){
var game = _game();
if(!game){
// posibble recreate game
_createNewGame(learnLang, nativeLang)
} else {
game.learn = learnLang;
game.native = nativeLang;
}
// if is language changed remove cached places
// it is mainly because if you are in intro
// you load sizes for fake language, but after
// changed learn and native language you want see real place sizes
// but if is fake language don't care
if(learnLang && learnLang != 'fake' && nativeLang && nativeLang != 'fake'){
placesInWorld = null;
placesInWorldIds = null;
}
}
function _getCoins(){
return self.game.coins;
}
function _createNewGame(learnLang, nativeLang){
self.game = {
coins: BASE,
learn:learnLang,
native: nativeLang,
placeId : 1,
visited : [1],
placesHistory : { '1' : {countVisit : 1}},
randomScenarios : {},
testsCounts : {
test : 0,
sentences : 0,
crosswords : 0,
quiz : 0
},
stats :{
correct : 0,
wrong : 0,
correctInRowScore : [0,0,0,0,0],
fastAnswerScore : [0,0,0],
correctInRowCoins : [0,0,0,0,0],
fastAnswerCoins : [0,0,0],
questionsAnswer : 0,
walkTotal : 0,
swimTotal :0,
flyTotal :0,
expTotal : 0,
wordTestTime : 0,
placesTotal : 0
}
}
// clean words
localStorageService.set('pinguin.vocabulary.words', null);
// old version - new version is with pEnguin.game2
localStorageService.set('pinguin.game', null);
_store();
return self.game;
}
function _game(){
if(!self.game){
self.game = localStorageService.get('penguin.game2');
}
return self.game;
}
function _store(){
localStorageService.set('penguin.game2', self.game);
}
function _update(scope){
if(!self.game){
_game();
}
//scope.coins = self.game.coins;
// scope.fly = self.game.fly;
// scope.walk = self.game.walk;
// scope.swim = self.game.swim;
// scope.exp = self.game.exp;
scope.levelInfo = _calcLevelInfo();
//scope.testsCounts = self.game.testsCounts;
scope.game = self.game;
_store();
return true;
}
function _calcLevelInfo(){
if(!self.game){
_game();
}
// step in levels
var scores = [75,175,300,450,625,850,1075,1400,1750,2000]
var lessons = [1001,1002,1003,1004,1005,2001,2002,2003,2004,2005,2006,2007,2008]
var levelInfo = {
level : 1,
levelExp : self.game.stats.correct,
baseLevelExp : 0,
nextLevelExp : 0
}
scores.some(function(score, idx){
if(score > self.game.stats.correct){
levelInfo.nextLevelExp = score;
levelInfo.level = idx + 1;
levelInfo.lesson = lessons[idx];
return true;
} else {
levelInfo.baseLevelExp = score;
}
})
return levelInfo;
}
function _place(place){
self.game.coins -= place.coins;
// self.game.fly -= place.fly;
// self.game.swim -= place.swim;
// self.game.walk -= place.walk;
if(self.game.visited.indexOf(self.game.placeId) == -1){
self.game.visited.push(self.game.placeId);
}
self.game.placeId = place.id;
self.game.stats.placesTotal += 1;
// remember how many times you was visited a single place
if(!self.game.placesHistory){
self.game.placesHistory = {}
}
if(self.game.placesHistory[place.id] && self.game.placesHistory[place.id].hasOwnProperty('countVisit')){
self.game.placesHistory[place.id].countVisit += 1;
} else {
self.game.placesHistory[place.id] = {
countVisit : 1
};
}
place.countVisit = self.game.placesHistory[place.id].countVisit;
_store();
}
function _addScore(score){
self.game.coins += score.totalCoins;
// maybe useles
self.game.lastScore = score;
_store();
var infostr = $translate.instant('score_add_info', {golds: score.totalCoins});
alertify.success(infostr);
}
function __separeSourceFromName(place){
if(place.name){
var regExp = /\[(.*)\]/;
// sources[0]: [www.seznam.cz]
// sources[1]: www.seznam.cz
var sources = place.name.match(regExp);
if(sources && sources.length == 2){
place.source = sources[1];
place.name = place.name.replace(sources[0], '');
}
}
}
function __setupPlaceWithLastVisit(place, cb){
if(self.game.placesHistory && self.game.placesHistory[place.id]){
place.countVisit = self.game.placesHistory[place.id].countVisit;
} else {
place.countVisit = 0;
}
}
function loadPlaces(cb){
if(placesInWorld && placesInWorldIds){
placesInWorld.forEach(function(place){
__setupPlaceWithHistory(place);
});
cb(placesInWorld, placesInWorldIds);
} else {
var url ='list/'+self.game.learn+'/'+self.game.native+'/?fields=id,name,posx,posy,size,preview';
requestGET($http, url, function(response, status){
placesInWorld = response;
placesInWorldIds = {};
placesInWorld.forEach(function(place){
__setupPlaceWithHistory(place);
__separeSourceFromName(place);
placesInWorldIds[place.id] = place;
});
cb(placesInWorld, placesInWorldIds);
});
}
}
function _isPossibleToMoveWithMessage(place){
if(self.game.placeId == place.id ||
self.game.coins >= place.coins) {
return true;
}
$('#game_resources_golds').css({color:'red'});
alertify.error($translate.instant('not_enought', {have:self.game.coins, need: place.coins}));
return false;
}
function getCurrentPlace(){
if(placesInWorldIds){
return placesInWorldIds[self.game.placeId];
} else {
return null;
}
}
function _getCurrentPlaceAsync(cb){
loadPlaces(function(){
cb(getCurrentPlace());
})
}
function setupPlacesDistancesAndExp(){
var gamePlace = getCurrentPlace();
placesInWorld.forEach(function(place){
var xd = gamePlace.posx - place.posx;
var yd = gamePlace.posy - place.posy;
var distance = Math.sqrt((xd*xd)+(yd*yd));
place.superDistance = Math.round(distance);
place.coins = place.superDistance;
var testsCounts = _game() ? _game().testsCounts : {};
var canTests = testsCounts && Object.keys(testsCounts).some(function(key) {
return testsCounts[key] > 0;
});
// the player can go the city without unlock
// info so charge him extra money
if(!canTests){
var pricePerInfo = 1;
if(place.history && place.history.countVisit){
pricePerInfo = place.history.countVisit;
}
// extra coins for unlock info
place.infoCoins = pricePerInfo * NUM_WORDS_FOR_UNLOCK_INFO;
} else {
place.infoCoins = 0;
}
//place.fly = Math.floor(place.superDistance / 9);
//place.swim = Math.floor((place.superDistance - (place.fly*6)) / 3);
//place.walk = (place.superDistance - (place.fly*5) - (place.swim*2));
});
}
function testEndGame(){
var canPlay = false;
var canUnlockInfo = false;
var testsCounts = _game() ? _game().testsCounts : {};
var canTests = testsCounts && Object.keys(testsCounts).some(function(key) {
return testsCounts[key] > 0;
});
if(canTests){
console.info('testGameOver', 'Can do tests');
return true;
}
canPlay = placesInWorld.some(function(place){
return(place.id != self.game.placeId && place.coins + place.infoCoins <= self.game.coins);
});
if(canPlay){
console.info('testGameOver', 'Can move to another place');
return canPlay;
}
var place = getCurrentPlace();
var infoUnlocked = _getPlaceHistoryValue(place, 'info')
if(!infoUnlocked){
infoUnlocked = self.game.coins > place.history.countVisit * NUM_WORDS_FOR_UNLOCK_INFO;
if(infoUnlocked){
console.info('testGameOver', 'can unlock info');
return true;
}
}
console.info('testGameOver', 'sorry');
return false;
}
function __setupPlaceWithHistory(place){
if(self.game.placesHistory && self.game.placesHistory[place.id]){
place.history = self.game.placesHistory[place.id];
} else {
// for case
if(!self.game.placesHistory){
self.game.placesHistory = {}
}
self.game.placesHistory[place.id] = {}
place.history = self.game.placesHistory[place.id];
}
}
function __generateCountOfLeftHistoryKey(place, name){
if(place.history.countVisit == undefined){
place.history.countVisit = 0;
}
return name + place.history.countVisit;
}
function _getPlaceHistoryValue(place, name){
var countVocTest = __generateCountOfLeftHistoryKey(place,name);
return self.game.placesHistory[place.id][countVocTest] || 0;
}
function _putPlaceHistoryValue(place, name, value){
var countVocTest = __generateCountOfLeftHistoryKey(place, name);
if(self.game.placesHistory[place.id][countVocTest] == undefined){
self.game.placesHistory[place.id][countVocTest] = value;
} else {
self.game.placesHistory[place.id][countVocTest] = value;
}
_store();
}
function _redirectToInfoIsTestsUnlockedWithAlert(place){
var unlocked = _getPlaceHistoryValue(place, 'info');
if(!unlocked){
var mess = $translate.instant('places-test-still-locked');
alertify.alert(mess);
$location.path('/info');
}
return unlocked;
}
function _testIsAlowedATest(testName, startTestCB){
_getCurrentPlaceAsync(function(place){
var repeats = self.game.testsCounts[testName];
// for case the user not yet visit a info
// to unlock place's test -> redirect him to info
if(repeats < 1) {
// test if the test was not run so offten
if(_redirectToInfoIsTestsUnlockedWithAlert(place)){
var mess = $translate.instant('voc-test-limit-test-max', {count:MAX_TEST_PER_VISITS[testName]});
alertify.alert(mess);
$location.path('/map')
}
} else {
startTestCB(place, repeats);
}
});
}
function loadPlace(placeid, cb){
var learn = self.game.learn;
if(!learn || learn == 'fake'){
learn = 'en';
}
// add native into place id,
// because first time when user not choice the learn language
// show to him a 'fake' info (info in english)
// but after he choice (for example spain) the learn lang
// give him new info with spain not again eng
var cacheId = placeid + '-' + learn;
if(cachedPlacesForInfo[cacheId]){
__setupPlaceWithHistory(cachedPlacesForInfo[cacheId])
cb(cachedPlacesForInfo[cacheId]);
return ;
}
var url ='get/'+placeid+'/'+learn+'/'+self.game.native+'/?fields=id,name,info,info_native&qfields=qid,question,answers,type&ifields=iid,image';
requestGET($http, url, function(response, status){
__separeSourceFromName(response);
cachedPlacesForInfo[cacheId] = response;
__setupPlaceWithHistory(cachedPlacesForInfo[cacheId]);
cb(cachedPlacesForInfo[cacheId])
});
}
/**
* get random numbers for specified scenarios images, questions
* key is for ensure it will be not generate the same random number
* for similar scenario
* @param scenario - identifier of scenario
* @param max - max for this number
*/
function getRandomNumber(scenario, max){
if(!self.game.randomScenarios){
self.game.randomScenarios = {};
}
var lastRandom = self.game.randomScenarios[scenario];
var rand = -1;
if(max < 2){
return 0;
}
do {
if(max >= 3){
rand = Math.floor((Math.random() * 1000)) % (max);
} else {
rand ++;
}
}while(lastRandom == rand);
self.game.randomScenarios[scenario] = rand;
return rand;
}
function getLearn(){
_game();
return self.game ? self.game.learn : null;
}
function getNative(){
_game();
return self.game ? self.game.native : null;
}
return {
createNewGame: _createNewGame
,game:_game
,update:_update
,store:_store
,setPlace:_place
,loadPlaces : loadPlaces
,setupPlacesDistancesAndExp: setupPlacesDistancesAndExp
,testEndGame:testEndGame
,getCurrentPlace: getCurrentPlace
,loadPlace:loadPlace
,isPossibleToMoveWithMessage : _isPossibleToMoveWithMessage
,getRandomNumber: getRandomNumber
,addScore:_addScore
,setup : setup
,getLearn : getLearn
,getNative : getNative
,getStats : function(){ return _game().stats; }
,calcLevelInfo : _calcLevelInfo
,getCoins : _getCoins
,getCurrentPlaceAsync : _getCurrentPlaceAsync
,putCountOfLeftToPlaceHistory: _putPlaceHistoryValue
,getCountOfLeftToPlaceHistory : _getPlaceHistoryValue
,redirectToInfoIsTestsUnlockedWithAlert: _redirectToInfoIsTestsUnlockedWithAlert
,testIsAlowedATest : _testIsAlowedATest
,MAX_TEST_PER_VISITS : MAX_TEST_PER_VISITS
,NUM_WORDS_FOR_UNLOCK_INFO : NUM_WORDS_FOR_UNLOCK_INFO
};
});
}).call(this);
|
import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import { connect } from 'react-redux';
import Select from '@material-ui/core/Select';
import MenuItem from '@material-ui/core/MenuItem';
import './TaskCreator.css';
import FormControl from '@material-ui/core/FormControl';
import InputLabel from '@material-ui/core/InputLabel';
class AddConstraint extends Component {
state={
constraint:{
constraint_table: '',
constraint_column: '',
constraint_comparison:{
comparison: '',
value: ''
}
},
currentTable: [],
saved: false
}
handleChange = field => event => {
let value = event.target.value
let currentTable = this.state.currentTable;
if (field === 'constraint_table' && event.target.value==='incubator'){
currentTable = this.props.reduxState.processDataTypes.incubatorTypes
}else if (field === 'constraint_table' && event.target.value==='growing_room'){
currentTable = this.props.reduxState.processDataTypes.growingRoomTypes
}
this.setState({
constraint:{
...this.state.constraint,
[field]: value
},
currentTable: currentTable
})
}
comparisonForm = () => {
console.log(`in value form`);
let column = this.state.constraint.constraint_column;
let dataType = this.typeCheck(column);
return(
<>
<TextField
disabled = {this.state.saved}
InputLabelProps={{ shrink: true }}
type={dataType}
className={"formField"}
label={'Value'}
value={this.state.constraint.constraint_comparison.value}
onChange={this.handleChangeComparison('value')}
margin="dense"
>
</TextField>
<TextField
className={"formField"}
InputLabelProps={{ shrink: true }}
disabled = {this.state.saved}
label={'Compare'}
select
value={this.state.constraint.constraint_comparison.comparison}
onChange={this.handleChangeComparison('comparison')}
margin={'dense'}
>
<MenuItem value={'>'}> > </MenuItem>
<MenuItem value={'>='}>>=</MenuItem>
<MenuItem value={'<'}><</MenuItem>
<MenuItem value={'<='}><=</MenuItem>
<MenuItem value={'='}>=</MenuItem>
</TextField>
</>
)
}
handleChangeComparison = field => event => {
this.setState({
constraint:{
...this.state.constraint,
constraint_comparison:{
...this.state.constraint.constraint_comparison,
[field]: event.target.value
}
}
})
}
typeCheck = (columnName) => {
let tableTypes = this.state.currentTable
for (let column of tableTypes) {
if (column.column_name === columnName && column.data_type === 'integer') {
console.log(`found type`, column);
return 'number'
} else if (column.column_name === columnName && column.data_type === 'timestamp without time zone') {
console.log(`found type`, column);
return 'date'
}
}
return 'text'
}
handleSave = event => {
console.log('in hanleSave ', this.props)
this.props.saveConstraint(this.state.constraint);
this.setState({
...this.state,
saved: true,
listPosition: this.props.listPosition
})
}
handleEdit = event => {
this.setState({
...this.state,
saved: false
})
this.props.editConstraint(this.state.listPosition)
}
render() {
let comparisonFormEl = null;
let columnSelectEl = null;
let saveEditEl = <button onClick={this.handleSave}>save</button>
;
let tableEl =
<TextField
className={"formField"}
select
label="Table"
value={this.state.constraint.constraint_table}
onChange={this.handleChange('constraint_table')}
margin="dense"
disabled={this.state.saved}
>
<MenuItem value={'incubator'}>incubator</MenuItem>
<MenuItem value={'growing_room'}>growing_room</MenuItem>
</TextField>
if (this.state.constraint.constraint_table){
columnSelectEl =
<FormControl margin={'dense'} >
<InputLabel shrink>Table</InputLabel>
<Select
disabled = {this.state.saved}
value={this.state.constraint.constraint_column}
onChange={this.handleChange('constraint_column')}
>
{this.state.currentTable.map((column,i) => (
<MenuItem key={i} value={column.column_name}>
{column.column_name}
</MenuItem>
))}
</Select>
</FormControl>;
if(this.state.constraint.constraint_column){
comparisonFormEl = this.comparisonForm()
}
}
if(this.state.saved){
saveEditEl=<button onClick={this.handleEdit}>edit</button>
}
console.log(`constraint state in render `, this.state);
return(
<div>
<p>Constraint</p>
{tableEl}
{columnSelectEl}
{comparisonFormEl}
{saveEditEl}
</div>
)
}
}
const mapReduxStateToProps = reduxState => ({
reduxState,
});
export default connect(mapReduxStateToProps)(AddConstraint);
|
const express = require('express');
const router = express.Router();
router.get('/me', (req, res) => {
res.render('me.ejs');
});
router.get('/me/skills', (req, res) => {
res.render('skills.ejs');
});
router.get('/me/projects', (req, res) => {
res.render('projects.ejs');
});
router.get('/me/contactinfo', (req, res) => {
res.render('contact.ejs');
});
router.get('/me/resume', (req, res) => {
res.render('resume.ejs');
});
module.exports = router;
|
var request = new XMLHttpRequest();
request.open('GET', 'img/svg.html', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var node = document.createElement('div');
node.classList.add('svg');
node.innerHTML = request.responseText;
document.body.insertBefore(node, document.body.lastChild);
localStorage.setItem('inlineSVGdata', request.responseText);
}
};
request.send();
|
import React from 'react';
import { Route } from 'react-router-dom';
import ProviderLayout from '../Layout/ProviderLayout';
export default function ({component: Component, ...rest}) {
return (
<Route {...rest}>
<ProviderLayout>
<Component/>
</ProviderLayout>
</Route>
)
}
|
export default {
fake: () => {
throw 'fake required'
},
count: 10,
pre: () => {
// no-op
},
post: (data) => {
return data
},
generate: function() {
const data = []
for (let i = 0; i < this.count; i++) {
data.push(this.fake())
}
return data
}
}
|
import React, { useState, useEffect, useRef } from "react";
const ContainerQoute = () => {
const [quotes, setQuotes] = useState('');
const changeColor = useRef();
const backgroundColors = ['#FF6633', '#FFB399', '#FF33FF', '#FFFF99', '#00B3E6',
'#E6B333', '#3366E6', '#999966', '#99FF99', '#B34D4D',
'#80B300', '#809900', '#E6B3B3', '#6680B3', '#66991A',
'#FF99E6', '#CCFF1A', '#FF1A66', '#E6331A', '#33FFCC',
'#66994D', '#B366CC', '#4D8000', '#B33300', '#CC80CC',
'#66664D', '#991AFF', '#E666FF', '#4DB3FF', '#1AB399',
'#E666B3', '#33991A', '#CC9999', '#B3B31A', '#00E680',
'#4D8066', '#809980', '#E6FF80', '#1AFF33', '#999933',
'#FF3380', '#CCCC00', '#66E64D', '#4D80CC', '#9900B3',
'#E64D66', '#4DB380', '#FF4D4D', '#99E6E6', '#6666FF']
/*Genera el Array de las frases*/
const getQuote = () => {
fetch("https://raw.githubusercontent.com/jovsz/quotes/main/quotes.json")
.then(res => res.json())
.then((data) => {
let mixNum = Math.floor(Math.random() * data.length);
setQuotes(data[mixNum]);
});
};
/*Se utilizar useEffect para inicializar con una fase al cargar la aplicacion*/
useEffect(()=> {
getQuote();
}, []);
/**/
useRef(() => {
changeColor.current.style.color = backgroundColors[Math.floor(Math.random * backgroundColors.length)]
}, [quotes])
function authorStyle(authorContent){
if(authorContent){
return '-'+authorContent;
}else{
return '';
}
}
/*Se crea el contenedor de las frases*/
return (
<div ref={changeColor} className="background">
<div className = "card">
<div className = "container-quote" >
<p >{quotes.quote}</p>
</div>
<div className="author-container">
<p>{authorStyle(quotes.author)}</p>
</div>
<div className="buttons">
<a href={`https://twitter.com/intent/tweet?text=${quotes.quote + ' Author: ' + quotes.author}`} target="_blank" rel="noopener noreferrer"><i class="fab fa-twitter"></i></a>
<button onClick= {getQuote}><i class="fas fa-book"></i></button>
</div>
</div>
</div>
);
}
export default ContainerQoute
|
export const BASE_URL = process.env.NODE_ENV === 'production'
? 'https://api.tesla.students.nomoredomains.icu'
: 'http://localhost:3000';
export const register = (email, password, name) => {
return fetch(`${BASE_URL}/signup`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email, password, name})
})
.then((res) => {
if (res.ok) {
console.log(`${res.status} MainApi ok`)
return res.json();
}
console.log(`${res.status} MainApi reject`)
return Promise.reject(res.status);
})
.catch(err => console.log(err))//
};
export const authorize = (email, password) => {
return fetch(`${BASE_URL}/signin`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({email, password})
})
.then((response => response.json()))
.then((data) => {
if (data.token) {
localStorage.setItem('jwt', data.token);
return data;
}
})
.catch(err => console.log(err))
};
// export const getContent = (token) => {
export const getUserInfo = (token) => {
return fetch(`${BASE_URL}/users/me`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`,
}
})
.then((res) => {
if (res.ok) {
return res.json();
}
return Promise.reject(res.status);
})
.catch(err => console.log(err))
}
class Api {
constructor({
baseUrl,
headers
}) {
this.baseUrl = baseUrl
this.headers = headers
}
_getHeaders() {
const token = localStorage.getItem('jwt')
return {
...this.headers,
'Authorization': `Bearer ${token}`,
}
}
_processingRes(res) {
if (res.ok) {
return res.json()
} else {
return Promise.reject(`Ошибка при обращении к серверу: ${res.status}`)
}
}
getUserData() {//
return fetch(`${this.baseUrl}/users/me`, {
headers: this._getHeaders(),
})
.then(this._processingRes)
}
getSavedNews() {//
return fetch(`${this.baseUrl}/articles`, {
headers: this._getHeaders(),
})
.then(this._processingRes)
}
saveArticle(article) {
const {
keyword,
title,
description,
publishedAt,
source,
url,
urlToImage,
} = article;
return fetch(`${this.baseUrl}/articles`, {
method: 'POST',
headers: this._getHeaders(),
body: JSON.stringify({
keyword,
title,
description,
publishedAt,
source,
url,
urlToImage,
})
})
.then(this._processingRes)
}
deleteArticle(_id) {
return fetch(`${this.baseUrl}/articles/${_id}`, {
method: 'DELETE',
headers: this._getHeaders(),
})
.then(this._processingRes)
}
}
export const api = new Api({
baseUrl: BASE_URL,
headers: {
'Content-Type': 'application/json'
}
})
|
$(document).ready(function() {
getCountryCode();
$("#guest").on("click", function() {
deleteAllCookies();
});
$("#indian-donation-button").on("click", function() {
$(".submit-button,.login-button").attr("disabled", "disabled");
$("#donationmodelpopup").modal();
$("#login-form,#guest").show();
$("#forgot-form,#guest2,#code,#mobilecode,#loginCheck").hide();
$("#login-mobileNumber,#password").val("");
$(".login-en").keyup(function() {
if ($("#mobileNumber").val() != "" && $("#password").val() != "") {
$(".login-button").removeAttr("disabled");
} else {
$(".login-button").attr("disabled", "disabled");
}
});
$(".forgot-en").keyup(function() {
if ($("#forgot-MobileNumber").val() != "") {
$(".submit-button").removeAttr("disabled");
} else {
$(".submit-button").attr("disabled", "disabled");
}
});
});
$("#foreign-donation-button").on("click", function() {
$(".submit-button,.login-button").attr("disabled", "disabled");
$("#donationmodelpopup").modal();
$("#login-form,#guest2,#code,#mobilecode").show();
$("#forgot-form,#guest,#loginCheck").hide();
$("#login-mobileNumber,#password,#code,#mobilecode").val("");
$(".login-en").keyup(function() {
if (
$("#mobileNumber").val() != "" &&
$("#password").val() != "" &&
$("#code").val() != ""
) {
$(".login-button").removeAttr("disabled");
} else {
$(".login-button").attr("disabled", "disabled");
}
});
$(".forgot-en").keyup(function() {
if (
$("#forgot-MobileNumber").val() != "" &&
$("#mobilecode").val() != ""
) {
$(".submit-button").removeAttr("disabled");
} else {
$(".submit-button").attr("disabled", "disabled");
}
});
});
$("#frgt-password").on("click", function() {
$("#forgot-form").show();
$("#login-form,#passwordCheckincorrect,#passwordChecksuccess").hide();
});
$("#login-2").on("click", function() {
$("#forgot-form").hide();
$("#login-form").show();
});
});
$(function() {
$("form[name='register']").validate({
rules: {
mobileNumber: {
required: true,
number: true,
minlength: 10
},
MobileNumber: {
required: true,
number: true,
minlength: 10
},
password: {
required: true,
minlength: 8
},
code: {
required: {
depends: function(element) {
if ("none" == $("#code").val()) {
$("#code").val("");
}
return true;
}
}
}
},
messages: {
mobileNumber: "Please enter a valid mobile number",
MobileNumber: "Please enter a valid mobile number",
code: "Please select Country Code",
password: {
required: "Enter old password",
minlength: jQuery.validator.format("Enter at least {0} characters")
}
},
submitHandler: function(form) {}
});
});
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 "";
}
function validateLogin() {
var formData = {};
formData["mobile_number"] = $("#code").val() + $("#login-mobileNumber").val();
formData["password"] = $("#password").val();
formData = JSON.stringify(formData);
$.ajax({
type: "POST",
headers: {
"content-type": "application/json"
},
data: formData,
url: "http://donations.sivanandaonline.org/shivananda/User/login",
success: function(result) {
var response = JSON.parse(result);
if (response.STATUS) {
var id = response.DATA[0].id;
var razorpay_customer_id = response.DATA[0].razorpay_customer_id;
var salutation = response.DATA[0].salutation;
var fullname = response.DATA[0].fullname;
var landline = response.DATA[0].landline;
var user_email_id = response.DATA[0].user_email_id;
var mobile_number = response.DATA[0].mobile_number;
var pan_num = response.DATA[0].pan_num;
var user_type = response.DATA[0].user_type;
var created_on = response.DATA[0].created_on;
var updated_on = response.DATA[0].updated_on;
var TOKEN = response.TOKEN;
var citizen = response.DATA[0].citizen;
var passport = response.DATA[0].passport;
// Set Cookies
setCookie("id", id, 1);
setCookie("razorpay_customer_id", razorpay_customer_id, 1);
setCookie("salutation", salutation, 1);
setCookie("fullname", fullname, 1);
setCookie("landline", landline, 1);
setCookie("user_email_id", user_email_id, 1);
setCookie("mobile_number", mobile_number, 1);
setCookie("pan_num", pan_num, 1);
setCookie("user_type", user_type, 1);
setCookie("created_on", created_on, 1);
setCookie("updated_on", updated_on, 1);
setCookie("TOKEN", TOKEN, 1);
setCookie("citizen", citizen, 1);
setCookie("passport", passport, 1);
if (citizen == "India") {
window.location.href = "indian";
$(".login-button").attr("disabled", "disabled");
} else {
window.location.href = "foreign";
$(".login-button").attr("disabled", "disabled");
}
} else {
$("#loginCheck")
.css("color", "red")
.show();
$(".login-button").attr("disabled", "disabled");
setTimeout(function() {
$("#login-mobileNumber").val();
$("#password").val("");
$("#code").val("");
$("#loginCheck").hide();
}, 3000);
}
}
});
}
function validatePassword() {
$("#loading-payment").modal({ backdrop: "static" });
var formData = {};
formData["mobile_number"] =
$("#mobilecode").val() + $("#forgot-MobileNumber").val();
formData = JSON.stringify(formData);
$.ajax({
type: "POST",
headers: {
"content-type": "application/json"
},
data: formData,
url: "http://donations.sivanandaonline.org/shivananda/User/getPass",
success: function(result) {
var response = JSON.parse(result);
if (response.STATUS) {
var frgtSucc = response.STATUS_MSG;
$("#loading-payment").modal("hide");
$("#passwordChecksuccess")
.text(frgtSucc)
.css("color", "green")
.show();
$("#code,#forgot-MobileNumber").val("");
$(".submit-button").attr("disabled", "disabled");
setTimeout(function() {
$("#code,#forgot-MobileNumber").val("");
$("#passwordChecksuccess")
.text(frgtSucc)
.css("color", "green")
.hide();
}, 3000);
} else {
$("#loading-payment").modal("hide");
var frgtErr = response.STATUS_MSG;
$("#passwordCheckincorrect")
.text(frgtErr)
.css("color", "red")
.show();
$("#forgot-MobileNumber").val("");
$("#code").val("");
$(".submit-button").attr("disabled", "disabled");
setTimeout(function() {
$("#forgot-MobileNumber").val("");
$("#code").val("");
$("#passwordCheckincorrect")
.text(frgtErr)
.css("color", "red")
.hide();
}, 3000);
}
}
});
}
function deleteAllCookies() {
var cookies = document.cookie.split(";");
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i];
var eqPos = cookie.indexOf("=");
var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/";
}
}
function getCountryCode() {
var dialingCodeOptions = "<option value=''>Country Code</option>";
for (let i = 0; i < dialingCodes.length; i++) {
let code = dialingCodes[i].code;
let Country = dialingCodes[i].Country;
dialingCodeOptions +=
"<option value='" + code + "'>" + code + " - " + Country + "</option>";
}
document.getElementById("code").innerHTML = dialingCodeOptions;
document.getElementById("mobilecode").innerHTML = dialingCodeOptions;
$("option[value='+91']").remove();
}
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + exdays * 24 * 60 * 60 * 1000);
var expires = "expires=" + d.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
|
import VenusAtmosphere from "./VenusAtmosphere.js";
class Venus {
constructor() {
const geom = new THREE.SphereGeometry(0.86, 40, 40);
this.atmosphere = new VenusAtmosphere();
const mat = new THREE.MeshPhongMaterial({
map: new THREE.TextureLoader().load("./assets/img/venus_surface.jpg")
});
this.mesh = new THREE.Mesh(geom, mat);
this.mesh.add(this.atmosphere.mesh);
}
animate() {
this.atmosphere.moveAtmosphere();
this.mesh.rotation.y -= 0.0004;
let date = Date.now() * -0.00000016;
this.mesh.position.set(Math.cos(date) * 400, 0, Math.sin(date) * 400);
}
}
export default Venus;
|
/**
* Created by xuwusheng on 16/1/27.
*/
define(['../app'], function (app) {
app.directive('topMenu', [function () {
return {
restrict:'EA',
replace:true,
transclude:true,
template:'<div ng-transclude></div>',
link: function ($scope,el,attr) {
$('.ui-view-container').height($(window).height()-$('.top-right').height());
$(el).on('click', function () {
$(this).addClass('hover').siblings().removeClass('hover');
});
}
}
}]);
});
|
import React from 'react';
import { connect } from 'react-redux';
import { Redirect } from 'react-router-dom';
import { login } from './actions';
import Login from './Login';
class LoginPage extends React.Component {
state = {
redirect: false
}
login = ({email, password}) => {
return this.props.login({ email, password }).then(
() => { this.setState({ redirect: true })},
);
}
render() {
return (
<div>
{
this.state.redirect ?
<Redirect to={`/user/${this.props.user._id}`} /> :
<Login
login={this.login}
/>
}
</div>
);
}
}
function mapStateToProps(state, props) {
return { user: state.user };
}
export default connect(mapStateToProps, { login })(LoginPage);
|
'use strict';
module.exports = function (tblcard_static) {
};
|
import React from 'react';
import s from './ProfileInfo.module.css';
import Preloader from '../../common/preloader/Preloader';
import ProfileData from './ProfileData';
const ProfileInfo = (props) =>
{
if (!props.profile) {
return <Preloader />
}
return (
<div className={s.descriptionBlock}>
<ProfileData isOwner={props.isOwner} profile={props.profile}
showAboutMe={false} unfollow={props.unfollow}
follow={props.follow} isFollowed={props.isFollowed}
followingInProgress={props.followingInProgress}/>
</div>
);
}
export default ProfileInfo;
|
//
//= require authorization
//= require cable_consumer
//= require_tree ./channels
|
import Orientation from 'react-native-orientation';
import React, { Component } from 'react';
import { StyleSheet,BackHandler } from 'react-native';
import { Container,Button,Title,Content,Header, View,Text, Left, Body, Icon } from 'native-base';
import QRCodeScanner from 'react-native-qrcode-scanner';
import { PermissionsAndroid } from 'react-native';
//same as QR page just the backhandler is different from accessing from sidebar and QRmooze footer
export default class QR33 extends Component {
onSuccess(e) {
// alert(e.data);
this.props.navigation.navigate('TabloPage',{ name: e.data});
}
// async UNSAFE_componentWillMount() {
// try {
// const granted = await PermissionsAndroid.request(
// PermissionsAndroid.PERMISSIONS.CAMERA,
// {
// 'title': 'Cool Photo App Camera Permission',
// 'message': 'Cool Photo App needs access to your camera ' +
// 'so you can take awesome pictures.'
// }
// )
// if (granted === PermissionsAndroid.RESULTS.GRANTED) {
// console.warn("You can use the camera")
// } else {
// console.warn("Camera permission denied")
// }
// } catch (err) {
// console.warn(err)
// }
componentDidMount() {
Orientation.lockToPortrait();
this.forceUpdate();
}
componentWillMount() {
this.backHandler = BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.navigate('Homeindex');
return true;
});
}
componentWillUnmount() {
this.backHandler.remove();
}
render() {
return (
<Container>
<Header>
<Left>
<Button
transparent
onPress={() => {
this.props.navigation.openDrawer()}}
>
<Icon name="menu" />
</Button>
</Left>
<Body style = {{
justifyContent: "flex-end",
alignItems: "flex-end"}}>
<Title>QR</Title>
</Body>
</Header>
<View style={{flex : 1}}>
<QRCodeScanner
fadeIn={false}
reactivate={true}
reactivateTimeout={2000}
showMarker={true}
onRead={this.onSuccess.bind(this)}
topContent={
<Text style={styles.centerText}>
<Text style={styles.textBold}>اسکن کنید !</Text>
</Text>
}
bottomContent={
<Content>
<Left>
<Icon name="md-qr-scanner" />
</Left>
<Body>
<Text>
به سمت کد بگیرید
</Text>
</Body>
</Content>
}
/>
</View>
</Container>
);
}
}
const styles = StyleSheet.create({
centerText: {
flex: 1,
fontSize: 18,
padding: 32,
color: '#777',
},
textBold: {
fontWeight: '500',
color: '#000',
},
buttonText: {
fontSize: 21,
color: 'rgb(0,122,255)',
},
buttonTouchable: {
padding: 16,
},
});
|
/**
* Created by sgupta on 6/18/16.
*/
angular.module('oms.interceptors.soa',['ngStorage'])
.config(['$httpProvider',function($httpProvider) {
var interceptor = ['$q','$sessionStorage',function($q,$sessionStorage) {
return {
'request':function(config) {
// if((config.url.indexOf('/v1/turnUp/update') >= 0)){
// config.params.dataSource = "SOA1"
// }
// if((config.url.indexOf('/soa') >= 0
// || config.url.indexOf('/v1/turnUp/update') >= 0
// || config.url.indexOf('/v1/turnUp/removeCustomerInfo') >= 0
// || config.url.indexOf('/v1/turnUp/loadCustomerInfoToRemoved') >= 0)
// && config.url.indexOf('.html') < 0) {
// config.params = config.params || {};
// if($sessionStorage.currentDataSource) {
// config.params.dataSource = $sessionStorage.currentDataSource.toUpperCase();
// }
// }
return config;
}
}
}];
$httpProvider.interceptors.push(interceptor);
}]);
|
import React, { Component } from "react";
import { NavLink, Route } from "react-router-dom";
import "./App.css";
class App extends Component {
render() {
return (
<div className="App">
<NavLink to="/register">Sign Up</NavLink>
<NavLink to="/login">Sign In</NavLink>
<NavLink to="/jokes">Dad Jokes!</NavLink>
<Route path="" />
</div>
);
}
}
export default App;
|
var agregarTarea = function(){
var lista = document.getElementById("lista"),
tarea = document.getElementById("tareaA"),
nuevaTarea = document.getElementById("boton");
var tarea = tareaA.value;
var nuevaTarea = document.createElement("div");
var contenido = document.createTextNode(tarea);
var icono = document.createElement("span");
icono.setAttribute("id","icon"),
icono.setAttribute("class","glyphicon glyphicon-trash");
icono.addEventListener("click", eliminarRegistro);
//icono.onclick(eliminarRegistro);
if (tarea === "") {
alert("Ingresar una tarea");
}
else{
nuevaTarea.appendChild(contenido);
nuevaTarea.appendChild(icono);
lista.appendChild(nuevaTarea);
tareaA.value = "";
for (var i = 0; i <= lista.children.length -1; i++) {
lista.children[i].addEventListener("click", function(){
this.parentNode.removeChild(this);
});
}
}
}
function eliminarTodo(){
lista.innerHTML = "";
}
var eliminarRegistro = function(){
this.parentNode.removeChild(this);
};
|
import {
MESSAGES_LOADED_SUCCESS,
MESSAGES_LOAD,
MESSAGE_LOAD,
MESSAGES_LOAD_FAIL,
MESSAGE_INFO_LOADED_SUCCESS,
MESSAGE_INFO_LOADING_FAIL,
MESSAGE_COUNTER_SUCCESS,
} from './types';
import {
SECRET_KEY,
DEVICE_OS,
MESSAGES_LOADING_URL,
MESSAGE_LOADING_URL,
} from './constants';
import axios from 'axios';
import md5 from 'js-md5';
let MSG_LIMIT = 100;
export const loadMessages = (token, offset = 0) => {
return dispatch => {
dispatch({
type: MESSAGES_LOAD,
});
const data = {
token: token,
limit: MSG_LIMIT,
offset: offset,
};
axios
.post(MESSAGES_LOADING_URL, data)
.then(messages => {
console.log('messages loaded success', messages);
let messagesAraay = [];
for (var message in messages.data.data) {
messagesAraay.push({
id: message,
title: messages.data.data[message],
});
}
onMessagesLoaded(dispatch, messagesAraay, offset);
})
.catch(error => {
console.log(error);
});
};
};
const onMessagesLoaded = (dispatch, messages, offset) => {
console.log(messages);
dispatch({
type: MESSAGES_LOADED_SUCCESS,
payload: messages,
offset: offset,
});
};
/* GET MESSAGE TEXT*/
export const getMessage = (token, messageId) => {
return dispatch => {
dispatch({
type: MESSAGE_LOAD,
});
const data = {
token: token,
message_id: messageId,
};
axios
.post(MESSAGE_LOADING_URL, data)
.then(message => {
console.log('message info loaded success', message);
onMessageInfoLoaded(dispatch, message.data);
})
.catch(error => {
console.log(error);
});
};
};
const onMessageInfoLoaded = (dispatch, message) => {
if (message.error == 0) {
dispatch({
type: MESSAGE_INFO_LOADED_SUCCESS,
payload: message.data,
});
} else {
var errorText = 'Сбой при загрузке сообщения';
if (message.error == 4) {
errorText = 'Сообщение не найдено';
}
dispatch({
type: MESSAGE_INFO_LOADING_FAIL,
payload: errorText,
});
}
};
export const countMessages = (token, offset = 0) => {
return dispatch => {
const data = {
token: token,
limit: MSG_LIMIT,
offset: offset,
only_not_views: 1,
};
axios
.post(MESSAGES_LOADING_URL, data)
.then(messages => {
onMessageCountLoaded(dispatch, messages.data);
})
.catch(error => {
console.log(error);
});
};
};
const onMessageCountLoaded = (dispatch, messages) => {
var counter = 0;
if (messages.error == 0 && messages.data) {
counter = messages.data.length;
}
dispatch({
type: MESSAGE_COUNTER_SUCCESS,
payload: counter,
});
};
|
/* eslint-env browser */ /*- global SVGAnim */
import SVGAnim from '@artdeco/snapsvg-animator'
// const json = require('./menu.json')
const menuContainer = document.getElementById('menu')
const width = 1226
const height = 818
const assignListeners = () => {
setTimeout(() => {
const about = menuContainer.querySelector('svg > g > g[token="4"]')
const node = menuContainer.querySelector('svg > g > g[token="3"]')
const packages = menuContainer.querySelector('svg > g > g[token="2"]')
const contact = menuContainer.querySelector('svg > g > g[token="1"]')
assignLink(about, 'about')
assignLink(node, 'node')
assignLink(packages, 'packages')
assignLink(contact, 'contact')
}, 100)
}
var jsonfile = 'js/menu.json'
let AJAX_req
AJAX_JSON_Req(jsonfile)
function handle_AJAX_Complete() {
const json = JSON.parse(AJAX_req.responseText)
const comp = new SVGAnim(json, width, height)
menuContainer.appendChild(comp.s.node)
assignListeners()
}
// if (AJAX_req.readyState == 4 && AJAX_req.status == 200) {
// var json = JSON.parse(AJAX_req.responseText)
// var comp = new SVGAnim(json, width, height, fps)
// menuContainer.appendChild(comp.s.node)
// setTimeout(function () {
// var about = menuContainer.querySelector('svg > g > g[token="4"]')
// var node = menuContainer.querySelector('svg > g > g[token="3"]')
// var packages = menuContainer.querySelector('svg > g > g[token="2"]')
// var contact = menuContainer.querySelector('svg > g > g[token="1"]')
// assignLink(about, 'about')
// assignLink(node, 'node')
// assignLink(packages, 'packages')
// assignLink(contact, 'contact')
// }, 100)
// }
// }
function assignLink(target, name) {
target.onclick = function () {
window.location = '#' + name
}
}
function AJAX_JSON_Req(url) {
AJAX_req = new XMLHttpRequest()
AJAX_req.open('GET', url, true)
AJAX_req.setRequestHeader('Content-type', 'application/json')
AJAX_req.onreadystatechange = handle_AJAX_Complete
AJAX_req.send()
}
|
import React from 'react';
import PropTypes from 'prop-types';
const ResultList = props => {
const { projects } = props;
return projects.map(value => (
<table key={value.projectId}>
<tbody>
<tr>
<th>Project Name</th>
<th>Project Description</th>
<th>Job Number</th>
<th>Project Type</th>
<th>Language</th>
</tr>
<tr>
<td>{value.name}</td>
<td>{value.description}</td>
<td>{value.jobNumber}</td>
<td>{value.type}</td>
<td>{value.language}</td>
</tr>
</tbody>
</table>
));
};
ResultList.defaultProps = {
projects: [],
};
ResultList.propTypes = {
projects: PropTypes.instanceOf(Array),
};
export default ResultList;
|
var express = require('express');
var router = express.Router();
var adminFunc = require('../../controllers/admin');
router
.post('/signup', adminFunc.signup)
.post('/login', adminFunc.login);
module.exports = router;
|
// Safe IIFE
(function(global, $) {
//
// Return a new empty object
const Greetr = function(firstName, lastName, language) {
return new Greetr.init(firstName, lastName, language);
};
// Hidden withing the IIFE and never directly accessible
const supportedLangs = ["en", "es", "fi"];
// Informal greetings
const greetings = {
en: "Hello",
es: "Hola",
fi: "Hei"
};
// Formal greetings
const formalGreetings = {
en: "Greetings",
es: "Saludos",
fi: "Tervehdys"
};
// Logger messages
const logMessages = {
en: "Logged in",
es: "Inició sesión",
fi: "Kirjautui sisään"
};
// Prototype holds all the methods to save memory
Greetr.prototype = {
fullName() {
return `${this.firstName} ${this.lastName}`;
},
validate() {
// Check if language is supported
if (supportedLangs.indexOf(this.language) === -1) {
throw "Invalid language";
}
},
greeting() {
return `${greetings[this.language]}, ${this.firstName}`;
},
formalGreeting() {
return `${formalGreetings[this.language]}, ${this.fullName()}`;
},
// The actual function that is called
greet(formal) {
let msg;
if (formal) {
msg = this.formalGreeting();
} else {
msg = this.greeting();
}
if (console) {
console.log(msg);
}
// After execution, refers back to the parent object
// making the commands chainable
return this;
},
log: function() {
if (console) {
console.log(`${logMessages[this.language]}: ${this.fullName()}`);
}
return this;
},
setLang: function(lang) {
this.language = lang;
this.validate();
return this;
},
HTMLGreeting(selector, formal) {
if (!$) throw "jQuery not loaded";
if (!selector) throw "Missing jQuery selector";
let msg;
if (formal) {
msg = this.formalGreeting();
} else {
msg = this.greeting();
}
$(selector).html(msg);
return this;
}
};
// The actual object being created, allowing
// us to return a new object from it
Greetr.init = function(
// Set the default values
firstName = "John",
lastName = "Doe",
language = "en"
) {
this.firstName = firstName;
this.lastName = lastName;
this.language = language;
// Validate the language
this.validate();
};
// Give access to all the methods
Greetr.init.prototype = Greetr.prototype;
// Expose, attach to the global object
// can be called via either 'Greetr' or 'G$'
global.Greetr = global.G$ = Greetr;
//
// Takes the global object and the selector
// library as parameters
// eslint-disable-next-line no-undef
})(window, jQuery);
// End of IIFE
|
// https://www.sanwebe.com/2014/08/css-html-forms-designs
import React from 'react';
//import useForm from '../hooks/useForm';
import useForm from '../hooks/useForm';
const initialValues = {
name: '',
email: '',
comment: '',
};
// const Api = useFetch('https://jsonplaceholder.typicode.com/users');
const AddComment = ({ addForm }) => {
const { values, handleChange, handleSubmit } = useForm(initialValues, addForm);
// const addForm = () => {
// console.log(values);
// };
// const { values, handleChange, handleSubmit } = useForm(initialValues, addForm);
// function addForm() {
// console.log(values);
// Api.post({
// values: values,
// })
// .then(data => {
// console.log('data-->', data);
// })
// .catch(err => {
// console.log('err', err);
// throw new err();
// });
// }
return (
<>
<div className="form-style-2">
<div className="form-style-2-heading">Provide your information</div>
<form onSubmit={handleSubmit} autoComplete="off">
<>
<label htmlFor="name">
<span>
Name <span className="required">*</span>
</span>
<input
type="text"
className="input-field"
name="name"
value={values.name}
onChange={handleChange}
required
/>
</label>
</>
<>
<label htmlFor="email">
<span>
Email <span className="required">*</span>
</span>
<input
type="text"
className="input-field"
name="email"
value={values.email}
onChange={handleChange}
required
/>
</label>
</>
<>
<label htmlFor="field5">
<span>
Message <span className="required">*</span>
</span>
<textarea
className="textarea-field"
name="comment"
value={values.comment}
onChange={handleChange}
required
/>
</label>
</>
<>
<label>
<span> </span>
<input type="submit" value="Submit" />
</label>
</>
</form>
</div>
</>
);
};
export default AddComment;
// import React from 'react';
// const AddComment = props => {
// const { addComment, newComment, setNewComment } = props;
// // onChangeHandler = e => {
// // setnewComment({ ...props, [e.target.name]: e.target.value });
// // };
// formSubmit = event => {
// event.preventDefault();
// console.log('Form Submit 👏🏻');
// addComment();
// };
// return (
// <>
// {/* <form>
// <input
// type="text"
// className="form-control"
// value={newTask}
// placeholder="Enter your name"
// onChange={event => setNewTask(event.target.value)}
// />
// <input
// type="email"
// className="form-control"
// value={newTask}
// placeholder="Enter your emailid"
// onChange={event => setNewTask(event.target.value)}
// />
// </form> */}
// {/* <textarea rows="4" cols="50" /> */}
// <form onSubmit={formSubmit}>
// <input
// type="text"
// name="name"
// placeholder="Enter your name"
// value={newComment}
// onChange={event => setNewComment(event.target.value)}
// />
// <input
// type="email"
// name="email"
// placeholder="Enter your emailid"
// value={newComment}
// onChange={event => setNewComment(event.target.value)}
// />
// <button>Submit</button>
// </form>
// </>
// );
// };
// export default AddComment;
|
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import { useSelector } from 'react-redux';
// Components
import Home from './containers/Home/Home';
import Products from './containers/Products/Products';
import Show from './containers/Show/Show';
import Cart from './containers/Cart/Cart';
import Shipping from './containers/Shipping/Shipping';
import Payment from './containers/Payment/Payment';
import Finish from './containers/Finish/Finish';
import Favorite from './containers/Favorite/Favorite';
import Account from './containers/Account/Accocunt';
import Admin from './containers/Admin/Admin';
import ProductReviews from './containers/ProductReviews/ProductReviews';
import Contact from './containers/Contact/Contact';
import Orders from './containers/Orders/Orders';
import Order from './containers/Order/Order';
import NotFound from './containers/NotFound/NotFound';
import Sale from './containers/Sale/Sale';
import AdminEdit from './containers/AdminEdit/AdminEdit';
import LoginPrompt from './containers/LoginPrompt/LoginPrompt';
import Footer from './components/Footer/Footer';
import Header from './components/Header/Header';
function App() {
// Protected route
const ProtectedRoute = ({ component, exact, path }) => {
const isLogged = useSelector((state) => state.isLogged);
return (
<>
{isLogged ? (
<Route path={path} exact={exact} component={component} />
) : (
<Route path={path} exact={exact} component={LoginPrompt} />
)}
</>
);
};
// Admin route
const AdminRoute = ({ component, exact, path }) => {
const isLogged = useSelector((state) => state.isLogged);
const userRole = useSelector((state) => state.userRole);
return (
<>
{isLogged && userRole === 'ADMIN' ? (
<Route path={path} exact={exact} component={component} />
) : (
<Route path={path} exact={exact} component={NotFound} />
)}
</>
);
};
// Checkout route
const CheckoutRoute = ({ component, exact, path }) => {
const allowCheckout = useSelector((state) => state.allowCheckout);
return (
<>
{allowCheckout ? (
<Route path={path} exact={exact} component={component} />
) : (
<NotFound />
)}
</>
);
};
// Payment route
const PaymentRoute = ({ component, exact, path }) => {
const allowPayment = useSelector((state) => state.allowPayment);
return (
<>
{allowPayment ? (
<Route path={path} exact={exact} component={component} />
) : (
<NotFound />
)}
</>
);
};
// Finish route
const FinishRoute = ({ component, exact, path }) => {
const allowFinish = useSelector((state) => state.allowFinish);
return (
<>
{allowFinish ? (
<Route path={path} exact={exact} component={component} />
) : (
<NotFound />
)}
</>
);
};
return (
<Router>
<Header />
<Switch>
<AdminRoute path='/admin' exact={true} component={Admin} />
<AdminRoute path='/edit/:product' exact={true} component={AdminEdit} />
<ProtectedRoute path='/my-account' exact={true} component={Account} />
<ProtectedRoute path='/favorite' exact={true} component={Favorite} />
<ProtectedRoute
path='/my-account/orders'
exact={true}
component={Orders}
/>
<ProtectedRoute
path='/my-account/order/:id'
exact={true}
component={Order}
/>
<CheckoutRoute
path='/checkout/shipping-information'
exact={true}
component={Shipping}
/>
<PaymentRoute
path='/checkout/order-payment'
exact={true}
component={Payment}
/>
<FinishRoute path='/finish-order' exact={true} component={Finish} />
<Route path='/' exact component={Home} />
<Route path='/category/:category' exact component={Products} />
<Route path='/product/:title' exact component={Show} />
<Route path='/cart' component={Cart} />
<Route
path='/products/phones/:title/reviews'
component={ProductReviews}
/>
<Route path='/contact-us' component={Contact} />
<Route path='/sale/:title' exact component={Sale} />
<Route path='*' component={NotFound} />
</Switch>
<Footer />
</Router>
);
}
export default App;
|
import Vue from 'vue';
import Router from 'vue-router';
import Home from '../pages/Home'
import Res from '../pages/Res.vue'
import ResDetail from '../components/ResDetail'
Vue.use(Router)
var router = new Router({
mode:'history',
routes: [
{
path:'/',
component:Home
},
{
path:'/home',
component:Home
},
{
path: '/home/resinfo/:id',
component: Res
},
{
path:'/home/resinfo/:id/detail',
component:ResDetail
},
]
});
export default router;
|
/**
* @param {number} N
* @return {number}
*/
var monotoneIncreasingDigits = function(N) {
var str = String(N);
str = str.split('');
var n = str.length, j = n;
for (var i = n-1; i>0; i--) {
if(str[i] >=str[i-1]) continue;
--str[i-1];
j = i;
}
for(var i = j; i<n; i++) {
str[i] = '9';
}
return parseInt(str.join(''));
};
console.log(monotoneIncreasingDigits(322));
console.log(monotoneIncreasingDigits(1234));
|
import React from 'react';
import { connect } from 'react-redux';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { setFilter, initializeMOBrowser, dismissMOsFetchError } from './mobrowser-actions';
import './mo-panel.css';
import { addTab } from '../layout/uilayout-actions';
import { Classes, Icon, ITreeNode, Tooltip, Tree, FormGroup, InputGroup, ProgressBar, Intent } from "@blueprintjs/core";
/**
* MO Browser Panel
*
* Displays a list of managed objects for a selected vendor and technology
*/
class MOBrowserPanel extends React.Component{
static icon = "puzzle-piece";
static label = "";
constructor(props){
super(props);
this.selectVendor = this.selectVendor.bind(this);
// this.selectTechnology = this.selectTechnology.bind(this);
this.changeEvent = this.changeEvent.bind(this);
this.updateFilter = this.updateFilter.bind(this);
this.dismissError = this.dismissError.bind(this);
this.reload = this.reload.bind(this);
this.rightClick = this.rightClick.bind(this);
this.onNodeDoubleClick = this.onNodeDoubleClick.bind(this);
this.updateTreeNodes = this.updateTreeNodes.bind(this);
this.text = this.props.filter.text;
this.technology = this.props.filter.technology;
this.vendor = this.props.filter.vendor;
this.treeNodes = []
}
componentDidMount(){
//Initialize if this is the fast time or if it as refresh
if (this.props.mos['Ericsson'].length === 0){
this.props.dispatch(initializeMOBrowser());
}
}
rightClick(info){
}
onNodeDoubleClick = (nodeData) => {
this.showMODataTab(nodeData.label, nodeData.vendorName );
}
showMODataTab(moName, vendorName){
let tabId = moName + '_' + vendorName + "_Tab";
this.props.dispatch(addTab(tabId, 'MODataBrowser', {
title: moName,
moName: moName,
vendorName: vendorName
}));
}
reload(){
this.props.dispatch(initializeMOBrowser());
}
updateFilter(){
this.props.dispatch(setFilter(this.text, this.vendor, this.technology));
}
changeEvent(e){
this.text = e.target.value;
this.updateFilter();
}
selectVendor(e){
this.vendor = e.target.value;
this.updateFilter();
}
dismissError(){
this.props.dispatch(dismissMOsFetchError());
}
updateTreeNodes(){
this.treeNodes = []
const vendorKey = this.props.filter.vendor;
const filterText = this.props.filter.text;
for(let vtKey in this.props.mos[vendorKey]){
let node = this.props.mos[vendorKey][vtKey]
if(filterText != ''){
var regex = new RegExp(filterText, 'i');
if ( !regex.test(node.name) ) continue;
}
this.treeNodes.push({
icon: <FontAwesomeIcon className="mb-2" icon="puzzle-piece" className="mb-0"/>,
id: node.pk,
moId: node.pk,
vendorName: vendorKey,
label: node.name
});
}
}
render(){
this.updateTreeNodes()
return (
<div>
<h6><FontAwesomeIcon icon={MOBrowserPanel.icon}/> MO Browser</h6>
<div>
<input type="text" className="form-control form-control-sm mb-1" placeholder="Search MO" aria-label="Search MO" aria-describedby="search-mo" value={this.props.filter.text} onChange={this.changeEvent}/>
<div className="row">
<div className="col-sm-4">Vendor</div>
<div className="col-sm-8">
<select className="form-control form-control-sm mb-1" value={this.props.filter.vendor} onChange={this.selectVendor} >
<option disabled>--Vendors--</option>
{this.props.vendors.map((v,k) => <option value={v} key={v}>{v}</option> )}
</select>
</div>
</div>
{this.props.fetchingMOs === false ? '':
<div className="pb-1">
<ProgressBar intent={Intent.PRIMARY}/>
</div>
}
{this.props.fetchError === null ? '':
<div className="alert alert-danger" role="alert">
{this.props.fetchError}
<button type="button" className="close" aria-label="Close" onClick={this.dismissError}>
<span aria-hidden="true">×</span>
</button>
</div>
}
<Tree className="mo-browser-tree"
contents={this.treeNodes}
onNodeDoubleClick={this.onNodeDoubleClick}
/>
</div>
</div>
);
}
}
function mapStateToProps(state){
return {
vendors: state.mobrowser.vendors,
filter: state.mobrowser.filter,
mos: state.mobrowser.mos,
fetchingMOs: state.mobrowser.fetchingMOs,
fetchError: state.mobrowser.fetchError
};
}
export default connect(mapStateToProps)(MOBrowserPanel);
|
'use strict'
const Event = use('Event')
const Mail = use('Mail')
Event.on('forgot::password', async (data) => {
await Mail.send('auth.emails.password_reset', data, (message) => {
message
.to(data.user.email)
.from('hello@podcast.com')
.subject('Password reset link')
})
})
Event.on('password::reset', async (data) => {
await Mail.send('auth.emails.password_reset_success', data, (message) => {
message
.to(data.user.email)
.from('hello@podcast.com')
.subject('Password reset successful')
})
})
Event.on('new::episode', async (data) => {
await Mail.send('emails.new_episode', data, (message) => {
data.subscribers.forEach(subscriber => {
message
.to(subscriber.email)
.from('hello@podcast.com')
.subject('New podcast episode')
})
})
})
|
export const RESET_ERROR = "RESET_ERROR";
export const USER_LOGIN_REQUEST = "USER_LOGIN_REQUEST";
export const USER_LOGIN_SUCCESS = "USER_LOGIN_SUCCESS";
export const USER_LOGIN_FAILURE = "USER_LOGIN_FAILURE";
export const USER_LOGOUT = "USER_LOGOUT";
|
angular.module('sxroApp')
.factory('PlatesInspectionFactory', function($http, $rootScope) {
return {
allPlatesExceptInstack: function() {
return $http.get($rootScope.baseUrl + 'allplatesexceptinstack');
},
containersWithSlotsAvailable: function() {
return $http.get($rootScope.baseUrl + 'containerswithslotsavailable');
},
availableSlotsInContainer: function(data) {
return $http.get($rootScope.baseUrl + 'availableslotsincontainer/' + data.id);
},
inspectionUpdate: function(inspectionData) {
return $http({
url: $rootScope.baseUrl + 'plateinspection',
method: 'PUT',
data: inspectionData
});
}
};
});
|
var express = require('express');
var router = express.Router();
var restaurantsController = require('../controllers/restaurantsController');
/* ADD RESTAURANT */
router.post('/', restaurantsController.addRestaurant);
/* SHOW RESTAURANTS */
router.get('/', restaurantsController.showRestaurants);
/* DELETE RESTAURANT */
router.delete('/:restaurantId', restaurantsController.deleteRestaurant);
/* UPDATE RESTAURANT */
router.put('/:restaurantId', restaurantsController.updateRestaurant);
/* FIND 1 RESTAURANT */
router.get('/:restaurantId', restaurantsController.findRestaurant)
/* RELEASE 3 */
router.post('/addmenu', restaurantsController.addMenu);
router.get('/showmenu', restaurantsController.showMenu);
module.exports = router;
|
({
jsLoaded: function(component, event, helper) {
console.log('canvas ready to go');
},
handleClick : function(cmp, event) {
var instructions = [{name: "publisher.selectAction", payload: {actionName:"Case.Email"}},
];
console.log(Sfdc)
Sfdc.canvas.publisher.publish(instructions);
}
})
|
/*
* AST Mail Sender Helper
*
* Copyright 2015 Astralink Technology
*
* Version 2.3
* Release date - 2015-05-12
* Released by - Fong Shi Wei
*
* Change Log
* ----------
*
*/
var config = _require('/config/webConfig');
var mailSendingConfig = config.mailConfig();
var sendgridKey = mailSendingConfig.sendGridApiKey;
var async = require('async');
var sendgrid = require('sendgrid')(sendgridKey);
var apiHelper = _require('/helpers/api');
exports.sendMail = function(
req
, res
, htmlContent
, text
, subject
, mailinglist
, importantMessage
, replyTo
, from
, fromName
, callback
){
var error = null;
var errorCode = null;
var errorDesc = null;
if (!fromName) fromName = mailSendingConfig.fromName;
if (!from) from = mailSendingConfig.from;
if (mailinglist && _.isArray(mailinglist) && !_.isEmpty(mailinglist)){
async.eachSeries(mailinglist, function(mailTo, sendMailCallback){
var receiverEmail = mailTo.email;
var receiverName = mailTo.name;
if (receiverEmail && receiverName && subject){
var mailObject = new Object();
mailObject.to = receiverEmail;
mailObject.toname = receiverName;
mailObject.from = from;
mailObject.fromname = fromName;
mailObject.subject = subject;
if (fromName) mailObject.fromname = fromName;
if (replyTo) mailObject.replyto = replyTo;
if (text) mailObject.text = text;
if (htmlContent) mailObject.html = htmlContent;
var email = new sendgrid.Email(mailObject);
sendgrid.send(email, function(err, json) {
if (!err){
sendMailCallback();
}else{
sendMailCallback(err);
}
});
}else{
sendMailCallback("Parameters required");
}
}, function(err){
if (!err){
apiHelper.apiResponse(req, res, null, null, null, null, true, null, callback);
}else{
error = true;
errorCode = 500;
errorDesc = err;
apiHelper.apiResponse(req, res, error, errorCode, errorDesc, null, null, null, callback);
}
});
}else{
error = true;
errorCode = 500;
errorDesc = "Parameters required";
apiHelper.apiResponse(req, res, error, errorCode, errorDesc, null, null, null, callback);
}
}
|
import ifElse from "crocks/logic/ifElse"
import isString from "crocks/predicates/isString"
const reverse = ifElse(
isString,
s =>
s
.split("")
.reverse()
.join(""),
xs => Array.prototype.slice.call(xs, 0).reverse()
)
export default reverse
|
import React from 'react';
import echarts from 'echarts';
class Bar extends React.Component{
componentDidMount(){
this.init()
}
init(){
const myCharts = echarts.init(document.getElementById('main2'))
const option = {
color: ['#3398DB'],
tooltip : {
trigger: 'axis',
axisPointer : { // 坐标轴指示器,坐标轴触发有效
type : 'shadow' // 默认为直线,可选为:'line' | 'shadow'
}
},
grid: {
left: '3%',
right: '4%',
bottom: '3%',
containLabel: true
},
xAxis : [
{
type : 'category',
data : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
axisTick: {
alignWithLabel: true
}
}
],
yAxis : [
{
type : 'value'
}
],
series : [
{
name:'直接访问',
type:'bar',
barWidth: '60%',
itemStyle:{//
normal: {
color: new echarts.graphic.LinearGradient(
0, 0, 0, 1,
[
{offset: 0, color: 'rgba(255,255,255,0)'},
{offset: 0.5, color: '#188df0'},
{offset: 1, color: '#188df0'}
]
)
},
},
data:[
{
value: 100,
itemStyle: {
color: new echarts.graphic.LinearGradient(
0, 0, 0, 1,
[
{offset: 0, color: "#f7798f"},
{offset: 0.5, color: '#f7b9c4'},
{offset: 1, color: '#ef3959'}
]
)
},
},
{
value: 90,
itemStyle:{
color: new echarts.graphic.LinearGradient(
0, 0, 0, 1,
[
{offset: 0, color: '#caefd0'},
{offset: 0.5, color: '#aaf1b5'},
{offset: 1, color: '#0cf31a'}
]
)
}
},
{
value: 10,
itemStyle: {
color: new echarts.graphic.LinearGradient(
0, 0, 0, 1,
[
{offset: 0, color: '#e2c3f3'},
{offset: 0.5, color: '#be64ef'},
{offset: 1, color: '#990ee4'}
]
)
}
},
{
value: 70,
itemStyle: {
color: new echarts.graphic.LinearGradient(
0, 0, 0, 1,
[
{offset: 0, color: '#ebf1b1'},
{offset: 0.5, color: '#e2ef64'},
{offset: 1, color: '#d2e608'}
]
)
}
},
{
value: 60,
itemStyle: {
color: new echarts.graphic.LinearGradient(
0, 0, 0, 1,
[
{offset: 0, color: '#c8f9f4'},
{offset: 0.5, color: '#6aefe2'},
{offset: 1, color: '#0aecd7'}
]
)
}
},
{
value: 40,
itemStyle: {
color: new echarts.graphic.LinearGradient(
0, 0, 0, 1,
[
{offset: 0, color: 'rgba(255,255,255,0)'},
{offset: 0.5, color: '#188df0'},
{offset: 1, color: '#188df0'}
]
)
}
} ,
{
value: 40,
itemStyle: {
color: new echarts.graphic.LinearGradient(
0, 0, 0, 1,
[
{offset: 0, color: '#efd328'},
{offset: 0.5, color: '#f58c6b'},
{offset: 1, color: '#f73b00'}
]
)
}
}
]
}
]
};
myCharts.setOption(option)
}
setOption(){
}
render(){
return (
<div>
{/* <div style={{width: '80px', height:' 50px', background:'pink'}}></div> */}
<div id="main2" style={{width: '400px', height:' 300px'}}></div>
</div>
)
}
}
export default Bar;
|
$('.cls-10').click(function(){
$(this).addClass('active').siblings().removeClass('active')
$(`[data-box=${$(this).data('item')}]`).fadeIn().siblings().hide();
})
|
let arr = []
function generatearr(arr) {
for (let i = 0; i < 1100; i++) {
arr.push(Math.random() * 1100)
}
return arr
}
function max(arr) {
let max = -1000000
let min = 1000000
let median = 0
for (let i = 0; i < arr.length; i++) {
if (max < arr[i]) {
max = arr[i]
}
if (min > arr[i]) {
min = arr[i]
}
}
arr.sort()
if (arr.length % 2 === 0)
median = (arr[arr.length / 2] + arr[arr.length / 2 - 1]) / 2;
else
median = arr[Math.round(arr.length / 2)];
console.log(max, min, median)
}
function swap(items, firstIndex, secondIndex) {
const temp = items[firstIndex];
items[firstIndex] = items[secondIndex];
items[secondIndex] = temp;
}
function partition(items, left, right) {
let pivot = items[Math.floor((right + left) / 2)],
i = left,
j = right;
while (i <= j) {
while (items[i] < pivot) {
i++;
}
while (items[j] > pivot) {
j--;
}
if (i <= j) {
swap(items, i, j);
i++;
j--;
}
}
return i;
}
function quickSort(items, left, right) {
var index;
if (items.length > 1) {
index = partition(items, left, right);
if (left < index - 1) {
quickSort(items, left, index - 1);
}
if (index < right) {
quickSort(items, index, right);
}
}
return items
}
function sortbyQuickSort(items) {
console.log(quickSort(items, 0, items.length - 1))
}
function consists(arr, element) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === element) {
return i
}
}
return -1
}
function count() {
let arr = document.getElementsByTagName('*')
let arr2 = []
let size = []
for (let i = 0; i < arr.length; i++) {
k = consists(arr2, arr[i].tagName.toLowerCase())
if (k !== -1) {
size[k]++
} else {
arr2.push(arr[i].tagName.toLowerCase())
size.push(1)
}
}
for (let i = 0; i < arr2.length; i++) {
console.log(arr2[i], " - ", size[i])
}
}
arr = generatearr(arr)
sortbyQuickSort(arr)
max(arr)
|
import React from 'react';
import PropTypes from 'prop-types';
import * as S from './styles';
const ErrorLabel = ({ text, action }) => (
<S.ErrorLabel>
<S.ErrorLabel.Text>{text}</S.ErrorLabel.Text>
{action && <S.ErrorLabel.Action onClick={action} />}
</S.ErrorLabel>
);
ErrorLabel.defaultProps = {
action: null,
};
ErrorLabel.propTypes = {
text: PropTypes.string.isRequired,
action: PropTypes.func,
};
export default ErrorLabel;
|
/*global module*/
const webpack = require('webpack');
const path = require('path');
const glob = require('glob');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var entryMap = getEntrys();
module.exports = env => {
var isProdEnv = env && env.prod;
return {
entry: entryMap,
resolve: {
modules: [
'./todolist/scripts',
'node_modules'
],
alias: {
'vue': isProdEnv ? 'vue/dist/vue.min' : 'vue/dist/vue'
}
},
resolveLoader: {
alias: {
'text': 'text-loader'
}
},
amd: {
$: true,
jQuery: true
},
externals: {
jquery: 'jQuery'
},
module: {
rules: [{
test: /\.html$/,
loader: 'text-loader'
}, {
test: /\.css$/,
loader: 'style-loader!css-loader'
}, {
test: /\.vue$/,
loader: 'vue-loader'
}, {
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader',
options: {
plugins: ['syntax-dynamic-import']
}
}
}]
},
devtool: isProdEnv ? 'hidden-source-map' : 'source-map',
plugins: isProdEnv ?
[new UglifyJsPlugin({
parallel: true,
cache: path.resolve(__dirname, './.tmp/jscache2'),
uglifyOptions: {
compress: {
drop_console: true
}
}
})]:
undefined
,
output: {
path: path.resolve(__dirname, './todolist/scripts/dist'),
filename: '[name].js',
// Tells webpack to include comments in bundles with information about the contained modules
pathinfo: isProdEnv ? false : true
}
};
};
/**
* [getEntrys 获取入口文件]
* @return {Object} [入口名称及路径]
*/
function getEntrys() {
var rootPath = './todolist/scripts/source/';
var entry = {};
var files = glob.sync('./todolist/scripts/source/**/*Main.js');
files.forEach(function(item, index) {
entry[item.substring(rootPath.length, item.lastIndexOf('.js'))] = item;
});
return entry;
}
|
'use strict';
const response = require('../res');
const connection = require('../conn');
exports.listKritik = function(req, res) {
connection.query('SELECT * FROM v_kritikdansaran', function (error, rows, fields){
if(error){
console.log(error)
} else{
response.ok(rows, res)
}
});
};
exports.lisKritikbkd = function(req, res) {
var bkdId = req.params.bkdId;
connection.query('SELECT * FROM v_kritikdansaran where idbkd = ?',
[ bkdId ],
function (error, rows, fields){
if(error){
console.log(error)
} else{
response.ok(rows, res)
}
});
};
exports.createKritik = function(req, res) {
const idBkd = req.body.idBkd;
const kritiksaran = req.body.kritiksaran;
const user = req.body.user;
const avatar = req.body.avatar;
connection.query('INSERT INTO kritikdansaran (idbkd, kritiksaran, user, avatar) values (?,?,?,?)',
[ idBkd, kritiksaran, user, avatar ],
function (error, rows, fields){
if(error){
console.log(error)
} else{
response.ok("Berhasil menambahkan kritik saran", res)
}
});
};
|
import {GET_CATEGORY_LIST} from '../action_types'
const initState = []
export default function(perState=initState,action){
const {type,data} = action
let newState
switch (type) {
case GET_CATEGORY_LIST:
newState = [...data.reverse()]
return newState
default:
return perState
}
}
|
export { default } from './BtnBox5.js'
|
import React, { useState, useEffect } from "react";
import { NavLink, Link } from "react-router-dom";
import SearchPanel from "../SearchPanel/SearchPanel";
import AuthForm from "../AuthForm/AuthForm";
import MessageForm from "../MessageForm/MessageForm";
import "../../App.css";
import "./style.css";
const Header = props => {
const [openAuth, setOpenAuth] = useState(false);
const [openMes, setOpenMes] = useState(false);
const handleAuthOpen = () => {
setOpenAuth(true);
};
const checkLogin = () => {
if (!props.login) {
setOpenAuth(true);
}
};
const handleClose = () => {
setOpenMes(false);
props.resetMesForm();
};
useEffect(() => {
if (props.message || props.error) {
setOpenMes(true);
}
}, [props.message, props.error]);
return (
<header className="header">
<div className="layout-row">
<Link to="/" className="logo">
<div>T-RBT Service</div>
</Link>
<ul className="layout-row li-links lang-links">
<li>EN</li>
<li>|</li>
<li>RU</li>
</ul>
</div>
<div className="layout-row">
<nav>
<ul className="layout-row li-links nav-menu">
<li>
<NavLink to="/catalog" className="nav-link">
Catalog
</NavLink>
</li>
<li>
<NavLink to="/news" className="nav-link">
News
</NavLink>
</li>
<li>
<NavLink
to="/myprofile"
className="nav-link"
onClick={checkLogin}
>
My profile
</NavLink>
</li>
</ul>
</nav>
{!props.login && (
<Link
to="/"
onClick={() => {
handleAuthOpen();
}}
>
Login
</Link>
)}
{!!props.login && (
<div>
<span>You entered as {props.login.subscriber.subsIdent} -> </span>
<Link
to="/"
onClick={() => {
props.logout();
}}
>
Logout
</Link>
</div>
)}
<AuthForm
open={openAuth}
handleClose={() => setOpenAuth(false)}
authorize={props.authorize}
/>
</div>
<SearchPanel searchContent={props.searchContent} />
<MessageForm
open={openMes}
handleClose={handleClose}
message={props.message}
error={props.error}
resetMesForm={props.resetMesForm}
/>
</header>
);
};
export default Header;
|
import React, { Component } from "react";
import PersonListItem from './PersonListItem';
import firebase from '../data/Firebase';
import { Link } from 'react-router-dom';
class PersonList extends Component {
constructor(props) {
super(props);
this.ref = firebase.firestore().collection('People');
this.unsubscribe = null;
this.state = {
people: []
};
}
onCollectionUpdate = (querySnapshot) => {
const persons = [];
querySnapshot.forEach((doc) => {
const { first_name, middle_name, last_name, birth_date, birth_location, married_date, death_date, death_location } = doc.data();
persons.push({
key: doc.id,
doc,
first_name,
middle_name,
last_name,
birth_date,
birth_location,
married_date,
death_date,
death_location,
});
});
this.setState({people: persons});
}
componentDidMount() {
this.unsubscribe = this.ref.onSnapshot(this.onCollectionUpdate);
}
render() {
return (
<div className="container">
<div className="panel panel-default">
<div className="panel-heading">
<h3 className="panel-title">
PEOPLE LIST
</h3>
<div className="panel-body">
<h4><Link to="/create">Add Person</Link></h4>
<div className="panel-body">
{this.state.people.map(person =>
<PersonListItem key={person.key}
firstname={person.first_name}
middlename={person.middle_name}
lastname={person.last_name}
birthdate={new Date(person.birth_date.seconds*1000).toLocaleDateString('en-US')}
birthplace={person.birth_location}
marriagedate={new Date(person.married_date.seconds*1000).toLocaleDateString('en-US')}
deathdate={new Date(person.death_date.seconds*1000).toLocaleDateString('en-US')}
deathplace={person.death_location}
age ={Math.floor((person.death_date.seconds - person.birth_date.seconds)/60/60/24/365)}
/>
)}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default PersonList;
|
//import logo from './logo.svg';
import './App.css';
import {Container, Button, Form} from 'react-bootstrap';
import Amplify from "aws-amplify";
import { API } from 'aws-amplify';
import { useLocation } from 'react-router-dom';
import queryString from query-String;
import awsExports from "./aws-exports";
Amplify.configure(awsExports);
async function addContact() {
const data = {
body: {
FirstName: formState.FirstName,
LastName: formState.LastName,
MailId: formState.MailId,
FeedbackMessage: formState.FeedbackMessage
}
};
console.log(data);
const apiData = await API.post('feedbackmap', '/feedform', data);
console.log({ apiData });
alert('Mail sent');
}
const formState = { FirstName: '', LastName: '', MailId: '', FeedbackMessage: '' };
function updateFormState(key, value) {
formState[key] = value;
}
function App() {
const { search } = useLocation();
console.log(search);
const { firstname, lastname, email } = queryString.parse(search);
return (
<Container>
<div>
<h3>Get in touch</h3>
<br/>
<Form>
<Form.Group>
<Form.Label>FirstName</Form.Label>
<Form.Control placeholder="FirstName" value = {firstname} onChange={updateFormState('FirstName', firstname)} />
</Form.Group>
<Form.Group>
<Form.Label>LastName</Form.Label>
<Form.Control placeholder="LastName" value = {firstname} onChange={updateFormState('LastName', lastname)} />
</Form.Group>
<Form.Group>
<Form.Label>MailId</Form.Label>
<Form.Control placeholder="MailId" value = {email} onChange={updateFormState('MailId', email)} />
</Form.Group>
<Form.Group>
<Form.Label>FeedbackMessage</Form.Label>
<Form.Control placeholder="FeedbackMessage" onChange={e => updateFormState('FeedbackMessage', e.target.value)} />
</Form.Group>
<Button onClick={addContact}>Send a message</Button>
</Form>
</div>
</Container>
);
}
export default App;
|
quitsmokingApp.BankbookFacade = function() {
this.bankbookProxy = clone(new quitsmokingApp.BankbookProxy(this));
this.bankbookCommand = clone(new quitsmokingApp.BankbookCommand(this));
this.bankbookMediator = clone(new quitsmokingApp.BankbookMediator(this));
quitsmokingApp.BankbookFacade.prototype.retrieveMediator = function() {
return this.bankbookMediator;
};
quitsmokingApp.BankbookFacade.prototype.retrieveProxy = function() {
return this.bankbookProxy;
};
quitsmokingApp.BankbookFacade.prototype.showBankbookListPage = function() {
this.bankbookCommand.saveStatementData();
//this.bankbookCommand.getStatementData();
/*this.bankbookMediator.initalizeBankbookListPage();
this.bankbookMediator.appendHtmlBankbookListPage();
this.bankbookMediator.attachEventBankbookListEvents();
this.bankbookMediator.displayEventBankbookListPage();*/
};
quitsmokingApp.BankbookFacade.prototype.getMoreStatementData = function(aMore_number) {
this.bankbookCommand.getMoreStatementData(aMore_number);
};
};
|
import request from 'supertest';
import { when } from 'jest-when';
import { updateLogEvent } from '../../middleware/logging';
import { sendRetrievalRequest, sendUpdateRequest } from '../../services/gp2gp';
import app from '../../app';
jest.mock('../../config/logging');
jest.mock('../../middleware/logging');
jest.mock('../../middleware/auth');
jest.mock('../../services/gp2gp');
const retrievalResponse = {
data: { serialChangeNumber: '123', patientPdsId: 'hello', nhsNumber: '1111111111' }
};
const invalidRetrievalResponse = {
data: { serialChangeNumber: '123', patientPdsId: 'hellno', nhsNumber: '1111111112' }
};
function generateLogEvent(message) {
return {
status: 'validation-failed',
validation: {
errors: message,
status: 'failed'
}
};
}
describe('POST /deduction-requests', () => {
beforeEach(() => {
process.env.AUTHORIZATION_KEYS = 'correct-key';
when(sendRetrievalRequest)
.calledWith('1234567890')
.mockResolvedValue({ status: 503, data: 'broken :(' })
.calledWith('1111111111')
.mockResolvedValue({ status: 200, data: retrievalResponse })
.calledWith('1111111112')
.mockResolvedValue({ status: 200, data: invalidRetrievalResponse });
when(sendUpdateRequest)
.calledWith('123', 'hello', '1111111111')
.mockResolvedValue({ status: 204 })
.calledWith('123', 'hellno', '1111111112')
.mockResolvedValue({ status: 503, data: 'could not update ods code on pds' });
});
it('should return a 204 if :nhsNumber is numeric and 10 digits and Authorization Header provided', done => {
request(app)
.post('/deduction-requests/1111111111')
.expect(204)
.end(done);
});
it('should return an error if :nhsNumber is less than 10 digits', done => {
const errorMessage = [{ nhsNumber: "'nhsNumber' provided is not 10 characters" }];
request(app)
.post('/deduction-requests/99')
.expect(422)
.expect('Content-Type', /json/)
.expect(res => {
expect(res.body).toEqual({
errors: errorMessage
});
expect(updateLogEvent).toHaveBeenCalledTimes(1);
expect(updateLogEvent).toHaveBeenCalledWith(generateLogEvent(errorMessage));
})
.end(done);
});
it('should return an error if :nhsNumber is not numeric', done => {
const errorMessage = [{ nhsNumber: "'nhsNumber' provided is not numeric" }];
request(app)
.post('/deduction-requests/xxxxxxxxxx')
.expect(422)
.expect('Content-Type', /json/)
.expect(res => {
expect(res.body).toEqual({
errors: errorMessage
});
expect(updateLogEvent).toHaveBeenCalledTimes(1);
expect(updateLogEvent).toHaveBeenCalledWith(generateLogEvent(errorMessage));
})
.end(done);
});
it('should return a 503 if sendRetrievalRequest throws an error', done => {
request(app)
.post('/deduction-requests/1234567890')
.expect(res => {
expect(res.status).toBe(503);
expect(res.body.errors).toBe('Unexpected Error: broken :(');
})
.end(done);
});
it('should return a 503 if patient is retrieved but not updated', done => {
request(app)
.post('/deduction-requests/1111111112')
.expect(503)
.expect(res => {
expect(res.body.errors).toBe('Failed to Update: could not update ods code on pds');
})
.end(done);
});
});
|
const express = require('express');
const router = express.Router();
const itemsController = require('../controllers/items');
const movieController = require('../controllers/movies');
const showController = require('../controllers/shows');
const personController = require('../controllers/persons');
router.get('/', itemsController.getHomePage);
router.get('/movies', movieController.getMoviesPage);
router.get('/movie/:itemId', movieController.getMovieDetailsPage);
router.post('/movie/:itemId/favorite', movieController.postFavoriteMovie);
router.get('/shows', showController.getShowsPage);
router.get('/show/:itemId', showController.getShowDetailsPage);
router.post('/show/:itemId/favorite', showController.postFavoriteShow);
router.get('/persons', personController.getPersonsPage);
router.get('/persons/:itemId', personController.getPersonDetailsPage);
router.get('/favorite', itemsController.getFavorite);
router.get('/about', itemsController.getAbout);
module.exports = router;
|
var input1 = document.getElementById('js-input');
var select = document.getElementById('js-select');
var input2 = document.getElementById('js-input2');
var button = document.getElementById('js-btn');
var textarea = document.getElementById('js-area');
// textarea.style.fontSize = '48px'
button.addEventListener('click', function (e) {
// console.log(input1.value, select.value, input2.value);
Number(input1.value);
Number(input2.value);
if (select.value == '+') {
textarea.textContent = Number(input1.value) + Number(input2.value);
} else if (select.value == '-') {
textarea.textContent = Number(input1.value) - Number(input2.value);
} else if (select.value == '*') {
textarea.textContent = Number(input1.value) * Number(input2.value);
} else if (select.value == '/') {
textarea.textContent = Number(input1.value) / Number(input2.value);
}
});
|
import React, { Fragment } from 'react';
import { shape, arrayOf, number, string } from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { mergeClasses } from '@magento/venia-ui/lib/classify';
import Pagination from '@magento/venia-ui/lib/components/Pagination';
import RichContent from '@magento/venia-ui/lib/components/RichContent';
import { Link } from '@magento/venia-drivers';
import path from 'path';
import defaultClasses from './blogs.css';
const BlogsContent = props => {
const { data, pageControl } = props;
const classes = mergeClasses(defaultClasses, props.classes);
const listItems = data && data.items ? data.items.map(blog => {
const { post_id: id, identifier, title, content, short_content, publish_time } = blog;
const linkTo = path.join('blog/post', String(identifier));
const formattedDate = new Date(publish_time).toLocaleDateString(
undefined,
{
year: 'numeric',
month: 'short',
day: 'numeric'
}
);
const blogDescription = short_content ? (
<RichContent html={short_content} />
) : <RichContent html={content} />;
return (
<li key={id} className={classes.postHolder}>
<div className={classes.postHeader}>
<div className={classes.postTitleHolder}>
<h2 className={classes.postTitle}>
<Link to={linkTo}>{title}</Link>
</h2>
</div>
<div className={classes.postInfo}>
<div className={classes.item}>
<span className={classes.label}>
<FormattedMessage
id={'blogsContent.posted'}
defaultMessage={'Posted: '}
/>
</span>
<span className={classes.value}>{formattedDate}</span>
</div>
</div>
</div>
<div className={classes.postContent}>
<div className={classes.postDescription, classes.clearfix}>
<div className={classes.clearfix}>
{blogDescription}
</div>
<Link className={classes.postReadMore} to={linkTo}>
<FormattedMessage
id={'blogsContent.readMore'}
defaultMessage={'Read more'}
/> »
</Link>
</div>
</div>
</li>
);
}) : '';
const content =
data && data.total_count === 0 ? (
<p>
<FormattedMessage
id={'blogsContent.notFound'}
defaultMessage={'Sorry! We couldn\'t find any blogs.'}
/>
</p>
) : (
<Fragment>
<ul className={classes.postList}>{listItems}</ul>
<div className={classes.pagination}>
<Pagination pageControl={pageControl} />
</div>
</Fragment>
);
return (
<Fragment>
{content}
</Fragment>
);
};
BlogsContent.prototype = {
data: shape ({
items: arrayOf(
shape({
id: number.isRequired,
identifier: string.isRequired,
title: string.isRequired,
content: string,
short_content: string,
publish_time: string
})
)
}).isRequired
};
export default BlogsContent;
|
import React, { Component } from 'react';
import './styles/design.scss';
import SubHeader from './subHeader';
// trip list images
import tripListSketch1 from './resources/planitScreens/trip-list-sketch-1.jpg';
import tripListSketch2 from './resources/planitScreens/trip-list-sketch-2.jpg';
import tripListLofi1 from './resources/planitScreens/trip-list-lofi-1.png';
import tripListLofi2 from './resources/planitScreens/trip-list-lofi-2.png';
import tripListHifi1 from './resources/planitScreens/trip-list-hifi-1.png';
import tripListHifi2 from './resources/planitScreens/trip-list-hifi-2.png';
// trip itinerary images
import tripItinSketch1 from './resources/planitScreens/trip-itin-sketch-1.jpg';
import tripItinLofi from './resources/planitScreens/trip-itin-lofi.png';
import tripItinHifi1 from './resources/planitScreens/trip-itin-hifi-1.png';
import tripItinHifi2 from './resources/planitScreens/trip-itin-hifi-2.png';
// create trip images
import createTripSketch from './resources/planitScreens/create-trip-sketch.jpg';
import createTripLofi1 from './resources/planitScreens/create-trip-lofi-1.png';
import createTripLofi2 from './resources/planitScreens/create-trip-lofi-2.png';
import createTripHifi1 from './resources/planitScreens/create-trip-hifi-1.png';
import createTripHifi2 from './resources/planitScreens/create-trip-hifi-2.png';
// create item images
import createEventSketch from './resources/planitScreens/create-event-sketch.jpg';
import createEventLofi1 from './resources/planitScreens/create-event-lofi-1.png';
import createEventLofi2 from './resources/planitScreens/create-event-lofi-2.png';
import createEventLofi3 from './resources/planitScreens/create-event-lofi-3.png';
import createEventHifi1 from './resources/planitScreens/create-event-hifi-1.png';
import createEventHifi2 from './resources/planitScreens/create-event-hifi-2.png';
class Design extends Component {
render() {
return (
<div>
<p className={'description'}>
My design went through many iterations. I began with multiple paper sketches, then low-fidelity
prototypes (using inVision Freehand), high-fidelity prototypes (using Sketch), and finally a
high-fidelity clickable prototype (using Sketch screens on inVision). Most screens went through this
cycle multiple times.
</p>
<SubHeader text={'Trip List'} />
<p className={'description'}>
The Trip List screen is where users can see all of the trips they've created.<br/><br/>
I struggled with whether to have global navigation on this screen. It feels like a home screen but
there are no global options that would apply to both this list and any other screen. I ended up
adding navigation for individual trips and none on screens like this one. The users had no issue
with this implementation and seemed to understand it intuitively.<br/>
I also moved from a hybrid android-iOS design to only iOS. It was confusing for users to see
unfamiliar patterns not native to their operating system.
</p>
<div className={'screenSection'}>
<img src={tripListSketch1} className={'screen'}
alt={'Sketch of trip list screen'} />
<img src={tripListSketch2} className={'screen'}
alt={'Sketch of trip list screen'}/>
<img src={tripListLofi1} className={'screen'}
alt={'Low fidelity trip list screen'}/>
<img src={tripListLofi2} className={'screen'}
alt={'Low fidelity trip list screen'}/>
<img src={tripListHifi1} className={'screen outline'}
alt={'High fidelity trip list screen'} />
<img src={tripListHifi2} className={'screen'}
alt={'High fidelity trip list screen'} />
</div>
<SubHeader text={'Trip Itinerary'}/>
<p className={'description'}>
The Trip Itinerary screen is where users can see all the events, documents, lists, and budget items
for a particular trip.<br/><br/>
In testing, users were confused by the list of dates that they saw once they opened the itinerary
for the first time. I implemented a new solution of showing empty state text that would be fun and
instructional. As a next step, I would like to add a button in the instructions to add an event so
it's even easier for the user to start right away, but I would want to test whether the user
remembers how to add an event with + button if they haven't practiced it when making the first
event.
</p>
<div className={'screenSection'}>
<img src={tripItinSketch1} className={'screen'}
alt={'Sketch of trip itinerary screen'} />
<img src={tripItinLofi} className={'screen'}
alt={'Low fidelity trip itinerary screen'} />
<img src={tripItinHifi1} className={'screen outline'}
alt={'High fidelity trip itinerary screen'} />
<img src={tripItinHifi2} className={'screen'}
alt={'High fidelity trip itinerary screen'} />
</div>
<SubHeader text={'Create Trip'}/>
<p className={'description'}>
The Create Trip screen is a form modal where a user inputs information to create a new trip.<br/><br/>
I began with a more complicated design where a user could input details about multiple locations
in their trip. I tried 4 different designs that didn't work well before deciding to keep it simple
and only include the necessary information. I thought it best that a user could input this
information later as they build the trip rather than have a confusing first experience.
</p>
<div className={'screenSection'}>
<img src={createTripSketch} className={'screen'}
alt={'Sketch of create trip screen'} />
<img src={createTripLofi1} className={'screen'}
alt={'Low fidelity create trip screen'} />
<img src={createTripLofi2} className={'screen'}
alt={'Low fidelity create trip screen'} />
<img src={createTripHifi1} className={'screen outline'}
alt={'High fidelity create trip screen'} />
<img src={createTripHifi2} className={'screen'}
alt={'High fidelity create trip screen'} />
</div>
<SubHeader text={'Create Event'}/>
<p className={'description'}>
The Create Event screen is a form modal where a user inputs information to create a new event within
a trip.<br/><br/>
As with the Create Trip screen, I started with something much more complicated: a 3 screen flow
where users picked categories of events, ending in a form specific to that kind of event. The
example here is for a flight. I didn't like that a user would have to go through such a
time-consuming process to make an event, which should be a fast process. I decided to make it all
one form and add more specific form options hidden under 'Advanced Options'. See the full version of
this form in my <a href='https://invis.io/TXPRKQZ6HZ7#/338472490_Create_Event_-_Empty'
target='_blank' rel='noopener noreferrer'>prototype</a>.
</p>
<div className={'screenSection'}>
<img src={createEventSketch} className={'screen'}
alt={'Sketch of create event screen'} />
<img src={createEventLofi1} className={'screen'}
alt={'Low fidelity create event screen'} />
<img src={createEventLofi2} className={'screen'}
alt={'Low fidelity create event screen'} />
<img src={createEventLofi3} className={'screen'}
alt={'Low fidelity create event screen'} />
<img src={createEventHifi1} className={'screen outline'}
alt={'High fidelity create event screen'} />
<img src={createEventHifi2} className={'screen'}
alt={'High fidelity create event screen'} />
</div>
</div>
);
}
}
export default Design;
|
const ControlForm = React.createClass({
getInitialState() {
return {
image: this.props.initialImage,
rows: this.props.initialRows,
columns: this.props.initialColumns,
curviness: this.props.initialCurviness,
barHeight: this.props.initialBarHeight
};
},
updateRows(event) {
this.setState({
rows: event.target.value
});
this.bars.setRows(event.target.value);
},
updateColumns(event) {
this.setState({
columns: event.target.value
});
this.bars.setColumns(event.target.value);
},
updateCurviness(event) {
this.setState({
curviness: event.target.value
});
this.bars.setCurviness(event.target.value);
},
updateBarHeight(event) {
this.setState({
barHeight: event.target.value
});
this.bars.setBarHeight(event.target.value);
},
render() {
return (
<form className='form-horizontal'>
<div className='form-group'>
<label className='col-sm-2 control-label' htmlFor='rows'>Rows</label>
<div className='col-sm-8'>
<input className='form-control' id='rows' type='range' min='1' max='100' value={this.state.rows} onChange={this.updateRows} />
</div>
<div className='col-sm-2'>
<p className='form-control-static'>{this.state.rows}</p>
</div>
</div>
<div className='form-group'>
<label className='col-sm-2 control-label' htmlFor='columns'>Columns</label>
<div className='col-sm-8'>
<input className='form-control' id='columns' type='range' min='1' max='100' value={this.state.columns} onChange={this.updateColumns} />
</div>
<div className='col-sm-2'>
<p className='form-control-static'>{this.state.columns}</p>
</div>
</div>
<div className='form-group'>
<label className='col-sm-2 control-label' htmlFor='curviness'>Curviness</label>
<div className='col-sm-8'>
<input className='form-control' id='curviness' type='range' min='0' max='1' step='0.1' value={this.state.curviness} onChange={this.updateCurviness} />
</div>
<div className='col-sm-2'>
<p className='form-control-static'>{this.state.curviness}</p>
</div>
</div>
<div className='form-group'>
<label className='col-sm-2 control-label' htmlFor='barHeight'>Bar height</label>
<div className='col-sm-8'>
<input className='form-control' id='barHeight' type='range' min='0' max='1' step='0.1' value={this.state.barHeight} onChange={this.updateBarHeight} />
</div>
<div className='col-sm-2'>
<p className='form-control-static'>{this.state.barHeight}</p>
</div>
</div>
</form>
);
},
componentDidMount() {
this.bars = new BarPortrait('canvas', this.state.image, this.state.rows, this.state.columns, this.state.curviness, this.state.barHeight);
}
});
ReactDOM.render(
<ControlForm initialImage='./cube.png' initialRows='20' initialColumns='20' initialCurviness='0.5' initialBarHeight='0.8' />,
document.getElementById('control-form'));
|
const crypto = require('crypto');
const util = require('util');
const randomBytes = util.promisify(crypto.randomBytes);
const token = async () => {
const rawToken = await randomBytes(32);
return rawToken.toString('hex')
}
module.exports = token;
|
console.log('printed 3');
|
/**
Author: Denis Zavgorodny denis.zavgorodny@gmail.com
17.07.14
Plugin for autoresize textarea
Fix original height calculate method
*/
$.sceditor.plugins.autoheight = function() {
var base = this;
var $editorContainer;
var $wysiwygBody;
var $wysiwygEditor;
base.signalReady = function(){
$editorContainer = $('body').find('.sceditor-container');
$wysiwygEditor = $editorContainer.find('iframe');
$wysiwygBody = $(this.currentNode()).closest('body');
$wysiwygBody.css('height', 'auto');
};
base.signalKeydownEvent = function() {
var options = this.opts;
$wysiwygBody = $(this.currentNode()).closest('body');
$wysiwygHTML = $(this.currentNode()).closest('html');
$wysiwygBody.css('height', 'auto');
//var currentHeight = $editorContainer.height(),
var height = $wysiwygBody.height();
//padding = (currentHeight - $wysiwygEditor.height()),
//maxHeight = options.resizeMaxHeight || ((options.height) * 2);
options.minHeight = options.minHeight || 26;
if(height > options.minHeight + 5)
height += 40;
if(height > options.minHeight)
this.height(height);
else
this.height(options.minHeight);
};
};
|
import CodeDemo from './CodeDemo';
it('calculates half-price discout', () => {
const discounter = new CodeDemo(0.5);
expect(discounter.calcNewPrice(100.00)).toBe(50.0);
});
|
/**
* @author Shreya Jain
*/
const Color = require('./MonopolyColor');
const Player = require('./player');
class Fortune {
constructor(string,wealthImpact) {
this.string=string;
this.wealthImpact = wealthImpact;
}
toString() {
return this.string;
}
applyWealthImpact(player) {
player.updateWealth(wealthImpact);
}
getWealthImpact() {
return this.wealthImpact;
}
}
var poo = new Fortune("Ay Caramba! You have to wait in line for the stirfry machine!",-50);
// console.log(poo);
// console.log(poo.getWealthImpact());
module.exports = Fortune;
// console.log(new Color("Purple"));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.