text
stringlengths 7
3.69M
|
|---|
// https://www.freecodecamp.org/challenges/where-do-i-belong
function getIndexToIns(arr, num) {
arr.sort(function(a, b){
return a - b;
});
for (var i = 0; i < arr.length; i++){
if (num <= arr[i]){
return i;
}
}
return i;
}
getIndexToIns([10, 20, 30, 40, 50], 30); // 2
|
import React from "react"
import { login, logout, isAuthenticated, getProfile } from "../utils/auth"
import { Link } from "gatsby"
import axios from 'axios'
const Home = ({ user }) => {
return <p>Hi, {user.name ? user.name : "friend"}!</p>
}
const Settings = () => <p>Settings</p>
const Billing = () => <p>Billing</p>
const Account = () => {
if (!isAuthenticated()) {
login()
return <p>Redirecting to login...</p>
}
const user = getProfile()
return (
<div>
<nav className="navBar">
<Link to="/account/">home</Link>{' | '}
<Link to="/foods/">Places</Link>{' | '}
<Link to="/places/">Foods</Link>{' | '}
<a href="#logout" onClick={e => {
e.preventDefault()
logout()
}}
>
Log Out
</a>
</nav>
<h1>Travel Foodie Express</h1>
</div>
)
}
export default Account
|
import regeneratorRuntime from '../../lib/regenerator-runtime'
import { connect } from '../../lib/wechat-weapp-redux'
import { displayError, clearError } from '../../store/actions/loader'
import { fetchWeappEntry, fetchGlobalData } from '../../store/actions/global'
import promisify from '../../lib/promisify'
import { defaultShareAppMessage, serialize } from '../../utils'
import { WEAPP_ENTRY_TYPE } from '../../constants'
import { getSessionId, postUserInfo } from '../../api/global'
import { setAuthHeader, setLocationHeader } from '../../api/_request'
const mapStateToData = state => {
return {
displayError: state.loader.displayError,
scene: state.global.scene,
shareTicket: state.global.shareTicket,
entryPath: state.global.entryPath,
entryQuery: state.global.entryQuery,
entryType: state.global.entryType,
promotionImgUrl: state.global.group.promotionImgUrl
}
}
const mapDispatchToPage = dispatch => ({
clearError: _ => dispatch(clearError()),
displayError: error => dispatch(displayError(error)),
fetchWeappEntry: ({ encryptedData, iv }) => dispatch(fetchWeappEntry({ encryptedData, iv })),
fetchGlobalData: _ => dispatch(fetchGlobalData())
})
const pageConfig = {
data: {
WEAPP_ENTRY_TYPE
},
onShareAppMessage: defaultShareAppMessage,
async onShow () {
console.log('Index: onShow')
wx.showShareMenu({
withShareTicket: true
})
const sessionId = wx.getStorageSync('sessionId')
let existSession = true
let needPostUserInfo = false
try {
await promisify(wx.checkSession)()
} catch (err) {
existSession = false
}
// login
if (!sessionId || !existSession) {
try {
const { code } = await promisify(wx.login)()
const { token } = await getSessionId(code)
wx.setStorageSync('sessionId', token)
setAuthHeader(token)
} catch (error) {
if (error.code === 500003) { // get sessionId => error
needPostUserInfo = true
} else {
return this.displayError(error)
}
}
}
// register
if (needPostUserInfo) {
try {
await promisify(wx.authorize)({ scope: 'scope.userInfo' })
const { authSetting } = await promisify(wx.getSetting)()
// 用户未授权 scope userInfo
if (!authSetting['scope.userInfo']) {
return this.handlerAuthFail()
}
const { encryptedData, iv, userInfo } = await promisify(wx.getUserInfo)({
withCredentials: true
})
// get code again
const { code } = await promisify(wx.login)()
const { token } = await postUserInfo({ encryptedData, iv, code })
setAuthHeader(token)
} catch (error) {
if (error.errMsg && error.errMsg.startsWith('authorize:fail')) {
return this.handlerAuthFail()
}
return this.displayError(error)
}
}
// get entry data
const { scene, shareTicket, entryPath } = this.data
try {
wx.showLoading()
let encryptedData, iv
if (shareTicket) {
const result = await promisify(wx.getShareInfo)({ shareTicket })
encryptedData = result.encryptedData
iv = result.iv
}
await this.fetchWeappEntry({ encryptedData, iv })
// APPLY_HERO: 0, GROUP_QRCODE: 1, FORWARD_TO_GROUP: 2,
// GROUP_NO_CREATE: 3, GROUP_NO_CLAIM: 4, GROUP_HOME: 5,
// GROUP_MANAGE: 6,
const { entryType, entryQuery } = this.data
if (WEAPP_ENTRY_TYPE.GROUP_HOME === entryType) {
const _globalDate = await this.fetchGlobalData()
if (!_globalDate) return
const { province, city } = _globalDate
if (province || city) {
setLocationHeader(city ? city.id : province.id)
}
if (entryPath != '/pages/index/index') {
// wx.navigateBack()
wx.redirectTo({ url: `${entryPath}?${serialize(entryQuery)}` })
} else {
wx.redirectTo({ url: '/pages/group/index/index' })
}
} else if (WEAPP_ENTRY_TYPE.GROUP_MANAGE === entryType) {
wx.redirectTo({ url: '/pages/group/manage/manage' })
}
} catch (error) {
this.displayError(error)
} finally {
wx.hideLoading()
}
},
reload () {
this.clearError()
this.onShow()
},
onUnload () {
this.clearError()
},
async handlerAuthFail () {
wx.setStorageSync('authFail', true)
const modal = await promisify(wx.showModal)({
title: '授权失败',
content: '请允许使用用户信息',
confirmText: '去授权',
showCancel: false
})
if (modal.confirm) {
wx.openSetting()
}
}
}
Page(
connect(
mapStateToData,
mapDispatchToPage
)(pageConfig)
)
|
var http = require('http');
var url = process.argv[2];
// GET our url
http.get(url, function (res){
var data = [];
// Set response data to be a string
res.setEncoding('utf8');
// Add all data to our data array
res.on('data', function (r){
data.push(r);
});
// Log the length of the received data
// Log a concatenated version of the data
res.on('end', function (r){
console.log(data.join('').length);
console.log(data.join(''));
});
// Log errors to the console
res.on('error', console.error);
});
|
import React from 'react';
import Point from './Point/Point';
const Marketing = (props) => {
return (
<div className="container" style={{ padding: '15px 0' }} >
<div className="columns">
{props.content.map((p, i) => {
return (
<div key={`column-${i}`} className="column">
<Point key={`${i}-${p.title}`} point={p} />
</div>
)
})}
</div>
</div>
);
}
export default Marketing;
|
function routeProvider($routeProvider) {
$routeProvider
.when('/', {
template: '<login></login>'
})
.when('/user/new', {
template: '<user-new></user-new>'
})
.when('/users', {
template: '<users></users>'
})
.when('/dashboard', {
template: '<dashboard-cards></dashboard-cards>'
})
.when('/logout', {
template: '<login></login>'
})
.when('/action-table', {
template: '<action-table></action-table>'
})
.when('/weather', {
template: '<weather-dashboard></weather-dashboard>'
});
}
routeProvider.$inject = ['$routeProvider'];
angular.module('root').config(routeProvider);
|
const Stack = require('../../Stack');
const stack = new Stack();
module.exports = {
async AddController(request, response) {
const { value } = request.body;
stack.add(value);
return response.json(value);
},
async SizeController(request, response) {
const tam = stack.size();
return response.json(tam);
},
async TopController(request, response) {
const top = stack.top();
return response.json(top);
},
async RemoveController(request, response) {
}
};
|
WMS.module('Models', function(Models, WMS, Backbone, Marionette, $, _) {
Models.EmployeeHours = Backbone.Model.extend({
defaults: {
firstName : "",
lastName : "",
hours : 0
},
maps: [
{ local: 'firstName', remote: 'nome' },
{ local: 'lastName', remote: 'cognome' },
{ local: 'hours', remote: 'ore_totali' }
],
computed: {
name: {
depends: ['firstName', 'lastName'],
get: function(fields) {
return fields.firstName + ' ' + fields.lastName;
}
}
},
canAddSheet: function() {
return !this.isNew();
}
}, {
_permission: "employeeHours"
, modelName: "employee:hours"
});
Models.EmployeeHoursCollection = Backbone.Collection.extend({
model: Models.EmployeeHours,
url: '/api/v1/dipendente/get_ore/',
initialize: function() {
_.extend(this, new Backbone.Picky.SingleSelect(this));
Backbone.Collection.prototype.initialize.call(this);
}
});
Models.Sheet = Backbone.Model.extend({
urlRoot: '/api/v1/consuntivo/',
defaults: {
employeeId : null,
commissionId: null,
date : Date.today(),
hours : 0,
workTypeId : null,
note : ""
},
maps: [
{ local: 'employeeId', remote: 'dipendente' },
{ local: 'commissionId', remote: 'commessa' },
{ local: 'workTypeId', remote: 'tipo_lavoro' },
{ local: 'workType', remote: 'tipo_lavoro_label' },
{ local: 'date', remote: 'data', type:'date' },
{ local: 'hours', remote: 'ore' },
{ local: 'note', remote: 'note' }
],
validation: {
employeeId : { required: true },
commissionId: { required: true },
workTypeId : { required: true },
hours : { min: 0.5 }
},
getCommissions: WMS.getCommissions,
getWorkTypes: WMS.getWorkTypes,
toString:function() {
var date = this.get('date');
return (date ? date.toString('dd/MM/yyyy') : '') + " - " + this.get('hours');
}
}, {
_permission: "sheets"
, modelName: "sheet"
});
Models.Sheets = Backbone.Collection.extend({
model: Models.Sheet,
url: function() {
return '/api/v1/dipendente/' + this.attr('employeeId') + '/consuntivo/';
},
parse: function(resp, options) {
if (_.isArray(resp)) {
resp = resp[0];
}
this.hours = resp.tatale_ore || 0;
return resp.consuntivi;
},
getHours: function() {
return this.reduce(function(memo, value) {
return memo + parseFloat(value.get('hours'));
}, 0);
}
}, {
_permission:'sheets'
});
WMS.reqres.setHandler('get:employeeHours:list', function(params) {
params = (params || {});
var list = new Models.EmployeeHoursCollection();
var defer = $.Deferred();
var data = {};
if (params.from) {
data.da = params.from.toString('yyyy-MM-dd');
}
if (params.to) {
data.a = params.to.toString('yyyy-MM-dd');
}
list.attr(params);
list.fetch({
data: data
}).always(function() {
defer.resolve(list);
});
return defer.promise();
});
WMS.reqres.setHandler('get:sheet:list', function(params) {
var defer = $.Deferred();
var sheets = new Models.Sheets();
if (!params.employeeId) {
defer.resolve(sheets);
} else {
sheets.attr(params);
var data = {};
data.da = params.from && params.from.toString('yyyy-MM-dd');
data.a = params.to && params.to.toString('yyyy-MM-dd');
sheets.fetch({
data: data
}).always(function() {
defer.resolve(sheets);
});
}
return defer.promise();
});
WMS.reqres.setHandler('get:sheet', function(id) {
var defer = $.Deferred();
if (typeof id === 'object' ? !id.id : !id) {
defer.resolve(undefined);
}
if (_.isObject(id)) {
id = id.id;
}
var sheet = new Models.Sheet({id: id});
sheet.fetch().always(function() {
defer.resolve(sheet);
});
return defer.promise();
});
});
|
import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import MainDrawerNavigator from './navigation/drawer/MainDrawerNavigator';
function App() {
return (
<NavigationContainer>
<MainDrawerNavigator />
</NavigationContainer>
);
}
export default App;
|
import colors from './colors'
import styles from './styles'
export { colors, styles }
|
const mongoose = require('mongoose');
//user Schema
const CitySchema = mongoose.Schema({
cityname:{
type: String,
required: true,
Unique:true
},
cityimg:{
type: String
},
postalcode:{
type:String,
required: true,
Unique:true
}
});
const City = module.exports = mongoose.model('cities', CitySchema);
|
import React from 'react';
import { mount, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Screen from '../component/Screen';
import { Provider } from '../component/Switch/context';
import faker from 'faker';
configure({ adapter: new Adapter() });
describe('<Screen />', () => {
let props = {
name: 'viewA',
viewComponent: jest.fn(props => <div />),
initialProps: {
[faker.random.objectElement()]: faker.random.objectElement()
}
};
let context = {
viewName: 'viewB',
viewProps: {
[faker.random.objectElement()]: faker.random.objectElement()
},
to: jest.fn()
};
beforeEach(() => {
jest.resetModules();
});
describe("while the viewName in context and name in component's props is different", () => {
const wrapper = mount(
<Provider value={context}>
<Screen {...props} />
</Provider>
);
test('viewComponent should not be rendered', () => {
expect(wrapper.isEmptyRender()).toBeTruthy();
});
});
describe('while the viewName in props and name in context is the same', () => {
const viewName = faker.random.objectElement();
const wrapper = mount(
<Provider value={Object.assign({}, context, { viewName })}>
<Screen {...props} name={viewName} />
</Provider>
);
test('the content should be rendered', () => {
expect(wrapper.exists()).toBeTruthy();
});
test('<ScreenView /> should be rendered', () => {
expect(wrapper.find('ScreenView').exists()).toBeTruthy();
});
});
test('Except for name and viewName, all props should be passed to child(ScreenView)', () => {
const viewName = faker.random.objectElement();
const wrapper = mount(
<Provider value={Object.assign({}, context, { viewName })}>
<Screen {...props} name={viewName} />
</Provider>
);
const { viewComponent, initialProps } = props;
const { viewProps, to } = context;
expect(wrapper.find('ScreenView').props()).toEqual({
viewComponent,
initialProps,
viewProps,
to
});
});
});
|
function Animal(name) {
this.speed = 0;
this.name = name;
this.run = function(speed) {
this.speed += speed;
console.log(this.name + ": his speed = " + this.speed);
};
this.stop = function() {
this.speed = 0;
console.log(this.name + ": his speed is stopped = " + this.speed)
};
}
var animal = new Animal("Lion");
animal.run(300);
animal.stop();
|
import "./styles.css";
import Header from "./components/Header";
import Headline from "./components/Headline/headline";
import Button from "./components/button/index";
import ListItem from "./components/listItem/listItem";
import { connect } from "react-redux";
import { fetchProps } from "./actions/index";
const tempArray = [
{
fname: "manikanta",
lname: "chinna",
email: "manikantakondapalli944@gmail.com",
age: 25,
onlineStatus: true
}
];
const App = (props) => {
const fetch = () => {
props.fetchProps();
};
const configButton = {
buttonText: "Get Posts",
emitEvent: fetch
};
return (
<div className="App">
<Header />
<Headline
desc="hey this is a description"
posts="Posts"
tempData={tempArray}
/>
<Button {...configButton} />
{props.posts.length !== 0 && (
<div>
{props.posts.map((post, index) => {
const { title, body } = post;
const configListItem = {
title,
desc: body
};
return <ListItem key={index} {...configListItem} />;
})}
</div>
)}
</div>
);
};
const mapStateToProps = (state) => {
return {
posts: state.posts
};
};
export default connect(mapStateToProps, { fetchProps })(App);
|
import {Component} from "react";
import React from "react";
import "./DragAndDropTable.css";
class DragAndDropTable extends Component {
constructor(props) {
super(props);
// this.state = {
// items: this.props.items,
// counter: 0
// };
this.dragDrop = this.dragDrop.bind(this);
this.dragStart = this.dragStart.bind(this);
this.dragOver = this.dragOver.bind(this);
this.createRows = this.createRows.bind(this);
}
dragDrop(ev) {
debugger
if (this.props.pos !== JSON.parse(ev.dataTransfer.getData("obj")).loc) {
this.props.tester(ev);
}
//ev.stopPropagation();
}
dragStart(ev) {
ev.dataTransfer.effectAllowed = 'move';
ev.dataTransfer.setData("obj", JSON.stringify({
id: ev.target.id,
loc: this.props.pos
}));
}
dragOver(ev) {
ev.preventDefault();
}
createRows() {
const items = this.props.items;
const array = items.map((item, index) => {
debugger
return (<tr key={index} id={item.id} draggable={true} onDragStart={this.dragStart}>
<td>{item.company}</td>
<td>{item.contact}</td>
<td>{item.country}</td>
</tr>);
});
return array;
}
render() {
return (
<div>
<table onDrop={this.dragDrop} onDragOver={this.dragOver}>
<tbody>
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
{this.createRows()}
</tbody>
</table>
</div>
);
}
}
export default DragAndDropTable;
|
player1_name=localStorage.getItem("player1");
player2_name=localStorage.getItem("player2");
var player1_score=0;
var player2_score=0;
var question_turn=player1_name;
var Answer_turn=player2_name;
document.getElementById("player1_name").innerHTML=player1_name+" : ";
document.getElementById("player1_score").innerHTML=player1_score;
document.getElementById("player2_name").innerHTML=player2_name+" : ";
document.getElementById("player2_score").innerHTML=player2_score;
document.getElementById("player_question").innerHTML="Question turn - "+player1_name;
document.getElementById("player_answer").innerHTML="Answer turn - "+player2_name;
function ask_question() {
var word=document.getElementById("word").value;
lowercase_word=word.toLowerCase();
var char1=lowercase_word.charAt(1);
var length_divide_2=Math.floor(lowercase_word.length/2);
var char2=lowercase_word.charAt(length_divide_2);
var char3=lowercase_word.charAt(lowercase_word.length-1)
var replace1=lowercase_word.replace(char1, "_");
var replace2=replace1.replace(char2, "_");
var final_word=replace2.replace(char3, "_");
var question="<h4 id='word_display'> Q. "+final_word+"</h4> <br>";
var input_box="Answer : <input type='text' id='input_check_box'> <br> <br>";
var check_button="<button class='btn btn-info' onclick='check()'> Check </button>";
var row=question+input_box+check_button;
document.getElementById("output").innerHTML=row;
document.getElementById("word").value="";
}
function check() {
var Answer=document.getElementById("input_check_box").value;
var lower_case_answer=Answer.toLowerCase();
if (lower_case_answer==lowercase_word) {
if (Answer_turn==player1_name) {
player1_score=player1_score+1;
document.getElementById("player1_score").innerHTML=player1_score;
}
else if (Answer_turn==player2_name) {
player2_score=player2_score+1;
document.getElementById("player2_score").innerHTML=player2_score;
}
}
if (question_turn==player1_name) {
question_turn=player2_name;
document.getElementById("player_question").innerHTML="Question turn - "+question_turn;
}
else if (question_turn==player2_name){
question_turn=player1_name;
document.getElementById("player_question").innerHTML="Question turn - "+question_turn;
}
if (Answer_turn==player1_name) {
Answer_turn=player2_name;
document.getElementById("player_answer").innerHTML="Answer turn - "+Answer_turn;
}
else if(Answer_turn==player2_name){
Answer_turn=player1_name;
document.getElementById("player_answer").innerHTML="Answer turn - "+Answer_turn;
}
document.getElementById("output").innerHTML="";
}
|
import React from 'react';
import { Grid,Paper, Avatar, TextField, Button } from '@material-ui/core'
import LockOutlinedIcon from '@material-ui/icons/LockOutlined';
import axios from 'axios';
export default class Register extends React.Component {
constructor(props){
super(props);
this.state = {
username: "",
role: "",
ceo: false,
company: "",
}
}
setUsername = e => {
this.setState({username: e})
console.log(e)
}
setCompany = e => {
this.setState({company: e})
}
setRole = e => {
if (e == "economist" || e == "lawyer"){
console.log(e)
this.setState({role:e})
}
else if (e == "ceo"){
this.setState({ceo:true})
}
}
submit = e => {
e.preventDefault();
axios.post('http://127.0.0.1:8080/user/register/', {
username: this.state.username,
role: this.state.role,
ceo: this.state.ceo,
company: this.state.company
})
.catch(err => console.log(err))
}
render(){
const paperStyle={padding :20,height:350, width:300, margin: "0 auto"}
const avatarStyle={backgroundColor:'#1bbd7e'}
const btnstyle={margin:'8px 0'}
return(
<form onSubmit={this.submit}>
<Paper style={paperStyle}>
<Grid align='center'>
<Avatar style={avatarStyle}><LockOutlinedIcon/></Avatar>
<h2>Sign up</h2>
</Grid>
<TextField type="login" label='Username' onChange={e=>this.setUsername(e.target.value)} placeholder='Enter username' fullWidth required/>
<TextField type="text" label='Company' placeholder='Enter your company' onChange={e=>this.setCompany(e.target.value)} fullWidth />
<TextField type="text" label='Role' placeholder='Enter your role: ceo, economist or lawyer' onChange={e=>this.setRole(e.target.value)} fullWidth />
<Button type='submit' color='primary' variant="contained" style={btnstyle} fullWidth>Sign up</Button>
</Paper>
</form>
)
}
}
|
const { AkagoClient, CommandHandler, ListenerHandler } = require('discord.js-akago');
const config = require('./src/config.json')
const db = require('./src/models/db')
const pdb = new db.table(`guild`)
class myClient extends AkagoClient {
constructor() {
super({
token: config.bot_token,
ownerID: config.owner_ID
}, {
disableMentions: 'everyone',
})
this.commandHandler = new CommandHandler(this, {
commandDirectory: './src/commands',
prefix: (message) => {
const prefix = pdb.get(`guild_${message.guild.id}.prefix`) || config.bot_prefix
return prefix
},
allowMentionPrefix: true,
blockBots: true,
});
this.listenerHandler = new ListenerHandler(this, {
listenerDirectory: './src/events',
});
}
start() {
this.build();
}
}
const client = new myClient();
client.start()
const { MessageEmbed } = require('discord.js')
this.embed = new MessageEmbed().setColor(config.embed_colour)
|
import React ,{Component} from 'react';
import {Link } from 'react-router-dom';
import { useApi } from "../../../hooks/useApi";
import useChat from "../../../useChat";
import axios from "axios";
import { useEffect, useState } from "react";
const Groupmini = ({ id })=> {
const [group, err, reload] = useApi("groups/group/"+id,null,"GET");
const [members, erre, reloads] = useApi("groupmember/members/"+id);
{
return (
(group?.Type=="Public"?( <div class="flex items-center space-x-4 py-3 hover:bg-gray-100 rounded-md -mx-2 px-2">
<div class="w-14 h-14 flex-shrink-0 rounded-md relative">
<img src={group?.photo} class="absolute w-full h-full inset-0 rounded-md object-cover" alt=""/>
</div>
<div class="flex-1">
<a href="timeline-group.html" class="text-lg font-semibold capitalize"> <Link to={`/group/${group?._id}`} > {group?.Name} </Link> </a>
<div class="text-sm text-gray-500 mt-0.5"> {members?.length} Member</div>
</div>
<a href="#" class="flex items-center justify-center h-9 px-4 rounded-md bg-gray-200 font-semibold">
<Link to={`/group/${group?._id}`} > View </Link>
</a>
</div>):(<div hidden></div>) )
)
}
}
export default Groupmini;
|
jQuery(window).on('load', function() {
"use strict";
jQuery("#status").fadeOut();
// will fade out the whole DIV that covers the website.
jQuery("#preloader").delay(500).fadeOut("slow");
})
|
define(['core/core-modules/framework.util'], function (util) {
function isIE() { //ie?
if (!!window.ActiveXObject || "ActiveXObject" in window)
return true;
else
return false;
}
const oldConsole = {
'info': console.info,
'debug': console.debug,
'error': console.error,
'warn': console.warn,
// 'log': console.log,
};
const textformat = "%c%s [%s] ";
const consoleStyles = {
'info': 'color:#2b82cf;',//text-shadow: 1px 1px 0px #fff
'debug': 'color:#b567df;',
'error': 'color:red;',
'warn': 'color:#ff8a57;',
}
const logtypes = {
'info': "INFO ",
'debug': 'DEBUG',
'error': 'ERROR',
'warn': 'WARN '
};
function trace() {
try {
let route = '';
let length = 0;
var caller = arguments.callee.caller;
while (caller && length < 9) {
route += ">" + caller.name;
caller = caller.caller;
length++;
}
console.log(route);
} catch (e) { }
}
console.info = function (text, ...arg) {
var func = 'info';
// console.trace();
// var date = util.dateformat(new Date(), "yyyy-MM-dd HH:mm:ss");
var date = '';
oldConsole[func](textformat + text, consoleStyles[func], date, logtypes[func], ...arg);
}
console.debug = function (text, ...arg) {
// var c = console.trace();
// trace();
// console.trace();
var func = 'debug';
// var date = util.dateformat(new Date(), "yyyy-MM-dd HH:mm:ss");
var date = '';
oldConsole[func](textformat + text, consoleStyles[func], date, logtypes[func], ...arg);
}
console.error = function (text, ...arg) {
var func = 'error';
// var date = util.dateformat(new Date(), "yyyy-MM-dd HH:mm:ss");
var date = '';
oldConsole[func](textformat + text, consoleStyles[func], date, logtypes[func], ...arg);
}
console.warn = function (text, ...arg) {
var func = 'warn';
// var date = util.dateformat(new Date(), "yyyy-MM-dd HH:mm:ss");
var date = '';
oldConsole[func](textformat + text, consoleStyles[func], date, logtypes[func], ...arg);
}
});
|
let YesComplianceTokenV1Impl = artifacts.require("YesComplianceTokenV1Impl");
let BigNumber = require('bignumber.js');
contract('YesComplianceTokenV1Impl', function ([owner, ALICE_ADDR1, BOB_ADDR1, ALICE_ADDR2, NONHOLDER_ACCOUNT1, VERIFIER_A_ADDR1, VERIFIER_B_ADDR1]) {
let contract;
let ENTITY_ALICE = 10000;
let ENTITY_BOB = 10001;
let ENTITY_VERIFIER_A = 10002;
let ENTITY_VERIFIER_B = 10003;
let USA_CODE = 840;
let INDIVIDUAL_FULL_COMPLIANCE = 1;
let ACCREDITED_INVESTOR = 2;
let ECOSYSTEM_VALIDATOR = 129;
beforeEach('setup contract for each test', async function () {
contract = await YesComplianceTokenV1Impl.new({ from: owner });
await contract.initialize('WYRE-YES-TEST', 'YESTEST');
});
it('has an owner', async function () {
assert.equal(await contract.ownerAddress(), owner);
});
it("should allow minter delegation and querying", async function () {
// create validator
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](VERIFIER_A_ADDR1, ENTITY_VERIFIER_A, true, 0, [ECOSYSTEM_VALIDATOR], {from: owner, gas: 1000000});
let queryResult = await contract.isYes.call(0, VERIFIER_A_ADDR1, 0, ECOSYSTEM_VALIDATOR);
assert.equal(queryResult, true);
// issue token for alice from verifier
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](ALICE_ADDR1, ENTITY_ALICE, true, USA_CODE, [INDIVIDUAL_FULL_COMPLIANCE], {from: VERIFIER_A_ADDR1, gas: 1000000});
// query validations
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
queryResult = await contract.isYes.call(ENTITY_VERIFIER_A, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
queryResult = await contract.isYes.call(ENTITY_BOB, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, false);
});
it("should allow yes-specific clearing", async function () {
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](VERIFIER_A_ADDR1, ENTITY_VERIFIER_A, true, 0, [ECOSYSTEM_VALIDATOR], {from: owner, gas: 1000000});
let queryResult = await contract.isYes.call(0, VERIFIER_A_ADDR1, 0, ECOSYSTEM_VALIDATOR);
assert.equal(queryResult, true);
// issue token for alice from verifier
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](ALICE_ADDR1, ENTITY_ALICE, true, USA_CODE, [INDIVIDUAL_FULL_COMPLIANCE], {from: VERIFIER_A_ADDR1, gas: 1000000});
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
// clear wrong one
await contract.contract.clearYes['uint256,uint16,uint8'](ENTITY_ALICE, USA_CODE+1, INDIVIDUAL_FULL_COMPLIANCE, {from: VERIFIER_A_ADDR1});
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
// clear wrong one
await contract.contract.clearYes['uint256,uint16,uint8'](ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE+1, {from: VERIFIER_A_ADDR1});
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
// clear right one
await contract.contract.clearYes['uint256,uint16,uint8'](ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE, {from: VERIFIER_A_ADDR1});
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, false);
});
it("should allow country-wide clearing", async function () {
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](VERIFIER_A_ADDR1, ENTITY_VERIFIER_A, true, 0, [ECOSYSTEM_VALIDATOR], {from: owner, gas: 1000000});
let r1 = await contract.isYes.call(0, VERIFIER_A_ADDR1, 0, ECOSYSTEM_VALIDATOR);
assert.equal(r1, true);
// issue token for alice from verifier
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](ALICE_ADDR1, ENTITY_ALICE, true, USA_CODE, [INDIVIDUAL_FULL_COMPLIANCE, ACCREDITED_INVESTOR], {from: VERIFIER_A_ADDR1, gas: 1000000});
r1 = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(r1, true);
r1 = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, ACCREDITED_INVESTOR);
assert.equal(r1, true);
// clear wrong one
await contract.contract.clearYes['uint256,uint16'](ENTITY_ALICE, USA_CODE+1, {from: VERIFIER_A_ADDR1});
r1 = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(r1, true);
// clear right one
await contract.contract.clearYes['uint256,uint16'](ENTITY_ALICE, USA_CODE, {from: VERIFIER_A_ADDR1, gas: 1000000});
r1 = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(r1, false);
r1 = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, ACCREDITED_INVESTOR);
assert.equal(r1, false);
});
it("should allow entity-wide clearing", async function () {
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](VERIFIER_A_ADDR1, ENTITY_VERIFIER_A, true, 0, [ECOSYSTEM_VALIDATOR], {from: owner, gas: 1000000});
let queryResult = await contract.isYes.call(0, VERIFIER_A_ADDR1, 0, ECOSYSTEM_VALIDATOR);
assert.equal(queryResult, true);
// issue token for alice from verifier
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](ALICE_ADDR1, ENTITY_ALICE, true, USA_CODE, [INDIVIDUAL_FULL_COMPLIANCE, ACCREDITED_INVESTOR], {from: VERIFIER_A_ADDR1, gas: 1000000});
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, ACCREDITED_INVESTOR);
assert.equal(queryResult, true);
// clear wrong one
await contract.contract.clearYes['uint256'](ENTITY_BOB, {from: VERIFIER_A_ADDR1});
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, ACCREDITED_INVESTOR);
assert.equal(queryResult, true);
// clear right one
await contract.contract.clearYes['uint256'](ENTITY_ALICE, {from: VERIFIER_A_ADDR1, gas: 1000000});
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, false);
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, ACCREDITED_INVESTOR);
assert.equal(queryResult, false);
});
it("should return all marks for country-wide query", async function () {
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](VERIFIER_A_ADDR1, ENTITY_VERIFIER_A, true, 0, [ECOSYSTEM_VALIDATOR], {from: owner, gas: 1000000});
let queryResult = await contract.isYes.call(0, VERIFIER_A_ADDR1, 0, ECOSYSTEM_VALIDATOR);
assert.equal(queryResult, true);
// issue token for alice from verifier
await contract.contract.mint['address,uint256,bool,uint16,uint8[]'](ALICE_ADDR1, ENTITY_ALICE, true, USA_CODE, [INDIVIDUAL_FULL_COMPLIANCE, ACCREDITED_INVESTOR], {from: VERIFIER_A_ADDR1, gas: 1000000});
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, ACCREDITED_INVESTOR);
assert.equal(queryResult, true);
// make sure both are there
queryResult = await contract.getYes.call(0, ALICE_ADDR1, USA_CODE);
assert.deepEqual(queryResult[0].toNumber(), INDIVIDUAL_FULL_COMPLIANCE);
assert.deepEqual(queryResult[1].toNumber(), ACCREDITED_INVESTOR);
assert.equal(queryResult.length, 2);
// should be empty
queryResult = await contract.getYes.call(0, ALICE_ADDR1, USA_CODE + 1);
assert.equal(queryResult.length, 0);
queryResult = await contract.getYes.call(0, BOB_ADDR1, USA_CODE);
assert.equal(queryResult.length, 0);
});
it("should have functioning finalization", async function () {
// setup/mint for alice
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
let token1 = await contract.mint.call(ALICE_ADDR1, ENTITY_ALICE, true, {from: owner});
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, true, {from: owner});
assert(await contract.isFinalized.call(token1) === false);
// alice finalizes her own token
await contract.finalize(token1, {from: ALICE_ADDR1});
assert(await contract.isFinalized.call(token1) === true);
// then she tries to move it
try {
await contract.transferFrom(ALICE_ADDR1, ALICE_ADDR2, token1, {from: ALICE_ADDR1});
assert.fail();
} catch (e) {
assert(e.toString().includes('revert'));
}
});
it("should pass YES query for non-control token holder", async function () {
// give the alice entity approved compliance
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
// issue token for alice
// await contract.methods['mint(address,uint256,bool)'](ALICE_ADDR1, ENTITY_ALICE, false, {from: owner});
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, false, {from: owner});
// query alice
let queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
});
it("should not pass YES query for non-token holder", async function () {
// give the alice entity approved compliance
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
// issue token for alice
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, false, {from: owner});
// query bob
let queryResult = await contract.isYes.call(0, BOB_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, false);
});
it("should pass YES query for control token holder", async function () {
// give the alice entity approved compliance
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
// issue token for alice
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, true, {from: owner});
// query alice
let queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
});
it("should allow control token holder to mint new control tokens", async function () {
// give the alice entity approved compliance
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
// issue control token for alice
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, true, {from: owner});
// have alice issue token to other address
await contract.mint(ALICE_ADDR2, ENTITY_ALICE, true, {from: ALICE_ADDR1});
// query alice addr 2
let queryResult = await contract.isYes.call(0, ALICE_ADDR2, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
});
it("should not allow non-control token holder to mint new tokens", async function () {
// give the alice entity approved compliance
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
// issue non control token for alice
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, false, {from: owner});
// have alice try to issue token to other address
try {
await contract.mint(ALICE_ADDR2, ENTITY_ALICE, false, {from: ALICE_ADDR1});
assert.fail();
} catch (e) {
assert(e.toString().includes('revert'));
/// console.log("expected failure: ", e);
}
// query alice addr 2
let queryResult = await contract.isYes.call(0, ALICE_ADDR2, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, false);
});
it("should not allow control token holder to mint new tokens for wrong entity", async function () {
// give the alice entity approved compliance
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
// issue non control token for alice
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, true, {from: owner});
// have alice try to issue token to other address for bob's entity
try {
await contract.mint(ALICE_ADDR2, ENTITY_BOB, false, {from: ALICE_ADDR1});
assert.fail();
} catch (e) {
// console.log("expected failure: ", e);
assert(e.toString().includes('revert')); // 'illegal entity id'));
}
// query alice addr 2
let queryResult = await contract.isYes.call(0, ALICE_ADDR2, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, false);
});
// test locking -----------------------------------------------------------------------------------------------
it("should have functioning locking", async function () {
// give the alice entity approved compliance
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
// issue token for alice
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, false, {from: owner});
// query alice
let queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
// set lock
await contract.setLocked(ENTITY_ALICE, true, {from: owner});
// query alice
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, false);
// remove lock
await contract.setLocked(ENTITY_ALICE, false, {from: owner});
// query alice
queryResult = await contract.isYes.call(0, ALICE_ADDR1, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
assert.equal(queryResult, true);
});
it("should not allow non-owner to assign locks", async function () {
// try with a control token owner
await contract.setYes(ENTITY_ALICE, USA_CODE, INDIVIDUAL_FULL_COMPLIANCE);
await contract.mint(ALICE_ADDR1, ENTITY_ALICE, true, {from: owner});
// set lock
try {
await contract.setLocked(ENTITY_ALICE, true, {from: ALICE_ADDR1});
assert.fail();
} catch (e) {
assert(e.toString().includes('revert'));
// console.log("fail: ", e);
}
// try with non-token holder
try {
await contract.setLocked(ENTITY_ALICE, true, {from: NONHOLDER_ACCOUNT1});
assert.fail();
} catch (e) {
assert(e.toString().includes('revert'));
// console.log("fail: ", e);
}
});
// todo test burns
// todo test moving coins around - general 721 testing
// describe('Token Holder', function() {
// it("should move coin correctly", function () {
// WyreYesComplianceToken.deployed().then(function(contract) {
//
// var startBalances = {};
// var endBalances = {};
// var amount = 1;
//
// contract.mint(HOLDER_ACCOUNT1, ENTITY0, true, { from: accounts[0] }).then(function() {
// return contract.getBalance.call(HOLDER_ACCOUNT1);
// }).then(function (balance) {
// startBalances[1] = balance.toNumber();
// return contract.getBalance.call(HOLDER_ACCOUNT2);
// }).then(function (balance) {
// startBalances[2] = balance.toNumber();
// return contract.transferFrom(HOLDER_ACCOUNT1, HOLDER_ACCOUNT2, amount, {from: HOLDER_ACCOUNT1});
// }).then(function () {
// return contract.getBalance.call(HOLDER_ACCOUNT1);
// }).then(function (balance) {
// endBalances[1] = balance.toNumber();
// return contract.getBalance.call(HOLDER_ACCOUNT2);
// }).then(function (balance) {
// endBalances[2] = balance.toNumber();
//
// assert.equal(endBalances[1], startBalances[1] - amount, "Amount wasn't correctly taken from the sender");
// assert.equal(endBalances[2], startBalances[2] + amount, "Amount wasn't correctly sent to the receiver");
// });
// });
//
// // Get initial balances of first and second account.
//
// });
// });
});
|
/**
* @fileOverview 配置文件
* @author 行列
* @version 1.0
*/
KISSY.add("app/ini", function(S, Node, Router) {
var T = {
routes: {
'app/views/default': [
// 首页
'/myunion/overview',
'/myunion/record',
'/myunion/message',
'/myunion/message_detail',
'/myunion/site/site',
'/myunion/zone/zone',
'/myunion/channel/channel',
// 联盟产品
'/promo/act/activity_detail_pub',
'/promo/act/activity_detail_mycreated',
'/promo/act/activity_detail',
'/promo/act/activity',
'/promo/act/activity_seller',
'/promo/act/activity_cpa',
'/promo/self/activity',
'/promo/self/items',
'/promo/self/shops',
'/promo/self/links',
'/promo/self/shop_detail',
'/promo/self/shop_detail_chart',
'/promo/self/shop_detail_activity',
'/promo/self/shop_detail_hot',
'/promo/self/notice',
'/promo/self/notice_detail',
'/promo/self/campaign',
'/promo/self/headline',
'/promo/self/search',
'/promo/taobao/weibo',
'/promo/taobao/weibo_promo',
'/promo/taobao/widget_publish',
'/promo/taobao/widget_private',
'/promo/taobao/widget_click',
'/promo/taobao/channel',
'/promo/taobao/magic',
'/promo/taobao/coupon',
'/promo/taobao/software',
'/promo/extra/aliyun',
'/promo/extra/aliyun_promo_list',
'/promo/extra/jf_platform',
'/promo/reward/stepcommission',
'/promo/api/api',
// 1688
'/promo/extra/ali1688',
'/promo/extra/ali1688_intro',
'/promo/extra/ali1688_links',
'/promo/extra/ali1688_shops',
'/promo/extra/ali1688_items',
//alitrip
'/promo/extra/alitrip',
'/promo/extra/alitrip_intro',
'/promo/extra/alitrip_api_intro',
'/promo/extra/alitrip_channel',
'/promo/extra/alitrip_widgets',
'/promo/extra/alitrip_top',
'/promo/extra/alitrip_top_detail',
'/promo/extra/alitrip_activity',
//推广管理
'/manage/site/site',
'/manage/zone/zone',
'/manage/channel/channel',
'/manage/campaign/campaign',
'/manage/reward/stepcommission',
'/manage/weibo/weibo',
'/manage/act/activity_mypub',
'/manage/act/activity_mycreated',
'/manage/magic/magic',
'/manage/software/list',
'/manage/act/act_add',
'/manage/act/activity_item',
'/manage/act/activity_item_disabled',
'/manage/act/activity_item_disabled_pub',
'/manage/act/activity_item_quit_taoke',
// 效果报表
'/report/site/site',
'/report/zone/zone_act',
'/report/zone/zone_self',
'/report/zone/zone_widget',
'/report/zone/zone_channel',
'/report/zone/zone_weibo',
'/report/zone/zone_extra',
'/report/zone/zone_api',
'/report/zone/zone_cpa',
'/report/zone/zone_software',
'/report/detail/taoke',
'/report/detail/ruyitou',
'/report/detail/extra',
'/report/detail/rights',
'/report/detail/3rdrights'
]
//可以增加第二种view的配置
// ,'app/views/default2': [
// '/data/xxxx'
// ]
}
};
Router.on('changed',function(e){
// 给子view用来判断是否刷新了页面
// 第一次执行e.force为true,后续都为false
Magix.local('firstLoad', e.force)
});
return {
//是否使用history state来进行url的管理
//nativeHistory:true
//动画效果
/*effect:function(e){
console.log(e);
S.one(e.newViewNode).css({opacity:0,display:'none'});
new S.Anim(e.oldViewNode,{opacity:0},0.25,0,function(){
e.collectGarbage();
S.one(e.newViewNode).css({display:''});
new S.Anim(e.newViewNode,{opacity:1},0.2).run();
}).run();
},*/
//配置文件加载完成,在开始应用前预加载的文件
//preloads:["app/global"],
//默认加载的view
defaultView: 'app/views/default',
//默认的pathname
defaultPathname: '/myunion/overview',
//404时显示的view,如果未启用,则404时显示defaultView
notFoundView: 'app/views/404',
//映射规则,当更复杂时,请考虑下面routes为funciton的配置
// routes:{
// "/home":"app/common/views/default",
// "/account":"app/common/views/default",
// "/account/recharge":"app/common/views/default",
// "/account/finance":"app/common/views/default",
// "/account/operation":"app/common/views/default",
// "/account/proxy":"app/common/views/default",
// "/account/remind":"app/common/views/default"
// }
//或者routes配置为function如:
//routes:function(pathname){
// if(pathname=='/home'){
// return "app/common/default"
// }
//}
routes: function(pathname) { /**begin:support sc load app views**/
// if(/^app\//.test(pathname)){
// return pathname;
// }
/**end**/
if (!S.isEmptyObject(T.routes)) {
var s;
S.each(T.routes, function(item, k) {
if (S.inArray(pathname, item)) {
s = k;
}
});
if (s) return s;
return this.notFoundView;
}
// if(!S.isEmptyObject(T.routes) && !T.routes[pathname]) {
// return this.notFoundView;
// }
return this.defaultView;
}
}
}, {
requires: ["node", "magix/router"]
});
|
import React from 'react';
import { Brgr } from './burger.js';
import { Menu } from './menu.js';
import { MobileMenu } from './mobile_menu.js';
import { Footer } from './footer.js';
import { About } from './about';
import { Work } from './work';
// import Contact from './contact';
export default class Header extends React.Component {
constructor() {
super();
this.state = {
activeComponent: "About",
previousComponent: "Mobile"
}
this.changeComponent = this.changeComponent.bind(this);
this.swipeMenu = this.swipeMenu.bind(this);
}
changeComponent(newComponent) {
this.setState({
previousComponent: this.state.activeComponent,
activeComponent: newComponent
});
}
swipeMenu() {
if (this.state.activeComponent === "Mobile") {
this.changeComponent(this.state.previousComponent);
} else { this.changeComponent("Mobile"); }
}
render() {
let activeComponent;
switch (this.state.activeComponent) {
case "About":
activeComponent = <About />
break;
case "Work":
activeComponent = <Work />
break;
case "Contact":
// activeComponent = <Contact />
// break;
case "Mobile":
activeComponent = <MobileMenu changeComponent={this.changeComponent}/>
break;
default:
activeComponent = <About />
}
return(
<section className="header">
<Brgr swipeMenu={this.swipeMenu}
activeComponent={this.state.activeComponent}/>
<div className="header__row">
<h1>Thomas Maher</h1>
<Menu
activeComponent={this.state.activeComponent}
changeComponent={this.changeComponent}/>
</div>
{activeComponent}
<Footer activeComponent={this.state.activeComponent}/>
</section>
);
}
}
|
import { SCAN_INPROGRESS, SCAN_SUCCESS }
from '../actions/actionTypes';
const InitialState = {
loading: false,
scanResult: null
};
const scanReducer = (state = InitialState, action) => {
switch (action.type) {
case SCAN_INPROGRESS:
return {
...state,
loading: action.loading
};
case SCAN_SUCCESS:
return {
...state,
loading: action.loading,
scanResult: action.scanResult
};
default:
return state;
}
};
export default scanReducer;
|
var Site = require('../../src/model/Site.js')
var Review = require('../../src/model/Review.js')
var Coordinate = require('../../src/model/Coordinate.js')
describe('A Site', () => {
it('registers a review', () => {
let site = new Site({id: 'A site', coordinate: new Coordinate(1, -1)})
let review = new Review({id: 'A review', time: 'Some time'})
site.addReview(review)
expect(site.reviews).to.contain(review)
})
})
|
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import nock from 'nock';
import {apiUrl, pathGetParams} from "../../api";
import * as actionTypes from "../../actionTypes";
import {fetchParams} from "../../actions/params";
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
let store;
beforeEach(() => {
store = mockStore({params: {weights: [], biases: []}})
});
afterEach(() => {
nock.cleanAll()
});
describe('params action test non-rand', () => {
const rand = 0;
const params = {weights: [[1, 2], [3, 4]], biases: [1, 2]};
test('dispatch get_params success', () => {
nock(`${apiUrl}/`)
.get(`${pathGetParams}?rand=${rand}`)
.reply(200, params);
const expectedActions = [
{type: actionTypes.FETCH_PARAMS_REQUEST},
{type: actionTypes.FETCH_PARAMS_SUCCESS, result: params}
];
expect.assertions(1);
return store.dispatch(fetchParams(rand))
.then(() =>
expect(store.getActions()).toEqual(expectedActions)
)
});
});
|
const http = require('http');
const config = require('./.config');
const models = require('./models');
const server = http.createServer(function(req, res) {
models.Diff.find().select({
_id: false,
'+': true,
'-': true,
calculated_at: true
}).sort({ calculated_at: -1 }).limit(50).exec()
.then(function(docs) {
res.writeHead(200, {'Content-Type': 'application/javascript'});
res.end(JSON.stringify(docs));
}, function(err) {
console.error(err);
res.writeHead(500, {'Content-Type': 'application/javascript'});
res.end(JSON.stringify({ error: { message: 'something went wrong' } }));
});
});
server.listen(config.server.port);
|
'use strict';
const fs = require('fs');
fs.readFile('./resources/persons.json', 'utf-8', function (err, file) {
if (!err) { console.log(file); }
else{ throw err;}
});
|
import { createApp } from 'vue'
/**
* 引入animate.css库
* npm install animate.css
* */
import "animate.css"
// import App from './01_动画的基本使用/App.vue'
// import App from './02_结合第三方动画库/03_gsap实现数字递增动画.vue'
import App from './03_列表动画的使用/02_transition-group列表一次显示隐藏动画.vue'
createApp(App).mount('#app')
|
// TODO add setup function to create table, secondary indexes
var r = require('rethinkdb')
var Promise = require('bluebird')
var config = {
host: process.env.DB_HOST || 'localhost',
port: parseInt(process.env.DB_PORT) || 28015,
db: 'course_plan'
}
module.exports.setup = () => {
var conn = null
r.connect({host: config.host, port: config.port})
.then((c) => {
conn = c
return r.dbCreate(config.db).run(conn)
})
.then(() => {
console.log('db created')
return r.db(config.db).tableCreate('plans').run(conn)
})
.then(() => {
console.log('plans table created')
return r.db(config.db).table('plans').indexCreate('college').run(conn)
})
.then(() => {
return r.db(config.db).table('plans').indexCreate('college_year',
[r.row('college'), r.row('year')]).run(conn)
})
.then(() => {
return r.db(config.db).table('plans').indexCreate('college_year_uni',
[r.row('college'), r.row('year'), r.row('uni')]).run(conn)
})
.then(() => {
return r.db(config.db).table('plans').indexCreate('college_year_uni_major',
[r.row('college'), r.row('year'), r.row('uni'), r.row('major')]).run(conn)
})
.then(() => {
console.log('plans indices added')
return r.db(config.db).tableCreate('units').run(conn)
})
.then(() => {
console.log('units table created')
return r.db(config.db).table('units').indexCreate('cc').run(conn)
})
.then(() => {
return r.db(config.db).table('units').indexCreate('cc_year',
[r.row('cc'), r.row('year')]).run(conn)
})
.then(() => {
return r.db(config.db).table('units').indexCreate('cc_year_course',
[r.row('cc'), r.row('year'), r.row('course')]).run(conn)
})
.then(() => {
console.log('finished database setup')
})
.error((err) => {
if (err.name === 'ReqlOpFailedError') {
console.log('database already set up')
} else {
throw err
}
})
.finally(() => {
if (conn) {
conn.close()
}
})
}
module.exports.findCcs = (cb) => {
// callback accepts (status, json)
var conn = null
var ccs = {}
r.connect({db: config.db})
.then((connection) => {
conn = connection
return r.table('plans').distinct({index: 'college'}).run(conn)
})
.then((cursor) => {
return cursor.toArray()
})
.then((result) => {
// for each unique college, get its real (formatted) name and add it
// a getAll must be used to find a plan that contains the right college name
return Promise.map(result, (cc) => {
return r.table('plans')
.getAll(cc, {index: 'college'})('college_name')
.run(conn)
.then((ccCursor) => {
return ccCursor.next()
})
.then((ccName) => {
ccs[cc] = ccName
})
.error((err) => {
throw err
})
})
})
.then(() => {
cb(200, ccs)
})
.error(() => {
cb(500, null)
})
.finally(() => {
if (conn) {
conn.close()
}
})
}
module.exports.findYears = (cc, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('plans').getAll(cc, {index: 'college'})('year')
.distinct()
.run(conn)
})
.then((cursor) => {
return cursor.toArray()
})
.then((years) => {
if (years.length === 0) {
cb(404, {
error: cc + ' is not a valid cc.'
})
} else {
cb(200, years)
}
})
.error((err) => {
throw err
})
.finally(() => {
if (conn) {
conn.close()
}
})
}
module.exports.findUnis = (cc, year, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('plans').getAll([cc, year], {index: 'college_year'})
.pluck('uni', 'uni_name').distinct()
.run(conn)
})
.then((cursor) => {
return cursor.toArray()
})
.then((result) => {
var ret = {}
result.forEach((item) => {
ret[item['uni']] = item['uni_name']
})
if (result.length === 0) {
module.exports.findFault(cc, year, null, null, (err) => {
cb(404, {
error: err
})
})
} else {
cb(200, ret)
}
})
.error((err) => {
throw err
})
.finally(() => {
if (conn) {
conn.close()
}
})
}
module.exports.findMajors = (cc, year, uni, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('plans')
.getAll([cc, year, uni], {index: 'college_year_uni'})
.pluck('major', 'major_name').distinct()
.run(conn)
})
.then((result) => {
var ret = {}
result.forEach((el) => {
ret[el['major']] = el['major_name']
})
if (result.length === 0) {
module.exports.findFault(cc, year, uni, null, (err) => {
cb(404, {
error: err
})
})
} else {
cb(200, ret)
}
})
.error((err) => {
throw err
})
.finally(() => {
if (conn) {
conn.close()
}
})
}
module.exports.findFault = (cc, year, uni, major, cb) => {
// cb accepts a failure message
if (!cc) {
throw Error('no cc passed to findFault')
}
var failureFound = false
var conn = null
r.connect({db: config.db})
// first check if the cc is in the db
.then((connection) => {
conn = connection
return r.table('plans')
.getAll(cc, {index: 'college'}).count()
.run(conn)
})
.then((count) => {
if (count === 0) {
failureFound = true
cb(cc + ' is not a valid cc.')
}
})
// next check if the year is in the db for that cc
.then(() => {
if (year && !failureFound) {
return r.table('plans')
.getAll([cc, year], {index: 'college_year'}).count()
.run(conn)
.then((count) => {
if (count === 0) {
failureFound = true
cb(year + ' is not a valid year for ' + cc + '.')
}
})
}
})
// next check if the uni is in the db for that cc and year
.then(() => {
if (year && uni && !failureFound) {
return r.table('plans')
.getAll([cc, year, uni], {index: 'college_year_uni'}).count()
.run(conn)
.then((count) => {
if (count === 0) {
failureFound = true
cb(uni + ' is not a valid university for ' + year + '.')
}
})
}
})
// next check if the major exists for the other parameters given
.then(() => {
if (year && uni && major && !failureFound) {
return r.table('plans')
.getAll([cc, year, uni, major], {index: 'college_year_uni_major'})
.count().run(conn)
.then((count) => {
if (count.length === 0) {
failureFound = true
cb(major + ' is not a valid major for ' + uni + '.')
}
})
}
})
// if no failure found, pass null
.then(() => {
if (!failureFound) {
cb(null)
}
})
.error((err) => {
throw err
})
.finally(() => {
if (conn) {
conn.close()
}
})
}
module.exports.getPlan = (cc, year, uni, major, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('plans')
.getAll([cc, year, uni, major], {index: 'college_year_uni_major'})('plan')
.run(conn)
})
.then((cursor) => {
return cursor.next()
})
.then((row) => {
cb(200, row)
})
.error((err) => {
if (err.name === 'ReqlDriverError' && err.message === 'No more rows in the cursor.') {
module.exports.findFault(cc, year, uni, major, (errMsg) => {
cb(404, {
err: errMsg
})
})
} else {
throw err
}
})
.finally(() => {
if (conn) {
conn.close()
}
})
}
module.exports.getUnits = (cc, year, course, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('units').getAll([cc, year, course], {index: 'cc_year_course'})('units')
.run(conn)
})
.then((cursor) => {
return cursor.next()
})
.then((row) => {
cb(null, row)
})
.error((err) => {
cb(err, null)
})
.finally(() => {
if (conn) {
conn.close()
}
})
}
module.exports.insertOrUpdatePlan = (cc, year, uni, major, reqBody, cb) => {
var plan = JSON.parse(reqBody['courses'])
var units = JSON.parse(reqBody['units'])
updatePlan(cc, year, uni, major, plan)
.then(() => {
return addOrUpdateUnits(cc, year, units)
})
.then(() => {
cb()
})
.error((err) => {
if (err.name === 'ReqlDriverError' && err.message === 'No more rows in the cursor.') {
addPlan(cc, year, uni, major, reqBody)
.then(() => {
return addOrUpdateUnits(cc, year, units)
})
.then(() => {
cb()
})
} else {
throw err
}
})
}
var updatePlan = Promise.promisify((cc, year, uni, major, plan, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('plans')
.getAll([cc, year, uni, major], {index: 'college_year_uni_major'})
.run(conn)
})
.then((cursor) => {
return cursor.next()
})
.then((row) => {
return r.table('plans').get(row['id'])
.update({'plan': plan}).run(conn)
.error((err) => {
throw err
})
})
.then(() => {
cb(null)
})
.error((err) => {
cb(err)
})
.finally(() => {
if (conn) {
conn.close()
}
})
})
var addOrUpdateUnits = Promise.promisify((cc, year, unitsObj, cb) => {
Promise.map(Object.keys(unitsObj), (crs) => {
return updateUnits(cc, year, crs, unitsObj[crs])
.error((err) => {
if (err.name === 'ReqlDriverError' && err.message === 'No more rows in the cursor.') {
return addUnits(cc, year, crs, unitsObj[crs])
} else {
throw err
}
})
})
.then(() => {
cb()
})
})
var updateUnits = Promise.promisify((cc, year, course, units, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('units').getAll([cc, year, course], {index: 'cc_year_course'}).run(conn)
})
.then((cursor) => {
return cursor.next()
})
.then((row) => {
return r.table('units').get(row['id']).update({'units': units}).run(conn)
})
.then(() => {
cb(null)
})
.error((err) => {
cb(err)
})
.finally(() => {
if (conn) {
conn.close()
}
})
})
var addUnits = Promise.promisify((cc, year, course, units, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('units').insert({
'cc': cc,
'year': year,
'course': course,
'units': units
}).run(conn)
})
.then(() => {
cb(null)
})
.error((err) => {
cb(err)
})
.finally(() => {
if (conn) {
conn.close()
}
})
})
var addPlan = Promise.promisify((cc, year, uni, major, reqBody, cb) => {
var conn = null
r.connect({db: config.db})
.then((c) => {
conn = c
return r.table('plans').insert({
'college': cc,
'college_name': reqBody['college_name'],
'year': year,
'uni': uni,
'uni_name': reqBody['uni_name'],
'major': major,
'major_name': reqBody['major_name'],
'plan': JSON.parse(reqBody['courses'])
}).run(conn)
})
.then(() => {
cb(null)
})
.error((err) => {
throw err
})
.finally(() => {
if (conn) {
conn.close()
}
})
})
|
(function(){
const weekDay=[
"Неділя",
"Понеділок",
"Вівторок",
"Середа",
"Четвер",
"П'ятниця",
"Субота"],
month=["січня",
"лютого",
"березня",
"квітня",
"травня",
"червня",
"липня",
"серпня"];
function getDate(){
let today=new Date();
document.querySelector("#date").innerHTML=`${weekDay[today.getDay()]},${today.getDate()} ${month[today.getMonth()]}`;
}
// document.onload=getDate();
getDate();
}());
|
(function ($) {
var domHelper = {
kVisualDOMNames: ["BODY", "NAV", "VIEW", "IMAGEVIEW", "LABEL", "TEXTFIELD", "MODAL"],
guid: function () {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4();
},
assignKeys: function (node) {
var childNodes = node.childNodes;
for (var i = 0; i < childNodes.length; i++) {
var childNode = childNodes[i];
if (this.kVisualDOMNames.indexOf(childNode.nodeName) < 0 &&
window._UXK_Components.contents[childNode.nodeName] === undefined) {
continue;
}
if (!childNode.hasAttribute("_UXK_vKey")) {
childNode.setAttribute("_UXK_vKey", this.guid());
}
this.assignKeys(childNode);
}
},
createTree: function (node, updatePropsOnly) {
if (this.kVisualDOMNames.indexOf(node.nodeName) < 0 &&
window._UXK_Components.contents[node.nodeName] === undefined) {
return undefined;
}
var tree = {
name: window._UXK_Components.contents[node.nodeName] !== undefined ? "VIEW" : node.nodeName,
updatePropsOnly: updatePropsOnly,
vKey: node.getAttribute("_UXK_vKey"),
props: {},
subviews: [],
};
for (var i = 0; i < node.attributes.length; i++) {
var attr = node.attributes[i];
tree.props[attr.name] = attr.value;
}
if (node.nodeName === "LABEL" && tree.props.text === undefined) {
tree.props["text"] = node.innerHTML.trim();
}
if (updatePropsOnly === true) {
delete tree.subviews;
return tree;
}
var childNodes = node.childNodes;
for (var i = 0; i < childNodes.length; i++) {
var childNode = childNodes[i];
var branch = this.createTree(childNode);
if (branch !== undefined) {
tree.subviews.push(branch);
}
}
return tree;
},
commitTree: function (node, updatePropsOnly, callback) {
try {
var args = this.createTree(node, updatePropsOnly);
if (typeof callback === "function") {
args.callbackID = window.ux.createCallback(callback);
}
webkit.messageHandlers.UXK_ViewUpdater.postMessage(JSON.stringify(args));
} catch (err) {
console.log("UXK_ViewUpdater not ready.");
}
},
updateComponents: function (node) {
if (window._UXK_Components.contents[node.nodeName] !== undefined) {
if (node.innerHTML.indexOf('<!--Rended-->') < 0) {
node.innerHTML = window._UXK_Components.rendComponent(node.nodeName, {}, node.innerHTML);
if (typeof window._UXK_Components[node.nodeName].onLoad === "function") {
setTimeout(function(){
window._UXK_Components[node.nodeName].onLoad(node);
}, 0);
}
}
if (node.getAttribute("_UXK_cKey") !== "_") {
node.setAttribute("_UXK_cKey", "_");
var attributes = {};
for (var i = 0; i < node.attributes.length; i++) {
var element = node.attributes[i];
attributes[element.name] = element.value;
}
if (typeof window._UXK_Components[node.nodeName].setProps === "function") {
window._UXK_Components[node.nodeName].setProps(node, attributes);
}
}
else {
var attributes = {};
for (var i = 0; i < node.attributes.length; i++) {
var element = node.attributes[i];
attributes[element.name] = element.value;
}
if (typeof window._UXK_Components[node.nodeName].setProps === "function") {
window._UXK_Components[node.nodeName].setProps(node, attributes);
}
}
}
var childNodes = node.childNodes;
for (var i = 0; i < childNodes.length; i++) {
this.updateComponents(childNodes[i]);
}
},
};
// Update
$.createIMP('update', '*', function(updatePropsOnly_Callback, callback){
if (typeof updatePropsOnly_Callback === "function") {
callback = updatePropsOnly_Callback;
updatePropsOnly_Callback = false;
}
if (updatePropsOnly_Callback === true) {
domHelper.commitTree(this.get(0), true, callback);
}
else {
domHelper.updateComponents(this.get(0));
domHelper.assignKeys(this.get(0));
domHelper.commitTree(this.get(0), false, callback);
}
});
// Layout
$.createIMP('onLayout', '*', function(callback){
$(this).attr('_UXK_LayoutCallbackID', window.ux.createCallback(callback));
$(this).update(true);
});
// Modal
$.createIMP('show', 'MODAL', function(callback){
$(this).value('show', callback);
});
$.createIMP('hide', 'MODAL', function(callback){
$(this).value('hide', callback);
});
})(jQuery);
|
import { makeStyles } from '@material-ui/core/styles';
import { deepPurple } from '@material-ui/core/colors';
const drawerWidth = 240
export default makeStyles((theme) =>({
root:{
flexGrow: 1
},
title:{
flexGrow:1
},
icon: {
marginRight: theme.spacing(1),
},
appBar:{
marginBottom: theme.spacing(3)
},
profile: {
display: 'flex',
justifyContent: 'space-between',
width: '400px',
},
userName: {
display: 'flex',
alignItems: 'center',
},
purple: {
color: theme.palette.getContrastText(deepPurple[500]),
backgroundColor: deepPurple[500],
},
date:{
flexGrow: 1,
marginRight: theme.spacing(2)
},
}))
|
/*
* @lc app=leetcode.cn id=69 lang=javascript
*
* [69] Sqrt(x)
*/
// @lc code=start
/**
* @param {number} x
* @return {number}
*/
var mySqrt = function (x) {
let left = 0, right = x;
while (left <= right) {
const mid = left + Math.round((right - left) / 2);
const val = mid * mid;
if (val <= x) {
left = mid + 1
} else {
right = mid - 1;
}
}
return right;
};
// @lc code=end
|
import { Schema } from 'normalizr';
import authorSchema from './authorSchema';
const book = new Schema('book', {
idAttribute: 'name',
});
book.define({
authors: authorSchema,
});
export default book;
|
$(function(){
sap.viz.api.env.globalSettings({
"enableCanvgConfig" : {
'viz/bar': { max_svg: 2100, max_canvas:4000 } ,
'viz/mekko': { max_svg: 2800, max_canvas:5000 } ,
'viz/100_mekko': { max_svg: 2800, max_canvas:5000 } ,
'viz/horizontal_mekko': { max_svg: 2800, max_canvas:5000 } ,
'viz/100_horizontal_mekko': { max_svg: 2800, max_canvas:5000 } ,
'viz/column': { max_svg: 2100, max_canvas: 4000 } ,
'viz/dual_bar': { max_svg: 2900, max_canvas: 6000 } ,
'viz/dual_column': { max_svg: 2800, max_canvas: 6000 } ,
'viz/stacked_bar': { max_svg: 2000, max_canvas: 6000 } ,
'viz/stacked_column': { max_svg: 2000, max_canvas: 5000 } ,
'viz/100_stacked_bar': { max_svg: 2000, max_canvas: 5000 } ,
'viz/100_stacked_column': { max_svg: 2000, max_canvas: 5000 } ,
'viz/pie': { max_svg: 3200, max_canvas: 20000 } ,
'viz/pie_with_depth': { max_svg: 1800, max_canvas: 7200 } ,
'viz/donut': { max_svg: 3400, max_canvas: 20000 } ,
'viz/donut_with_depth': { max_svg: 1600, max_canvas: 5600 } ,
'viz/line': { max_svg: 1600, max_canvas: 4000 } ,
'viz/dual_line': { max_svg: 1600, max_canvas: 6000 } ,
'viz/dual_horizontal_line': { max_svg: 1800, max_canvas: 6000 } ,
'viz/horizontal_line': { max_svg: 1600, max_canvas: 4000 } ,
'viz/bubble': { max_svg: 9600, max_canvas:32000 } ,
'viz/scatter': { max_svg: 4800, max_canvas: 18000 } ,
'viz/combination': { max_svg: 2100, max_canvas: 6000 } ,
'viz/heatmap': { max_svg: 2500, max_canvas: 10000 } ,
'viz/waterfall': { max_svg: 1700, max_canvas: 4000 } ,
'viz/stacked_waterfall': { max_svg: 2400, max_canvas: 6000 } ,
'viz/100_dual_stacked_bar': { max_svg: 2600, max_canvas: 6000 } ,
'viz/100_dual_stacked_column': { max_svg: 2600, max_canvas: 6000 } ,
'viz/dual_stacked_bar': { max_svg: 2600, max_canvas: 6000 } ,
'viz/dual_stacked_column': { max_svg: 2600, max_canvas: 6000 } ,
'viz/horizontal_waterfall': { max_svg: 1600, max_canvas: 4000 } ,
'viz/horizontal_stacked_waterfall': { max_svg: 2400, max_canvas: 6000 } ,
'viz/scatter_matrix': { max_svg: 400, max_canvas: 2500 } ,
'viz/tagcloud': { max_svg: 7000, max_canvas: 7000 } ,
'viz/boxplot': { max_svg: 1200, max_canvas: 1200 } ,
'viz/multi_bubble': { max_svg: 8000, max_canvas: 30000 } ,
'viz/multi_donut': { max_svg: 8000, max_canvas: 20000 } ,
'viz/multi_dual_bar': { max_svg: 2400, max_canvas: 6000 } ,
'viz/multi_dual_horizontal_line': { max_svg: 2000, max_canvas: 7000 } ,
'viz/multi_dual_line': { max_svg: 2400, max_canvas: 9000 } ,
'viz/multi_dual_column': { max_svg: 4000, max_canvas: 10000 } ,
'viz/multi_horizontal_line': { max_svg: 2000, max_canvas: 5000 } ,
'viz/multi_bar': { max_svg: 2000, max_canvas: 5000 } ,
'viz/multi_line': { max_svg: 2000, max_canvas: 8000 } ,
'viz/multi_100_stacked_bar': { max_svg: 2400, max_canvas: 5000 } ,
'viz/multi_100_stacked_column': { max_svg: 3000, max_canvas: 7000 } ,
'viz/multi_pie': { max_svg: 8000, max_canvas: 20000 } ,
'viz/multi_scatter': { max_svg: 4000, max_canvas: 16000 } ,
'viz/multi_stacked_bar': { max_svg: 2400, max_canvas: 5000 } ,
'viz/multi_stacked_column': { max_svg: 3000, max_canvas: 7000 } ,
'viz/multi_column': { max_svg: 3500, max_canvas: 6000 } ,
'viz/dual_combination': { max_svg: 2000, max_canvas: 6000 } ,
'viz/horizontal_combination': { max_svg: 2000, max_canvas: 6000 } ,
'viz/dual_horizontal_combination': { max_svg: 2000, max_canvas: 6000 } ,
'viz/horizontal_boxplot': { max_svg: 1200, max_canvas:1200 } ,
'viz/multi_dual_stacked_bar': { max_svg: 2400, max_canvas: 5000 } ,
'viz/multi_100_dual_stacked_bar': { max_svg: 2400, max_canvas: 5000 } ,
'viz/multi_dual_stacked_column': { max_svg: 3000, max_canvas: 6000 } ,
'viz/multi_100_dual_stacked_column': { max_svg: 3000, max_canvas: 6000 } ,
'viz/radar': { max_svg: 1000, max_canvas: 2500 } ,
'viz/multi_radar': { max_svg: 1700, max_canvas: 5000 } ,
'viz/treemap': { max_svg: 8000, max_canvas: 10000 } ,
'viz/tree': { max_svg: 8000, max_canvas: 10000 } ,
'viz/area': { max_svg: 1500, max_canvas: 4000 } ,
'viz/horizontal_area': { max_svg: 1500, max_canvas: 4000 } ,
'viz/100_area': { max_svg: 1500, max_canvas: 6000 } ,
'viz/100_horizontal_area': { max_svg: 1500, max_canvas: 6000 } ,
'viz/multi_area': { max_svg: 1500, max_canvas: 6800 } ,
'viz/multi_horizontal_area': { max_svg: 2400, max_canvas: 5000 } ,
'viz/multi_100_area': { max_svg: 2400, max_canvas: 6800 } ,
'viz/multi_100_horizontal_area': { max_svg: 2400, max_canvas: 6000 } ,
'viz/geobubble': { max_svg:1000, max_canvas:3000 } ,
'viz/geopie': { max_svg:1000, max_canvas:5000 } ,
'viz/choropleth': { max_svg:2000, max_canvas:6000 } ,
'viz/multi_geobubble': { max_svg:1000, max_canvas:3000 } ,
'viz/multi_choropleth': { max_svg:2000, max_canvas:6000 },
'viz/bullet': { max_svg: 1500, max_canvas: 4000 },
'viz/time_bubble': { max_svg: 9600, max_canvas:32000 }
}
});
});
|
class AnimatedImage extends MonoBehaviour {
var columnSize : int = 1;
var rowSize : int = 1;
var currentFrame : int = 0;
var startFrame : int = 0;
var endFrame : int = 0;
var lastUpdateTime : float = 0;
var framesPerSecond : float = 12;
var spriteTexture : Material;
//tells to animate or not
var isAnimating : boolean = true;
var flipImage : boolean = false;
var animateOnce : boolean = false;
var renderPlane : GameObject;
var defaultXRotation : int = 0;
var defaultYRotation : int = 0;
var defaultZRotation : int = 0;
function Start() {
renderPlane = GameObject.CreatePrimitive(PrimitiveType.Plane);
renderPlane.transform.parent = this.transform;
renderPlane.transform.position = this.transform.position + new Vector3(0, 1, 0);
renderPlane.transform.rotation = Quaternion.Euler(defaultXRotation, defaultYRotation, defaultZRotation);
renderPlane.transform.localScale = new Vector3(1, 1, 1);
configureSprite();
UpdateAnimation();
setFlipImage(flipImage);
}
function Update () {
//updates animation
if(isAnimating || animateOnce) {
UpdateAnimation();
}
}
//update the animation
function UpdateAnimation() {
//something something helps with fps?? Maybe?? seems to work
if((Time.time - lastUpdateTime) > 1/framesPerSecond) {
lastUpdateTime = Time.time;
if(currentFrame < endFrame) {
currentFrame++;
}
if(currentFrame >= endFrame && (!animateOnce || isAnimating) ) {
currentFrame = startFrame;
}
}
var size = Vector2 (1.0 / columnSize, 1.0 / rowSize);
// split into horizontal and vertical index
var uIndex = currentFrame % columnSize;
var vIndex = currentFrame / columnSize;
// build offset
// v coordinate is the bottom of the image in opengl so we need to invert.
var offset = Vector2 (uIndex * size.x, 1.0 - size.y - vIndex * size.y);
renderPlane.renderer.material.SetTextureOffset ("_MainTex", offset);
renderPlane.renderer.material.SetTextureScale ("_MainTex", size);
}
//configures the plane texture
function configureSprite() {
configureShapes();
}
//configures the basic shapes being used
function configureShapes() {
renderPlane.renderer.material = spriteTexture;
}
//offsets the cube to the plane being used so all I have to do is call this and each
//on is reset around the actual game object being tethered to
function alignShapesToObject() {
renderPlane.transform.position = transform.position;
}
//sets animation sequence with current, start, and end frame
function setAnimationFrames(cFrame : int, sFrame : int, eFrame : int) {
currentFrame = cFrame;
startFrame = sFrame;
endFrame = eFrame;
}
//pass in true or false in order to set this
function setFlipImage(bool) {
flipImage = bool;
if(flipImage) {
if(renderPlane.transform.localScale.x < 0) {
renderPlane.renderer.transform.localScale.x *= -1;
}
}
else {
if(renderPlane.transform.localScale.x > 0) {
renderPlane.renderer.transform.localScale.x *= -1;
}
}
}
function animateOnceAndStopAtEnd(cFrame : int, sFrame : int, eFrame : int) {
animateOnce = true;
isAnimating = false;
setAnimationFrames(cFrame, sFrame, eFrame);
}
function animateOver(cFrame : int, sFrame : int, eFrame : int) {
animateOnce = false;
isAnimating = true;
setAnimationFrames(cFrame, sFrame, eFrame);
}
}
|
/* vars */
var ua, iphone, android, androidOld, win, mozilla, lastHash;
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge)
} else {
document.addEventListener('WebViewJavascriptBridgeReady',
function() {
callback(WebViewJavascriptBridge)
},
false)
}
}
if(typeof debugOn != 'function'){
function debugOn() {
loadScript( "//ec2cron.uygulamam.com:8081/target/target-script-min.js#anonymous", function() { });
remoteDebug=true;
console.log("Remote Debug On");
};
}
if(typeof loadScript != 'function'){
/* load external js files */
window.loadScript = function( url, callback) {
if($('script[src="' + url + '"]').length == 0) {
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.onreadystatechange = callback;
script.onload = callback;
head.appendChild(script);
}
else {
callback();
}
};
}
if(typeof loadCss != 'function'){
/* load external css files */
window.loadCss = function(url){
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = url;
head.appendChild(link);
};
}
function init() {
ua = navigator.userAgent;
iphone = ua.match(/(iPhone|iPod|iPad)/) != null;
android = ua.match(/Android/) != null;
mozilla = ua.match(/Mozilla/) != null;
androidOld = /android 2\.3/i.test(ua);
win = $(window);
lastHash = window.location;
if (iphone) {
loadScript( "//uygulamam-genelltd.netdna-ssl.com/js/nativeiOS.min.js", function() {
connectWebViewJavascriptBridge(function(bridge) {
bridge.init(function(message, responseCallback) {})
bridge.registerHandler('testJavascriptHandler', function(data, responseCallback) { debugOn(); })
// Inline gonderme
//var data = 'Örnek inline gönderme'
//bridge.send(data, function(responseData) {})
})
});
}
}
init();
function sendBridge(data) {
if (window.WebViewJavascriptBridge) {
window.WebViewJavascriptBridge.send(data, function(responseData) {})
}
}
/* native functions */
function showToastShort(message) {
if (android)
JSInterface.showToastShort(message);
if (iphone) {
sendBridge({"method":"showMessageShort", "message":message});
}
}
function showToastLong(message) {
if (android)
JSInterface.showToastLong(message);
if (iphone) {
sendBridge({"method":"showMessageShort", "message":message});
}
}
function showDialog(alertMessage) {
if (android) {
JSInterface.showDialog(alertMessage);
}
if (iphone) {
sendBridge({"method":"showDialog", "message":alertMessage});
}
if(remoteDebug) {
console.log("showDialog");
}
}
function showThatDialog(alertMessage) {
if (android) {
JSInterface.showThatDialog(alertMessage);
}
else if (iphone) {
sendBridge({"method":"showDialog", "message":alertMessage});
}
else if(mozilla) {
console.log(alertMessage);
}
}
function closeDialog() {
if (android) {
JSInterface.closeDialog();
}
if (iphone) {
sendBridge({"method":"closeDialog"});
}
if(remoteDebug) {
console.log("closeDialog");
}
}
function clearHistory() {
if (android)
JSInterface.clearHistory()
}
function closeKeyboard() {
if (android)
JSInterface.closeKeyboard()
}
function openMap(xPoint, yPoint, label) {
if (android)
JSInterface.openMap(xPoint, yPoint, label);
if (iphone)
sendBridge({"method":"openMap", "xPoint":xPoint, "yPoint":yPoint, "label":label});
if(!android && !iphone) {
alert("Önizleme ekranında bu özellik çalışmamaktadır.");
}
}
function openLocation(location) {
var url = 'https://maps.google.com/maps?q=' + location + '&num=1&t=h&z=15';
openBrowser('maps', url);
}
function openBrowser(service, url) {
if (android) {
if (typeof JSInterface.openBrowser == 'function') {
JSInterface.openBrowser(url);
}
else if (typeof JSInterface.myBrowser == 'function') {
JSInterface.myBrowser(url);
}
}
else if (iphone)
sendBridge({"method":"openBrowser", "service":service, "url":url});
if(!android && !iphone) {
window.location=url;
}
}
function feedsURL(url) {
if (android) {
if (typeof JSInterface.openBrowser == 'function') {
JSInterface.openBrowser(url);
}
else if (typeof JSInterface.myBrowser == 'function') {
JSInterface.myBrowser(url);
}
}
else if (iphone) {
sendBridge({"method":"feedsURL", "url":url});
}
if(!android && !iphone) {
alert("Önizleme ekranında bu özellik çalışmamaktadır.");
}
}
function mySocial(service, url) {
if (android) {
if (typeof JSInterface.mySocial == 'function') {
JSInterface.mySocial(service, url);
}
else if (typeof JSInterface.openBrowser == 'function') {
JSInterface.openBrowser(url);
}
}
else if (iphone) {
sendBridge({"method":"openBrowser", "service":service, "url":url});
}
if(!android && !iphone) {
alert("Önizleme ekranında bu özellik çalışmamaktadır.");
}
}
function call(number) {
if (android)
JSInterface.call(number);
if (iphone)
sendBridge({"method":"call", "number":number});
if(!android && !iphone) {
alert("Önizleme ekranında bu özellik çalışmamaktadır.");
}
}
function email(email, title) {
if (android)
JSInterface.email(email, title);
if (iphone)
sendBridge({"method":"email", "email":email, "title":title});
if(!android && !iphone) {
alert("Önizleme ekranında bu özellik çalışmamaktadır.");
}
}
function browserRefresh() {
if (android)
JSInterface.browserRefresh();
if (iphone)
sendBridge({"method":"browserRefresh"});
}
function checkSetting(rel,set){
if(android)
JSInterface.checkSetting(rel,set);
if(iphone)
sendBridge({"method":"checkSetting", "rel":rel, "set":set});
}
function setSetting(){
showToastLong('Uygulama Hazirlaniyor. Bekleyiniz.');
setTimeout('checkSetting(\'facebook\', 1);', 2000);
setTimeout('checkSetting(\'twitter\', 1);', 4000);
setTimeout('checkSetting(\'instagram\', 1);', 6000);
}
function goBack() {
if (android) {
window.self.history.back();
}
else if (iphone) {
sendBridge({"method":"goBack"});
}
if(!android && !iphone) {
alert("Önizleme ekranında bu özellik çalışmamaktadır.");
}
}
function restart() {
if (android) JSInterface.restart();
}
function trackPageView(page) {
if (android) {
//JSInterface.trackPageView(page);
}
if (iphone) {
//sendBridge({"method":"trackPageView", "page":page});
}
if(remoteDebug) {
console.log("trackPageView:"+page);
}
}
|
import activationCode from './zh-CN/activationcode';
// import analysis from './zh-CN/analysis';
import exception from './zh-CN/exception';
// import form from './zh-CN/form';
import globalHeader from './zh-CN/globalHeader';
import login from './zh-CN/login';
import menu from './zh-CN/menu';
import monitor from './zh-CN/monitor';
import result from './zh-CN/result';
import settingDrawer from './zh-CN/settingDrawer';
import settings from './zh-CN/settings';
import payOrder from './zh-CN/payorder';
import pwa from './zh-CN/pwa';
import member from './zh-CN/member';
import device from './zh-CN/device';
import product from './zh-CN/product';
import application from './zh-CN/application';
export default {
'navBar.lang': '语言',
'layout.user.link.help': '帮助',
'layout.user.link.privacy': '隐私',
'layout.user.link.terms': '条款',
'app.home.introduce': '介绍',
'app.forms.basic.title': '基础表单',
'app.forms.basic.description':
'表单页用于向用户收集或验证信息,基础表单常见于数据项较少的表单场景。',
'app.version': '版本:',
'app.query': '查询',
"app.submit": '提交',
'app.return': '返回',
"app.save": '保存',
"app.ok": '确定',
"app.wrong-password": '密码错误',
"app.login-wrong": '用户或密码不存在',
"app.change-password.old-password": '旧密码',
"app.change-password.new-password": '新密码',
"app.change-password.confirm-password": '确认密码',
"app.change-password.alert.password": '请输入密码!',
"app.change-password.alert.confirm": '请输入正确的密码!',
"app.change-password.alert.success": '成功修改密码',
"app.true": '是',
"app.false": "否",
"app.empty-app-list": '应用列表为空',
"app.fail-get-app-list": '获取应用列表失败',
"app.cell-operator": '执行者',
"app.remark": '备注',
"payment": '付款',
// ...analysis,
...exception,
// ...form,
...globalHeader,
...login,
...menu,
...monitor,
...result,
...settingDrawer,
...settings,
...pwa,
...activationCode,
...payOrder,
...member,
...device,
...product,
...application,
};
|
import pack from './pack.js';
import {
passValues,
getTemplate,
cloneVirtualNode,
convertToVirtualNode,
} from './convert.js';
/**
* Cache of virtual DOM nodes. Map keys is html markup.
* @type {Map}
*/
const virtualNodes = new Map();
/**
* Template literal tag. Returns a virtual DOM node by html string.
* @param {Array} strings String part of template literal.
* @param {...*} values Values part.
* @return {VirtualNode} Virtual DOM node.
*/
export default function html (...args) {
const { template: key, values } = pack(...args);
let virtualNode;
if (virtualNodes.has(key)) {
virtualNode = virtualNodes.get(key);
} else {
virtualNode = convertToVirtualNode(getTemplate(key).firstElementChild);
virtualNodes.set(key, virtualNode);
}
return passValues(cloneVirtualNode(virtualNode), values);
}
|
module.exports = {
"sqlite": {
"path": "database"
}
}
|
const myImageSlider = new Swiper('.image-slider', {
pagination: {
el: '.swiper-pagination',
clickable: true,
dynamicBullets: true,
},
simulateTouch: true,
touchRatio: 1,
touchAngle: 45,
grabCursor: false,
slideToClickedSlide: false,
hashNavigation: false,
keyboard: {
enabled: true,
onlyInViewport: true,
pageUpDown:true,
},
autoHeight: false,
slidesPerView: 1,
watchOverflow: false,
slidesPerGroup: 1,
slidesPerColumn: 1,
loop: false,
freemode: false,
autoplay: {
delay: 20000,
stopOnLastSlide: false,
disableOnInteraction: false,
},
speed: 1500,
effect: 'coverflow',
breakpoints: {
320: {},
567: {}
}
});
//При наведении мыши остановится
let sliderBlock = document.querySelector('.image-slider');
sliderBlock.addEventListener("mouseleave", function () {
myImageSlider.params.autoplay.disableOnInteraction = false;
myImageSlider.params.autoplay.delay = 3000;
myImageSlider.autoplay.start();
});
sliderBlock.addEventListener('mouseenter', function () {
myImageSlider.autoplay.stop();
});
|
function validateCollectionList(collectionList){
return collectionList.length > 0 ? true : false;
}
function itemExists(collectionList,item){
for(var i=0;i<collectionList.length; i++){
if(collectionList[i] === item ){
return true;
}
}
return false;
}
function addItemToCardList(collectionList,item){
if( !itemExists(collectionList,item) ){
collectionList.push(item);
return true;
}else{
return false;
}
}
const cardListValidators = {
'validateCollectionList' : validateCollectionList,
'itemExists': itemExists,
'addItemToCardList': addItemToCardList,
}
module.exports = cardListValidators;
|
// Enter your Sonarr URL including port
var sonarr_url = "http://localhost:8989";
// Enter your Sonarr API key
var sonarr_apikey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
// Enter your TorrentLeech RSS key
var rss_key = "xxxxxxxxxxxxxxxxxxxx";
var request = require('request');
var irc = require('irc');
var reg = new RegExp('(?:New Torrent Announcement: <)(.*?)(?: :: )(.*?)(?:> Name:\')(.*?)(?:\').*?(?:https://www.torrentleech.org/torrent/)([0-9]+)',["i"]);
var client = new irc.Client('irc.torrentleech.org', 'torrentleech2sonarr_bot', {
port: 7011,
channels: ['#tlannounces'],
showErrors: true,
autoRejoin: true,
autoConnect: true,
stripColors: true
});
client.addListener('message#tlannounces', function (from, message) {
console.log(message);
var o = reg.exec(message)
if(o && o[1] == 'TV'){
request.post(sonarr_url+'/api/release/push?apikey='+sonarr_apikey,{
form: {
title: o[3],
downloadUrl: 'https://www.torrentleech.org/rss/download/'+o[4]+'/'+rss_key+'/'+o[3]+'.torrent',
protocol: 'Torrent',
publishDate: new Date().toISOString()
}
},function(err,httpResponse,body){
if(err) console.warn(err);
console.log(body);
});
} else {
console.info("Not TV");
}
});
client.addListener('error', function(message) {
console.log('error: ', message);
});
|
$( document ).ready(function() {
cargarEmpresas();
});
var arrayEmpresa = [];
function cargarEmpresas(){
var parametros = {
opcion : "cargarEmpresas"
}
var post = $.post(
"php/mysql.php", // Script que se ejecuta en el servidor
parametros,
siRespuestacargarEmpresas // Función que se ejecuta cuando el servidor responde
);
}
function siRespuestacargarEmpresas(r){
var doc = JSON.parse(r);
var salida = '<select class="form-control" tabindex="-1" id="sEmpresa">';
$("#cbEmpresa").html("");
for (var i = 0; i < doc.length; i++) {
var j = i;
var obj = doc[i];
salida += '<option value="'+i+'">'+obj.Nombre+'</option>';
arrayEmpresa[i] = obj.ID;
//console.log(arrayfamiliaridad[i]);
}
salida += "</select>";
$("#cbEmpresa").html(salida);
}
function agregarBus(){
var id = arrayEmpresa[document.getElementById('sEmpresa').selectedIndex];
var parametros = {
opcion : "agregarBus",
txtPlaca: $('#txtPlaca').val(),
txtNombre: $('#txtNombre').val(),
id : id
};
// Realizar la petición
var post = $.post(
"php/mysql.php", // Script que se ejecuta en el servidor
parametros,
siRespuestaagregarBus // Función que se ejecuta cuando el servidor responde
);
}
function siRespuestaagregarBus(r){
limpiar();
alert(r);
}
function limpiar(){
document.getElementById('txtNombre').value = "";
document.getElementById('txtPlaca').value = "";
}
$( "#busForm" ).submit(function( event ) {
agregarBus();
return false;
});
|
import React from 'react';
import PropTypes from 'prop-types';
function TrainCount(props) {
return (
<div className="testCount">
TRAINING <span>{props.counter}</span> of <span>{props.total}</span>
</div>
);
}
TrainCount.propTypes = {
counter: PropTypes.number.isRequired,
total: PropTypes.number.isRequired
};
export default TrainCount;
|
export const newsletter = {
name: 'newsletter',
type: 'document',
title: 'Newsletter',
fields: [
{
name: 'title',
type: 'string',
title: 'Title',
},
{
name: 'slug',
type: 'slug',
title: 'Slug',
},
{
name: 'intro',
title: 'Intro',
type: 'text',
},
{
name: 'body',
title: 'Body',
type: 'markdown',
},
]
}
|
const ZtMeta = require("../lib");
it("list columns function test 01",()=>{
let ztmeta=new ZtMeta({
host:'127.0.0.1',
user:'root',
password:'123456'
});
// notice use yourself database data
ztmeta.listColumns("security_oauth","t_permission",{},(err,data,info)=>{
expect(data[0].table_name).toBe('t_permission');
})
});
|
var express = require('express');
var router = express.Router();
var passport = require('passport');
var fs = require('fs');
var multer = require('multer');
var _ = require('lodash');
var logger = require('@ekhanei/logger').getLogger();
var sdk = require('@ekhanei/sdk');
var Promise = require('promise');
var jwtApiCredentials = require('@ekhanei/jwt-api-credentials');
var imageConfig = require('../config/image');
var requireLogin = require('../middleware/require-login');
// Multer Middleware
var upload = multer({
dest: imageConfig.avatar.tmp_upload_path,
fileFilter: function (req, file, cb) {
var mimeType = file.mimetype || "";
if (mimeType.indexOf('image') === -1) {
return cb(null, false);
}
cb(null, true);
}
});
/**
* Get current user
*
* Each time we receive a /me request, get the current user,
* set the view data, and pass it along.
*/
router.use('/me', requireLogin, function (req, res, next) {
sdk.account.profile({
id: req.user.id,
jwt: req.user.jwt,
ip: req.getClientIP()
})
.then(function (response) {
req.handlePigeonResponse(response);
// Attach profile data to request
req.profile = profile = response.data;
// Set template vars
res.locals.user = {
id: profile.id,
name: profile.attributes.name,
verified: (profile.attributes.status === 'verified'),
preferences: profile.attributes.preferences
};
res.locals.loggedIn.name = profile.attributes.name;
next();
})
.catch(function (err) {
if (err.is(sdk.account.errors.NOT_FOUND)) {
var error = new Error("Profile not found");
error.status = 404;
return next(err);
}
next(err);
});
});
/**
* My profile
*/
router.get('/me', requireLogin, function (req, res, next) {
var title = req.i18n.__('My profile');
// Send phone number for verification
var phoneNum = '';
res.render('profile/edit', {
title: title,
scripts: ['/js/profile-edit.js'],
header: {
title: title,
joined: true
},
phone: phoneNum
});
});
/**
* Upload Profile Avatar
*/
router.post('/me/edit', upload.single('photo'), function (req, res, next) {
// If no photo uploaded
if (!req.file) {
return next();
}
var avatarImageId = 'default';
sdk.image.upload({
ip: req.getClientIP(),
jwt: req.user.jwt,
source: req.getDevice(),
image: fs.createReadStream(req.file.path)
})
// Associate uploaded photo with profile
.then(function (response) {
// Delete temporary image
fs.unlinkSync(req.file.path);
avatarImageId = response.data.id;
return sdk.account.update({
id: req.user.id,
data: {
preferences: {
avatarImageId: response.data.id
}
},
ip: req.getClientIP(),
jwt: req.user.jwt
});
})
.then(function (response) {
req.handlePigeonResponse(response);
req.user.avatar = avatarImageId;
res.locals.loggedIn.avatar = avatarImageId;
req.flash('info', req.i18n.__("Profile picture updated"));
req.flash('changedAvatar', true);
return next();
})
.catch(function (err) {
next(err);
});
});
/**
* Update profile
*/
router.post('/me/edit', requireLogin, function (req, res, next) {
// Make numeric to integer
req.body.preferences.dob.day = parseInt(req.body.preferences.dob.day) || null;
req.body.preferences.dob.month = parseInt(req.body.preferences.dob.month) || null;
req.body.preferences.dob.year = parseInt(req.body.preferences.dob.year) || null;
//delete objects if form inputs are empty
if(!(req.body.preferences.gender = parseInt(req.body.preferences.gender))){
delete req.body.preferences.gender;
}
// Validate form
var invalid = req.validateForm(global.validate.updateProfile);
if (req.body.preferences.dob.year >= new Date().getFullYear()) {
invalid = {errors: { 'preferences/dob': true }};
}
if (invalid) {
req.flash('errors', invalid.errors);
req.flash('form', req.body);
return res.redirect('/profile/me');
}
// Is phone currently hidden?
var phoneHidden = (req.profile.attributes.hasOwnProperty('preferences')
&& req.profile.attributes.preferences.hasOwnProperty('hidePhone')
&& req.profile.attributes.preferences.hidePhone);
// Does user want to hide phone?
var hidePhone = typeof req.body.preferences.hidePhone !== 'undefined';
// Explicitly set hidePhone Bool in preferences.
// Note that form value is either string or undefined.
req.body.preferences.hidePhone = hidePhone;
// Track event
if (!phoneHidden && hidePhone) {
req.visitor.event('Edit Profile', 'Hide Phone Number').send();
} else if (phoneHidden && !hidePhone) {
req.visitor.event('Edit Profile', 'Show Phone Number').send();
}
if((req.body.preferences.dob.day == null) ||
(req.body.preferences.dob.month == null) ||
(req.body.preferences.dob.year == null)){
delete req.body.preferences.dob;
}
// Update profile
sdk.account.update({
id: req.user.id,
ip: req.getClientIP(),
jwt: req.user.jwt,
data: _.merge(req.body, {
parameters: {
userAgent: req.headers['user-agent'],
source: req.getDevice(),
}
})
})
.then(function (response) {
req.handlePigeonResponse(response);
req.flash('info', req.i18n.__("Profile updated"));
res.redirect('/profile/me');
})
.catch(function (err) {
next(err);
});
});
/**
* User profile by ID
*/
router.get('/:userId', function (req, res, next) {
// Use a non-user ID as this is a public route
var jwt = jwtApiCredentials.generateJwt({
service: 'pigeon',
secret: process.env.PIGEON_API_SECRET,
apikey: process.env.PIGEON_API_KEY
});
// Get the user
sdk.account.profile({
id: req.params.userId,
jwt: jwt,
ip: req.getClientIP()
})
// Render the template
.then(function (response) {
req.handlePigeonResponse(response);
var profile = response.data;
res.render('profile/index', {
title: profile.attributes.name,
header: {
title: profile.attributes.name,
joined: true,
back: true
},
user: {
id: profile.id,
name: profile.attributes.name,
verified: (profile.attributes.status === 'verified'),
preferences: profile.attributes.preferences
}
});
})
.catch(function (err) {
// If profile doesn't exist make sure error page is 404
if (err.is(sdk.account.errors.NOT_FOUND)) {
var error = new Error("Profile not found");
error.status = 404;
return next(error);
}
next(err);
});
});
module.exports = router;
|
import { SET_REPAIRS, SET_REPAIRS_TOTAL_COSTS, ADD_REPAIR, SET_ERROR } from "../actions/repairs";
const repairsReducer = (state = { repairs: {}, repairsTotalCosts: {}, repair: {}, status: 0 }, action = {}) => {
switch (action.type) {
case SET_REPAIRS :
return {
...state,
repairs: action.repairs
};
case SET_REPAIRS_TOTAL_COSTS :
return {
...state,
repairsTotalCosts: action.repairsTotalCosts
};
case ADD_REPAIR :
return {
...state,
repair: action.repair
};
case SET_ERROR :
return {
...state,
error: action.error
};
default : return state;
}
}
export default repairsReducer;
|
//8D Re-do Atomic JS-06F. Prompt the user for all 3 legs of a triangle, then prompt again (for all three legs) if the triangle is not valid.
var userNumber = parseInt(prompt("Please enter a number between 1 and 8"));
while ((userNumber >= 1) && (userNumber <= 8)){
alert("Great job.");
var userNumber = parseInt(prompt("Please enter a number between 1 and 8"));
}
if ((userNumber < 1) || (userNumber > 8)) {
alert("You screwed up. You don't get to keep guessing.");
}
|
import TopBar from "../TopBar/TopBar"
import NavBar from "../NavBar/NavBar"
const Header = () =>
<>
<TopBar />
<NavBar/>
</>
export default Header
|
import React, { useState, useRef, useContext } from 'react'
import { MDBBtn, MDBProgress } from "mdbreact";
import axios from 'axios';
import { Link } from 'react-router-dom';
// import { createBrowserHistory } from 'history';
import Context from '../contexts/Context';
import { DropzoneArea } from 'material-ui-dropzone';
import '../styles/upload.scss';
const Upload = () => {
const { state, dispatch } = useContext(Context);
const { files } = state;
// const history = createBrowserHistory();
const [progress1, setProgress1] = useState(null);
const [progress2, setProgress2] = useState(null);
const [progress3, setProgress3] = useState(null);
const redirectEl = useRef(null);
const handleChange = (filesChange) => {
dispatch({ type: 'SET_FILES', payload: filesChange });
}
const handleDrop = (filesDrop) => {
// console.log(filesDrop);
}
// const handleRedirect = () => {
// history.push('/');
// };
const fileUploadHandler = () => {
let i = 0;
let fd = [];
let total = [];
let loaded = [];
files.map((file, index) => {
fd[index] = new FormData();
fd[index].append('image', file, file.name);
return axios.post('https://us-central1-fb-cloud-functions-e686c.cloudfunctions.net/uploadFile', fd[index], {
onUploadProgress: progressEvent=> {
if (index === 0) {
loaded[0] = progressEvent.loaded;
total[0] = progressEvent.total;
setProgress1(Math.round(loaded[0] / total[0] * 100));
} else if (index === 1) {
loaded[1] = progressEvent.loaded;
total[1] = progressEvent.total;
setProgress2(Math.round(loaded[1] / total[1] * 100));
} else if (index === 2) {
loaded[2] = progressEvent.loaded;
total[2] = progressEvent.total;
setProgress3(Math.round(loaded[2] / total[2] * 100));
}
}
})
.then(res => {
i = i + 1;
if (i === files.length) {
redirectEl.current.click();
}
});
})
}
return (
<div className='container'>
<DropzoneArea
onChange={handleChange}
onDrop={handleDrop}
/>
<MDBBtn onClick={fileUploadHandler} color="unique" className='upload-button'>Upload</MDBBtn>
<Link style={{ display: 'none' }} to='/' ref={redirectEl}>Redirect</Link>
{progress1 && <MDBProgress value={progress1} className="my-2" />}
{progress1 && <p>{progress1}%</p>}
{progress2 && <MDBProgress value={progress2} className="my-2" />}
{progress2 && <p>{progress2}%</p>}
{progress3 && <MDBProgress value={progress3} className="my-2" />}
{progress3 && <p>{progress3}%</p>}
</div>
)
}
export default Upload;
|
var InboxSheetView = Backbone.View.extend({
initialize: function () {
_.bindAll(this, "render", "updateTitle", "createTask", "newTaskCreated");
this.stack = [];
this.account = new AccountModel();
this.inbox = new TaskListModel();
this.areas = new AreaCollection();
this.tags = new TagCollection();
this.model = new TaskListModel();
HoverApp.vent.on("newtaskcreated", this.newTaskCreated);
},
template: Handlebars.compile($("#inbox-sheet-template").html()),
updateTitle: function (title) {
// Update the title for this model.
this.model.set({ title: title });
this.model.save();
// Also update title for the inbox stored at the sheet level.
this.inbox.set({ title: title });
},
createTask: function (title) {
// Get tasks collection.
var tasks = this.model.get("tasks");
// Create task.
tasks.create({
title: title,
taskListID: this.model.get("id")
}, { wait: true });
},
getTaskList: function (id) {
// Create a single task list collection from the areas.
var taskLists = new TaskListCollection();
this.areas.each(function (area) {
area.get("taskLists").each(function (taskList) {
taskLists.add(taskList);
});
});
// Find task list by id.
var found = taskLists.find(function(taskList) {
return taskList.get("id") == id;
});
// Return found.
return found;
},
newTaskCreated: function (task) {
if (task.get("taskListID") == this.model.get("id")) {
this.model.get("tasks").add(task);
}
},
render: function () {
// Render view.
$(this.el).html(this.template(this.model.toJSON()));
// Create a sheet title view.
var sheetTitle = new SheetTitleView({
el: $("#sheet-title"),
title: this.model.get("title")
}).render();
// Bind to title updated event.
sheetTitle.bind("sheettitle:updated", this.updateTitle);
// Greate a task group view.
var tasks = new TaskGroupView({
el: $("#tasks"),
model: this.model.get("tasks"),
taskListID: this.model.get("id")
}).render();
// Bind to task created event.
tasks.bind("taskgroup:taskcreated", this.createTask);
// Make group sortable.
tasks.sortable();
return this;
},
});
|
$(function(){
// Initialize Swiper 轮播图
var swiper = new Swiper('.swiper-container', {
delay: 1000, //1秒切换一次
autoplay: true,
loop: true,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
});
var pno=1
// 分页器
$(function() {
$("#pagination2").pagination({
currentPage: pno,//当前默认选中页数
totalPage: 4, //总页数
isShow: false, //首尾页的现实
count: 4, //显示页数
prevPageText: "< 上一页",
nextPageText: "下一页 >",
callback: function(current) {
$("#current2").text(current)
add(current)
}
});
});
add()
function add(current){
$.ajax({
url:"http://localhost:3000/product",
type:"get",
data:{
pno:current, //pno:pno 页码
pageSize:11 //pageSize 页大小
},
success:function(result){
console.log(result.data)
var p1=result.data;
var html="";
for(var p of p1){
// 调用价格函数
// p.oprice=$oprice(p.oprice)
// p.price=$oprice(p.price)
html+=`<section class="pong">
<ul>
<li>
<!-- 左边图 -->
<div class="img-fath">
<a href="${p.href}"><img src="${p.pic}" alt=""></a>
<i>${p.label}</i>
</div>
<!-- 中间详情页 -->
<div>
<h3><a href=""> ${p.headline}</a></h3>
<span>${p.title}</span>
<ul>
<li class="out1">编号:${p.snumber}</li>
<li class="out2">出发地:${p.site}</li>
<li class="out3">行程:${p.route}</li>
<li class="red">最近班次:${p.lately}</li>
</ul>
</div>
<!-- 右边订购板块 -->
<div>
<dl>
<dt>抢购价<b>${p.price}</b>起</dt>
<dd>${p.oprice}</dd>
</dl>
<div>
<a href="${p.href}">立即抢购</a>
</div>
</div>
</li>
</ul>
</section>`
}
$(".product").html("").prepend(html)
}
})
}
})
|
const {expect} = require('chai');
const {firefox} = require('playwright-firefox');
let browser, page;
function json(data) {
return {
status: 200,
headers: {
'Access-Control-Allow-Origin': '*',
'Content-type': 'application/json'
},
body: JSON.stringify(data)
};
}
describe('Book tests...', () => {
before(async () => {
browser = await firefox.launch();
});
after(async () => {
await browser.close();
});
beforeEach(async () => {
page = await browser.newPage();
});
afterEach(async () => {
await page.close();
});
it('load all books ', async function () {
await page.goto('http://localhost:3000/');
await page.click('#loadBooks');
await page.waitForSelector('tbody tr');
const rows = await page.$$eval('tbody tr', (books)=>books.map(tr=>tr.getAttribute('data-id')));
console.log(rows);
expect(rows.length).to.equal(2);
});
it.only('add book ', async function () {
const title = 'Star Wars';
const author = 'George Lucas';
//const postContent = {title,author};
await page.goto('http://localhost:3000/');
await page.fill('[name=title]','Star Wars');
// await page.fill('[name=author]','George Lucas');
//await page.route('**/jsonstore/collections/books', request => request.fulfill(json(postContent)));
const [request] = await Promise.all([
page.waitForRequest(request => request.url().includes('/jsonstore/collections/books') && request.method() === 'POST'),
page.click('text=submit')
]);
const postData = JSON.parse(request.postData());
console.log(postData);
expect(postData.title).to.equal(title);
expect(postData.author).to.equal(author);
});
it('edit book', async () => {
await page.goto('http://localhost:3000/');
//LOAD ALL BOOKS AND CLICK ON THE FIRST EDIT BUTTON
await page.click('text=load all books');
await page.click('text=edit');
//CHANGE TITLE AND AUTHOR
await page.fill('#editForm >> css=[name="title"]', "TestTitle");
await page.fill('#editForm >> css=[name="author"]', "TestAuthor");
//SAVE AND LOAD ALL BOOKS AGAIN
await page.click('text=save');
await page.click('text=load all books');
//GET TABLE CONTENT
let tableContent = await page.$$eval('td', t => t.map(s => s.textContent));
//CHECK IF THE FIRST ROW IS CHANGED
expect(tableContent[0]).to.equal("TestTitle");
expect(tableContent[1]).to.equal("TestAuthor");
});
it('delete book', async () => {
await page.goto('http://localhost:3000/');
//LOAD ALL BOOKS AND CLICK ON THE FIRST DELETE BUTTON
const [loadResponse] = await Promise.all([
page.waitForResponse('http://localhost:3030/jsonstore/collections/books'),
page.click('text=load all books'),
]);
//GET THE FIRST BOOK ID
let books = await loadResponse.json();
let ids = [];
Object.entries(books).map(getId);
function getId([id, book]){
ids.push(id);
}
// ACCEPT ANY FUTURE DIALOG MESSAGES
page.on('dialog', async dialog => {
dialog.accept();
});
// DELETE THE FIRST BOOK
const [deleteResponse] = await Promise.all([
page.waitForResponse('http://localhost:3030/jsonstore/collections/books/'+ ids[0]),
page.click('text=delete')
]);
// GET THE STATUS OF THE DELETE REQUEST
let status = deleteResponse.status();
// EXPECT THE STATUS TO BE 200
expect(status).to.equal(200);
});
});
|
import React from 'react';
import {Card, CardHeader, CardMedia, CardText} from 'material-ui/Card';
import Paper from 'material-ui/Paper';
import Divider from 'material-ui/Divider';
export default class ListCard extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: false,
};
}
handleExpandChange = (expanded) => {
this.setState({expanded: expanded});
};
render() {
const product = this.props.product;
let path = require("../images/"+product.productImage);
let subtitle = '';
if(product.isExclusive)
{
subtitle = "Exclusive";
}
if(product.isSale)
{
subtitle += " Sale";
}
return (
<Card
expanded={this.state.expanded}
onExpandChange={this.handleExpandChange}
style={{width:'380px'}}
>
<CardHeader
title = {product.productName}
subtitle = {subtitle}
actAsExpander={true}
showExpandableButton={true}
style={{minHeight:'70px',color:'#1976D2'}}
titleColor="#e91685"
titleStyle={{fontSize:'20px'}}
subtitleColor="#000"
/>
<Divider/>
<CardMedia>
<img src={path} alt="Cloth" style={{padding:'auto',margin:'auto'}}/>
</CardMedia>
<CardText
style={{display:'flex',flexWrap:'wrap',justifyContent:'flex-end'}}
>
</CardText>
<Divider/>
<CardText
expandable={true}
style={{display:'flex',flexWrap:'wrap',
justifyContent:'center'}}
>
<Paper
zDepth={2}
style={{height:'35px',backgroundColor:'#e91685',color:"#fff",
padding:'10px',marginRight:'10px'}}
>
Price : {product.price}
</Paper>
<Paper
zDepth={2}
style={{height:'35px',backgroundColor:'#e91685',color:"#fff",padding:'10px'}}
>
Sizes Available : {product.size.join(' , ')}
</Paper>
</CardText>
</Card>
);
}
}
|
const postContainer = document.querySelector("#chosen-post-container");
const queryString = document.location.search;
const params = new URLSearchParams(queryString);
const id = params.get("id");
const footer = document.querySelector("footer");
const url = "https://makra-stenkloev.no/thebean/wp-json/wp/v2/posts/" + id + "?_embed";
async function fetchPost(){
footer.style.marginTop = "650px";
// gives the footer distance when loading icon is active
try{
const response = await fetch(url);
const json = await response.json();
const posts = json;
const featuredImage = posts._embedded["wp:featuredmedia"][0].source_url;
const altImageText = posts._embedded["wp:featuredmedia"][0].alt_text;
footer.style.marginTop = "75px";
// changes the top margin back after URL fetch
//creates the HTML/content based on the ID of the post the user have chosen
postContainer.innerHTML =
`<div class="blog-post">
<h1>${posts.title.rendered}</h1>
<p class="date">Posted:${posts.date}</p>
<div class="featured-image" style="background-image:url(${featuredImage})" alt="${altImageText}"></div>
<div class="post-content">
${posts.content.rendered}
</div>
</div>`;
// changes the title based on the blogpost
let pageTitle = document.querySelector("title");
pageTitle.innerHTML += posts.title.rendered;
console.log(document.title);
const modalImage = document.querySelectorAll("figure");
const modalContainer = document.querySelector("#modal-container");
//Creates an Image modal when the user clicks any of the images in the chosen post
for(let i=0; i<modalImage.length; i++){
//variable for the modal HTML
const modalHtml =
`<div class="image-modal"></div>
<div>
<div class="post-image-modal" style="background-image:url(${modalImage[i].childNodes[0].src})"></div>
<button><i tabindex="0" class="fas fa-times"></i></button>
</div>`
//adding tabIndex to post images for accessibility
modalImage[i].tabIndex="0";
modalImage[i].addEventListener("click", function(){
modalContainer.innerHTML += modalHtml;
});
modalImage[i].onkeyup = function(){
modalContainer.innerHTML += modalHtml;
};
//Closes the modal when clicked outside
document.addEventListener("click", function(event){
if(event.target.closest(".image-modal") || event.target.matches(".fa-times")){
modalContainer.innerHTML = "";
}
})
}
}
catch(error){
console.log(error);
//creates the error message
carouselContainer.innerHTML = errorMessage("error", `The website messed up. Please try to <a href="posts.html" class="reload-link">reload</a> the page.`);
}
}
fetchPost();
|
;(function(window, document) {
'use strict';
// throw an error if required functions not defined
if (typeof validateFields === "undefined") {
throw new Error("validateFields() is required and is not defined");
}
if (typeof showNotification === "undefined") {
throw new Error("showNotification() is required and is not defined");
}
if (typeof toggleElemDisabled === "undefined") {
throw new Error("toggleElemDisabled() is required and is not defined");
}
// throw an error if required globals not defined
if (typeof API_BASE_URL === "undefined") {
throw new Error("API_BASE_URL is required and is not defined");
}
// global variables/constants for this script
var license_table = $('').DataTable();
function activateLicense() {
var selector = "#add";
var modal_body = $(selector + ' .modal-body');
var payload = {
"license_key": modal_body.find(".key").val(),
"key_encrypted": false,
};
$.ajax({
type: "PUT",
url: API_BASE_URL + "licensing/activate",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(payload),
success: function(response, textStatus, jqXHR) {
if (response.error.length !== 0) {
showNotification(response.msg, true);
return;
}
hideModal('#add');
showNotification(response.msg);
license_table.row.add({
"type": response.data[0].type,
"license_key": response.data[0].license_key,
"active": response.data[0].active,
"valid": response.data[0].valid,
"expires": response.data[0].expires,
}).draw();
},
})
}
function deactivateLicense() {
var modal_body = $('#delete .modal-body');
var license_key = modal_body.find(".key").val().trim();
var payload = {
"license_key": license_key,
"key_encrypted": false,
};
$.ajax({
type: "PUT",
url: API_BASE_URL + "licensing/deactivate",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(payload),
success: function(response, textStatus, jqXHR) {
if (response.error.length !== 0) {
showNotification(response.msg, true);
return;
}
hideModal('#delete');
showNotification(response.msg);
license_table.row(function(idx, data, node) {
return data.license_key === license_key;
}).remove().draw();
},
});
}
// noinspection JSUnusedLocalSymbols
function updateDeleteModal(self=null) {
// attached via vanilla js event listener or called outside an event listener
if (self === null) {
self = $(this);
}
// attached via jQuery event listener
else if (self instanceof jQuery.Event) {
self = $(self.currentTarget);
}
// calling node passed ref to itself
else {
self = $(self);
}
var modal_body = $('#delete .modal-body');
var license_key = self.closest('tr').find('.key').val().trim();
modal_body.find(".key").val(license_key);
}
// export function to make it available in scope when called via dataTable widgets
window.updateDeleteModal = updateDeleteModal;
// noinspection JSUnusedLocalSymbols
function togglePasswordHidden(self=null) {
// attached via vanilla js event listener or called outside an event listener
if (self === null) {
self = $(this);
}
// attached via jQuery event listener
else if (self instanceof jQuery.Event) {
self = $(self.currentTarget);
}
// calling node passed ref to itself
else {
self = $(self);
}
var input = $(self.attr("data-toggle"));
if (input.attr("type") === "password") {
input.attr("type", "text");
self.removeClass("glyphicon glyphicon-eye-close");
self.addClass("glyphicon glyphicon-eye-open");
}
else {
input.attr("type", "password");
self.removeClass("glyphicon glyphicon-eye-open");
self.addClass("glyphicon glyphicon-eye-close");
}
}
// export function to make it available in scope when called via dataTable widgets
window.togglePasswordHidden = togglePasswordHidden;
function createDeleteButton() {
return '' +
'<div class="dt-resize-height">' +
' <button class="open-Delete btn btn-danger btn-xs" data-title="Deactivate" data-toggle="modal" data-target="#delete" onclick="updateDeleteModal(this)">' +
' <span class="glyphicon glyphicon-trash"></span>' +
' </button>' +
'</div>';
}
function createLicenseKeyField(data, type, row, meta) {
var unique_key_id = "key-" + meta.row;
return '' +
'<div class="wrapper-fieldicon-right dt-resize-height">' +
' <input id="' + unique_key_id + '" class="key" type="password" name="key" value="' + data + '" readonly>' +
' <span class="field-icon toggle-password glyphicon glyphicon-eye-close" data-toggle="#' + unique_key_id + '" onclick="togglePasswordHidden(this)"></span>' +
'</div>';
}
function createReadonlyInputField(data, type, row, meta) {
return '' +
'<div class="dt-resize-height">' +
' <input type="text" value="' + data + '" readonly>' +
'</div>';
}
function dtDrawCallback(settings) {
var rows = $('#licensing > tbody > tr');
var row_height = rows.eq(0).find('td:eq(0)').get(0).clientHeight;
rows.find('td .dt-resize-height').css({'height': row_height});
}
function hideModal(selector) {
var modal_elem = $(selector);
// do nothing if not visible
if (modal_elem.is(':visible')) {
// hide the modal after 1.5 sec
setTimeout(function() {
modal_elem.modal('hide');
}, 1500);
}
}
$(document).ready(function() {
// datatable init
license_table = $('#licensing').DataTable({
"ajax": {
"url": API_BASE_URL + "licensing/list",
"type": "GET",
"error": function(xhr, error, code) {
var response = JSON.parse(xhr.responseText);
requestErrorHandler(xhr.status, response.msg, response.error);
}
},
"columns": [
{"data": "type", "render": createReadonlyInputField},
{"data": "license_key", "render": createLicenseKeyField},
{"data": "active", "render": createReadonlyInputField},
{"data": "valid", "render": createReadonlyInputField},
{"data": "expires", "render": createReadonlyInputField},
{"data": null, "render": createDeleteButton, "searchable": false, "orderable": false},
],
"order": [[0, 'asc']],
"drawCallback": dtDrawCallback,
});
// make license key a password hidden field
$(".toggle-password").on('click', togglePasswordHidden);
// reset add modal before displaying
$('#open-LicenseAdd').click(function() {
var modal_body = $('#add .modal-body');
var key = modal_body.find(".key");
var toggle = modal_body.find(".toggle-password");
// clear fields
key.val('');
// reset toggles
if (key.attr("type") !== "password") {
key.attr("type", "password");
toggle.removeClass("glyphicon glyphicon-eye-open");
toggle.addClass("glyphicon glyphicon-eye-close");
}
});
// submit activation request to api
$('#addButton').click(function(ev) {
/* prevent form default submit */
ev.preventDefault();
if (validateFields('#add')) {
activateLicense();
}
});
// submit deactivation request to api
$('#deleteButton').click(function(ev) {
ev.preventDefault();
deactivateLicense();
});
});
})(window, document);
|
var Stage = Class.create(Scene, {
initialize: function(game){
Scene.call(this);
this.game = game;
this.backgroundColor = '#000';
this.sprites = [];
this.movingFloors = [];
this.view = this.createView();
this.map = this.createMap();
this.player = this.createPlayer();
this.pad = this.createPad();
this.button = this.createButton();
this.message = this.createMessage();
this.scoreLabel = this.createScoreLabel();
this.timeLabel = this.createTimeLabel();
this._element.style.opacity = 0;
},
assets: {
get: function(){
return this.game.assets;
}
},
input: {
get: function(){
return this.game.input;
}
},
score: {
get: function(){
return this.prestage.score;
},
set: function(value){
this.prestage.score = value;
this.scoreLabel.text = 'SCORE ${score}'.format(this);
}
},
time: {
get: function(){
return this._time;
},
set: function(value){
this._time = value;
}
},
cleared: {
get: function(){
return !!this._cleared;
},
set: function(value){
this._cleared = value;
this.prestage.cleared = value;
}
},
start: function(prestage){
this.prestage = prestage;
this.score = this.score;
var opacity = 0;
this.addEventListener('enterframe', function listener(){
opacity += 0.05;
if(opacity >= 1){
this.removeEventListener('enterframe', listener);
this._element.style.opacity = 1;
this.run();
}else{
this._element.style.opacity = opacity;
}
});
},
run: function(){
var a = false;
this.addEventListener('abuttondown', function(){
if(a)
return;
a = true;
this.player.jump();
this.addEventListener('abuttonup', function(){
a = false;
});
});
var now = 0;
this.timeLabel.addEventListener('enterframe', function(){
now += 1000 / GAME_FPS;
this.time = this.timeLimit - now / 1000 | 0;
this.timeLabel.text = 'TIME ${time}'.format(this);
if(this.time === 0){
this.end('END');
}
}.bind(this));
},
end: function(message){
this.showMessage(message);
this.clearEventListener('abuttondown');
this.clearEventListener('abuttonup');
this.view.clearEventListener('enterframe');
this.timeLabel.clearEventListener('enterframe');
for(var i = 0, l = this.sprites.length; i < l; i++){
this.sprites[i].clearEventListener('enterframe');
}
if(!this.cleared){
this.prestage.life--;
asyncCall(function(){
this.player.frame = 3;
}, this);
}
this.setTimeout(3000, function(){
var opacity = 1;
this.addEventListener('enterframe', function(){
opacity -= 0.05;
if(opacity <= 0){
this._element.style.opacity = 0;
this.game.popScene();
}else{
this._element.style.opacity = opacity;
}
});
});
},
hitAny: function(points){
for(var i = 0, l = points.length, j, f; i < l; i++){
if(this.map.hitTest(points[i].x, points[i].y))
return true;
for(j = 0; f = this.movingFloors[j]; j++){
if(f.hitTest(points[i].x - f.x, points[i].y - f.y))
return true;
}
}
return false;
},
getMapData: function(){
throw Error('not implemented');
},
getMapCollisionData: function(){
throw Error('not implemented');
},
adjustView: function(){
this.view.x = Math.max(GAME_WIDTH - this.map.width,
Math.min(0, GAME_WIDTH / 2 - 20 - this.player.x));
this.view.y = Math.max(GAME_HEIGHT - this.map.height,
Math.min(0, GAME_HEIGHT / 2 + 32 - this.player.y));
},
createView: function(){
var view = new Group();
view.x = 0;
view.y = 0;
view.addEventListener('enterframe', function(){
this.adjustView();
}.bind(this));
this.addChild(view);
return view;
},
createMap: function(){
var map = new MapEx({
tileWidth: 32,
tileHeight: 32,
x: 0,
y: 0,
image: this.assets['map.png'],
data: function(data){
var result = [], table = {
' ': 9,
'G': 19,
'g': 17,
'l': 18,
'{': 0,
'-': 1,
'}': 2,
'(': 10,
'0': 11,
')': 12,
',': 20,
'_': 21,
'.': 22,
'[': 30,
'=': 31,
']': 32,
'^': 3,
':': 13,
';': 23,
'#': 33,
};
for(var i = 0, l = data.length, j, k; i < l; i++){
result.push([]);
for(j = 0, k = data[i].length; j < k; j++)
result[i].push(table[data[i].charAt(j)]);
}
return result;
}(this.getMapData()),
collisionData: function(data){
if(data == null)
return null;
var result = [], table = {' ': 0, '#': 1};
for(var i = 0, l = data.length, j, k; i < l; i++){
result.push([]);
for(j = 0, k = data[i].length; j < k; j++)
result[i].push(table[data[i].charAt(j)]);
}
return result;
}(this.getMapCollisionData()),
parent: this.view
});
return map;
},
createPlayer: function(){
var player = new SpriteEx({
x: 48,
y: 257,
width: 32,
height: 32,
image: this.assets['chick.png'],
parent: this.view
});
this.sprites.push(player);
player.vx = 0;
player.vy = 0;
player.scaleX = 1;
player._style.webkitTransformOrigin = '20px 16px';
player._style.MozTransformOrigin = '20px 16px';
player._style.msTransformOrigin = '20px 16px';
player._style.OTransformOrigin = '20px 16px';
player.getRect = function(){
return new Rect(this.x + 10, this.y + 2, 20, 28);
};
player.getTopLeft =
function(){ return new Point(player.x + 10, player.y + 2); };
player.getTopRight =
function(){ return new Point(player.x + 30, player.y + 2); };
player.getBottomLeft =
function(){ return new Point(player.x + 10, player.y + 30); };
player.getBottomRight =
function(){ return new Point(player.x + 30, player.y + 30); };
this.initPlayerWalk(player);
this.initPlayerJump(player);
player.addEventListener('enterframe', function(){
if(this.map.height < player.y){
this.end('Game Over');
}
}.bind(this));
return player;
},
initPlayerWalk: function(player){
var MAX_SPEED = 3; // Pixel per frame
var ACCELERATION = 0.5;
player.walkFrames = [1, 1, 1, 0, 0, 2, 2, 2, 0, 0];
player.addEventListener('enterframe', function(){
if(this.input.left){
player.vx = Math.max(-MAX_SPEED, player.vx - ACCELERATION);
}else if(this.input.right){
player.vx = Math.min(MAX_SPEED, player.vx + ACCELERATION);
}else if(player.jumpCount === 0){
if(player.vx > 0){
player.vx = Math.max(0, player.vx - ACCELERATION);
}else if(player.vx < 0){
player.vx = Math.min(0, player.vx + ACCELERATION);
}
}
if(player.vx !== 0)
player.scaleX = player.vx > 0? 1: -1;
player.wall = 0;
player.x = player.x + player.vx | 0;
if(this.hitAny([
player.getTopLeft(), player.getTopRight(),
player.getBottomLeft(), player.getBottomRight()
])){
do{
player.x += player.vx > 0? -1: 1;
}while(this.hitAny([
player.getTopLeft(), player.getTopRight(),
player.getBottomLeft(), player.getBottomRight()
]));
player.wall = player.vx > 0? 1: -1;
player.vx = 0;
asyncCall(function(){
player.frame = 0;
player.walkFrames = [1, 1, 1, 0, 0, 2, 2, 2, 0, 0];
});
}else if(player.vx !== 0){
asyncCall(function(){
player.frame = player.walkFrames.shift();
player.walkFrames.push(player.frame);
});
}else{
asyncCall(function(){
player.frame = 0;
});
}
}.bind(this));
},
initPlayerJump: function(player){
var MAX_SPEED = 6;
var GRAVITY = 0.4;
player.jumpCount = 0;
player.jump = function(){
if(player.jumpCount === 2)
return;
player.vy = -6 - GRAVITY;
player.jumpCount++;
}.bind(this);
player.addEventListener('enterframe', function(){
player.vy = Math.min(MAX_SPEED, player.vy + GRAVITY);
if(player.vy === 0)
return;
player.y = player.y + player.vy | 0;
if(this.hitAny([
player.getTopLeft(), player.getTopRight(),
player.getBottomLeft(), player.getBottomRight()
])){
do{
player.y += player.vy > 0? -1: 1;
}while(this.hitAny([
player.getTopLeft(), player.getTopRight(),
player.getBottomLeft(), player.getBottomRight()
]));
if(player.vy > 0)
player.jumpCount = 0;
player.vy = 0;
}else if(player.vy > GRAVITY * 2 && player.jumpCount === 0){
player.jumpCount++;
}
}.bind(this));
},
createApple: function(){
var apple = new Apple({
image: this.assets['apple.png'],
player: this.player,
map: this.map,
parent: this.view
});
apple.addEventListener('hit',
this.end.bind(this, 'Hit'));
apple.addEventListener('fallen', function(){
this.view.removeChild(apple);
}.bind(this));
this.sprites.push(apple);
return apple;
},
createBanana: function(){
var banana = new Banana({
image: this.assets['banana.png'],
player: this.player,
map: this.map,
parent: this.view
});
banana.addEventListener('hit',
this.end.bind(this, 'バナナにぶつかった'));
this.sprites.push(banana);
return banana;
},
createStar: function(){
var star = new SpriteEx({
x: -16,
y: -16,
width: 16,
height: 16,
image: this.assets['star.png'],
parent: this.view
});
this.sprites.push(star);
star.listenWhile('enterframe', function(){
if(!Rect.intersect(this.player.getRect(), star.getRect()).area)
return true;
this.score += 100;
this.prestage.stars.push(star.number);
this.view.removeChild(star);
this.addChild(star);
star.x += this.view.x;
star.y += this.view.y;
star.opacity = 1;
star.listenWhile('enterframe', function(){
star.opacity *= 0.9;
if(star.opacity < 0.01)
star.opacity = 0;
star.x *= 0.9;
if(star.x < 8)
star.x = 8;
star.y *= 0.9;
if(star.y < 8)
star.y = 8;
if(star.opacity === 0 && star.x === 8 && star.y === 8){
this.removeChild(star);
return false;
}
return true;
}.bind(this));
return false;
}.bind(this));
return star;
},
createPad: function(){
var pad = new Pad();
pad.x = 0;
pad.y = 220;
this.addChild(pad);
return pad;
},
createButton: function(){
var button = new SpriteEx({
buttonMode: 'a',
image: this.assets['zbutton.png'],
x: 220,
y: 220,
width: 100,
height: 100,
parent: this
});
return button;
},
createMessage: function(){
var message = new TextLabel({
x: 0,
width: 320,
height: 40,
lineHeight: '40px',
textAlign: 'center',
font: 'bold 16px sans-serif',
color: '#FFF',
visible: false,
backgroundColor: 'rgba(0, 0, 0, 0.7)',
parent: this
});
message._style.textShadow = '0 0 1px #FFF';
return message;
},
showMessage: function(message){
this.message.text = message;
this.message.y = 140;
this.message.visible = true;
},
createScoreLabel: function(){
var scoreLabel = new TextLabel({
x: 5,
y: 5,
width: 155,
height: 20,
lineHeight: '20px',
text: 'SCORE 0',
color: '#222',
parent: this
});
scoreLabel._style.textShadow = '0 0 1px #FFF';
return scoreLabel;
},
createTimeLabel: function(){
var timeLabel = new TextLabel({
x: 160,
y: 5,
width: 155,
height: 20,
lineHeight: '20px',
text: 'TIME ${timeLimit}'.format(this),
textAlign: 'right',
color: '#222',
parent: this
});
timeLabel._style.textShadow = '0 0 1px #FFF';
return timeLabel;
},
createGoal: function(){
var goal = new EntityEx({
parent: this.view
});
goal.listenWhile('enterframe', function(){
if(!Rect.intersect(this.player.getRect(), goal.getRect()).area)
return true;
this.cleared = true;
this.score += 1000 * Math.max(0, 2 - this.prestage.retry);
this.score += this.time * 10;
this.end('END');
return false;
}.bind(this));
return goal;
},
createMovingFloor: function(data){
var movingFloor = new MapEx({
tileWidth: 32,
tileHeight: 32,
x: 0,
y: 0,
image: this.assets['map.png'],
data: function(data){
var result = [], table = {
' ': -1,
'G': 19,
'g': 17,
'l': 18,
'{': 0,
'-': 1,
'}': 2,
'(': 10,
'0': 11,
')': 12,
',': 20,
'_': 21,
'.': 22,
'[': 30,
'=': 31,
']': 32,
'^': 3,
':': 13,
';': 23,
'#': 33,
};
for(var i = 0, l = data.length, j, k; i < l; i++){
result.push([]);
for(j = 0, k = data[i].length; j < k; j++)
result[i].push(table[data[i].charAt(j)]);
}
return result;
}(data),
parent: this.view
});
movingFloor.moveBy = function(dx, dy){
var pr = this.player.getRect();
if(pr.bottom + 1 === movingFloor.y &&
movingFloor.x <= pr.right &&
pr.x <= movingFloor.x + movingFloor.width){
this.player.x += dx;
this.player.y += dy;
}
movingFloor.x += dx;
movingFloor.y += dy;
var points = [this.player.getTopLeft(), this.player.getTopRight(),
this.player.getBottomLeft(), this.player.getBottomRight()];
if(points.some(function(point){
return movingFloor.hitTest(point.x - movingFloor.x,
point.y - movingFloor.y);
})){
this.player.x += dx;
this.player.y += dy;
}
}.bind(this);
this.sprites.push(movingFloor);
this.movingFloors.push(movingFloor);
return movingFloor;
},
createHint: function(x, y, imageName){
var hint = new SpriteEx({
x: x,
y: y,
width: 128,
height: 64,
image: this.assets[imageName],
parent: this.view
});
return hint;
}
});
|
var Tacit = Tacit || {};
Tacit.TimeCircle = function(gameState, position, group, properties) {
"use strict";
Phaser.Graphics.call(this, gameState.game, position.x, position.y);
this.gameState = gameState;
if(group) {
this.gameState.groups[group].add(this);
}
this.anchor.setTo(0.5, 0.5);
};
Tacit.TimeCircle.prototype = Object.create(Phaser.Graphics.prototype);
Tacit.TimeCircle.prototype.constructor = Tacit.TimeCircle;
Tacit.TimeCircle.prototype.update = function () {
"use strict";
}
Tacit.TimeCircle.prototype.setTime = function(sec) {
this.clear();
// clear之后一定要设置lineStyle
this.lineStyle(3, 0xFFFFFF);
this.arc(0, 0, 460, -Math.PI/2 + sec * Math.PI/this.gameState.LevelTime, Math.PI/2);
this.arc(0, 0, 460, Math.PI/2, Math.PI*3/2 - sec * Math.PI/this.gameState.LevelTime);
}
|
/*
* @lc app=leetcode.cn id=520 lang=javascript
*
* [520] 检测大写字母
*/
// @lc code=start
/**
* @param {string} word
* @return {boolean}
*/
// 解法一
// var detectCapitalUse = function(word) {
// // 通过判断大写字母的个数
// // 1. 个数 == 单词长度
// // 2. 个数 == 1
// let num = 0;
// const len = word.length;
// for (let i = 0; i < len; i++) {
// if(/[A-Z]/.test(word[i])) {
// num++;
// }
// }
// if (num == word.length || num == 1 && (/[A-Z]/.test(word[0])) || num == 0) {
// return true;
// }
// return false
// };
// 解法二 正则表达式
var detectCapitalUse = function(word) {
const reg = /^[A-Z]*$|^[A-Z][a-z]*$|^[a-z]*$/;
return reg.test(word)
}
// @lc code=end
|
import React from "react";
import "./PageNotFoud.css"
import {Button, Container} from "@material-ui/core";
import { useHistory} from "react-router-dom";
export default function PageNotFound() {
const history = useHistory();
return (
<Container maxWidth={"md"}>
<div className="four_zero_four_bg">
<h1 align="center">404</h1>
</div>
<center>
<h1>
Something is missing.
</h1>
<Button
variant={"contained"}
size={"large"}
color="primary"
style={{ marginTop:"20px",padding:"15px 30px"}}
onClick={history.goBack}
>
Go Back
</Button>
</center>
</Container>
);
}
|
/**
* @author v.lugovsky
* created on 16.12.2015
*/
(function() {
'use strict';
angular.module('ROA.pages.calcularRiesgoTotal', [])
.config(function($stateProvider) {
$stateProvider
.state('calcularRiesgoTotal', {
url: '/calcularRiesgoTotal',
templateUrl: 'app/pages/calcularRiesgoTotal/calcularRiesgoTotal.html',
title: 'Calcular Riesgo Total',
sidebarMeta: {
icon: 'ion-android-home',
order: 0
},
controller: 'CalcularRiesgoTotalCtrl',
data: {
requireLogin: true
}
});
})
.controller('CalcularRiesgoTotalCtrl', ['$rootScope', '$scope', 'layoutColors', 'layoutPaths', '$filter', 'Map','RestApi','$uibModal','$sce',
function($rootScope, $scope, layoutColors, layoutPaths, $filter, Map, RestApi, $uibModal, $sce) {
RestApi.getAllPacientes()
.then(function (result) {
$scope.pacientes = result;
$scope.startCalculation();
})
.catch(function(error){
});
$scope.writeLogEntry = function(message){
try{
$scope.importLog = $sce.trustAsHtml($scope.importLog + '<p><strong>' + moment().format('YYYY/MM/DD hh:mm:ss a').toString() + ' >></strong> ' + message + '</p>');
}catch(e){
console.log(e);
}
};
$scope.importLog = $sce.trustAsHtml('<h5>log de procesamiento: </h5>');
$scope.startCalculation = function(){
$scope.writeLogEntry('Se ha iniciado el proceso de cálculo');
$scope.queryVisita(0);
};
$scope.queryVisita = function(i){
var doc = $scope.pacientes[i].paciente_doc;
$scope.writeLogEntry('Calculando riesgo para el paciente con CC ' + doc + ' y nombre ' + $scope.pacientes[i].paciente_nombre1);
if(i >= $scope.pacientes.length){
return;
}
RestApi.getVisitaPaciente(doc)
.then(function (visita) {
var puntos = [];
var edad = parseInt($scope.pacientes[i].edad);
if(edad <= 29 || edad > 75){
$scope.writeLogEntry('El paciente ' + doc + ' no esta entre los 30 y 74 años');
i++;
$scope.queryVisita(i);
}
// Set point for edad
if(edad < 34){
puntos.push(1);
}else if(edad < 40){
puntos.push(0);
} else if(edad < 45){
puntos.push(1);
} else if(edad < 50){
puntos.push(2);
}else if(edad < 55){
puntos.push(3);
} else if(edad < 60){
puntos.push(4);
} else if(edad < 65){
puntos.push(5);
} else if(edad < 70){
puntos.push(6);
} else if(edad < 75){
puntos.push(7);
}
var diabetes = visita.dx_diabetes.replace(/[']/g, '');
switch (diabetes){
case 'No Diabetico':
puntos.push(0);
break;
default:
puntos.push(2);
}
var fumador = visita.habito_tabaquismo.replace(/[']/g, '');
switch (fumador){
case 'No':
puntos.push(0);
break;
default:
puntos.push(2);
}
var colesterol_total = parseInt(visita.paracli_colestotal.replace(/[']/g, ''));
if(colesterol_total < 160){
puntos.push(-3);
}else if(colesterol_total < 200){
puntos.push(0);
} else if(colesterol_total < 240){
puntos.push(1);
} else if(colesterol_total < 280){
puntos.push(2);
} else if(colesterol_total >= 280){
puntos.push(3);
}
var colesterol_hdl = parseInt(visita.paracli_coleshdl.replace(/[']/g, ''));
if(colesterol_hdl < 35){
puntos.push(2);
}else if(colesterol_hdl < 45){
puntos.push(1);
} else if(colesterol_hdl < 50){
puntos.push(0);
} else if(colesterol_hdl < 60){
puntos.push(0);
} else if(colesterol_hdl >= 60){
puntos.push(-2);
}
var pres_sistolica = parseInt(visita.ef_ta_sist.replace(/[']/g, ''));
var pres_diastolica = parseInt(visita.ef_ta_sist.replace(/[']/g, ''));
if(pres_sistolica < 130 && pres_diastolica < 85){
puntos.push(0);
}else if(pres_sistolica < 140 && pres_diastolica < 90){
puntos.push(1);
} else if(pres_sistolica < 160 && pres_diastolica < 100){
puntos.push(2);
} else if(pres_sistolica > 160 && pres_diastolica > 100){
puntos.push(3);
}else{
puntos.push(0);
}
var total_puntos = puntos.reduce(function (total, num) {
return total + num;
});
// corrección
total_puntos = total_puntos * 0.75;
var porcentaje_riesgo = 0;
console.log(total_puntos);
if(total_puntos <= -2){
porcentaje_riesgo = 2;
}else if(total_puntos <= 0){
porcentaje_riesgo = 3;
} else if(total_puntos <= 1){
porcentaje_riesgo = 3;
} else if(total_puntos <= 2){
porcentaje_riesgo = 4;
} else if(total_puntos <= 3){
porcentaje_riesgo = 5;
} else if(total_puntos <= 4){
porcentaje_riesgo = 7;
} else if(total_puntos <= 5){
porcentaje_riesgo = 8;
} else if(total_puntos <= 6){
porcentaje_riesgo = 10;
} else if(total_puntos <= 7){
porcentaje_riesgo = 13;
} else if(total_puntos <= 8){
porcentaje_riesgo = 16;
} else if(total_puntos <= 9){
porcentaje_riesgo = 20;
} else if(total_puntos <= 10){
porcentaje_riesgo = 25;
} else if(total_puntos <= 11){
porcentaje_riesgo = 31;
} else if(total_puntos <= 12){
porcentaje_riesgo = 37;
} else if(total_puntos <= 13){
porcentaje_riesgo = 45;
} else if(total_puntos <= 14){
porcentaje_riesgo = 53;
} else if(total_puntos <= 15){
porcentaje_riesgo = 53;
} else if(total_puntos <= 16){
porcentaje_riesgo = 53;
} else if(total_puntos >=17){
porcentaje_riesgo = 53;
}
$scope.writeLogEntry('El paciente ' + doc + ' tiene un porcentaje de riesgo de '+porcentaje_riesgo + '%');
RestApi.updatePacienteRiesgo(doc, porcentaje_riesgo)
.then(function (result) {
})
.catch(function(error){
});
i++;
$scope.queryVisita(i);
})
.catch(function (error) {
i++;
$scope.queryVisita(i);
});
};
}
]);
})();
|
// キャッシュファイルの指定
var CACHE_NAME = "pwa-sample-caches";
var urlsToCache = ["/runstackjp.github.io/"];
// インストール処理
self.addEventListener("install", function (event) {
console.log("ServiceWorker install");
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
return cache.addAll(urlsToCache);
})
);
});
/*
想定パターン
既に検索したことのある検索条件の
フェッチパターンとしては、キャッシュのみ、キャッシュ+ネットワーク等のパターンがあるが、
キャッシュ+ネットワークを試す。
*/
// [メモ]ただリクエストをネットワークにフォールバックさせたい時は"fetch"のfunction内でただreturnすればいい。event.respondWith(fetch(event.request))は不要。
// [メモ] respondWithを実行しない場合、リクエストはブラウザによって処理される(つまりServiceWorkerが関与していないかのように処理される)
// リソースフェッチ時のキャッシュロード処理
self.addEventListener("fetch", function (event) {
console.log("fetch");
// 検索(オフライン対応)のリクエストの場合
if (event.request.url.indexOf("https://httpbin.org") != -1) {
console.log("fetch if");
/* レスポンス編集
* 以下の優先度でデータを返す。
* 1.ネットワークリクエストデータ
* 2.キャッシュデータ
* 3.ブラウザDBから検索したデータ
*/
event.respondWith(
// 1.ネットワークリクエスト実行
fetch(event.request)
// 2.ネットワークリクエストが成功した場合
.then(response => {
console.log("fetch response return");
// キャッシュに追加
return caches.open("CACHE_NAME").then(function (cache) {
cache.put(event.request, response.clone());
return response;
})
})
// 3.ネットワークリクエストが失敗した場合
.catch(function (error) {
// キャッシュにデータがあるかチェック
return caches.match(event.request).then(function (response) {
// データあり
if (response) {
console.log("fetch caches.match キャッシュあり response return");
// キャッシュのデータを返す
return response;
} else {
console.log("fetch caches.match キャッシュなし!!! new response return");
// データなし
var init = { "status": 201, "statusText": "SuperSmashingGreat!" };
var myResponse = new Response(null, init);
// ステータス201で返す
return myResponse;
}
});
})
);
} else {
// その他のリクエストの場合
// ※このサンプルだと画面にアクセスした時のリクエストが該当する
event.respondWith(
// キャッシュにリクエストがあればキャッシュからレスポンスを返す。無い場合は、ネットワークからレスポンスを取得して返す。
caches.match(event.request).then(function (response) {
console.log("fetch else. return cacheResponse or fetch(event.request);");
return response ? response : fetch(event.request);
})
);
}
});
|
$(function() {
// Side Bar Toggle
$('.hide-sidebar').click(function() {
$('#sidebar').hide('fast', function() {
$('#content').removeClass('span9');
$('#content').addClass('span12');
$('.hide-sidebar').hide();
$('.show-sidebar').show();
});
});
$('.show-sidebar').click(function() {
$('#content').removeClass('span12');
$('#content').addClass('span9');
$('.show-sidebar').hide();
$('.hide-sidebar').show();
$('#sidebar').show('fast');
});
$('.navbar-list li >a').each(function(){
var linkurl = $(this).attr('href');
var localurl = window.location.href;console.log(linkurl+'///'+localurl)
if( localurl.indexOf(linkurl)!=-1) {
$(this).parent().addClass('active').siblings().removeClass('active');
}
})
});
|
import { sanitize } from "./sanitize.js";
export const template = (strings, ...values) => {
const tmpl = document.createElement('template');
tmpl.innerHTML = values.reduce(
(html, value, index) => html + sanitize(value) + strings[index + 1],
strings[0]
);
return tmpl;
};
|
// Apostrophe, lightweight name mentions for jQuery
// Version 0.1
// (c) Syme (git @ symeapp)
// Released under the MIT license
(function($, _) {
$.apostrophe = {};
// Default config
$.apostrophe.config = {
// Handlers that trigger the update event (separated by spaces)
eventHandlers: 'input',
// After how many characters do we start considering a word as a
// potential name?
minimalLength: 3,
// Computed textarea styles that have to be copied to the mirror.
mirroredStyles: [
'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
'border-top', 'border-right', 'border-bottom', 'border-left',
'font-family', 'font-size', 'font-weight', 'font-style',
'letter-spacing', 'text-transform', 'word-spacing', 'text-indent',
'line-height'
],
// Verbose enum keycodes
keycodes: {
BACKSPACE: 8 , TAB: 9 , COMMA: 188, SPACE: 32,
RETURN: 13, ESC: 27, LEFT: 37 , UP: 38,
RIGHT: 39, DOWN: 40
},
template: _.template(
'<ul>' +
'<% _.each(people, function(person) { %>' +
'<li data-id="<%= person.id %>"><%= person.name %></li>' +
'<% }); %>' +
'</ul>'
)
};
// jQuery function. Makes mirror and bind events.
$.fn.apostrophe = function(config) {
// Extend global config with config arguments
var config = $.extend($.apostrophe.config, config || {});
// Add unique IDs to people
_.each(config.people, function(person){ person.id = _.uniqueId(); });
this
// Keep only uninitialized textareas
.filter('textarea')
.filter(function(){ return !this.mirror })
// Iterate on each
.each(function(){
// Shortcuts to DOM and jQuery versions of textarea
var el = this, $el = $(this);
// Get textarea position and dimensions
var posAndDims = {
top: $el.offset().top, left: $el.offset().left,
width: $el.outerWidth(), height: $el.outerHeight()
}
// Merge them with the computed styles that matter
var style = $.extend(posAndDims,
$.apostrophe.getStyles(el, config.mirroredStyles));
// Create mirror, style it and append it to body
var $mirror = $('<div class="apostrophe-mirror" />')
.css(style).appendTo('body');
// Initialize element DOM properties
el.mentionned = [];
el.charCount = el.value.length;
el.config = config;
el.mirror = $mirror.get(0);
// Bind events
$el
.on(config.eventHandlers, $.apostrophe.update)
.on('keyup click', $.apostrophe.caretPositionChanged)
.on('apostrophe.update', $.apostrophe.update)
.on('apostrophe.destroy', function(){
$el
.off(config.eventHandlers, $.apostrophe.update)
.off('keyup click', $.apostrophe.caretPositionChanged)
.off('apostrophe.update')
.removeProp('mirror');
$mirror.remove();
});
});
// Chainability
return this;
};
// Update mirror and check for mentionned names.
$.apostrophe.update = function(e) {
var el = this,
charIndex = el.selectionStart <= 0 ? 0 : el.selectionStart,
charDiff = el.value.length - el.charCount;
// Update charCount now that we now charDiff
el.charCount = el.value.length;
// If characters have been added, check if a mention
// has been severed.
if ( charDiff >= 0 ) {
// Has a mention been severed?
var overlappingPerson = _.find(el.mentionned, function(person){
return charIndex - charDiff > person.pos &&
charIndex - charDiff < person.pos + person.name.length;
});
// If it is the case, pass the mentionned name from
// the names to the people list
if (overlappingPerson) {
el.config.people.push(overlappingPerson);
el.mentionned = _.reject(el.mentionned, function(p){
return p.name == overlappingPerson.name;
});
}
// If characters have been deleted, check if one or
// several mentions have been severed.
} else {
var oldPos = charIndex - charDiff,
newPos = charIndex;
_.any(el.mentionned, function(person) {
var nameStart = person.pos,
nameEnd = person.pos + person.name.length;
var isSevered =
(newPos < nameStart && oldPos > nameStart && oldPos < nameEnd) || // left
(newPos > nameStart && newPos < nameEnd && oldPos > nameEnd) || // right
(newPos >= nameStart && oldPos <= nameEnd) || // inside
(newPos <= nameStart && oldPos >= nameEnd); // outside
if (isSevered) {
el.config.people.push(person);
el.mentionned = _.reject(el.mentionned, function(p){
return p.name == person.name;
});
}
});
}
// Update positions
var furtherPeople = _.filter(el.mentionned, function(person){
return person.pos >= charIndex - charDiff ;
});
_.each(furtherPeople, function(person){ person.pos = person.pos + charDiff; });
// Check if any name has been inputted
$.apostrophe.checkForName.call(el, charIndex);
// Add the highlight tags in the mirror copy
var formatted_content = el.value;
_.each(_.flatten(_.indexBy(el.mentionned, 'pos')), function(person, i) {
// 7 characters are added by "<b></b>". We add them linearly
// following the sorted mentions index order, thus: i * 7
var nameIndex = person.pos + i * 7;
formatted_content = [
formatted_content.slice(0, nameIndex),
'<b>' + person.name + '</b>',
formatted_content.slice(nameIndex + person.name.length)
].join('');
});
// Push HTML-linebreaked content to the mirror
el.mirror.innerHTML = formatted_content.replace(/\n/g, "<br/>");
};
$.apostrophe.checkForName = function(charIndex){
var el = this;
// Get current word with enclosing text at caret position
var parts = $.apostrophe.getParts(this.value, charIndex);
// Does the current word look like a name?
var isLongEnough = parts.word.length >= el.config.minimalLength;
var isOutsideMentions = !_.any(el.mentionned, function(person) {
return charIndex >= person.pos &&
charIndex <= person.pos + person.name.length;
});
// Are there names that ressemble it?
var potentialPeople = _.filter(el.config.people, function(person){
return _.any(person.name.split(' '), function(partOfName){
// Prepare parts for match testing
var a = parts.word.toLowerCase(), b = partOfName.toLowerCase();
// Jaro-winkler distance to rank
var score = $.apostrophe.distance(a, b);
return score > 0.8 ? score : false;
});
});
// If there are resembling names, trigger dropdown.
// BEGIN: TO REFACTOR
if ( isLongEnough && isOutsideMentions && potentialPeople.length > 0 ) {
var popup_template = el.config.template({ people: potentialPeople });
$('#popup-container').html(popup_template);
$('#popup-container li').click(function(){
var personId = $(this).data('id').toString(),
person = _.findWhere(el.config.people, { id: personId });
$.apostrophe.placeName.call(el, person, parts);
});
} else {
$('#popup-container').html('');
}
// END: TO REFACTOR
};
$.apostrophe.placeName = function (selectedPerson, parts) {
var el = this;
var before = parts.before,
word = parts.word,
after = parts.after;
// Update textarea with selected name
el.value = before + selectedPerson.name + after;
// Update charCount
el.charCount = el.value.length;
// Push further mentionned people
var furtherPeople = _.filter(el.mentionned, function(person){
return person.pos >= before.length ;
});
_.each(furtherPeople, function(person){
person.pos = person.pos - word.length + selectedPerson.name.length;
});
// Pass the mentionned name from the names to the mentionned list
el.mentionned.push( _.extend(selectedPerson, { pos: before.length }) );
el.config.people = _.reject(el.config.people, function(person){
return person.name == selectedPerson.name;
});
// Place the text caret after the mentionned name
var newCaretPos = before.length + selectedPerson.name.length;
el.setSelectionRange(newCaretPos, newCaretPos);
// Update the textarea
$(el).trigger('apostrophe.update');
return true;
};
$.apostrophe.caretPositionChanged = function(e) {
var el = this;
var keycodes = $.apostrophe.config.keycodes,
arrowKeys = [keycodes.UP, keycodes.RIGHT, keycodes.DOWN, keycodes.LEFT];
if ( _.contains(arrowKeys, e.which) || e.type =="click") {
var charIndex = el.selectionStart <= 0 ? 0 : el.selectionStart;
$.apostrophe.checkForName.call(el, charIndex);
}
};
// Given a string 'content', and an index in it 'charIndex',
// Will return the current word, the string before it, and
// the string after it.
$.apostrophe.getParts = function(content, charIndex) {
var before = content.substr(0, charIndex),
after = content.substr(charIndex);
var leftPart = '', rightPart = '';
for (var i = before.length; i > 0; i--) {
if (/\s/g.test(before[i - 1])) {
before = before.slice(0, i); break;
} else leftPart = before[i - 1] + leftPart;
}
for (var j = 0; j < after.length; j++) {
if (/\s/g.test(after[j])) {
after = after.slice(j, after.length); break;
} else rightPart += after[j];
}
var word = leftPart + rightPart;
if (before == word) before = "";
return { before: before, word: word, after: after };
};
// Polyfill helper to get computed styles
// 'el' should be a DOM element, and 'props' an array of
// CSS properties or a string of a single property .
$.apostrophe.getStyles = function (el, props) {
var results = {};
if (typeof props === "string") props = [props];
$.each(props, function(i, prop) {
if (el.currentStyle) {
results[prop] = el.currentStyle[prop];
} else if (window.getComputedStyle) {
results[prop] = document.defaultView
.getComputedStyle(el, null)
.getPropertyValue(prop);
} else {
results[prop] = $(el).css(prop);
}
});
return results;
};
// Jaro-winkler distance
// https://github.com/zdyn/jaro-winkler-js
$.apostrophe.distance = function(a, c) {
var h,b,d,k,e,g,f,l,n,m,p;a.length>c.length&&
(c=[c,a],a=c[0],c=c[1]);k=~~Math.max(0,c.length/2-1);e=[];g=[];b=n=0;for(p=a.length;n<p;b=++n)
for(h=a[b],l=Math.max(0,b-k),f=Math.min(b+k+1,c.length),d=m=l;l<=f?m<f:m>f;d=l<=f?++m:--m)
if(null==g[d]&&h===c[d]){e[b]=h;g[d]=c[d];break}e=e.join("");g=g.join("");if(d=e.length){b=f=k=0;
for(l=e.length;f<l;b=++f)h=e[b],h!==g[b]&&k++;b=g=e=0;for(f=a.length;g<f;b=++g)if(h=a[b],h===c[b])
e++;else break;a=(d/a.length+d/c.length+(d-~~(k/2))/d)/3;a+=0.1*Math.min(e,4)*(1-a)}else a=0;return a;
}
})(jQuery, _);
|
import React from "react";
import { Switch, Route } from "react-router-dom";
import Customer360 from "../pages/Customer360/Customer360";
export default (
<Route>
<Route exact path="/" component={Customer360} />
<Route exact path="/login" component={Customer360} />
</Route>
);
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom'
import Actions from '../flux/Actions'
import SessionStore from '../flux/stores/SessionStore'
import connectToStores from 'alt-utils/lib/connectToStores';
import { Nav, Navbar, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
class MMNav extends Component {
componentDidMount() {
}
static getStores() {
return [SessionStore];
}
static getPropsFromStores() {
return SessionStore.getState();
}
logoutClick() {
Actions.logout();
}
render() {
var navBar;
if (this.props != null
&& this.props.sessionInfo != null
&& this.props.sessionInfo.loggedIn) {
navBar =
<Navbar collapseOnSelect>
<Navbar.Header>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav pullRight>
<NavItem eventKey={1}><Link to="/home">INICIO</Link></NavItem>
<NavItem eventKey={2} ><Link to="/assets">BOLETAS</Link></NavItem>
<NavItem eventKey={2} onClick={this.logoutClick}>CERRAR SESIÓN</NavItem>
</Nav>
</Navbar.Collapse>
</Navbar>;
}
else {
navBar = <div className="spacer-48"> </div>;
}
return (
<div>
<div className="container-fluid bkg-000 inshadow">
<div className="container">
<div className="row">
<div className="col-md-12">
{navBar}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default connectToStores(MMNav);
|
import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchUserd } from "../../actions";
class UserListShow extends Component {
componentDidMount() {
this.props.fetchUserd(this.props.match.params._id);
}
render() {
if (!this.props.userd) {
return "";
}
const { title, content } = this.props.userd;
return (
<div>
<h3 style ={{color : 'yellowgreen'}}>* Name : </h3>
<h5>{title}</h5>
<h3 style ={{color : 'yellowgreen'}}>* Content :</h3>
<h5>{content}</h5>
</div>
);
}
}
function mapStateToProps({ usersd }, ownProps) {
return { userd: usersd[ownProps.match.params._id] };
}
export default connect(mapStateToProps, { fetchUserd })(UserListShow);
|
module.exports = {
transform: {
'^.+\\.js?$': require.resolve('babel-jest'),
},
transformIgnorePatterns: [
'/node_modules/(?!d3|d3-array|internmap|delaunator|robust-predicates)',
],
};
|
const Parser = require('./parser');
const Str = require('./parsers/str');
const SequenceOf = require('./parsers/sequenceof');
const Match = require('./parsers/match');
const Choice = require('./parsers/choice');
const Many = require('./parsers/many');
const Type = require('./utils');
const Between = (leftParser, rightParser) => contentParser => SequenceOf([
leftParser,
contentParser,
rightParser
]).map(r => r[1])
const BetweenBrackets = Between(Str('('), Str(')'));
const BetweenCurly = Between(Str('{'), Str('}'))
const StringParser = Match(Type.isLetter)
const NumberParser = Match(Type.isDigit).map(r => Number(r))
const HexParser = SequenceOf([
Str('#'),
Match(Type.isHex)
]).map(([, r]) => `#${r}`)
const PropertyParser = SequenceOf([
Many(Str(' ')),
Match(Type.isLetter),
Many(Str(' ')),
Str(':'),
]).map(([, r]) => r).chain(property => {
switch (property) {
case 'color': return { property, value: HexParser };
case 'width': return NumberParser;
case 'background': return StringParser;
default: return Match(Type.isLetter);
}
});
const parser = SequenceOf([
// Match(Type.isLetter),
// BetweenCurly(Many(SequenceOf([
// Match(Type.isLetter),
// Str(':'),
// Match(Type.isLetter),
// Str(';')
// ]))),
PropertyParser
]);
// var r = parser.run('body{color:red;display:block;}#ab33')
var r = parser.run('color:#abc')
console.log(r);
console.log(JSON.stringify(r.result));
|
/*
Create a function that counts the integer's number of digits.
Examples
count(318) ➞ 3
count(-92563) ➞ 5
count(4666) ➞ 4
count(-314890) ➞ 6
count(654321) ➞ 6
count(638476) ➞ 6
*/
function count(n) {
let ans = 0;
while(n>0){
let rem = Math.floor(n%10);
n = Math.floor(n/10);
ans++;
}
return ans;
}
console.log(count(318));
console.log(count(654321));
|
import * as validator from 'src/validations/settingValidator'
import basedModel from './baseModel'
class SettingModel extends basedModel {
constructor (data) {
super()
this.resetState()
if (data !== null && data !== undefined) {
var setting = data
var preferences = null
var location = null
var notifications = null
preferences = (typeof setting.preferences === 'object' ? setting.preferences : JSON.parse(setting.preferences))
if (preferences === null) {
return
}
location = (typeof preferences.location === 'object' ? preferences.location : JSON.parse(preferences.location))
notifications = (typeof preferences.notifications === 'object' ? preferences.notifications : JSON.parse(preferences.notifications))
this.preferences = {
localCurrency: preferences.localCurrency === '-' ? null : preferences.localCurrency,
location: {
country: location.country === '-' ? null : location.country,
state: location.state === '-' ? null : location.state,
city: location.city === '-' ? null : location.city
},
notifications: {
expired: notifications.expired,
accepted: notifications.accepted,
denied: notifications.denied
}
}
this.verifications = (typeof setting.verifications === 'object' ? setting.verifications : JSON.parse(setting.verifications))
}
}
static validationScheme () {
return {
localCurrency: validator.mandatory,
location: {
country: validator.mandatory,
state: validator.mandatory,
city: validator.mandatory
}
}
}
resetState () {
this.preferences = {
localCurrency: null,
location: {
country: '',
state: '',
city: ''
},
notifications: {
expired: true,
accepted: true,
denied: true
}
}
this.verifications = {
emailVerified: false,
addressVerified: false,
mobileVerified: false,
identityVerified: false
}
}
}
export default SettingModel
|
/*
* Copyright (C) 2012-2013 DFKI GmbH
* Deutsches Forschungszentrum fuer Kuenstliche Intelligenz
* German Research Center for Artificial Intelligence
* http://www.dfki.de
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
define ( [ 'commonUtils', 'helper' ],
/**
* @name Controller
* @class
*/
function (
commonUtils, Helper
){
/** @scope Controller.prototype */
/**
* #@+
* @memberOf Controller.prototype
*/
/**
* The Controller Class is a kind of interface-class which gives access to the methods of a controller and its helper. <br>
* Also holds information about views and partials associated with the controller.
*
* @constructs Controller
* @param {String} name Name of the Controller
* @param {Object} jsonDef Information about the controllers views and partials
* @category core
*/
function Controller(name, jsonDef){
// console.log("controller name " + name);
/**
* The definition of the controller object, containing all properties and functions of the controller.<br>
* A method of the controller can be called via:
this.script.methodController(parameter);
*
* @property script
* @type Object
* @public
*/
// this can only be invoked, if a function with the name "name" exists
this.script = new window[name]();
/**
* The json definition of the views and partials associated with the controller. Also contains paths to controller and its views/partials.
*
* @property def
* @type Object
* @public
*/
this.def = jsonDef;//new JPath(jsonDef);
/**
* The name of the controller.
*
* @property name
* @type String
* @public
*/
this.name = name;
var viewDefs = this.def.views;//.query('views');
/**
* An array holding the names of all views associated with the controller.
*
* @property views
* @type Array
* @public
*/
this.views = new Array();
this.parseViews(viewDefs);
// parsing the partials and saving the names in an array
var partialDefs = this.def.partials;//.query('partials');
/**
* An array holding the names of all partials associated with the controller.
*
* @property partials
* @type Array
* @public
*/
this.partials = new Array();
this.parsePartials(partialDefs);
/**
* The instance of the with the controller associated helper.
*
* @property helper
* @type Object
* @public
*/
this.helper;
/**
* The layout for this controller (if undefined, the default layout should be used)
* @property layout
* @type Object
*/
this.layout = this.def.layout;
}
/**
* This function loads the helper of the controller - if it exists.
*
* @function loadHelper
* @param {String} name Name of the Helper to be loaded
* @param {String} helperPath Path to the helper file to load
* @public
*/
Controller.prototype.loadHelper = function(name, helperPath){
var self = this;
//TODO move check of helper existance to Controller.foundControllersCallBack ?
//determine if there is a helper for the controller:
var path = helperPath;
var fileName = path;
var lastPathSeparatorIndex = path.lastIndexOf('/');
if(lastPathSeparatorIndex !== -1){
path = path.substring(0,lastPathSeparatorIndex);
fileName = fileName.substring( lastPathSeparatorIndex + 1 );
}
//get contents of the helper directory:
var dirContents = commonUtils.getDirectoryContents(path);
if(!dirContents){
console.warn('Could not determine contents for directory "'+path+'"');
return; ////////////////////// EARLY EXIT //////////////////////////////
}
else if(! commonUtils.isArray(dirContents) || dirContents.length < 1){
console.warn('Invalid information for contents of directory "'+path+'": '+dirContents);
return; ////////////////////// EARLY EXIT //////////////////////////////
}
//check, if there is an implementation file for this helper:
var helperIsSpecified = false;
for(var i=0, size= dirContents.length; i < size; ++i){
if(dirContents[i] === fileName){
helperIsSpecified = true;
break;
}
}
if( ! helperIsSpecified){
if(IS_DEBUG_ENABLED) console.debug("[HELPER] no helper available (not implemented) at '"+ helperPath+"'");//debug
return; ////////////////////// EARLY EXIT //////////////////////////////
}
//if there is a file: load the helper
commonUtils.getLocalScript(helperPath, function(data, textStatus, jqxhr){
if(IS_DEBUG_ENABLED) console.debug("[HELPER] load "+ helperPath);//debug
self.helper = new Helper(self, name);//new window["GoogleMapHelper"]();
},
function(exception) {
// print out an error message
console.warn("[WARN] Could not load helper -> " + exception + ": '" + helperPath + "'"); //failure
}
);
};
/**
* This function performs an action of a controller - which is represented by this instance of the Controller <br>
* class - by calling the method from the corresponding controller, e.g. assets/www/controllers/application.js
*
* @function perform
* @param {String} actionName Name of the method to be executed
* @param {Object} data Data to pass to the method of the controller as argument
* @returns {Object} The return value of the executed method
* @public
*/
Controller.prototype.perform = function(actionName, data){
if(IS_DEBUG_ENABLED) console.debug("should perform '" + actionName + "' of '" + this.name + "'"+ ((typeof data !== 'undefined' && data !== null)? " with data: "+JSON.stringify(data): ""));//debug
return this.script[actionName](data);
};
/**
*
* This function performs an action of a controller, but only if an action with this name exists; otherwise nothing is done.
*
* In difference to perform(..), the method does not trigger an ERROR, if the action does not exist / is not implemented.
* As a consequence, this method refers to "optionally" implemented functions, whereas perform(..) refers to mandatory functions.
*
* @function perform
* @param {String} actionName Name of the method to be executed
* @param {Object} data Data to pass to the method of the controller as argument
* @returns {Object} The return value of the executed method
* @public
*/
Controller.prototype.performIfPresent = function(actionName, data){
if(typeof this.script[actionName] === 'function'){
if(IS_DEBUG_ENABLED) console.debug("performing '" + actionName + "' of '" + this.name + "'"+ ((typeof data !== 'undefined' && data !== null)? " with data: "+JSON.stringify(data): ""));//debug
return this.script[actionName](data);
} else if(typeof this.script[actionName] !== 'undefined'){
if(IS_DEBUG_ENABLED) console.info("could not perform '" + actionName + "' of '" + this.name + "'"+ ((typeof data !== 'undefined' && data !== null)? " with data: "+JSON.stringify(data): "")+": no function ("+typeof this.script[actionName]+")");//debug
} else {
if(IS_DEBUG_ENABLED) console.debug("could not perform '" + actionName + "' of '" + this.name + "'"+ ((typeof data !== 'undefined' && data !== null)? " with data: "+JSON.stringify(data): "")+": not implemented (undefined)");//debug
}
};
/**
* This function performs a helper action of a controller by calling the appropriate method<br>
* {@link Helper#perform} of the instance of the helper class associated with the controller.
*
* @function performHelper
* @param {String} actionName Name of the helper method to be executed
* @param {Object} data Data to pass to the helper method as argument
* @returns {Object} The return value of the executed method
* @public
*/
Controller.prototype.performHelper = function(actionName, data){
if(arguments.length > 2){
return this.helper.perform(actionName, data, arguments[2]);
}
else {
return this.helper.perform(actionName, data);
}
};
/**
* Returns the helper of the controller instance.
*
* @function getHelper
* @returns {Object} The helper instance
* @public
*/
Controller.prototype.getHelper = function(){
return this.helper;
};
/**
* Stores all names of the views of the controller by iterating over the array of the views definition.<br>
* This function is called by the constructor of the {@link mmir.Controller} class.
*
* @function parseViews
* @param {Array} viewDefs Array of the json-definition of the controllers views - containing name of the views and their corresponding path to the js-files
* @public
*/
Controller.prototype.parseViews = function(viewDefs){
for(var i=0, size = viewDefs.length; i < size; ++i){
this.views.push(viewDefs[i].name);
}
};
/**
* Stores all names of the partials of the controller by iterating over the array of the partials definition.<br>
* This function is called by the constructor of the {@link mmir.Controller} class.
*
* @function parseViews
* @param {Array} partialDefs Array of the json-definition of the controllers partials - containing name of the partials and their corresponding path to the js-files
* @public
*/
Controller.prototype.parsePartials = function(partialDefs){
for(var i=0, size = partialDefs.length; i < size; ++i){
this.partials.push(partialDefs[i].name);
}
};
/**
* Returns the view names for the controller instance.
*
* @function getViewNames
* @returns {Array<String>} An array of the controllers views
* @public
*/
Controller.prototype.getViewNames = function(){
return this.views;
};
/**
* Returns the view names for the controller instance.
*
* TODO should this be private/hidden? -> provides "internal" JSON-details object (used in PresentationManager)
*
* Each info object has properties:
* {String} name
* {String} path
*
* @function getViews
* @returns {Array<Object>} An array of the controllers views
* @public
*/
Controller.prototype.getViews = function(){
return this.def.views;
};
/**
* Returns the partial names for the controller instance.
*
* @function getPartialNames
* @returns {Array<String>} An array of the controllers partials
* @public
*/
Controller.prototype.getPartialNames = function(){
return this.partials;
};
/**
* Returns the partial info object for the controller instance.
*
* TODO should this be private/hidden? -> provides "internal" JSON-details object (used in PresentationManager)
*
* Each info object has properties:
* {String} name
* {String} path
*
* @function getPartials
* @returns {Array<Object>} An array of the controllers partials
* @public
*/
Controller.prototype.getPartials = function(){
return this.def.partials;
};
/**
* Returns the layout of the controller instance.
*
* If undefined, the default layout should be used.
*
* TODO should this be private/hidden? -> provides "internal" JSON-details object (used in PresentationManager)
*
* The info object has properties:
* {String} name
* {String} path
* {String} fileName
*
* @function getLayout
* @returns {Object} The controller's layout (may be undefined)
* @public
*/
Controller.prototype.getLayout = function(){
return this.layout;
};
/**
* Returns the layout name for the controller instance.
*
* This is equal to the controller name.
*
* If undefined, the default layout should be used.
*
* @function getLayoutName
* @returns {String} The controller's layout name (may be undefined)
* @public
*/
Controller.prototype.getLayoutName = function(){
return this.layout? this.layout.name : this.layout;
};
/**
* Returns the name of the controller instance.
*
* @function getName
* @returns {String} The name of the controller
* @public
*/
Controller.prototype.getName = function(){
return this.name;
};
return Controller;
/** #@- */
});
|
"use strict";
const express = require('express');
const bodyParser = require('body-parser');
const stream = require('stream');
function Middleware(logger, messageValidatorService) {
this._logger = logger;
this._stream = this._createStream();
this._buffer = null;
this._app = express();
this._app.use(bodyParser.text({ type: "*/*" }));
this._validateMessageSignature(messageValidatorService);
this._configureEndpoints();
}
Middleware.prototype.getIncoming = function() {
return this._app;
};
Middleware.prototype.getStream = function() {
return this._stream;
};
Middleware.prototype._configureEndpoints = function() {
const self = this;
this._app.get("/ping", (request, response) => {
response.send("pong");
response.end();
});
this._app.post("/", (request, response) => {
self._logger.debug("Request data:", request.body);
self._stream.push(request.body);
if (self._buffer) {
response.send(self._buffer);
}
response.end();
});
};
Middleware.prototype._createStream = function() {
const self = this;
const duplexStream = new stream.Duplex();
duplexStream._read = function noop() {};
duplexStream._write = (chunk, encoding, done) => {
self._buffer = chunk.toString();
done();
};
return duplexStream;
};
Middleware.prototype._validateMessageSignature = function(messageValidatorService) {
const self = this;
this._app.use((request, response, next) => {
const serverSideSignature = request.headers.X_Viber_Content_Signature || request.query.sig;
if (!messageValidatorService.validateMessage(serverSideSignature, request.body)) {
self._logger.warn("Could not validate message signature", serverSideSignature);
return;
}
next();
});
};
module.exports = Middleware;
|
$(document).ready(function() {
function modal(kind, switchButton){
$.post('/pages/modal/' + kind + '/' + switchButton, function( data ) {
$('#timeForm').validator('destroy');
$('#timeForm').remove();
$( "body" ).append( data );
$("#timeForm").modal('show');
$("#timeForm").validator();
});
}
var c = new Calendar(modal);
$("#calendar").fullCalendar(c);
$(document).on('click', '#switch', function () {
var kind = $(this).attr("data-next")
modal(kind);
});
$(document).on('shown.bs.modal', function () {
$('input[name="timeIn"]').focus();
});
$(document).on('hidden.bs.modal', function () {
$('#timeForm').validator('destroy');
$('#timeForm').remove();
});
$(document).on('click keyup', '[data-submit="modal"]', function(e) {
if(e.type == "click" || e.which == 13){
var eventData = new Event("option:selected", c);
if(eventData.isValid()) {
$.post('/events/create', JSON.stringify(eventData), function(){
$('#calendar').fullCalendar('renderEvent', eventData, true);
});
$('#calendar').fullCalendar('unselect');
$('#timeForm').remove();
}
}
});
$(document).on('keydown', function(e) {
if($('#timeForm').length == 0) {
var map = {
37: c.move.bind(null, { days: -1 }),
38: c.move.bind(null, { weeks: -1 }),
39: c.move.bind(null, { days: 1 }),
40: c.move.bind(null, { weeks: 1 }),
13: function () {
var start = c.getDate();
var end = start.clone();
c.select(start, end);
}
}
var key = e.which;
if(key in map) {
map[key]();
e.preventDefault();
}
}
});
});
|
angular.module('clipr', [])
.controller('CliprListing',['$scope','$http', function($scope, $http){
$http({ method: 'GET', url: '/list' }).success(function (data) {
$scope.list= data;
}).
error(function (data) {
$scope.list={plugins:[]};
});
}]);
|
import React from 'react';
import {FlatList, StyleSheet} from 'react-native';
import {CATEGORIES} from './../../data/dummy-data';
import Colors from './../../constants/Colors';
import CategoryGridItem from '../components/CategoryGridItem';
const CategoriesScreen = ({navigation}) => {
return (
<FlatList
style={{width: '100%'}}
data={CATEGORIES}
keyExtractor={(item, index) => item.id}
contentContainerStyle={styles.contentContainer}
renderItem={({item}) => (
<CategoryGridItem
title={item.title}
color={item.color}
id={item.id}
onSelect={() => {
navigation.navigate({
routeName: 'CategoryMeals',
params: {
categoryId: item.id,
color: item.color,
},
});
}}
/>
)}
numColumns={2}
/>
);
};
CategoriesScreen.navigationOptions = {
headerTitle: 'Meal Categories',
};
const styles = StyleSheet.create({
contentContainer: {
backgroundColor: Colors.lightGrey,
justifyContent: 'space-between',
},
});
export default CategoriesScreen;
|
import React from 'react';
import LazyLoad from 'react-lazy-load';
const DummyChart = () => {
return (
<div>
<LazyLoad height={762}>
<h2>DummyChart</h2>
</LazyLoad>
</div>
);
};
export default DummyChart;
|
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
var _require = require('@uppy/core'),
Plugin = _require.Plugin;
var toArray = require('@uppy/utils/lib/toArray');
var findDOMElement = require('@uppy/utils/lib/findDOMElement');
/**
* Add files from existing file inputs to Uppy.
*/
var AttachFileInputs = /*#__PURE__*/function (_Plugin) {
_inheritsLoose(AttachFileInputs, _Plugin);
function AttachFileInputs(uppy, opts) {
var _this;
_this = _Plugin.call(this, uppy, opts) || this;
_this.id = _this.opts.id || 'AttachFileInputs';
_this.type = 'acquirer';
_this.handleChange = _this.handleChange.bind(_assertThisInitialized(_this));
_this.inputs = null;
return _this;
}
var _proto = AttachFileInputs.prototype;
_proto.handleChange = function handleChange(event) {
this.addFiles(event.target);
};
_proto.addFiles = function addFiles(input) {
var _this2 = this;
var files = toArray(input.files);
files.forEach(function (file) {
try {
_this2.uppy.addFile({
source: _this2.id,
name: file.name,
type: file.type,
data: file
});
} catch (err) {
if (!err.isRestriction) {
_this2.uppy.log(err);
}
}
});
};
_proto.install = function install() {
var _this3 = this;
this.el = findDOMElement(this.opts.target);
if (!this.el) {
throw new Error('[AttachFileInputs] Target form does not exist');
}
var restrictions = this.uppy.opts.restrictions;
this.inputs = this.el.querySelectorAll('input[type="file"]');
this.inputs.forEach(function (input) {
input.addEventListener('change', _this3.handleChange);
if (!input.hasAttribute('multiple')) {
if (restrictions.maxNumberOfFiles !== 1) {
input.setAttribute('multiple', 'multiple');
} else {
input.removeAttribute('multiple');
}
}
if (!input.hasAttribute('accept') && restrictions.allowedFileTypes) {
input.setAttribute('accept', restrictions.allowedFileTypes.join(','));
} // Check if this input already contains files (eg. user selected them before Uppy loaded,
// or the page was refreshed and the browser kept files selected)
_this3.addFiles(input);
});
};
_proto.uninstall = function uninstall() {
var _this4 = this;
this.inputs.forEach(function (input) {
input.removeEventListener('change', _this4.handleChange);
});
this.inputs = null;
};
return AttachFileInputs;
}(Plugin);
module.exports = AttachFileInputs;
|
describe('P.models.workouts.Scheduler', function() {
var Model = P.models.workouts.Scheduler;
it('ignores timezones ... for now', function() {
var data = new Model().parse({
date: '2015-11-20T00:00:00Z'
});
if (data.date.getTimezoneOffset() !== 0) {
expect(data.date.getHours()).toBe(0);
}
});
});
|
import React, { Component } from 'react'
import FormUser from './FormUser.js'
export default class simplePage1 extends Component {
render() {
return (
<div>
<h1 style={{ textAlign: "center"}}>Article 2 : Règles d’écriture d’un article d’enquête /de reportage </h1>
<p style={{textAlign: "justify", margin:"20px"}}><span style={{fontFamily:"verdana ",fontWeight: "bold"}}>Écrire un article est un exercice particulier</span>. Il est indispensable de suivre quelques règles journalistiques
afin d’écrire un bon article. Animés par le désir d’accrocher les lecteurs, les journalistes trouvent les
images, affinent les formules, inventent les rythmes qui disent la vigueur de la langue d’aujourd’hui.</p>
<p style={{textAlign: "justify", margin:"20px"}}><span style={{fontFamily:"verdana ",fontWeight: "bold"}}>Le sujet de l’article</span>. Il faut sélectionner une bonne information : avoir des témoignages, des
chiffres fiables. Il faut pouvoir répondre aux cinq questions de référence : Qui, quand, comment,
où, quoi, pourquoi… L’article doit apporter au lecteur des informations précises, des détails
concrets qu’il tient de sources fiables. Il faut éviter les généralités que tout le monde connaît. Des
informations concrètes, ce sont des descriptions précises de quelque chose qu’on a vue et qui
existe vraiment. Ce sont aussi des citations (entre guillemets. Par exemple: Monsieur Alain est
boulanger et aime son métier: “Je fais du pain depuis 20 ans et toujours avec le même bonheur...”)
de personnes qu’on a rencontrées et interrogées. Ce sont enfin des INFORMATIONS précises. Il
ne faut pas écrire: “Monsieur Alain a expliqué comment il fait son pain tous les jours” mais il faut
écrire ce qu’il a dit: “Tous les matins, il allume son four (1) tout en chantant pour se réveiller et
commencer la journée dans la bonne humeur (2). Puis il mélange sa farine avec de l’eau (3)...” Il y
a là trois informations concrètes qui permettent au lecteur de bien savoir ce que fait monsieur Alain
alors que si le journaliste écrit seulement: “Monsieur Alain a expliqué comment il fait son pain tous
les jours”, le lecteur ne sait pas comment cela se passe.
</p>
<p style={{textAlign: "justify", margin:"20px"}}><span style={{fontFamily:"verdana ",fontWeight: "bold"}}>Le traitement de l’information</span>. Pour écrire un article intéressant, l’information brute ne suffit pas.
Il faut analyser le contenu et le mettre en valeur par une écriture claire, précise et soignée. Le titre
doit être soigneusement choisi et parlant. La première phrase doit donner envie de continuer et
l’information doit se trouver au début de l’article. Utiliser les expressions, les images, les anecdotes
les plus " parlantes ". Ne pas hésiter à rajouter une image (photo, caricature, schéma…) pour
illustrer son propos. Privilégier une mise en page aérée. </p>
<p style={{textAlign: "justify", margin:"20px"}}><span style={{fontFamily:"verdana ",fontWeight: "bold"}}>Le style de l’article</span>. Selon le sujet et la façon dont l’auteur veut l’aborder, on peut choisir un ton :
ton clinique, distant, sensible, grave, léger, humoristique, pédagogique, solennel ou complice.
Donner du rythme à votre article : utiliser des phrases courtes et incisives (sujet, verbe,
compléments), choisir des mots simples et concrets. Les points et les virgules doivent apparaitre
clairement et utiliser les mots de liaison (en effet, car, mais, pourtant, aussi, donc…). Privilégier les
verbes actifs et le temps présent. L’article doit être clair, facile à comprendre… et c’est souvent
difficile « de faire simple »
</p>
<p style={{textAlign: "justify", margin:"20px"}}><span style={{fontFamily:"verdana ",fontWeight: "bold"}}>Le plan</span>. Le plan doit être simple et logique. Le premier paragraphe est l’accroche : il donne en
général l’information la plus importante (cela peut être une citation, une description de lieu, une
anecdote). Les autres paragraphes doivent suivre cette règle simple : une idée importante par
paragraphe et une succession logique entre tous les paragraphes. Il est donc important de sauter
une ligne à chaque fin de partie, pour visualiser l’articulation de votre argumentaire.</p>
<FormUser/>
</div>
)
}
}
|
import React from 'react';
import { Typography,Grid,Link } from '@material-ui/core';
import { makeStyles } from '@material-ui/core/styles';
import newsImg from '../../../assets/images/newsImg.jpg'
import newImgBg from '../../../assets/images/newsImgBg.svg'
const useStyles = makeStyles(theme => ({
newsItemImg: {
padding:"16px 14px",
position:"absolute",
},
ImgBg: {
position: "relative"
},
newsCaption: {
background: "#F2D1C2",
padding: "2px 10px",
borderRadius: 60,
},
}));
export default function NewsItem({
image,title,subtitle,article,link
}) {
const classes = useStyles();
return (
<Grid item xs={12}>
<Grid container justify="flex-start" alignItems="flex-start" spacing={4}>
<Grid item xs>
<div>
<a href="/"><img src={newsImg} className={classes.newsItemImg}></img></a>
<img src={newImgBg} className={classes.newsItemBg}></img>
</div>
</Grid>
<Grid item xs={9}>
<div className={classes.gridContent}>
<Typography className={classes.newsCaption} variant="caption">{article}</Typography>
<a href="/"><Typography variant="h5">{title}</Typography></a>
<Typography variant="body2" style={{padding:"15px 0 30px 0"}}>{subtitle}</Typography>
<Link to={link} href={link} component="a">Узнать больше</Link>
</div>
</Grid>
</Grid>
<hr style={{marginTop: "50px"}} />
</Grid>
);
};
|
const fs = require('fs-extra');
const {getDestDir} = require('./paths');
const reload = require('./reload');
const {createTask} = require('./task');
const enLocale = fs.readFileSync('src/_locales/en.config', {encoding: 'utf8'}).replace(/^#.*?$/gm, '');
global.chrome = global.chrome || {};
global.chrome.i18n = global.chrome.i18n || {};
global.chrome.i18n.getMessage = global.chrome.i18n.getMessage || ((name) => {
const index = enLocale.indexOf(`@${name}`);
if (index < 0) {
throw new Error(`Message @${name} not found`);
}
const start = index + name.length + 1;
let end = enLocale.indexOf('@', start);
if (end < 0) {
end = enLocale.length;
}
const message = enLocale.substring(start, end).trim();
return message;
});
global.chrome.i18n.getUILanguage = global.chrome.i18n.getUILanguage || (() => 'en-US');
const tsConfig = require('../src/tsconfig.json');
require('ts-node').register({
...tsConfig,
compilerOptions: {
...tsConfig.compilerOptions,
module: 'commonjs',
},
});
require('tsconfig-paths').register({
baseUrl: './',
paths: {
'malevic/*': ['node_modules/malevic/umd/*'],
'malevic': ['node_modules/malevic/umd/index'],
}
});
const Malevic = require('malevic/umd/index');
const MalevicString = require('malevic/umd/string');
const DevToolsBody = require('../src/ui/devtools/components/body').default;
const PopupBody = require('../src/ui/popup/components/body').default;
const CSSEditorBody = require('../src/ui/stylesheet-editor/components/body').default;
const {getMockData, getMockActiveTabInfo} = require('../src/ui/connect/mock');
const pages = [
{
cwdPath: 'ui/popup/index.html',
rootComponent: PopupBody,
props: {
data: getMockData({isReady: false}),
tab: getMockActiveTabInfo(),
actions: null,
},
},
{
cwdPath: 'ui/devtools/index.html',
rootComponent: DevToolsBody,
props: {
data: getMockData({isReady: false}),
actions: null,
},
},
{
cwdPath: 'ui/stylesheet-editor/index.html',
rootComponent: CSSEditorBody,
props: {
data: getMockData({isReady: false}),
tab: getMockActiveTabInfo(),
actions: null,
},
},
];
async function bundleHTMLPage({cwdPath, rootComponent, props}, {production}) {
let html = await fs.readFile(`src/${cwdPath}`, 'utf8');
const bodyText = MalevicString.stringify(Malevic.m(rootComponent, props));
html = html.replace('$BODY', bodyText);
const getPath = (dir) => `${dir}/${cwdPath}`;
const outPath = getPath(getDestDir({production}));
const firefoxPath = getPath(getDestDir({production, firefox: true}));
await fs.outputFile(outPath, html);
await fs.copy(outPath, firefoxPath);
}
async function bundleHTML({production}) {
for (const page of pages) {
await bundleHTMLPage(page, {production});
}
}
function getSrcPath(cwdPath) {
return `src/${cwdPath}`;
}
async function rebuildHTML(changedFiles) {
await Promise.all(
pages
.filter((page) => changedFiles.some((changed) => changed === getSrcPath(page.cwdPath)))
.map((page) => bundleHTMLPage(page, {production: false}))
);
}
module.exports = createTask(
'bundle-html',
bundleHTML,
).addWatcher(
pages.map((page) => getSrcPath(page.cwdPath)),
async (changedFiles) => {
await rebuildHTML(changedFiles);
reload({type: reload.UI});
},
);
|
var searchData=
[
['handling_20time_35',['Handling time',['../group__TimeFunctions.html',1,'']]]
];
|
const Exercice = require('./model');
module.exports = {
create: async (request, exam) => {
const exerciceToSave = new Exercice(request);
const maxOrder = Math.max(...exam.exercices.map(ex => ex.order));
exerciceToSave.order = exerciceToSave.order || maxOrder + 1;
const exercice = await exerciceToSave.save();
exam.exercices.push(exercice._id);
await exam.save();
return exercice;
},
getById: async id => Exercice.findById(id).populate('questions'),
update: async (_id, exercice) => Exercice.findOneAndUpdate({ _id }, exercice),
delete: async _id => Exercice.findByIdAndDelete(_id),
/**
* Updates the order of the other exercices that are contained
* in the same exam if it is needed
* @param {Exam} exam the parent exam that contains the exercices
* @param {Exercice} exercice the exercice that's being dragged and dropped
* @param {number} newExerciceOrder the new order of the exercice that's being dragged and dropped
*/
async updateOrderOfOtherExercices(exam, exercice, newExerciceOrder) {
const promisesUpdateOrder = exam.exercices.map(async (syblingExercice) => {
// if it is a different exercice than the one we are updating
// and if it has a higher order
// then increment its order
if (syblingExercice._id !== exercice._id && syblingExercice.order >= newExerciceOrder) {
const newSyblingExercice = syblingExercice;
newSyblingExercice.order += 1;
await newSyblingExercice.save();
}
return true;
});
// wait for all the exercises to be updated
await Promise.all(promisesUpdateOrder);
},
};
|
const mongoose = require('mongoose');
const safeSchema = new mongoose.Schema({
insuranceName: [String],
insuranceCoverage: [String],
insuranceADT: [Number],
SafenumADT: [Number],
insuranceCHD: [Number],
SafenumCHD: [Number],
insuranceINF: [Number],
SafenumINF: [Number],
insuranceCoin: [String],
insuranceTOT: [Number],
ticketsName: [String],
ticketsADT: [Number],
TicketnumADT: [Number],
ticketsCHD: [Number],
TicketnumCHD: [Number],
ticketsINF: [Number],
TicketnumINF: [Number],
ticketsCoin: [String],
ticketsTOT: [Number],
otherName: [String],
otherADT: [Number],
OthernumADT: [Number],
otherCHD: [Number],
OthernumCHD: [Number],
otherINF: [Number],
OthernumINF: [Number],
otherCoin: [String],
otherTOT: [Number],
}, { timestamps: true, static: false });
const SafeSchema = mongoose.model('Safe', safeSchema);
class Safe {
/**
* Get all Users from database
* @returns {Array} Array of Users
*/
static getAll() {
return new Promise((resolve, reject) => {
SafeSchema.find({}).exec().then((results) => {
resolve(results);
}).catch((err) => {
reject(err);
});
});
}
/**
* Get a Safe by it's id
* @param {string} id - Safe Id
* @returns {Object} - Safe Document Data
*/
static getById(id) {
return new Promise((resolve, reject) => {
SafeSchema.findById(id).exec().then((result) => {
resolve(result);
}).catch((err) => {
reject(err);
});
});
}
/**
* Create a new User
* @param {Object} safe - User Document Data
* @returns {string} - New User Id
*/
static create(safe) {
return new Promise((resolve, reject) => {
SafeSchema.create(safe).then((result) => {
resolve(result._id);
}).catch((err) => {
reject(err);
});
});
}
/**
* Update a User
* @param {string} id - User Id
* @param {Object} safe - User Document Data
* @returns {null}
*/
static update(id, safe) {
return new Promise((resolve, reject) => {
SafeSchema.findByIdAndUpdate(id, safe).then(() => {
resolve();
}).catch((err) => {
reject(err);
});
});
}
/**
* Delete a Safe
* @param {string} id - Safe Id
* @returns {null}
*/
static delete(id) {
return new Promise((resolve, reject) => {
SafeSchema.findByIdAndDelete(id).then(() => {
resolve();
}).catch((err) => {
reject(err);
});
});
}
static getByIdArray(id_array){
return new Promise((resolve, reject)=> {
SafeSchema.find({ _id: {$in: id_array} }).then((safes)=>{
resolve(safes);
}).catch((err) => {
reject(err);
});
})
}
}
module.exports = Safe;
|
import React from 'react';
import css from './Circle.css';
export function Circle() {
return (
<>
<style>{`${css}`}</style>
<div className="lds-circle">
<div></div>
</div>
</>
);
}
|
'use strict';
angular.module('basesManagement');
|
"use strict";
/*jslint browser:true */
/*jslint node:true */
var ball = require('./ball');
var stick = require('./stick');
var animate;
/**
* Context prototype.
* With this object (Singleton) by the way. We manage game context: points, on/off, balls location
* on screen. It is a bridge that let you traverse whole game objects
*
* @constructor
*/
function Context(){
this.score=0;
this.state = "stop"; //STOP OR RUN
this.speed = 1.8; //1 - 20;
this.restart();
var self = this; //Trick to run setInterval properly
this.initWebSockets();
this.getContextSelf = function(){return self;};
//If both paddles are autopilot we start the game directly
if (this.stick.autopilot && this.stick2.autopilot) this.start();
}
Context.prototype.initWebSockets = function(){
this.socket = io(); //Third party lib loaded on html not included with require
this.socket.on('stick id and position',function(msg){
console.log(msg);
});
this.socket.on('ball position',function(msg){
console.log(msg);
});
};
/** Restart pong game after a resizing event*/
Context.prototype.restart = function(){
this.viewPortWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; //ViewportX
this.viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;//ViewportY
this.speed = this.viewPortWidth/1000;
console.log(this.viewPortWidth+ " speed = "+this.speed);
if (this.ball && this.stick && this.stick2) {
this.ball.scaleAndRealocate();
this.stick.scaleAndRealocate();
this.stick2.scaleAndRealocate();
}else{
this.ball = new ball("bola",this);
this.stick = new stick("stick","left",this,true);
this.stick2 = new stick("stick2","right",this,true);
}
/** We put ball in the middle of the screen */
this.ball.locate((this.viewPortWidth/2)-(this.ball.imageBallView.width/2),(this.viewPortHeight/2)-this.ball.imageBallView.height);
/** Vertical dotted separator decoration */
var verticalSeparator = document.getElementById("vertical");
var verticalSeparatorWidth = this.viewPortWidth * 0.02;
verticalSeparator.setAttribute("style","left:"+(this.viewPortWidth/2-verticalSeparatorWidth/2)+";border-left: "+verticalSeparatorWidth+"px dotted #444; ");
};
Context.prototype.increaseSpeed = function(){
if(this.ball.count==4){
this.ball.count=0;
if(this.speed>=2){
this.speed=2;
}else{
this.speed=this.speed+0.1;
}
console.log(this.speed);
}
};
Context.prototype.showBanner = function(message,millis){
var bannerEl = document.getElementById("banner");
bannerEl.style.display = "block";
bannerEl.innerHTML = message;
if (millis && (millis !== 0))
setInterval(this.hideBanner,millis);
};
/** Hide game informative Banner */
Context.prototype.hideBanner = function(){
var bannerEl = document.getElementById("banner");
bannerEl.style.display = "none";
};
/** Start pong game */
Context.prototype.start = function(){
//this.state = "run";
this.viewPortWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; //ViewportX
this.speed = this.viewPortWidth/1000;
var self = this.getContextSelf();
self.state = "run";
self.ball.ramdomDepartureAngle();
self.lastTime = new Date();
animate=setInterval(function(){self.animate();}, 1);
};
/** Reset pong game scores*/
Context.prototype.resetScores = function(){
this.stick.score = 0;
this.stick2.score = 0;
var scoreLeftEl = document.getElementById("scorePlayerLeft");
var scoreRightEl = document.getElementById("scorePlayerRight");
scoreLeftEl.innerHTML = this.stick.score;
scoreRightEl.innerHTML = this.stick2.score;
};
/** Stop pong game */
Context.prototype.stop = function(){
this.state = "stop";
clearTimeout(animate);
//if (this.stick.autopilot && this.stick2.autopilot) this.start();
this.start();
};
/** Animate one new game frame */
Context.prototype.animate =function(){
if (this.stick.autopilot) this.processAI(this.stick);
if (this.stick2.autopilot) this.processAI(this.stick2);
var currTime = new Date();
var millis = currTime.getTime() - this.lastTime.getTime();
this.lastTime = currTime;
var ball_ = this.ball;
ball_.locate(ball_.ballX + ((ball_.ballVx*millis)*this.speed) , ball_.ballY + ((ball_.ballVy*millis)*this.speed) );
};
/** Arificial intelligence behind stick movements when it is autopiloted by the computer */
Context.prototype.processAI = function(stick_){
var stickPos = stick_.getPosition();
var StickMAXSPEED = 10; //Max pixel speed per frame
var stickVy = 1;
var iamLeftStickAndBallIsCloseAndTowardsMe = (stick_.sideLocation === "left" && (this.ball.ballX < (this.viewPortWidth/2)) && (this.ball.ballVx < 0) );
var iamRightStickAndBallIsCloseAndTowardsMe = (stick_.sideLocation === "right" && (this.ball.ballX > (this.viewPortWidth/2)) && (this.ball.ballVx > 0) );
if (iamLeftStickAndBallIsCloseAndTowardsMe || iamRightStickAndBallIsCloseAndTowardsMe) {
var timeTilCollision = ((this.viewPortWidth-stick_.gap-stick_.imageStickView.width) - this.ball.ballX) / (this.ball.ballVx);
if (stick_.sideLocation === "left") timeTilCollision = ((stick_.imageStickView.width+stick_.gap) - this.ball.ballX) / (this.ball.ballVx);
var distanceWanted = (stickPos.y+(stick_.imageStickView.height/2)) - (this.ball.ballY+(this.ball.imageBallView.width/2));
var velocityWanted = -distanceWanted / timeTilCollision;
if(velocityWanted > StickMAXSPEED)
stickVy = StickMAXSPEED;
else if(velocityWanted < -StickMAXSPEED)
stickVy = -StickMAXSPEED;
else
stickVy = velocityWanted*3;
stick_.locate(stickPos.x,stick_.stickY + stickVy);
}
};
module.exports = Context;
|
import { Game, Animation } from 'alpha'
import Loading from 'components/loading'
import Wecome from 'components/wecome'
import Home from 'components/home'
class Main extends Game{
constructor() {
super()
this.name = 'gameRoot'
this.index = -1
this.go('wecome')
console.log(this.stage)
}
createComponents(classObj, routerName) {
const that = this
const component = new classObj()
const index = this.stage.childrem.length
this.stage.appendChild(component)
this['has' + routerName] = true
this['len' + routerName] = index
component.routerName = routerName
component.go = function (n) {
that.go(n)
}
return component
}
loadComponents(routerName) {
let component = null
if (this['len' + routerName]) {
const i = this['len' + routerName]
component = this.stage.childrem[i]
} else {
const cl = this.getRouterClass(routerName)
component = this.createComponents(cl, routerName)
}
return component
}
go(routerName) {
if (!this['has' + routerName] && this.index === -1) {
const cl = this.getRouterClass(routerName)
const component = this.createComponents(cl, routerName)
this.nextPage(component)
} else {
const index = this.index
const lastcomponent = this.stage.childrem[index]
const nextcomponent = this.loadComponents(routerName)
this.lastPage(lastcomponent)
this.nextPage(nextcomponent)
}
this.index = this['len' + routerName]
}
getRouterClass(routerName) {
switch (routerName) {
case 'wecome':
return Wecome
case 'loading':
return Loading
case 'home':
return Home
default:
break;
}
}
lastPage(component) {
component.opacity = 1
component.index = -1
Animation(component, {
data: {
opacity: 0
},
duration: 800,
callback: function (e) {
component.visibility = false
}
})
}
nextPage(component) {
component.opacity = 0
component.index = 1
component.visibility = true
Animation(component, {
data: {
opacity: 1
},
duration: 800
})
}
}
new Main()
|
import React from 'react'
// local libs
import Typography from '@material-ui/core/Typography'
import ErrorMessage from 'src/generic/ErrorMessage'
const
ErrorContent = () => <div>
<Typography variant="body1" gutterBottom>Some shit is happened 8==э</Typography>
<Typography variant="body1" gutterBottom>Please try again</Typography>
<ErrorMessage/>
</div>
export default ErrorContent
|
import 'bootstrap.native/dist/bootstrap-native-v4';
import Darkmode from 'darkmode-js';
import Headroom from 'headroom.js';
import LazyLoad from 'vanilla-lazyload';
import { Search } from './search';
import { Redirect } from './redirect';
import { Matomo } from './matomo';
import './player';
var darkmode = new Darkmode({
saveInCookies: true,
label: '<i class="fas fa-lightbulb"></i>',
autoMatchOsTheme: true
});
darkmode.showWidget();
var headroom = new Headroom(document.querySelector('nav'), {
onPin: function () {
darkmode.button.hidden = false;
if (!darkmode.isActivated()) {
darkmode.layer.hidden = false;
}
},
onUnpin: function () {
darkmode.button.hidden = true;
if (!darkmode.isActivated()) {
darkmode.layer.hidden = true;
}
}
});
headroom.init();
new LazyLoad({ elements_selector: '.lazyload' });
// Matomo
Matomo.trackPageView();
// Search
if (document.querySelector('#search')) {
Search.init('#search');
}
// Redirect
window.Redirect = Redirect;
|
import React ,{useState , useEffect} from 'react';
import {Link} from 'react-router-dom';
import axios from 'axios';
import CreateRoom from "./videoChat/components/modal/CreateModal";
import JoinRoom from './videoChat/components/modal/Join';
const Header = ({history}) =>{
const [show, setShow] = useState(false);
const handleClose = () => setShow(false);
const handleShow = () => setShow(true);
const [showCreateRoom, setShowCreateRoom] = useState(false);
const showCreateRoomFunc = () => {
setShowCreateRoom(!showCreateRoom);
};
const [showJoinRoom, setShowJoinRoom] = useState(false);
const [userId, setUserId] = useState("");
const showJoinRoomFunc = () => {
setShowJoinRoom(!showJoinRoom);
};
const [user, setUser]= useState(Object);
const [notif, setNotif]= useState([]);
useEffect(() => {
if(!localStorage.getItem("authToken")){
history.push("/login")
}
const config = {
headers: {
"Content-Type":"appliation/json",
Authorization: `Bearer ${localStorage.getItem("authToken")}`
}
}
try {
axios.get("https://aaweni.herokuapp.com/api/auth/details_user",config).then((response)=>{
setUser(response.data.data);
console.log(user)});
} catch (error) {
console.log(error)
}
axios.get(`https://aaweni.herokuapp.com/notif/getAll`, config)
.then((response) => {
setNotif(response.data);
console.log(response.data)
})
.catch((error) => {
console.log(error)
})
}
,[history]);
const logoutHandler = async () => {
try {
localStorage.clear()
window.location.href = "/" ;
} catch (err) {
window.location.href = "/" ;
}
}
return (
<div>
<header style={{zIndex:100}}>
<div class="header_wrap">
<div class="header_inner mcontainer">
<div class="left_side">
<span class="slide_menu" uk-toggle="target: #wrapper ; cls: is-collapse is-active">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="24" height="24"><path d="M3 4h18v2H3V4zm0 7h12v2H3v-2zm0 7h18v2H3v-2z" fill="currentColor"></path></svg>
</span>
<div id="logo">
<Link to={"/posts"}>
<img src="assets/user/images/logoo.png" alt=""/>
<img src="assets/user/images/logoo.png" class="logo_mobile" alt="" />
</Link>
</div>
</div>
{/* <!-- search icon for mobile -->*/}
<div class="header-search-icon" uk-toggle="target: #wrapper ; cls: show-searchbox"> </div>
<div class="header_search">
<input value="" type="text" class="form-control" placeholder="Search for Friends , Videos and more.." autocomplete="off"/>
<i class="uil-search-alt"></i>
</div>
<div uk-drop="mode: click" class="hidden md:w-1/3 w-11/12 shadow-lg rounded-md -mt-2 bg-white">
<div class="-mt-2 p-3">
<h4 class="font-semibold mb-1 mt-2 px-2.5 text-lg"> Recently </h4>
<ul>
<li>
<a href="#" class="flex items-center space-x-2 p-2 hover:bg-gray-100 rounded-md">
<img src="assets/user/images/avatars/avatar-4.jpg" alt="" class="border mr-3 rounded-full shadow-sm w-8"/>
Erica Jones
</a>
</li>
<li>
<a href="#" class="flex items-center space-x-2 p-2 hover:bg-gray-100 rounded-md">
<img src="assets/user/images/group/group-2.jpg" alt="" class="border mr-3 rounded-full shadow-sm w-8"/>
Coffee Addicts
</a>
</li>
<li>
<a href="#" class="flex items-center space-x-2 p-2 hover:bg-gray-100 rounded-md">
<img src="assets/user/images/group/group-4.jpg" alt="" class="border mr-3 rounded-full shadow-sm w-8"/>
Mountain Riders
</a>
</li>
<li>
<a href="#" class="flex items-center space-x-2 p-2 hover:bg-gray-100 rounded-md">
<img src="assets/user/images/group/group-5.jpg" alt="" class="border mr-3 rounded-full shadow-sm w-8"/>
Property Rent And Sale
</a>
</li>
</ul>
</div>
</div>
<div class="right_side">
<div class="header_widgets">
<Link to={"/posts"} class="is_link">
Home
</Link>
<a href="#" class="is_icon">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M15 17h5l-1.405-1.405A2.032 2.032 0 0118 14.158V11a6.002 6.002 0 00-4-5.659V5a2 2 0 10-4 0v.341C7.67 6.165 6 8.388 6 11v3.159c0 .538-.214 1.055-.595 1.436L4 17h5m6 0v1a3 3 0 11-6 0v-1m6 0H9" />
</svg>
<span>1</span>
</a>
<div uk-drop="mode: click" class="header_dropdown">
<div class="dropdown_scrollbar" data-simplebar>
<div class="drop_headline">
<h4>Notifications </h4>
<div class="btn_action">
<Link to="/notifications"><a>
<i class="icon-feather-settings" uk-tooltip="title: Notifications settings ; pos: left" title="" aria-expanded="false"></i>
</a></Link>
</div>
</div>
<ul>
{ notif?.map((val,key) => {
return(
<li key={key}>
<Link to={`/userdetails/${val._id}`}><a>
<div class="drop_avatar"> <img src={val.profilePicture} alt=""/>
</div>
<div class="drop_text">
<p>
You have a new invitation from <strong> {val.username}</strong>
<span class="text-link"> View his profile</span>
</p>
</div>
</a>
</Link>
</li>
)})}
</ul>
</div>
</div>
{/*<!-- Message --> */}
<Link to={`/chat/${user._id}`} >
<a href="#" class="is_icon">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
</svg>
<span>4</span>
</a>
</Link>
<Link to="/postsprofile">
<img src={user.profilePicture} class="is_avatar" alt=""/>
</Link>
<div uk-drop="mode: click;offset:5" class="header_dropdown profile_dropdown">
<Link to="/postsprofile" class="user">
<div class="user_avatar">
<img src={user.profilePicture} alt=""/>
</div>
<div class="user_name">
<div> {user.username} </div>
<span> {user.email} </span>
</div>
</Link>
<hr class="border-gray-100"/>
<a>
<svg fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M11.49 3.17c-.38-1.56-2.6-1.56-2.98 0a1.532 1.532 0 01-2.286.948c-1.372-.836-2.942.734-2.106 2.106.54.886.061 2.042-.947 2.287-1.561.379-1.561 2.6 0 2.978a1.532 1.532 0 01.947 2.287c-.836 1.372.734 2.942 2.106 2.106a1.532 1.532 0 012.287.947c.379 1.561 2.6 1.561 2.978 0a1.533 1.533 0 012.287-.947c1.372.836 2.942-.734 2.106-2.106a1.533 1.533 0 01.947-2.287c1.561-.379 1.561-2.6 0-2.978a1.532 1.532 0 01-.947-2.287c.836-1.372-.734-2.942-2.106-2.106a1.532 1.532 0 01-2.287-.947zM10 13a3 3 0 100-6 3 3 0 000 6z" clip-rule="evenodd"></path></svg>
<Link to="/postsprofile">My Account </Link>
</a>
<a>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M3 6a3 3 0 013-3h10a1 1 0 01.8 1.6L14.25 8l2.55 3.4A1 1 0 0116 13H6a1 1 0 00-1 1v3a1 1 0 11-2 0V6z" clip-rule="evenodd" />
</svg>
<Link to="/mypages" class="lg:px-2">Manage Pages</Link>
</a>
<a>
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"></path>
</svg>
<Link to="/" onClick={logoutHandler}>Logout </Link>
</a>
</div>
</div>
</div>
</div>
</div>
</header>
{/* <!-- sidebar -->*/}
<div class="sidebar">
<div class="sidebar_header">
<img src="assets/user/images/logo.png" alt=""/>
<img src="assets/user/images/logo-icon.html" class="logo-icon" alt=""/>
<span class="btn-mobile" uk-toggle="target: #wrapper ; cls: is-collapse is-active"></span>
</div>
<div class="sidebar_inner" data-simplebar>
<ul>
<li class="active">
<Link to={"/posts"}>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="text-blue-600"
>
<path d="M10.707 2.293a1 1 0 00-1.414 0l-7 7a1 1 0 001.414 1.414L4 10.414V17a1 1 0 001 1h2a1 1 0 001-1v-2a1 1 0 011-1h2a1 1 0 011 1v2a1 1 0 001 1h2a1 1 0 001-1v-6.586l.293.293a1 1 0 001.414-1.414l-7-7z" />
</svg>
<span> Feed </span>
</Link>
</li>
<li><Link to="/pages">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="text-yellow-500">
<path fill-rule="evenodd" d="M3 6a3 3 0 013-3h10a1 1 0 01.8 1.6L14.25 8l2.55 3.4A1 1 0 0116 13H6a1 1 0 00-1 1v3a1 1 0 11-2 0V6z" clip-rule="evenodd"></path>
</svg>
Pages </Link>
</li>
<Link to={`/groups`} alt="enlarge your experience">
<li><a >
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="text-blue-500">
<path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z" />
</svg><span> Groups </span></a>
</li>
</Link>
<li>
<Link to="/homecourse" alt="online courses">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="text-green-500">
<path d="M10.394 2.08a1 1 0 00-.788 0l-7 3a1 1 0 000 1.84L5.25 8.051a.999.999 0 01.356-.257l4-1.714a1 1 0 11.788 1.838L7.667 9.088l1.94.831a1 1 0 00.787 0l7-3a1 1 0 000-1.838l-7-3zM3.31 9.397L5 10.12v4.102a8.969 8.969 0 00-1.05-.174 1 1 0 01-.89-.89 11.115 11.115 0 01.25-3.762zM9.3 16.573A9.026 9.026 0 007 14.935v-3.957l1.818.78a3 3 0 002.364 0l5.508-2.361a11.026 11.026 0 01.25 3.762 1 1 0 01-.89.89 8.968 8.968 0 00-5.35 2.524 1 1 0 01-1.4 0zM6 18a1 1 0 001-1v-2.065a8.935 8.935 0 00-2-.712V17a1 1 0 001 1z" />
</svg>
<span> Course</span>
</Link>
</li>
<li>
<Link to={"/jobs"} alt="provide opportunities">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="text-pink-500"
>
<path
fill-rule="evenodd"
d="M6 6V5a3 3 0 013-3h2a3 3 0 013 3v1h2a2 2 0 012 2v3.57A22.952 22.952 0 0110 13a22.95 22.95 0 01-8-1.43V8a2 2 0 012-2h2zm2-1a1 1 0 011-1h2a1 1 0 011 1v1H8V5zm1 5a1 1 0 011-1h.01a1 1 0 110 2H10a1 1 0 01-1-1z"
clip-rule="evenodd"
/>
<path d="M2 13.692V16a2 2 0 002 2h12a2 2 0 002-2v-2.308A24.974 24.974 0 0110 15c-2.796 0-5.487-.46-8-1.308z" />
</svg>
<span> Jobs</span>
</Link>
</li>
<li><a href="javascript:void(0);" >
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="text-red-500">
<path fill-rule="evenodd" d="M2 5a2 2 0 012-2h8a2 2 0 012 2v10a2 2 0 002 2H4a2 2 0 01-2-2V5zm3 1h6v4H5V6zm6 6H5v2h6v-2z" clip-rule="evenodd" />
<path d="M15 7h1a2 2 0 012 2v5.5a1.5 1.5 0 01-3 0V7z" />
</svg>
<span> Room </span>
<div uk-drop="mode: click;offset:5" class="header_dropdown profile_dropdown">
<button onClick={ showCreateRoomFunc} style={{marginLeft:"20px"}} >
Create Room
</button>
<br/>
<button style={{marginLeft:"20px"}} onClick={ showJoinRoomFunc}>
Join Room
</button>
</div>
</a>
</li>
{showCreateRoom ? (
<CreateRoom
show
onclick={showCreateRoomFunc}
title="Create Your Own Room"
placeholder="Enter Your Room"
btnName="Create"
/>
) : (
<CreateRoom />
)}
{showJoinRoom ? (
<JoinRoom
show
onclick={showJoinRoomFunc}
title="Join A Room"
placeholder="Paste Your URL Room"
btnName="Join"
/>
) : (
<JoinRoom />
)}
<li id="more-veiw" hidden><Link to="/profile_accepted" alt="build career">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" class="text-yellow-500">
<path fill-rule="evenodd" d="M6 2a1 1 0 00-1 1v1H4a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V6a2 2 0 00-2-2h-1V3a1 1 0 10-2 0v1H7V3a1 1 0 00-1-1zm0 5a1 1 0 000 2h8a1 1 0 100-2H6z" clip-rule="evenodd" />
</svg><span> ProfileAccepted </span></Link>
</li>
<li id="more-veiw" hidden>
<Link to={"/problems"} alt="share problems">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="text-blue-500"
>
<path d="M2 5a2 2 0 012-2h7a2 2 0 012 2v4a2 2 0 01-2 2H9l-3 3v-3H4a2 2 0 01-2-2V5z" />
<path d="M15 7v2a4 4 0 01-4 4H9.828l-1.766 1.767c.28.149.599.233.938.233h2l3 3v-3h2a2 2 0 002-2V9a2 2 0 00-2-2h-1z" />
</svg>
<span> forum</span>
</Link>
</li>
</ul>
<a href="#" class="see-mover h-10 flex my-1 pl-2 rounded-xl text-gray-600" uk-toggle="target: #more-veiw; animation: uk-animation-fade">
<span class="w-full flex items-center" id="more-veiw">
<svg class=" bg-gray-100 mr-2 p-0.5 rounded-full text-lg w-7" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd"></path></svg>
See More
</span>
<span class="w-full flex items-center" id="more-veiw" hidden>
<svg class="bg-gray-100 mr-2 p-0.5 rounded-full text-lg w-7" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M14.707 12.707a1 1 0 01-1.414 0L10 9.414l-3.293 3.293a1 1 0 01-1.414-1.414l4-4a1 1 0 011.414 0l4 4a1 1 0 010 1.414z" clip-rule="evenodd"></path></svg>
See Less
</span>
</a>
<br/>
<br/>
</div>
</div>
</div>
)
}
export default Header;
|
angular
.module('altairApp')
.controller("annualCtrlGovBlackTypeAll",[
'$scope',
'$rootScope',
'$state',
'utils',
'mainService',
'sweet',
'lic_type',
'app_status',
'rep_type',
'min_group',
function ($scope,$rootScope,$state,utils,mainService,sweet,lic_type,app_status,rep_type,min_group) {
$scope.loadOnCheck = function(item) {
if(item.reporttype==3){
if(item.lictype==1){
$state.go('restricted.pages.GovPlanFormH',{param:item.id, id:item.repstepid});
}
else{
$state.go('restricted.pages.GovPlanFormA',{param:item.id, id:item.repstepid});
}
}
else{
if(item.lictype==1){
$state.go('restricted.pages.GovReportFormH',{param:item.id,groupid:item.groupid});
}
else{
$state.go('restricted.pages.GovReportFormA',{param:item.id,groupid:item.groupid});
}
}
};
var xtype=[{text: "X - тайлан", value: 0}];
console.log(min_group);
$scope.PlanExploration = {
dataSource: {
transport: {
read: {
url: "/user/angular/AnnualRegistrationColor",
data: {"custom":"where reporttype=4 and divisionid=3 and repstepid=1 and repstatusid in (7,2) "},
contentType:"application/json; charset=UTF-8",
type:"POST"
},
parameterMap: function(options) {
return JSON.stringify(options);
}
},
schema: {
data:"data",
total:"total",
model: {
id: "id"
}
},
pageSize: 10,
serverPaging: true,
serverFiltering: true,
serverSorting: true
},
filterable: {
mode:"row"
},
sortable: {
mode: "multiple",
allowUnsort: true
},
scrollable: true,
pageable: {
refresh:true,
buttonCount: 3
},
columns: [
{title: "#",template: "<span class='row-number'></span>", width:"60px"},
{ field:"lpName", title: "<span data-translate='Company name'></span>" },
{ field:"licenseXB", title: "<span data-translate='License number'></span>"},
{ field:"reportyear", title: "<span data-translate='Report year'></span>" },
{ field:"groupid", title: "АМ-ын ангилал", values:min_group },
{
field:"repstatusid", values:[{text:"Засварт буцаасан",value:"2"},{text:"Илгээсэн",value:"7"},{text:"Хүлээлгэн өгсөн",value:"1"}],template: kendo.template($("#status").html()), title: "<span data-translate='Status'></span>"
},
{ field:"submissiondate", title: "<span data-translate='Submitted date'></span>" },
{ field:"approveddate", title: "<span data-translate='Received date'></span>" },
{
template: kendo.template($("#main").html()), width: "120px"
}],
dataBound: function () {
var rows = this.items();
$(rows).each(function () {
var index = $(this).index() + 1
+ ($(".k-grid").data("kendoGrid").dataSource.pageSize() * ($(".k-grid").data("kendoGrid").dataSource.page() - 1));;
var rowLabel = $(this).find(".row-number");
$(rowLabel).html(index);
});
},
editable: "popup"
};
}
]);
|
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const methodOverride = require('method-override')
// set our port
app.set('port', 6500)
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json())
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }))
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))
// override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'))
// routes
require('./app/routes')(app)
// start app
app.listen(app.get('port'), function () {
process.stderr.write(`Node app is running on port ${app.get('port')}\n`)
})
// expose app
exports = module.exports = app
|
import { bannerPlugin } from '@freesewing/plugin-banner'
import { base } from './base.mjs'
const pluginBanner = ({ points, Point, paths, Path, macro, options, part }) => {
if (['banner', 'all'].indexOf(options.plugin) !== -1) {
points.from = new Point(0, 0)
points.to = new Point(320, 0)
paths.banner = new Path().move(points.from).line(points.to)
macro('banner', {
path: paths.banner,
text: 'banner plugin',
dy: options.bannerDy,
spaces: options.bannerSpaces,
repeat: options.bannerRepeat,
})
// Prevent clipping of text
paths.box = new Path().move(new Point(0, -20)).line(new Point(0, 20)).attr('class', 'hidden')
}
return part
}
export const banner = {
name: 'plugintest.banner',
plugins: bannerPlugin,
after: base,
options: {
bannerDy: { count: -1, min: -15, max: 15, menu: 'banner' },
bannerSpaces: { count: 10, min: 0, max: 20, menu: 'banner' },
bannerRepeat: { count: 10, min: 1, max: 20, menu: 'banner' },
},
draft: pluginBanner,
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.