text
stringlengths 7
3.69M
|
|---|
var IP = "192.168.2.131";
var HTTP_PORT = 3200;
// var ELECT_IMG = "../../uploads";
// var BUSS_IMG = "../../uploads";
var IMG_PATH = "../uploads";
exports.mysql = function(){
return {
HOST:'uws7-087.cafe24.com',
USER:'tiddler',
PSWD:'a7693707!',
DB:'tiddler'
}
};
exports.solarmy_server = function(){
return {
SERVER_IP: IP,
HTTP_PORT: HTTP_PORT,
IMG_PATH: IMG_PATH
};
};
|
import React from 'react';
import { Link } from 'react-router-dom';
import person1 from '../../img/person1.jpg';
import person2 from '../../img/person1.jpg';
import person3 from '../../img/person1.jpg';
export const Blog = () => {
return (
<div id="fh5co-blog" className="fh5co-bg-section">
<div className="container">
<div className="row animate-box row-pb-md" data-animate-effect="fadeInUp">
<div className="col-md-8 col-md-offset-2 text-center fh5co-heading">
<span>Thoughts & Ideas</span>
<h2>Our Blog</h2>
<p>Dignissimos asperiores vitae velit veniam totam fuga molestias accusamus alias autem provident. Odit ab aliquam dolor eius.</p>
</div>
</div>
<div className="row">
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 12th</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person1} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 23rd</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person2} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 24th</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person3} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 12th</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person1} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 23rd</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person2} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 24th</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person3} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 12th</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person1} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 23rd</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person2} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-4 col-sm-4 animate-box" data-animate-effect="fadeInUp">
<div className="fh5co-post">
<span className="fh5co-date">Sep. 24th</span>
<h3><Link to="/">Web Design for the Future</Link></h3>
<p>Facilis ipsum reprehenderit nemo molestias. Aut cum mollitia reprehenderit. Eos cumque dicta adipisci architecto culpa amet.</p>
<p className="author"><img src={person2} alt="Free HTML5 Bootstrap Template by FreeHTML5.co" /> <cite> Mike Adam</cite></p>
</div>
</div>
<div className="col-md-12 text-center">
<nav aria-label="Page navigation">
<ul className="pagination">
<li>
<Link to="/" aria-label="Previous">
<span aria-hidden="true">«</span>
</Link>
</li>
<li className="active"><Link to="/">1</Link></li>
<li><Link to="/">2</Link></li>
<li><Link to="/">3</Link></li>
<li><Link to="/">4</Link></li>
<li><Link to="/">5</Link></li>
<li>
<Link to="/" aria-label="Next">
<span aria-hidden="true">»</span>
</Link>
</li>
</ul>
</nav>
</div>
</div>
</div>
</div>
)
}
|
//Licensed to the Apache Software Foundation (ASF) under one or more
//contributor license agreements. See the NOTICE file distributed with
//this work for additional information regarding copyright ownership.
//The ASF licenses this file to You under the Apache License, Version 2.0
//(the "License"); you may not use this file except in compliance with
//the License. You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
//express or implied. See the License for the specific language governing
//permissions and limitations under the License.
// Declare your book-specific javascript overrides in this file.
//= require 'waypoints/waypoint'
//= require 'waypoints/context'
//= require 'waypoints/group'
//= require 'waypoints/noframeworkAdapter'
//= require 'waypoints/sticky'
window.onload = function() {
Bookbinder.boot();
var sticky = new Waypoint.Sticky({
element: document.querySelector('#js-to-top'),
wrapper: '<div class="sticky-wrapper" />',
stuckClass: 'sticky',
offset: 100
});
}
|
const { handler: minify } = require('./minify');
const { handler: towebp } = require('./towebp');
const { handler: resize } = require('./resize');
module.exports = {
cmd: 'img:build',
desc: 'Process images (minify, convert to webp and resize).',
opts: {
source: {
alias: 'src',
describe: 'Source path of the images without optimization.',
type: 'string',
default: 'src/assets/img/src',
},
distribution: {
alias: 'dist',
describe: 'Distribution path for optimized image .',
type: 'string',
default: 'src/assets/img/dist',
},
use: {
describe: 'Tool to use',
type: 'string',
default: 'sharp',
choices: ['mogrify', 'sharp'],
},
exclude: {
alias: 'exc',
describe: 'Files to exclude / ignore, separated by spaces',
type: 'array',
default: ['opengraph'],
},
},
handler: async (argv) => {
const dist = argv.dist;
await minify(argv);
argv.dist = 'src/assets/img/dist/webp';
await towebp(argv);
argv.src = dist;
await resize(argv);
},
};
|
import React, { Component } from "react";
import Track from "./track";
class Tracks extends Component {
state = {};
render() {
const { searchedTracks } = this.props;
console.log("logged from tracks", searchedTracks);
return (
<div>
<table
className="table table-striped"
style={{
width: "90%",
tablelayout: "fixed",
margin: "auto",
marginTop: "2%",
border: "1px solid black"
}}
>
<thead
style={{
fontSize: "20px",
fontWeight: "bold",
backgroundColor: "Grey",
color: "white"
}}
>
<tr>
<th></th>
<th>Master_Id</th>
<th style={{ width: "30%" }}>Title</th>
<th>Action</th>
</tr>
</thead>
<tbody>{this.renderTracks(searchedTracks)}</tbody>
<tfoot
style={{
fontSize: "15px",
fontWeight: "bold",
backgroundColor: "Grey",
color: "white"
}}
>
<tr>
<td></td>
<td></td>
<td>Powered By @Discogs-Api</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td>Developed by :Mehul Bhavsar, AMi Dave, Krishna Panchal</td>
<td></td>
</tr>
</tfoot>
</table>
</div>
);
}
renderTracks = searchedTracks => {
console.log("inside Method", searchedTracks);
let { TracksForSearch } = this.props;
console.log("abc", TracksForSearch);
if (searchedTracks !== "undefined") {
console.log("inside if");
return searchedTracks.map(track => (
<Track
key={track.id}
id={track.master_id}
AddTrack={this.HandlerAddTrackToPlayList}
DeleteTrack={this.HandlerDeleteTrackFromPlayList}
EditTrack={this.HandlerEditTrackFromPlayList}
track={track}
TracksForSearch={TracksForSearch}
/>
));
} else {
console.log("inside else");
return (
<tr>
<td></td>
<td></td>
<td>No track available for serach result</td>
<td></td>
</tr>
);
}
};
HandlerAddTrackToPlayList = track => {
let plyId = this.props.selectedPlayList.id;
fetch("http://localhost:8000/track", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
playListID: plyId,
title: track.title,
uri: track.uri,
masterID: track.master_id
})
})
.then(response => response.json())
.then(response => {
this.props.onStatusChange(response.data);
})
.catch(err => console.log(err));
};
HandlerDeleteTrackFromPlayList = track => {
let uri = "http://localhost:8000/tracks/" + track.id;
console.log(uri);
fetch(uri, {
method: "Delete",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
})
.then(response => response.json())
.then(response => {
this.props.onStatusChange(response.data);
})
.catch(err => console.log(err));
};
}
export default Tracks;
|
import React from 'react';
import PropTypes from 'prop-types';
import DatePicker from 'react-datepicker';
import { FormGroup, Label, UncontrolledTooltip } from 'reactstrap';
import s from '../styles/Profile.module.scss';
import cx from 'classnames';
function DatePickerField(props) {
const {
name,
values,
setFieldValue,
setFieldTouched,
touched,
errors,
} = props;
// const { name } = props.field;
const handleChange = (date) => {
setFieldValue(name, date, true); //field,value,shouldValidate
setFieldTouched(name, true, true); //field,touched,shouldValidate
};
return (
<FormGroup>
<Label for='last_donated_date'>
If donated before please select the donation date:
</Label>
<div>
<DatePicker
className='form-control'
placeholderText='Click to select a date'
dateFormat='dd-MMM-yyyy'
showMonthDropdown
showYearDropdown
dropdownMode='select'
selected={values.last_donated_date}
maxDate={new Date()}
isClearable
onChange={handleChange}
// onBlur={handleBlur}
/>
</div>
{errors.last_donated_date && touched && (
<div className='input-feedback'>{errors.last_donated_date}</div>
)}
</FormGroup>
);
}
DatePicker.propTypes = {};
export default DatePickerField;
|
var Cache = require('Cache');
function Population(room) {
this.cache = new Cache();
this.room = room;
this.population = 0;
this.populationLevelMultiplier = 8;
this.typeDistribution = {
CreepMiner: {
total: 0,
max: 5,
minExtensions: 0
},/*
CreepCarrier: {
total: 0,
max: 15,
minExtensions: 0
},
CreepBuilder: {
total: 0,
max: 15,
minExtensions: 0
},*/
CreepWorker: {
total: 0,
max: 15,
minExtensions: 0
},
/*CreepHealer: {
total: 0,
max: 1,
minExtensions: 2
},
CreepSoldier: {
total: 0,
max: 1,
minExtensions: 2
},
CreepShooter: {
total: 0,
max: 1,
minExtensions: 10
}*/
};
this.creeps = this.room.find(FIND_MY_CREEPS);
for(var i = 0; i < this.creeps.length; i++) {
var creepType = this.creeps[i].memory.role;
if(!this.typeDistribution[creepType]) {
//this.typeDistribution[creepType] = createTypeDistribution(creepType);
continue; // Ignore this creep
}
this.typeDistribution[creepType].total++;
}
};
Population.prototype.goalsMet = function() {
for(var n in this.typeDistribution) {
var type = this.typeDistribution[n];
if(type.total == 0 || type.total < type.max) {
return false;
}
}
return true;
};
Population.prototype.getType = function(type) {
return this.typeDistribution[type];
};
Population.prototype.getTypes = function(type) {
var types = [];
for(var n in this.typeDistribution) {
types.push(n);
}
return types;
};
Population.prototype.getTotalPopulation = function() {
return this.creeps.length;
};
Population.prototype.getMaxPopulation = function() {
return this.cache.remember(
'max-population',
function() {
var population = 0;
for(var n in this.typeDistribution) {
population += this.typeDistribution[n].max;
}
return population;
}.bind(this)
);
};
Population.prototype.getNextExpectedDeath = function() {
return this.cache.remember(
'creep-ttl',
function() {
var ttl = 100000;
var cname = "";
for(var i = 0; i < this.creeps.length; i++) {
var creep = this.creeps[i];
if(creep.ticksToLive < ttl) {
ttl = creep.ticksToLive;
cname = creep.name;
}
return ttl + ' ticks -> ' +cname.split('-')[0];
}
}.bind(this)
);
};
module.exports = Population;
// Private
function createTypeDistribution(type) {
return {
total: 0,
max: 20,
minExtensions: 0
};
};
|
import Vue from 'vue'
import Vuetify from 'vuetify/lib'
import 'material-design-icons-iconfont/dist/material-design-icons.css'
import 'vuetify/src/stylus/app.styl'
Vue.use(Vuetify, {
theme: {
primary: '#f6ad8',
secondary: '#444054',
accent: '#794c8a',
error: '#d92550',
info: '#78C3FB',
success: '#3ac47d',
warning: '#f7b924'
},
options: {
customProperties: true
},
iconfont: 'md' || 'mdi',
})
|
export default {
color: `primary`,
textDecoration: `none`,
userSelect: `none`,
':visited': {
color: 'primary'
},
':hover': {
color: 'primaryDark'
}
}
|
import React, { Component } from 'react';
class CreatePost extends Component {
constructor(props) {
super(props);
this.state = {
title: null,
subtitle: null,
image: null,
content: null
}
this.handleChange = props.handleChange.bind(this);
}
render () {
return (
<form className="form-control-lg" onSubmit={(e) => this.props.handleCreateSubmit(e, this.state)}>
<div className="form-group-sm">
<input className="form-control" type="text" onChange={this.handleChange} name="title" placeholder="Title"/>
</div>
<div className="form-group-sm">
<input className="form-control" type="text" onChange={this.handleChange} name="subtitle" placeholder="Subtitle"/>
</div>
<div className="form-group-sm">
<input className="form-control" type="text" onChange={this.handleChange} name="image" placeholder="Image"/>
</div>
<div className="form-group-sm">
<textarea className="form-control" type="text" onChange={this.handleChange} name="content" placeholder="Content"/>
</div>
<button className="btn btn-outline-primary" type="submit">Create Post</button>
</form>
)
}
}
export default CreatePost;
|
import icons from 'url:../../img/icons.svg';
class TopBar {
constructor() {
this._searchBtn = document.querySelector('.search__btn');
this._bookmarkBtn = document.querySelector('.nav__btn--bookmarks');
this._addRecipeBtn = document.querySelector('.nav__btn--add-recipe');
this._searchSvg = this._searchBtn.querySelector('svg');
this._bookmarkSvg = this._bookmarkBtn.querySelector('svg');
this._addSvg = this._addRecipeBtn.querySelector('svg');
this._addAllIcons();
}
_addIcons(parent, markup, removedEl) {
removedEl.remove();
parent.insertAdjacentHTML('afterbegin', markup);
}
_addAllIcons() {
this._addIcons(
this._searchSvg,
`<use href="${icons}#icon-search"></use>`,
this._searchSvg.querySelector('use')
);
this._addIcons(
this._bookmarkSvg,
`<use href="${icons}#icon-bookmark"></use>`,
this._bookmarkSvg.querySelector('use')
);
this._addIcons(
this._addSvg,
`<use href="${icons}#icon-edit"></use>`,
this._addSvg.querySelector('use')
);
}
}
export default new TopBar();
|
let express = require('express');
let app = express();
app.use(express.urlencoded({extended:true}));
app.use(express.json());
// Résolution API
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
let sql = require ('./db.js');
router = require('./routes');
app.use('/', router);
let port = 5000;
app.listen(port, function() {
console.log('Server running on port ' + port);
})
|
import React, { useContext, useState } from 'react';
import './Dashboard.css';
import logo from "../../../images/fav-icon.png";
import SideBar from '../SideBar/SideBar';
import BookService from '../../Client/BookService/BookService';
import BookedServices from '../../Client/BookedServices/BookedServices';
import { UserContext } from '../../../App';
import ManageOrder from '../../Admin/ManageOrder/ManageOrder';
let DefaultTab = null;
const style = {
logo: {
display: 'flex',
alignItems: 'center',
color: 'rgb(138, 48, 48)',
fontWeight: 700,
fontSize: '.8em'
},
logoImg: {
marginRight: '0.5em'
}
}
const Dashboard = (props) => {
const [tab, setTab] = useState(null);
const [loggedInUser,] = useContext(UserContext);
if (loggedInUser?.isAdmin) {
DefaultTab = <ManageOrder></ManageOrder>;
}
else {
if (props?.tabName) {
if (props.tabName === 'BookService') {
DefaultTab = <BookService></BookService>;
}
}
else {
DefaultTab = <BookedServices></BookedServices>;
}
}
return (
<section>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container-fluid">
<a style={style.logo} id="logo" class="navbar-brand" href="#">
<img style={style.logoImg} src={logo} alt="" width="60" height="48" class="d-inline-block align-top" />
AB SHIP MANAGEMENT
</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#sidebar" aria-controls="sidebar" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</div>
</nav>
<div class="container-fluid">
{
loggedInUser?.email
?
<div class="row">
<SideBar setTab={setTab}></SideBar>
<main class="col-md-9 ml-sm-auto col-lg-10 px-md-4 py-4" style={{ position: "absolute", right: 0 }}>
{tab || DefaultTab}
</main>
</div>
:
<div class="text-center my-5 py-5 text-info">
<div class="spinner-border" role="status">
<span class="visually-hidden">Loading...</span>
</div>
</div>
}
</div>
</section>
);
};
export default Dashboard;
|
var checkboxes = document.getElementsByName("imggiud");
function selectAll() {
for ( var i = 0; i < checkboxes.length; i++)
checkboxes[i].checked = true;
}
function cancleSelected() {
for ( var i = 0; i < checkboxes.length; i++)
checkboxes[i].checked = false;
}
function delSelectedImgS() {
var checkedBox = new Array();
for ( var i = 0; i < checkboxes.length; i++)
if (checkboxes[i].checked)
checkedBox.push(checkboxes[i].parentNode.parentNode.parentNode.parentNode.getAttribute("value"));
if (checkedBox.length == 0)
return;
// 向后台发送请求删除操作,然后执行下面代码
jQuery.ajaxSettings.traditional = true;
$.ajax({
// async:false,
type : 'post',
url : 'http://localhost:8080/ovs/user/managercenter/image-manager!deleteMoreImage.action',
dataType : 'json',
data : {
'delImageIds' :checkedBox
},
success : function(msg) {
if (msg.status == 1) {
// 提交成功
alert(msg.message);
for ( var i = 0; i < checkboxes.length; i++)
document.getElementById("ImgMenu").removeChild(checkboxes[i].parentNode.parentNode.parentNode.parentNode);
} else {
alert(msg.message);
}
console.log(msg);
},
error : function(msg) {
alert("连接异常");
}
});
}
function delOneImg(which) {
var delImageId = which.getAttribute("value");
// 向后台发送请求删除操作,然后执行下面代码
$.ajax({
// async:false,
type : 'post',
url : 'http://localhost:8080/ovs/user/managercenter/image-manager!deleteOneImage.action',
dataType : 'json',
data : {
'delImageId' : delImageId
},
success : function(msg) {
if (msg.status == 1) {
// 提交成功
alert(msg.message);
document.getElementById("ImgMenu").removeChild(which);
} else {
alert(msg.message);
}
console.log(msg);
},
error : function(msg) {
alert(msg.message)
//alert("连接异常");
}
});
}
|
export default class initThreeBasic {
constructor(vertexShader,fragmentShader,texturePath1,texturePath2,texturePath3) {
this.DOM = {};
this.DOM.container = document.getElementById('canvas-container');
this.DOM.textElement = document.getElementById('text');
this.textRect;
this.fixedAxis;
this.meshInitOffsetY = 0;
this.geometry;
this.material;
this.camera = new THREE.Camera();
this.light;
this.scene = new THREE.Scene();
this.mesh;
this.loader = new THREE.TextureLoader();
this.renderer = new THREE.WebGLRenderer();
this.mouseP = new THREE.Vector2();
this.scrollP = new THREE.Vector2();
this.mousemoveFn = e => {
this.mouseCoordGet(e.clientX, e.clientY);
};
this.scrollFn = e => {
this.scrollPositionGet();
};
this.initDomEvents();
this.initThree();
}
initDomEvents() {
document.addEventListener("mousemove", this.mousemoveFn, false);
document.addEventListener("scroll", this.scrollFn, false);
}
mouseCoordGet(x,y) {
this.mouseP.x = x - (window.innerWidth / 2);// 原点を中心に持ってくる
this.mouseP.y = -y + (window.innerHeight / 2);// 軸を反転して原点を中心に持ってくる
// ライトの xy座標 をマウス位置にする
this.light.position.x = this.mouseP.x;
this.light.position.y = this.mouseP.y;
}
scrollPositionGet() {
this.scrollP.x = window.pageXOffset;
this.scrollP.y = window.pageYOffset;
}
initThree() {//three.js開始
this.getDomRect();
this.domAxisToGl();
this.setCanvas();
this.setPixelRatio();
this.setCamera();
this.setLight();
this.setGeometry();
this.setMaterial();
this.addScene();
this.setCanvasSize();
this.renderTick();
}
getDomRect() {
this.textRect = this.DOM.textElement.getBoundingClientRect();
}
domAxisToGl() {
this.fixedAxis = new THREE.Vector2(this.textRect.x - (window.innerWidth / 2) + (this.textRect.width / 2), this.textRect.y - (window.innerHeight / 2) + (this.textRect.height / 2));
}
setGeometry() {//ジオメトリ(形状)をセットする〜シェーダーに渡す頂点と考えてOK
this.geometry = new THREE.BoxGeometry(this.textRect.width, this.textRect.height, 300);
}
setPixelRatio() {
this.renderer.setPixelRatio( window.devicePixelRatio );
}
setCanvas() {
this.DOM.container.appendChild( this.renderer.domElement );
}
setCanvasSize() {//canvasを用意する
this.renderer.setSize( window.innerWidth, window.innerHeight );
}
setCamera() {//カメラをセット
const fov = 60;
const fovRad = (fov / 2) * (Math.PI / 180);
const dist = (window.innerHeight / 2) / Math.tan(fovRad);
this.camera = new THREE.PerspectiveCamera(fov, window.innerWidth / window.innerHeight, 1, dist * 2);
this.camera.position.z = dist;
this.camera.lookAt(new THREE.Vector3(0, 0, 0));
let axesHelper = new THREE.AxesHelper( dist );
this.scene.add( axesHelper );
}
setLight() {
this.light = new THREE.PointLight(0x00fa9a);
this.light.position.set(0, 0, 500);
}
setMaterial() {
this.material = new THREE.MeshLambertMaterial({ color: 0xffffff });
}
addScene() {//メッシュ(表示3Dオブジェクト)を作成し、シーンに追加する
this.mesh = new THREE.Mesh(this.geometry, this.material);
console.log(this.fixedAxis);
this.mesh.position.set(this.fixedAxis.x, -(this.fixedAxis.y + this.scrollP.y), (-300 / 2));
this.meshInitOffsetY = this.mesh.position.y;
// this.mesh.rotation.x = Math.PI / 4;
// this.mesh.rotation.y = Math.PI / 4;
this.scene.add( this.light );
this.scene.add( this.mesh );
}
renderTick() {//レンダリング開始
this.renderer.render(this.scene, this.camera);
// this.renderer.setScissorTest(true);
let width = this.textRect.right - this.textRect.left;
let height = this.textRect.bottom - this.textRect.top;
let left = this.textRect.left;
let bottom = this.renderer.domElement.clientHeight - this.textRect.bottom;
// this.renderer.setViewport( 400, 375, 300, 300 );
// this.renderer.setScissor(400, 375, 300, 300);
// this.renderer.setViewport( left, bottom, width, height );
// this.renderer.setScissor( left, bottom, width, height );
this.mesh.position.y = this.meshInitOffsetY + this.scrollP.y;
requestAnimationFrame(this.renderTick.bind(this));
}
}
|
// ---------------------------------------------
// [Author] Christopher Ciufo
// [Description] Omnibox App Launcher controller
// [Created] 2015/06/18
// ---------------------------------------------
(function () {
'use strict';
function escapeText(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function generateDescription (result) {
return escapeText(result.name) + (escapeText(result.description) ? " - <dim>" + escapeText(result.description) + "</dim>" : "");
}
var fuse;
var idStore = {};
var currentContent = "";
var previousText = "";
chrome.omnibox.onInputChanged.addListener(function (text, suggest) {
if (text.length) {
if (typeof fuse === 'undefined') {
chrome.management.getAll(function (searchList) {
fuse = new Fuse(searchList, {
keys:['name', 'description']
});
displaySuggestions(text, suggest);
});
} else {
displaySuggestions(text, suggest);
}
}
});
function displaySuggestions(text, suggest) {
var results = fuse.search(text);
if (results.length) {
var topSuggestion = {
description: "<dim>Launch</dim> " + generateDescription(results[0])
};
currentContent = results[0].name;
idStore[currentContent] = results[0].id;
previousText = text;
chrome.omnibox.setDefaultSuggestion(topSuggestion);
var suggestions = [];
for (var i = 1; i < Math.min(results.length, 5); i++) {
suggestions.push({
content: results[i].name,
description: generateDescription(results[i])
});
idStore[results[i].name] = results[i].id;
}
suggest(suggestions);
}
}
chrome.omnibox.onInputEntered.addListener(function (text, disposition) {
var searchKey;
if (text == previousText) {
searchKey = currentContent;
} else {
searchKey = text;
}
chrome.management.launchApp(idStore[searchKey]);
});
})();
|
import axios from 'axios';
import md5 from 'js-md5';
import {SECRET_KEY, API_URL} from './constants';
axios.defaults.headers.common['Content-Type'] = 'application/json';
axios.defaults.baseURL = API_URL;
axios.interceptors.request.use(
function (config) {
console.log('---axios.interceptors.request---', config.url.indexOf('wp-json'));
if (config.data) {
if (config.url.indexOf('wp-json') < 1) {
const jsonData = JSON.stringify(config.data);
const signature = md5(SECRET_KEY + jsonData);
config.headers.Signature = signature;
}
}
return config;
},
function (error) {
return Promise.reject(error);
},
);
export default axios;
|
/****************************************************************************************************************************************************************************/
/*CARREGA TIPOS CONTATO*/
$(document).ready(function () {
ajaxCarregaTiposContato();
});
function ajaxCarregaTiposContato() {
$.ajax({ url: '/Autuacao/TiposContato' })
.done(function (dados) {
//console.log("Tipo Contato");
//console.log(dados);
$.each(dados, function (i) {
var optionhtml = '<label class="radio-inline">';
optionhtml += '<input type="radio" name="tipotelefone" data-id="' + this.id + '" data-digitos="' + this.quantidadeDigitos + '" value="' + this.descricao + '"/>' + this.descricao;
optionhtml += '</label>';
$('.tiposContato').append(optionhtml);
});
$('#formPessoaFisicaContatos input[type="radio"]:first').prop('checked', true);
$('#formPessoaJuridicaContatos input[type="radio"]:first').prop('checked', true);
})
.fail(function () {
toastr["warning"]("Não foi possível realizar esta operação!");
});
}
/***********************************************************ENJOYHINT**************************************************************/
function checkSelector(help, passo) {
if (help.selector == passo) {
console.log(age.s);
return age.s;
}
}
// Mostra o guia do campo em que o botão help for clicado
$('.help').click(function () {
var enjoyhint_instance = new EnjoyHint({});
var passo = $(this).attr('data-help');
var novopasso = $.grep(enjoyhint_script_steps, function (n, i) {
return (n.selector == passo);
});
novopasso[0].showNext = false;
// console.log(novopasso);
enjoyhint_instance.set(novopasso);
enjoyhint_instance.run();
});
// Inicia o guia pelo botão tutorial
$('#ajuda').click(function () {
var enjoyhint_instance = new EnjoyHint({
onSkip: function () {
$('.help').removeAttr('disabled');
}
});
enjoyhint_instance.set(enjoyhint_script_steps);
$('.nav a[href="#tab_1"]').tab('show');
$('.help').attr('disabled', 'disabled');//bloqueia o botão help nesse momento
$.each(enjoyhint_script_steps, function (i, passo) {
if ('showNext' in passo) {
// console.log(passo);
passo.showNext = true;
}
});
enjoyhint_instance.run();
});
|
import { Routes, Route, useParams, Link, Outlet } from "react-router-dom";
import "./index.css";
import { getMessageById, messages } from "./messages";
import { NoMatch } from "./no-match";
export default function InboxApp() {
return (
<Routes>
{/* Routes in this app don't need to worry about which URL prefix they are
mounted at. They can just assume they are mounted at /. Then, if they
are moved under a different basename later on, all routes and links will
continue to work. */}
<Route path="/" element={<Layout />}>
<Route index element={<Inbox />} />
<Route path=":id" element={<Message />} />
<Route path="*" element={<NoMatch />} />
</Route>
</Routes>
);
}
function Layout() {
return (
<div>
<h1>Welcome to the Inbox app!</h1>
<nav>
<ul>
<li>
{/* Using a normal link here will cause the browser to reload the
document when following this link, which is exactly what we want
when navigating to the "Home" app so we execute its entry
point (see home/main.jsx). */}
<a href="/">Home</a>
</li>
<li>
<a href="/about">About</a>
</li>
<li>
<Link to="/">Inbox</Link>
</li>
</ul>
</nav>
<hr />
<Outlet />
</div>
);
}
function Inbox() {
return (
<div>
<div style={{ maxWidth: 800, margin: "0 auto" }}>
{messages.map((message) => (
<Link
to={message.id}
key={message.id}
style={{
display: "flex",
borderBottom: "1px solid #ccc",
padding: "10px",
width: "100%",
textDecoration: "none",
color: "#000",
}}
>
<span
style={{
flexBasis: 100,
marginRight: "1rem",
}}
>
{message.from.name}
</span>
<div
style={{
flexGrow: 1,
textOverflow: "ellipsis",
width: "100%",
whiteSpace: "nowrap",
overflow: "hidden",
marginRight: "1rem",
}}
>
<span>{message.subject}</span>
<div style={{ color: "#999", display: "inline" }}>
<span>{" — "}</span>
<span>{message.body}</span>
</div>
</div>
<span style={{ flexShrink: 0 }}>
{new Date(message.date).toDateString()}
</span>
</Link>
))}
</div>
</div>
);
}
function Message() {
let { id } = useParams();
let message = getMessageById(id);
if (!message) {
return <NoMatch />;
}
return (
<div>
<h2>{message.subject}</h2>
<div>
<h3 style={{ fontSize: 14 }}>
<span>{message.from.name}</span>{" "}
<span><{message.from.email}></span>
</h3>
<div>{message.body}</div>
</div>
</div>
);
}
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExercisesType = void 0;
var ExercisesType;
(function (ExercisesType) {
ExercisesType[ExercisesType["multipleChoices"] = 0] = "multipleChoices";
ExercisesType[ExercisesType["discursive"] = 1] = "discursive";
})(ExercisesType = exports.ExercisesType || (exports.ExercisesType = {}));
|
var SC_ID = '528dd3394707d2e437879317d161890a'
var Lineup = (function($) {
var artists,
isOpen = false,
$player = $('<div id="player"></div>'),
$currentPopup;
var show = function() {
hideAll()
var $popup = $(this).data('artistPopup'),
$currentPopup = $popup,
left = $(this).offset().left
if (left - 100 > $('#main-container').width() / 2) {
left -= 20 + $popup.width()
$popup.removeClass('right').addClass('left')
} else {
left += $(this).width() + 20
$popup.removeClass('left').addClass('right')
}
$popup.show().css({
top: ($(this).offset().top - ($(this).height() / 2)),
left: left
})
$(this).addClass('active')
isOpen = true
if (!$(this).data('tracks')) {
$.proxy(load, this)()
}
}
var hide = function() {
isOpen = false
$(this).data('artistPopup').hide()
}
var hideAll = function() {
isOpen = false
$('.artist-popup').hide()
$('.lineup h1').removeClass('active')
}
var load = function() {
var _this = this;
$(this).data('tracks', 'loading')
SC.get('/resolve.json?limit=5&url=http://soundcloud.com/' + $(this).data('artist').soundcloud + '/tracks', {limit: 5}, function(tracks){
//debugger
tracks = tracks.slice(tracks.length - 5)
$(_this).data('tracks', tracks)
drawTracks($(_this).data('artistPopup').find('ul.tracks'), tracks)
});
}
var scPlay = function() {
debugger
var _this = this,
scTrack = $(this).data('scTrack')
$('#jplayer').jPlayer('setMedia', { mp3: scTrack.stream_url + '?client_id=' + SC_ID }).jPlayer('play')
$('#player').find('.title').html(scTrack.title)
$(this).find('.icon-play').attr('class', 'icon-pause')
}
var drawTracks = function($el, tracks) {
$(tracks).each(function() {
var track = $('<li>').html('<i class="icon-play"></i>' + this.title)
track.data('scTrack', this)
track.click(scPlay)
$el.append(track)
})
}
var mouseOut = function() {
if ($currentPopup == $(this).data('artistPopup')) {
hideAll()
}
}
var render = function() {
}
var getSoundcloud = function($artist) {
var link = $artist.find('a[href*="soundcloud.com"]').attr('href')
if (link) return _.last(link.split('/'))
}
var initArtist = function() {
var artistId = $(this).find('.portfolio-item-title').text().toLowerCase().replace(/ /g, '_').replace('(', '').replace(')', ''),
soundcloudUsername = getSoundcloud($(this)),
template = window.templates['app/templates/artist_popup.hbs'];
var context = {
artist: artists[artistId],
soundcloudUsername: soundcloudUsername
}
console.log(context)
$popup = $(template(context))
$(document.body).append($popup)
$(this).hover(show)
$(this).data('artistPopup', $popup).data('artist', context.artist)
$popup.mouseleave(function(evt) {
console.log('mouseleave')
console.log($(this))
console.log(evt)
$popup.hide()
})
}
var init = function() {
$('.portfolio-items li').each(initArtist)
$('.portfolio-items').mouseleave(function(evt) {
console.log(evt)
if ($(evt.relatedTarget).parents('.artist-popup').length > 0) return false;
setTimeout(hideAll, 1000)
})
var playerTemplate = window.templates['app/templates/player.hbs']
$player.html(playerTemplate())
$(document.body).append($player)
$player.css({ left: $('.menu-black-menu-container').offset().left + 460 })
//$('#mini-header .container .nav-wrap').append($player)
$('#jplayer').jPlayer({
cssSelectorAncestor: '#jp_container',
})
$player.show()
}
$(function() {
artists = LineupData
init()
$(window).scroll(function() {
if ($(this).scrollTop() > $('#nav-section').offset().top) {
$('#player').addClass('fixed')
} else {
$('#player').removeClass('fixed')
}
});
})
return {
hideAll: hideAll
}
})(jQuery)
var LineupData = {
'crystal_castles': {
'name': 'Crystal Castles',
'image': 'http://wildtonicmusic.files.wordpress.com/2010/06/crystal-castles-celestica-bear-in-heaven-remix.jpg?w=700&h=610',
'website': 'http://crystalcastles.com',
'soundcloud': 'crystal-castles',
'facebook': 'ccrystalccastles',
'twitter': 'CRYSTALCASTLESS',
'description': 'Crystal Castles is an electronic experimental band formed in 2004 in Toronto consisting of producer Ethan Kath and vocalist Alice Glass. The duo is known for their chaotic live shows and lo-fi melancholic homemade productions.'
},
'gold_panda': {
'name': 'Gold Panda',
'image': 'http://revistaogrito.ne10.uol.com.br/page/wp-content/uploads/2011/07/Gold-Panda.jpg',
'website': 'http://www.iamgoldpanda.com/',
'soundcloud': 'gold-panda',
'description': 'Gold Panda is a musical composer, performer and producer from the United Kingdom. He was born in Peckham, London, in 1980 and hails from Chelmsford, Essex'
},
'soul_clap_records': {
'name': 'Soul Clap Records',
'image': 'http://pulseradio.net/media/filter/585x249/transfer/img/articleimage/2012-12/soul_clap.jpg',
'soundcloud': 'soulclap',
'description': '',
'website': 'http://soulclaprecords.com',
},
'voices_of_black_live': {
'name': 'Voices of Black (Live)',
'image': 'http://b.vimeocdn.com/ps/394/923/3949235_300.jpg',
'soundcloud': 'voicesofblack',
'description': "Voices of Black is an American duo consisting of Julian ‘Jules Born’ Randolph and Baba Doherty",
},
'mathew_jonson_live': {
'name': 'Matthew Johnson (Live)',
'image': 'http://4.bp.blogspot.com/_6cf3bFVNe_w/TA7EYECH-yI/AAAAAAAAAM8/kJERPVubCrY/s1600/mathew+jonson.jpg',
'soundcloud': 'mathew-jonson',
'description': "Mathew Jonson really is one of a kind. He's developed one of the most distinctive voices in electronic dance music: when you hear one of Jonson's tracks, you almost immediately know it's his. And yet there's no mistaking any given track for another."
}
}
Handlebars.templates = [];
|
/*
SPDX-License-Identifier: Apache-2.0
*/
/*
* This application has 6 basic steps:
* 1. Select an identity from a wallet
* 2. Connect to network gateway
* 3. Access logging-system network
* 4. Construct request to accept contract
* 5. Submit transaction
* 6. Process response
*/
'use strict';
// Bring key classes into scope, most importantly Fabric SDK network class
const fs = require('fs');
const yaml = require('js-yaml');
const { FileSystemWallet, Gateway } = require('fabric-network');
const DigiContract = require('../../employer/contract/lib/paper.js');
// A wallet stores a collection of identities for use
const wallet = new FileSystemWallet('../identity/user/balaji/wallet');
// Main program function
async function main () {
// A gateway defines the peers used to access Fabric networks
const gateway = new Gateway();
try {
// Specify userName for network access
const userName = 'Admin@org1.example.com';
// Load connection profile; will be used to locate a gateway
let connectionProfile = yaml.safeLoad(fs.readFileSync('../gateway/networkConnection.yaml', 'utf8'));
// Set connection options; identity and wallet
let connectionOptions = {
identity: userName,
wallet: wallet,
discovery: { enabled: false, asLocalhost: true }
};
// Connect to gateway using application specified parameters
console.log('Connect to Fabric gateway.');
await gateway.connect(connectionProfile, connectionOptions);
// Access logging-system network
console.log('Use network channel: mychannel.');
const network = await gateway.getNetwork('mychannel');
//TODO: change the naming
// Get addressability to commercial paper contract
console.log('Use org.papernet.commercialpaper smart contract.');
const contract = await network.getContract('papercontract', 'org.papernet.commercialpaper');
// Accept contract
console.log('Submit accept contract transaction.');
const acceptResponse = await contract.submitTransaction('acceptContract', 'User1@org1.example.com', '00001', userName, '4900000', '2020-05-31');
// process response
console.log('Process accept contract transaction response.');
let paper = DigiContract.fromBuffer(acceptResponse);
console.log(`${paper.issuer} offered contract : ${paper.paperNumber} successfully accepted by ${paper.owner}`);
console.log('Transaction complete.');
} catch (error) {
console.log(`Error processing transaction. ${error}`);
console.log(error.stack);
} finally {
// Disconnect from the gateway
console.log('Disconnect from Fabric gateway.');
gateway.disconnect();
}
}
main().then(() => {
console.log('Accept program complete.');
}).catch((e) => {
console.log('Accept program exception.');
console.log(e);
console.log(e.stack);
process.exit(-1);
});
|
/**
* Created by xuwusheng on 15/12/18.
*/
define(['../../../app'], function (app) {
app.factory('personalBusiness', ['$http','$q','$filter','HOST',function ($http,$q,$filter,HOST) {
return {
getThead: function () {
return [
{name:'',check:true,checkAll:true},
{field:'taskId',name:'业务单号'},
{field:'receAdd',name:'收货地址'},
{field:'acceTypeCount',name:'商品种类'},
{field:'createTime',name:'创建时间'},
{field:'remarks',name:'备注',style:'width: 300px'},
{field:'pay',name:'配送费'},
{
field:'op',
name:'操作',
type:'operate',
buttons:[{
text:'修改',
btnType:'btn',
call:'updateCustom',
openModal:'#addCustomerModal'
},{text:'|'},{
text:'删除',
btnType:'btn',
call:'deleteCustom'
}]
}
]
},
getTheadSecond: function () {
return [
{field: 'pl4GridCount',
name: '序号',
type: 'pl4GridCount'},
{field:'taskId',name:'业务单号'},
{field:'receAdd',name:'收货地址'},
{field:'acceTypeCount',name:'商品种类'},
{field:'createTime',name:'创建时间'},
{field:'remarks',name:'备注',style:'width: 300px'},
{field:'pay',name:'配送费'},
{
field:'op',
name:'操作',
type:'operate',
buttons:[{
text:'打印业务单',
btnType:'btn',
call:'printFirst'
}]
}
]
},
getDataTable: function (url,data) {
//将parm转换成json字符串
data.param=$filter('json')(data.param);
var deferred=$q.defer();
$http.post(HOST+url,data)
.success(function (data) {
deferred.resolve(data);
})
.error(function (e) {
deferred.reject('error:'+e);
});
return deferred.promise;
}
}
}]);
});
|
import _ from 'lodash'
class QuestionProviderAgent {
static get $inject(){ return ['StateManagerAgent']};
stateAgent = {};
constructor(stateManagerAgent){
this.stateAgent = stateManagerAgent;
};
getQuestions(){
var resultingQuestions = [];
if(this.stateAgent.isLeveling)
resultingQuestions = this.getLevelingQuestions();
else {
const questions = _.shuffle(_questions);
resultingQuestions = _.take(questions.filter(q => q.level == this.stateAgent.currentLevel), 10);
}
return angular.copy(resultingQuestions);
}
getLevelingQuestions(){
const questions = _.shuffle(_questions);
const lv1 = _.take(questions.filter(q => q.level == 1), 2);
const lv2 = _.take(questions.filter(q => q.level == 2), 2);
const lv3 = _.take(questions.filter(q => q.level == 3), 2);
const lv4 = _.take(questions.filter(q => q.level == 4), 2);
const lv5 = _.take(questions.filter(q => q.level == 5), 2);
return [...lv1,...lv2,...lv3,...lv4,...lv5]
}
}
export default () => angular.module('med-edu').service('QuestionProviderAgent', QuestionProviderAgent)
const _questions = [
{
"level": 1,
"question": "Quais os possíveis sintomas da miopia?",
"option1": "Dor de cabeça, irritação ocular e lacrimejamento.",
"option2": "Dor de cabeça, irritação auricular e cansaço.",
"option3": "Irritação ocular, dor de cabeça e cansaço.",
"correct": "1",
"explanationVideo": "https://www.youtube.com/embed/McPPZBlg6OQ?start=82",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 1,
"question": "Além da má digestão, qual pode ser o motivo causador da azia?",
"option1": "O hábito de fumar pode lesionar as células do esôfago causando dor.",
"option2": "O retorno do suco gástrico para o esôfago, que por ser ácido acaba lesionando as células do esôfago e causando dor.",
"option3": "Todas as respostas acima.",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "A azia pode ser causada por fatores como má digestão dos alimentos, excesso de peso, gravidez e ter o hábito de fumar. O principal sintoma de azia é a sensação de queimação que inicia no final do osso esterno, que está entre as costelas, e que vai até a garganta. Fonte: https://www.tuasaude.com/causas-da-azia/",
"explanationImage": "",
},
{
"level": 1,
"question": "Quais os primeiros socorros se alguém está tendo um Acidente Vascular Cerebral - AVC?",
"option1": "Verificar a respiração do indivíduo, colocando-o de barriga para cima e caso não respire iniciar a massagem cardíaca.",
"option2": "Chamar a ambulância, verificar a respiração do indivíduo e após garantir a respiração colocá-lo de lado para aguardar o socorro.",
"option3": "Chamar a ambulância, verificar a respiração do indivíduo, colocando-o de barriga para cima e caso não respire iniciar a massagem cardíaca.",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Os primeiros socorros para AVC podem evitar sequelas graves, como ficar paralisado ou não falar e, em alguns casos, podem permanecer para toda a vida, diminuindo a qualidade de vida do paciente. Por isso, por isso, é importante socorrer o individuo que está tendo um AVC o mais rápido possível para evitar sequelas. Fonte: https://www.tuasaude.com/primeiros-socorros-para-avc/",
"explanationImage": "",
},
{
"level": 1,
"question": "Uma pessoa está com crise hipertensiva se...",
"option1": "Sua pressão arterial está abaixo de 12x8.",
"option2": "Sua pressçao arterial está acima de 12x8.",
"option3": "Sua pressão arterial está acima de 12x18.",
"correct": "2",
"explanationVideo": "https://www.youtube.com/embed/1HDSpB_nYxs",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 1,
"question": "Por que a insulina é importante?",
"option1": "Diminui a quantidade de glicose nas células.",
"option2": "Permite que a glicose entre na corrente sanguínea.",
"option3": "Permite que a glicose entre nas células.",
"correct": "3",
"explanationVideo": "https://www.youtube.com/embed/vAUbt17h6Co",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 1,
"question": "O que é tuberculose?",
"option1": "Uma doença bacteriana que ataca os pulmões.",
"option2": "Uma doença viral que ataca os pulmões.",
"option3": "Uma doença genética que ataca os pulmões.",
"correct": "1",
"explanationVideo": "https://www.youtube.com/embed/F0UVtuoTAGI",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 1,
"question": "Como surge o câncer?",
"option1": "O câncer surge por um vírus que altera o DNA da célula, que passa a receber instruções erradas para sua ações.",
"option2": "O câncer surge por uma mutação genética que altera o DNA da célula, que passa a receber instruções erradas para sua atividades.",
"option3": "O câncer surge por uma mutação genética que altera mata as células e pode atingir todo o corpo, causando a morte do paciente.",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "O câncer surge a partir de uma mutação genética, ou seja, de uma alteração no DNA da célula, que passa a receber instruções erradas para as suas atividades. As alterações podem ocorrer em genes especiais, denominados proto-oncogenes, que a princípio são inativos em células normais. Quando ativados, os proto-oncogenes tornam-se oncogenes, responsáveis por transformar as células normais em células cancerosas. Fonte: https://www.inca.gov.br/como-surge-o-cancer",
"explanationImage": "",
},
{
"level": 1,
"question": "Qual é a relação entre a fibrilação atrial e AVC?",
"option1": "O AVC pode causar a fibrilação atrial.",
"option2": "A fibrilação atrial pode causar o AVC.",
"option3": "Nenhuma das respostas anteriores.",
"correct": "2",
"explanationVideo": "https://www.youtube.com/embed/jQgj_pcXtLg",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 1,
"question": "Quando ocorre a biodisponibilidade do álcool?",
"option1": "Quando o álcool permanece no sangue por mais tempo do que o esperado porque as células não o absorvem.",
"option2": "Quando o álcool permanece nas células por mais tempo porque foi absorvido rápido demais.",
"option3": "Quando o álcool fica exposto no cérebro por mais tempo porque a quantidade ingerida foi alta demais.",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "alcool.jpg",
},
{
"level": 1,
"question": "Quais são as causas da embolia pulmonar?",
"option1": "Cirurgias extensas, câncer, gravidez, obesidade e traumas.",
"option2": "Pneumonia, doenças virais, cirurgias extensas.",
"option3": "Genética e pneumonia.",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Embolia pulmonar é causada pela obstrução das artérias dos pulmões por coágulos. Fatores de risco são imobilidade prolongada, cirurgias, câncer, tabagismo, anticoncepcionais com estrógeno e reposição hormonal. Fonte: https://drauziovarella.uol.com.br/doencas-e-sintomas/embolia-pulmonar/",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 1,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Quais os alimentos corretos e frutas para diabéticos?",
"option1": "Qualque alimento e sem controle algum.",
"option2": "Os mesmos que os dos năo diabéticos desde que forma controlada.",
"option3": "Só pode comer verduras e legumes.",
"correct": "2",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=20",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "A dieta pra quem tem diabetes Tipo 1 é diferente de quem tem Tipo 2?",
"option1": "Năo.",
"option2": "Sim. Há uma contagem da quantidade de carboidrtos para adequar a quantidade de insulina baseado na quantidade de carboidrato consumido.",
"option3": "As duas estăo erradas.",
"correct": "2",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=70",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "O que comer diante de um quadro de prá-diabetes?",
"option1": "Focar em alimentos ricos em fibras.",
"option2": "Aumentar a quantidade de sal nos alimentos.",
"option3": "Năo alterar a limentaçăo.",
"correct": "1",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=143",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "Água de coco faz mal pro diabético?",
"option1": "Pode consumir sem restriçăo, năo faz mal algum.",
"option2": "Pode consumir, mas com atençăo, pois tęm carboidratos.",
"option3": "Năo deve consumir.",
"correct": "2",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=226",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "Comida integral(Arroz, Păo, ETC) săo liberados?",
"option1": "Năo săo liberados, pois săo fontes de carboidratos e deve-se controlar o consumo.",
"option2": "Săo proibidos",
"option3": "Năo há restriçőes para alimentos integrais. Consumo liberado.",
"correct": "1",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=254",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "Como controlar a vontade de comer doce?",
"option1": "Comer doces diet.",
"option2": "Equilibrar a alimentaçăo e optar por doces mais naturais. Desde que controlado da para inserir doces na dieta.",
"option3": "Pode comer doces a vontade.",
"correct": "2",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=305",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "Quais săo a pequenas opçőes de lanche para um diabético?",
"option1": "Para os lanches intermediários: frutas secas, desidratadas e/ou oleaginosas. Para substituir o jantar: alimentos que săo fontes de vitaminas, minerais, fibras, carboidrato e proteína.",
"option2": "Para substituir o jantar: frutas secas, desidratadas e/ou oleaginosas. Para os lanches intermediários: alimentos que săo fontes de vitaminas, minerais, fibras, carboidrato e proteína.",
"option3": "Nenhuma das anteriores.",
"correct": "1",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=382",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "O excesso de batata doce atrapalha no tratamento da diabetes?",
"option1": "A batata doce năo atrapalha no tratamento mesmo consumida em excesso.",
"option2": "A consumida em excesso a batata doce pode aumentar a glicose.",
"option3": "A consumida em excesso a batata doce pode diminuir muito a glicose.",
"correct": "2",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=454",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "Quais os alimentos da dieta indispensáveis na manutençăo dos níveis de glicemia?",
"option1": "Alimentos fibroso.",
"option2": "Distribuir a alimentaçăo ao longo do dia.",
"option3": "Todas a opçőes anteriores.",
"correct": "3",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=509",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "Qual a alimentaçăo básica para uma dieta saudável?",
"option1": "Ter uma alimentaçăo mista: Conseguir colocar pelo menos um representante de cada grupo.",
"option2": "Ter uma alimentaçăo vegetaria.",
"option3": "Ter uma alimentaçăo portéica.",
"correct": "1",
"explanationVideo": "https://www.youtube.com/embed/-HKjqNuy6C0?start=557",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 2,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "As artérias vertebrais derivam de quais artérias?",
"option1": "artéria axilares",
"option2": "artérias subclávias",
"option3": "artérias umerais",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "Qual o nome da parede que separa os dois átrios?",
"option1": "septo interatrial",
"option2": "septo intermitral",
"option3": "septo venoso",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question":"Qual dos ramos abaixo deriva do tronco braquiocefalico arterial?",
"option1": "artéria subclávia esquerda",
"option2": "artéria axilar esquerda",
"option3": "artéria subclávia direita",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "A circulação pulmonar termina em qual cavidade?",
"option1": "átrio direito",
"option2": "ventrículo direito",
"option3": "átrio esquerdo",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "Nome do saco que reveste o coração?",
"option1": "pericárdio",
"option2": "miocárdio",
"option3": "mesentério",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "Qual vaso parte do ventrículo esquerdo?",
"option1": "aorta",
"option2": "veia cava superior",
"option3": "artéria pulmonar esquerda",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "Qual dos ramos abaixo deriva da artéria coronária direita?",
"option1": "artéria circunflexa",
"option2": "artéria marginal esquerda",
"option3": "artéria interventricular posterior",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "Qual a principal artéria medial do antebraço?",
"option1": "artéria axilar",
"option2": "artéria ulnar",
"option3": "artéria braquial",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "Qual dos ramos abaixo pode ser considerado o 3º ramo da porção da curva da aorta?",
"option1": "artéria subclávia esquerda",
"option2": "artéria subclávia direita",
"option3": "artéria carótida comum esquerda",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "É característica de uma artéria?",
"option1": "Levar sangue aos órgãos",
"option2": "esticar",
"option3": "deprimir",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Questionário de Anatomia - Sistema cardiovascular - Link: https://www.auladeanatomia.com/novosite/teste-seus-conhecimentos/questionario-sobre-sistema-cardiovascular/",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 3,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Uma pessoa está com crise hipertensiva se...",
"option1": "Sua pressão arterial está abaixo de 12x8.",
"option2": "Sua pressçao arterial está acima de 12x8.",
"option3": "Sua pressão arterial está acima de 12x18.",
"correct": "2",
"explanationVideo": "https://www.youtube.com/embed/1HDSpB_nYxs",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 4,
"question": "Quando ocorre a biodisponibilidade do álcool?",
"option1": "Quando o álcool permanece no sangue por mais tempo do que o esperado porque as células não o absorvem.",
"option2": "Quando o álcool permanece nas células por mais tempo porque foi absorvido rápido demais.",
"option3": "Quando o álcool fica exposto no cérebro por mais tempo porque a quantidade ingerida foi alta demais.",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "alcool.jpg",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 4,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Por que a insulina é importante?",
"option1": "Diminui a quantidade de glicose nas células.",
"option2": "Permite que a glicose entre na corrente sanguínea.",
"option3": "Permite que a glicose entre nas células.",
"correct": "3",
"explanationVideo": "https://www.youtube.com/embed/vAUbt17h6Co",
"explanationAudio": "",
"explanationText": "",
"explanationImage": "",
},
{
"level": 5,
"question": "Quais são as causas da embolia pulmonar?",
"option1": "Cirurgias extensas, câncer, gravidez, obesidade e traumas.",
"option2": "Pneumonia, doenças virais, cirurgias extensas.",
"option3": "Genética e pneumonia.",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Embolia pulmonar é causada pela obstrução das artérias dos pulmões por coágulos. Fatores de risco são imobilidade prolongada, cirurgias, câncer, tabagismo, anticoncepcionais com estrógeno e reposição hormonal. Fonte: https://drauziovarella.uol.com.br/doencas-e-sintomas/embolia-pulmonar/",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "2",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "1",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
{
"level": 5,
"question": "Bla bla bla?",
"option1": "XXX",
"option2": "YYY",
"option3": "ZZZ",
"correct": "3",
"explanationVideo": "",
"explanationAudio": "",
"explanationText": "Fonte: Bla bla bla. Link: ",
"explanationImage": "",
},
];
|
var mongoose = require('mongoose');
//在app/moduel/client创建新的数据库表文件
// Define the schema
//通过html文件里面的fromdate.value获取value等属性
//client:id ,client_name,interest_rate,interest,begin_date,last_modify_time,balance
//账户表:id,用户名字,利率,利息,开始日期,上次修改日期,金额
//时间都初始化为当前时间
module.exports = mongoose.model('Client', {
client_id: {
type: String,
default: ''
},
password: {
type: String,
default: ''
},
client_name: {
type: String,
default: ''
},
interest_rate:{
type: Number,
//初始利润为0.028
default:0.028
},
interest:{
type:Number,
default:0
},
begin_date:{
type:Date,
default:new Date()
},
last_modify_time:{
type:Date,
default:new Date()
},
balance:{
type:Number,
default:0
}
});
|
import Subject from './Subject'
class Completion extends Subject {
constructor({stem, branch, type, answer}) {
super({stem, branch, type, answer})
}
attrValidation() {
super.attrValidation();
if (!(this.answer instanceof Array)) {
throw new Error('答案必须是数组')
}
}
validateAnswer(answer) {
if(({}).toString.call(answer).slice(8, -1).toLowerCase()!=='object'){
throw new Error('用户答应必须是一个对象')
}
let len=this.answer.length;
let result={};
for(let i=0;i<len;i++){
let item=answer[i]
if(!item||!this.answer[i]||item!==this.answer[i]){
result[i]=false
}else{
result[i]=true
}
}
return result
}
}
export default Completion
|
P.views.log.ListItem = P.views.Item.extend({
templateId: 'log.list_item',
className: 'set list-group-item js-log-nav',
events: {
'click .js-toggle-done': 'done'
},
initialize: function() {
this.listenTo(this.model, 'change:state', this.render);
},
done: function(event) {
event.stopPropagation();
var model = this.model;
if (this.model.is_done()) {
this.model.unset('state');
this.$el.removeClass('set-done');
} else {
if (model.get('rest')) {
P.views.log.set.Timer.add(model, model.get('rest'));
}
model.set('state', 'done');
}
window.Sisse.commands.execute('save:log');
},
serializeData: function() {
var context = this.model.toJSON();
context.set = this.model;
context.done = this.model.is_done();
return context;
},
onRender: function() {
var model = this.model,
$el = this.$el;
if (model.is_done()) {
$el.addClass('set-done');
}
$el.data('set', model.index);
}
});
|
var TableTable_Couplelevel = {
map: function() {
if (!this._map)
this._map = pi.JsonLoader.getInstance().load_dict("map/Table_Couplelevel_Auto.js")
if (!this._map)
PILogE("Table_Couplelevel: load map fail");
return this._map;
},
info: function(id) {
var map = this.map();
if (!map)
return null;
var val = map[id];
if (!val)
PILogE("Table_Couplelevel: id not found");
return val;
},
getLuckValue: function(id) {
var info = this.info(id);
return info ? info["luckValue"] : null;
},
getName: function(id, translate) {
var info = this.info(id);
if (!info)
return;
return translate ? _V(info["name"]) : info["name"];
},
getLevel: function(id) {
var info = this.info(id);
return info ? info["level"] : null;
},
getAddition: function(id) {
var info = this.info(id);
return info ? info["addition"] : null;
},
getDigSuccessAddLuckValue: function(id) {
var info = this.info(id);
return info ? info["digSuccessAddLuckValue"] : null;
},
getDigFailReduceLuckValue: function(id) {
var info = this.info(id);
return info ? info["digFailReduceLuckValue"] : null;
},
_map : null,
_cache_sign : null,
_cache_mark : null,
_cache_name : null
}
|
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/building/comments/_item" ], {
b11f: function(e, t, n) {
function i(e) {
return e && e.__esModule ? e : {
default: e
};
}
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var o = i(n("8e44")), c = i(n("9554")), l = n("aad7"), s = n("371c"), a = n("cbd7"), r = wx.getSystemInfoSync().windowWidth / 750, u = 40 * r, m = 38 * r, d = {
components: {
WxUsername: function() {
n.e("pages/building/comments/_wx_username").then(function() {
return resolve(n("2f02"));
}.bind(null, n)).catch(n.oe);
}
},
data: function() {
return {
liking: !1,
show_all_reply: !1,
show_comment_fold: !1,
is_fold_comment: !1,
show_reply: []
};
},
computed: {
like_count: function() {
var e = this.comment, t = e.is_liked, n = e.like_count;
return (0, l.getLikeCount)(t, n);
}
},
created: function() {
var e = this;
this.$watch(function() {
return {
items: e.comment && e.comment.reply_comments && e.comment.reply_comments.items ? e.comment.reply_comments.items : [],
show_all_reply: e.show_all_reply
};
}, function(t) {
var n = t.items, i = [];
(i = t.show_all_reply ? n.slice(0) : n.slice(0, 3)).forEach(function(e) {
e.is_fold_reply = !1, e.show_reply_fold = !1;
}), e.show_reply = i;
}, {
immediate: !0
});
},
mounted: function() {
this.getCommentHeight(), this.getReplyHeight();
},
methods: {
getCommentHeight: function() {
var e = this;
this.getElementHeight(".content").then(function(t) {
if (t.list[0].height) {
var n = t.list[0].height;
e.is_fold_comment = n > 3 * u, e.show_comment_fold = e.is_fold_comment;
}
});
},
getReplyHeight: function(e) {
var t = this;
this.getElementHeight(".reply-content").then(function(e) {
e.list && e.list.length && e.list.forEach(function(e, n) {
e.height > 3 * m && (t.show_reply[n].is_fold_reply = !0, t.show_reply[n].show_reply_fold = !0);
});
});
},
toogleComment: function() {
this.is_fold_comment = !this.is_fold_comment;
},
toogleReply: function(e) {
this.show_reply[e].is_fold_reply = !this.show_reply[e].is_fold_reply;
},
getElementHeight: function(e) {
var t = this;
return new Promise(function(n) {
t.$mp.component.createSelectorQuery().selectAll(e).fields({
size: !0
}).exec(function(e) {
n({
list: e[0] ? e[0] : null
});
});
});
},
goDetail: function() {
var e = this.$root.$mp.query, t = e.name, n = e.building_id;
wx.navigateTo({
url: "/pages/building/comments/detail/main?building_id=".concat(n, "&id=").concat(this.comment.id, "&name=").concat(t || "")
});
},
openBigV: function(e) {
var t = e.currentTarget.dataset.waid;
t && wx.navigateTo({
url: "/pages/packageB/bigV/main?id=".concat(t)
});
},
onConsult: function(e) {
var t = this.$root.$mp.query.building_id;
(0, s.sendCtmEvtLog)("咨询点击-置业顾问评论", {
consultant_id: e
}), (0, a.openChat)(e, {
from: "评论区",
building_id: t
});
},
replyUser: function(e) {
var t = this, n = e.currentTarget.dataset.index;
if (this.is_building_page) return this.goDetail();
(0, c.default)(e, function() {
t.$emit("addComment", t.index, n);
}, "需要授权用户信息才可以进行回复");
},
onLike: function(e) {
var t = this;
if (!this.liking) {
this.liking = !0;
var n = e.currentTarget.dataset.id, i = this.comment, c = "likeComment";
i.is_liked && (c = "delLikedComment"), o.default[c](n).then(function() {
t.changeLike(!i.is_liked);
});
}
},
changeLike: function(e) {
var t = this.comment;
t.is_liked = e, t.like_count = e ? t.like_count + 1 : t.like_count - 1, this.liking = !1,
this.$emit("changeComment", t, this.index);
},
goReply: function(e) {
var t = this;
if (this.is_building_page) return this.goDetail();
(0, c.default)(e, function() {
t.$emit("addComment", t.index);
}, "需要授权用户信息才可以进行回复");
},
stopClick: function() {},
previewImg: function(e) {
var t = this.comment.photos_urls, n = t[0];
wx.previewImage({
current: n,
urls: t
});
}
},
props: {
index: {
type: Number
},
comment: {
type: Object
},
is_building_page: {
type: Boolean,
default: !1
}
}
};
t.default = d;
},
c03b: function(e, t, n) {
n.r(t);
var i = n("e79c"), o = n("ea99");
for (var c in o) [ "default" ].indexOf(c) < 0 && function(e) {
n.d(t, e, function() {
return o[e];
});
}(c);
var l = n("f0c5"), s = Object(l.a)(o.default, i.b, i.c, !1, null, null, null, !1, i.a, void 0);
t.default = s.exports;
},
e79c: function(e, t, n) {
n.d(t, "b", function() {
return o;
}), n.d(t, "c", function() {
return c;
}), n.d(t, "a", function() {
return i;
});
var i = {
fangchanAuthUser: function() {
return n.e("node-modules/fangchan-base/components/views/fangchan-auth-user").then(n.bind(null, "e86c"));
}
}, o = function() {
var e = this;
e.$createElement;
e._self._c;
}, c = [];
},
ea99: function(e, t, n) {
n.r(t);
var i = n("b11f"), o = n.n(i);
for (var c in i) [ "default" ].indexOf(c) < 0 && function(e) {
n.d(t, e, function() {
return i[e];
});
}(c);
t.default = o.a;
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/building/comments/_item-create-component", {
"pages/building/comments/_item-create-component": function(e, t, n) {
n("543d").createComponent(n("c03b"));
}
}, [ [ "pages/building/comments/_item-create-component" ] ] ]);
|
/*
* Represents a row of student data.
*/
class StudentRow extends Row {
/*
* @override
*/
constructor(data, index) {
// Convert necessary items to numbers.
data[1] = parseFloat(data[1]);
data[3] = parseFloat(data[3]);
data[4] = parseFloat(data[4]);
data[5] = parseFloat(data[5]);
// Make a copy of the original values.
const original = data.slice();
// Round some values.
data[1] = roundToPlaces(data[1], 1);
data[3] = roundToPlaces(data[3], 1);
data[4] = roundToPlaces(data[4], 2);
data[5] = roundToPlaces(data[5], 1);
super(data, index);
// Set variables.
this.id = original[0];
this.rawPercentage = original[1];
this.analyzedPercentage = original[3];
this.location = original[4];
this.recommendedPercentage = original[5];
this.oldGrade = original[2];
this.newGrade = original[6];
}
/*
* Converts a grade to a numeric value.
* @param {string} grade The grade to convert.
* @return {number} The numeric grade.
*/
gradeToNum(grade) {
const gradeMap = {
// Arbitrary values. The only restriction is that they are in descending order.
9: 'A+',
8: 'A',
7: 'A-',
6: 'B+',
5: 'B',
4: 'B-',
3: 'C+',
2: 'C',
1: 'C-',
0: 'D+',
};
gradeMap[-1] = 'D';
gradeMap[-2] = 'D-'
return parseInt(getKeyByValue(gradeMap, grade), 10);
}
/*
* @override
*/
status() {
// Determine if the change to the student is good, bad, or neutral.
const newGrade = this.newGrade;
const oldGrade = this.oldGrade;
// The new grade is better than the old grade.
if (this.gradeToNum(newGrade) > this.gradeToNum(oldGrade)) {
return 'good';
} else if (this.gradeToNum(newGrade) < this.gradeToNum(oldGrade)) {
return 'poor';
} else {
return 'neutral';
}
}
/*
* Generates a string with the percentage correct.
* @return {string} A string representing the percentage of correct answers.
*/
getPercentage() {
return 'Raw percentage: ' + roundToPlaces(this.rawPercentage, 2) + '%';
}
/*
* Generates a string with the analyzed percentage correct.
* @return {string} A string representing the percentage of correct answers.
*/
getAnalyzedPercentage() {
return 'Analyzed percentage: ' + roundToPlaces(this.analyzedPercentage, 2) + '%';
}
}
|
import React from "react";
import { connect } from "react-redux";
import { getActs, getContacts } from "../actions";
class HomePage extends React.Component {
state = {
randomGenerated: {
act: "",
contact: ""
}
};
componentDidMount() {
console.log(":: IN COMPONENT DID MOUNT ::");
const token = localStorage.getItem("token");
this.props
.getContacts(this.props.user.id, token)
.then(async () => {
await this.props.getActs(this.props.user.id, token);
})
.then(async () => {
await this.handleGenerateRandom();
});
}
handleGenerateRandom = () => {
console.log(":: HANDLE GENERATE RANDOM");
console.log(":: ACTS ::" + JSON.stringify(this.props.acts));
console.log(":: CONTACTS ::" + JSON.stringify(this.props.contacts));
var randomContact = this.props.contacts[
Math.floor(Math.random() * this.props.contacts.length)
];
var randomAct = this.props.acts[
Math.floor(Math.random() * this.props.acts.length)
];
if (randomContact !== undefined && randomAct !== undefined) {
this.setState({
randomGenerated: {
act: randomAct.description,
contact: `${randomContact.contactFirst} ${randomContact.contactLast}`
}
});
}
};
render() {
if (this.props.isGettingActs) {
return <div>Loading ...</div>;
}
if (this.props.isGettingContacts) {
return <div>Loading ...</div>;
}
console.log(
":: RENDER OF HOMEPAGE :: " + JSON.stringify(this.state.randomGenerated)
);
return (
<div>
<div>
<div>
{this.state.randomGenerated.contact}
</div>
<div>
{this.state.randomGenerated.act}
</div>
</div>
<div className="generate-btn" onClick={this.handleGenerateRandom}>
Generate a new act of kindness
</div>
<div className="login-filler" />
</div>
);
}
}
const mapStateToProps = state => {
console.log(":: HOMEPAGE USER OBJECT IS ::" + JSON.stringify(state.user));
return {
user: state.user,
isLoggedIn: state.isLoggedIn,
loggingIn: state.loggingIn,
error: state.error,
contacts: state.contacts,
acts: state.acts,
isGettingActs: state.isGettingActs,
isGettingContacts: state.isGettingContacts
};
};
export default connect(
mapStateToProps,
{ getActs, getContacts }
)(HomePage);
|
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/personal_package/feedback/_tag_filter" ], {
"292c": function(e, a, n) {
n.d(a, "b", function() {
return t;
}), n.d(a, "c", function() {
return o;
}), n.d(a, "a", function() {});
var t = function() {
var e = this;
e.$createElement;
e._self._c;
}, o = [];
},
"397b": function(e, a, n) {
n.r(a);
var t = n("a64a"), o = n.n(t);
for (var c in t) [ "default" ].indexOf(c) < 0 && function(e) {
n.d(a, e, function() {
return t[e];
});
}(c);
a.default = o.a;
},
"89d5": function(e, a, n) {},
a64a: function(e, a, n) {
Object.defineProperty(a, "__esModule", {
value: !0
}), a.default = void 0;
var t = {
data: function() {
return {
tags: [ "数据缺失/错误", "优化建议", "程序错误", "其他" ]
};
},
methods: {
onSelect: function(e) {
this.$emit("change", e);
}
},
props: {
status: {
type: String
}
}
};
a.default = t;
},
e950: function(e, a, n) {
n.r(a);
var t = n("292c"), o = n("397b");
for (var c in o) [ "default" ].indexOf(c) < 0 && function(e) {
n.d(a, e, function() {
return o[e];
});
}(c);
n("ed1f");
var r = n("f0c5"), f = Object(r.a)(o.default, t.b, t.c, !1, null, "a00653a2", null, !1, t.a, void 0);
a.default = f.exports;
},
ed1f: function(e, a, n) {
var t = n("89d5");
n.n(t).a;
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/personal_package/feedback/_tag_filter-create-component", {
"pages/personal_package/feedback/_tag_filter-create-component": function(e, a, n) {
n("543d").createComponent(n("e950"));
}
}, [ [ "pages/personal_package/feedback/_tag_filter-create-component" ] ] ]);
|
var state = {
init: function () {
this.effects = []
this.splats = []
this.buildings = []
this.houses = {}
this.taken = {}
this.platforms = []
this.newplatforms = []
this.hsectors = {}
this.addhouse(0, 0, "elgo")
this.addhouse(-2, 1, "wari")
this.addhouse(3, 1, "semt")
this.addhouse(-3, 3, "pald")
this.addhouse(0, 5, "lume")
this.addhouse(2, 3, "lige")
this.addhouse(-3, -4, "sank")
this.addhouse(-6, 4, "mian")
this.addhouse(3, 8, "sarf")
this.load(UFX.resource.data.gamedata)
this.you = new You(this.houses.elgo.x, this.houses.elgo.y + 4)
this.sortplatforms()
this.monsters = []
this.basesector = null
this.filledsectors = {}
this.njump = 1
this.jhang = 0
this.canbuild = false
this.canwarp = false
this.sun = false
this.gp = 0
this.builddepth = 110
this.lastlanding = this.houses.elgo.parent
this.done = {
knowelgo: true,
rescueelgo: true,
rescuewari: true,
rescuesarf: true,
}
this.bosses = {
semt: [],
pald: [],
lume: [],
lige: [],
sank: [],
mian: [],
}
this.loadgame()
},
resetfall: function () {
this.you.x = this.lastlanding.x + this.lastlanding.dx * 0.5
this.you.y = this.lastlanding.y + 0.8
this.you.kjump = 999
this.you.drop()
},
addhouse: function (sx, sy, hname) {
var x = (sx + 0.5) * settings.sectorsize, y = (sy + 0.5) * settings.sectorsize
var p = new Platform(x - 4, y, 8)
var h = new House(x, y, hname)
h.parent = p
p.house = h
this.buildings.push(h)
this.platforms.push(p)
this.houses[hname] = h
this.hsectors[sx + "," + sy] = h
},
nearhouse: function (you) {
if (!you.parent) return false
if (!you.parent.house) return false
if (Math.abs(you.x - you.parent.house.x) > 2) return false
if (!this.done["rescue" + you.parent.house.name]) return false
return you.parent.house
},
talk: function (house) {
content["talk" + house.name]()
this.you.hp = this.you.maxhp
this.gp = Math.max(this.gp, settings.housegp)
this.savegame()
},
sortplatforms: function () {
this.platforms.sort(function (p1, p2) { return p1.y - p2.y })
},
claimtiles: function (platform) {
var y = platform.y
this.taken[y] = this.taken[y] || {}
for (var j = 0 ; j < platform.dx ; ++j) {
this.taken[y][platform.x + j] = 1
}
},
removeplatform: function (platform) {
this.platforms = this.platforms.filter(function (p) { return p !== platform })
this.taken = {}
for (var j = 0 ; j < this.platforms.length ; ++j) {
this.claimtiles(this.platforms[j])
}
},
canplace: function (platform) {
var y = platform.y
if (y > this.builddepth) return false
if (this.gp < settings.pcost) return false
if (!this.taken[y]) return true
for (var j = 0 ; j < platform.dx ; ++j) {
if (this.taken[y][platform.x + j]) return false
}
return true
},
fillsector: function (sx, sy) {
var s = settings.sectorsize
var h = this.hsectors[sx + "," + sy]
if (h) {
if (this.done["rescue" + h.name]) return
var hx = h.x, hy = h.y + 1
this.bosses[h.name] = []
if (h.name == "semt") {
for (var j = 0 ; j < 9 ; ++j) {
this.bosses[h.name].push(new Lance(hx, hy, j/9))
}
} else if (h.name == "pald") {
for (var j = 0 ; j < 11 ; ++j) {
this.bosses[h.name].push(new Wilson(hx, hy, j/11))
}
} else if (h.name == "lume") {
for (var j = 0 ; j < 10 ; ++j) {
this.bosses[h.name].push(new Percy(hx, hy))
}
} else if (h.name == "lige") {
for (var j = 0 ; j < 9 ; ++j) {
this.bosses[h.name].push(new Lance(hx, hy, j/9))
this.bosses[h.name].push(new Percy(hx, hy))
}
} else if (h.name == "mian") {
for (var j = 0 ; j < 11 ; ++j) {
this.bosses[h.name].push(new Wilson(hx, hy, j/11))
this.bosses[h.name].push(new Percy(hx, hy))
}
} else if (h.name == "sank") {
for (var j = 0 ; j < 11 ; ++j) {
this.bosses[h.name].push(new Wilson(hx, hy, j/11))
this.bosses[h.name].push(new Lance(hx, hy, j/11))
}
}
} else if (sy < 8) {
var batprob = 16
var zatprob = 2 * Math.max(this.you.maxhp - 3, 0)
var watprob = 4 * Math.max(this.you.maxhp - 5, 0)
UFX.random.spread(200).forEach(function (p) {
var r = UFX.random(200)
r -= batprob
if (r < 0) { new Bat(s * (sx + p[0]), s * (sy + p[1])) ; return }
r -= zatprob
if (r < 0) { new Zat(s * (sx + p[0]), s * (sy + p[1])) ; return }
r -= watprob
if (r < 0) { new Wat(s * (sx + p[0]), s * (sy + p[1])) ; return }
})
}
},
clearsector: function (key) {
this.monsters = this.monsters.filter(function (m) { return m.sectorkey != key })
},
checksectors: function () {
var sx0 = Math.floor(this.you.x / settings.sectorsize)
var sy0 = Math.floor(this.you.y / settings.sectorsize)
var nbasesector = sx0 + "," + sy0
if (this.basesector == nbasesector) return
var nfilledsectors = {}
for (var dx = -1 ; dx <= 1 ; ++dx) {
for (var dy = -1 ; dy <= 1 ; ++dy) {
var sx = sx0 + dx, sy = sy0 + dy, key = sx + "," + sy
if (!this.filledsectors[key]) this.fillsector(sx, sy)
nfilledsectors[key] = 1
}
}
for (var key in this.filledsectors) {
if (!nfilledsectors[key]) this.clearsector(key)
}
this.basesector = nbasesector
this.filledsectors = nfilledsectors
console.log(this.monsters.length)
},
forplatforms: function (y0, y1, callback) {
// j = lowest index <= y0, k = highest index > y0
var j = 0, k = this.platforms.length
while (j + 1 < k) {
var i = Math.floor((j + k) / 2)
if (this.platforms[i].y > y0) {
k = i
} else {
j = i
}
}
for ( ; j < this.platforms.length && this.platforms[j].y <= y1 ; ++j) {
callback(this.platforms[j])
}
},
checkbosses: function () {
for (var h in this.bosses) {
if (this.done["rescue" + h]) continue
if (this.bosses[h].length && !this.bosses[h].some(function (b) { return b.alive })) {
delete this.bosses[h]
this.done["rescue" + h] = true
playsound("defeat")
this.savegame()
console.log("saved", h)
}
}
},
dump: function () {
var pdata = this.platforms.filter(function (p) {
return !p.house
}).map(function (p) {
return [p.x, p.y, p.dx, p.ischeck ? 1 : 0]
})
var obj = {
pdata: pdata,
}
window.open("data:text/json," + JSON.stringify(obj))
},
load: function (obj) {
for (var j = 0 ; j < obj.pdata.length ; ++j) {
var p = obj.pdata[j]
var platform = new Platform(p[0], p[1], p[2])
if (p[3]) platform.ischeck = true
this.platforms.push(platform)
}
},
gamename: "adastrasave",
savegame: function () {
console.log("saving")
var pdata = this.newplatforms.map(function (p) {
return [p.x, p.y, p.dx]
})
var obj = {
youpos: [this.you.x, this.you.y],
maxhp: this.you.maxhp,
done: this.done,
njump: this.njump,
jhang: this.jhang,
canbuild: this.canbuild,
canwarp: this.canwarp,
gp: this.gp,
pdata: pdata,
sun: this.sun,
}
localStorage[this.gamename] = JSON.stringify(obj)
},
loadgame: function () {
if (!localStorage[this.gamename]) return null
var obj = JSON.parse(localStorage[this.gamename])
this.you.x = obj.youpos[0]
this.you.y = obj.youpos[1] + 0.4
this.you.hp = this.you.maxhp = obj.maxhp
this.you.drop()
this.done = obj.done
this.njump = obj.njump
this.jhang = obj.jhang
this.canbuild = obj.canbuild
this.canwarp = obj.canwarp
this.gp = obj.gp
this.sun = obj.sun
for (var j = 0 ; j < obj.pdata.length ; ++j) {
var p = obj.pdata[j]
var platform = new Platform(p[0], p[1], p[2])
console.log(platform)
this.platforms.push(platform)
this.newplatforms.push(platform)
}
this.sortplatforms()
},
}
|
const restify = require('restify');
const db = require('../database/delete');
module.exports = {
deleteItem: async function(req,res,next){
let getResult = await db.deleteItem(req.params.id)
res.send(getResult.code)
},
deleteList: async function(req,res,next){
let getResult = await db.deleteList(req.params.id)
res.send(getResult.code)
}
};
|
define(['jquery', 'jquery.cookie', 'serializeObject'], function($, cookie, serializeObject) {
// 登陆
$(function() {
animateTime = 300;
$tip = $('#ST_tip');
$form = $('#login_form');
if($.cookie('U_email')) {
$form.find('input[name="email"]').val($.cookie('U_email'));
}
var formCheck = {
email: function(that) {
var $t = $(that),
_val = $t.val(),
emailReg = /^[0-9a-z_][_.0-9a-z-]{0,31}@([0-9a-z][0-9a-z-]{0,30}\.){1,4}[a-z]{2,4}$/;
if( !emailReg.test(_val) ) {
$tip.html('请输入正确邮箱格式').addClass('alert-warning').slideDown(animateTime);
} else {
$tip.html('').slideUp(animateTime);
}
},
password: function(that) {
var $t = $(that),
_val = $t.val(),
_val_length = _val.length;
if(!_val || _val_length < 6 || _val_length > 16) {
$tip.html('密码由6-16位字符组成, 区分大小写').addClass('alert-warning').slideDown(animateTime);
} else {
$tip.html('').slideUp(animateTime);
}
}
};
$form.on('blur', 'input[type="email"], input[type="password"]', function(e) {
var $t = $(this);
formCheck[$t.attr("name")](this);
});
$form.on('submit', function(e) {
e.preventDefault();
var url = '/manage/api/login',
data = $form.serializeObject(),
remember = $('#remember').is(':checked');
data.remember = remember;
$.ajax({
url: url,
data: data,
method: 'POST',
success: function(res, h) {
var M = res.data,
msg = M.msg,
code = M.code;
if(!code) {
$tip.removeClass('alert-warning alert-success alert-danger alert-info');
$tip
.addClass('alert-warning')
.html(msg)
.slideDown(animateTime);
} else {
$tip.removeClass('alert-warning alert-success alert-danger alert-info');
$tip
.addClass('alert-success')
.html(msg)
.show();
// 设置 cookie
if(!!remember) {
$.cookie('U_email', data.email, { expires: 7, path: '/' });
} else {
$.removeCookie('U_email');
}
// 跳转到登录页面
window.location.href = '/';
}
},
error: function(e) {
$tip.removeClass('alert-warning alert-success alert-danger alert-info');
$tip
.addClass('alert-warning')
.html('出错了,请重试')
.slideDown(animateTime);
console.log(e);
}
});
});
});
});
|
// What is the return value of the below code sample? Provide a sentence or two of explanation.
typeof( 15 );
number
// What is the return value of the below code sample? Provide a sentence or two of explanation.
typeof( "hello" );
string
// What is the return value of the below code sample? Provide a sentence or two of explanation.
typeof( [ "dog", "cat", "horse" ] );
array
// What is the return value of the below code sample? Provide a sentence or two of explanation.
typeof( NaN );
number
// What is the return value of the below code sample? Provide a sentence or two of explanation.
"hamburger" + "s";
hamburgers concatation
// What is the return value of the below code sample? Provide a sentence or two of explanation.
"hamburgers" - "s";
NaN because you cant subtract letters/words
// What is the return value of the below code sample? Provide a sentence or two of explanation.
"johnny" + 5;
johnny5 concatation
// What is the return value of the below code sample? Provide a sentence or two of explanation.
99 * "luftbaloons";
NaN
// What will the contents of the below array be after the below code sample is executed.
var numbers = [ 2, 4, 6, 8 ];
numbers.pop();
numbers.push( 10 );
numbers.unshift( 3 );
[3, 2, 4, 6, 10]
// What is the return value of the below code sample?
var morse = [ "dot", "pause", "dot" ];
var moreMorse = morse.join( " dash " );
moreMorse.split( " " );
[ 'dot', 'dash', 'pause', 'dash', 'dot' ]
// What will the contents of the below array be after the below code sample is executed.
var bands = [];
var beatles = [ "Paul", "John", "George", "Pete" ];
var stones = [ "Brian", "Mick", "Keith", "Ronnie", "Charlie" ];
bands.push( beatles );
bands.unshift( stones );
bands[ bands.length - 1 ].pop();
bands[0].shift();
bands[1][3] = "Ringo";
|
import React, { Component } from 'react';
import Tweet from './Tweet';
import buildConfigObj from './Data';
class Stream extends Component {
render() {
const data = buildConfigObj();
let tweetStream = [];
data.forEach(element => {
tweetStream.push(<Tweet key={element.key} details={element} />)
});
return(
<div className="mt-4">
{ tweetStream }
</div>
);
}
}
export default Stream;
|
import Reforma from '@reforma/core'
import { snakeCase } from './helpers'
const URL = global.URL || require('url').URL
const absoluteUrlRegex = /^https?:\/\//i
const pathSeparator = '/'
const defaultHost = 'https://2fn5i627ppxfy2fg.move4.app'
export function isAbsolutePath(path) {
return absoluteUrlRegex.test(path)
}
export function joinPaths(path1, path2) {
path1 = do {
if (path1 == null) {
''
} else if (path1.charAt(path1.length - 1) === pathSeparator) {
path1.substring(0, path1.length - 1)
} else {
path1
}
}
path2 = do {
if (path2 == null) {
''
} else if (path2.charAt(0) === pathSeparator) {
path2.substring(1)
} else {
path2
}
}
return [path1, path2].filter(p => !!p).join(pathSeparator)
}
export function getBaseURL() {
const base = do {
const baseUrl = Reforma.config.http.baseUrl
if (baseUrl == null) {
new URL(defaultHost)
} else {
new URL(baseUrl, defaultHost)
}
}
base.search = ''
base.hash = ''
return base
}
export function resolvePath(path, params) {
const url = do {
if (path == null) {
resolvePath('/')
} else if (isAbsolutePath(path)) {
new URL(path)
} else {
const url = getBaseURL()
url.pathname = joinPaths(url.pathname, path)
url
}
}
if (params != null && typeof params === 'object') {
const names = Object.getOwnPropertyNames(params)
for (let i = 0; i < names.length; i++) {
const name = names[i]
const paramName = snakeCase(name)
const value = params[name]
if (url.pathname.indexOf(`:${paramName}`) !== -1) {
const pathValue = do {
if (Array.isArray(value)) {
value.join('/') // e.g. [1, 2, 3] => 1/2/3
} else {
value
}
}
url.pathname = url.pathname.replace(`:${paramName}`, pathValue)
} else if (Array.isArray(value)) {
for (let j = 0; j < value.length; j++) {
url.searchParams.append(paramName, value[j])
}
} else {
url.searchParams.append(paramName, value)
}
}
}
return do {
if (url.origin === defaultHost) {
`${url.pathname}${url.search}`
} else {
url.href
}
}
}
|
const { expect } = require("chai");
const noSpaces = require("../checks/no-spaces-in-exports");
describe("No Spaces in Exports Check", () => {
it("skips if there is no orders file", async () => {
const deployment = {
serviceName: "streamliner"
};
const results = await noSpaces(deployment);
expect(results.length).to.equal(0);
});
it("allows orders where all exports have proper spacing", async () => {
const deployment = {
serviceName: "streamliner",
ordersPath: "streamliner/orders",
ordersContents: [
"export HEALTHCHECK=/diagnostic",
"export SECURITY_MODE=jwt",
'export CAT="pants"',
"dockerdeploy github/glg/streamliner/main:latest"
],
};
const results = await noSpaces(deployment);
expect(results.length).to.equal(0);
});
it("rejects orders if they include exports with incorrect spacing", async () => {
const deployment = {
serviceName: "streamliner",
ordersPath: "streamliner/orders",
ordersContents: [
"export HEALTHCHECK =/diagnostic",
"export SECURITY_MODE= jwt",
'export CAT = "pants"',
],
};
const results = await noSpaces(deployment);
expect(results.length).to.equal(3);
expect(results[0].problems[0]).to.equal(
`Trim out this whitespace\n\`\`\`suggestion
export HEALTHCHECK=/diagnostic
\`\`\``
);
expect(results[1].problems[0]).to.equal(
`Trim out this whitespace\n\`\`\`suggestion
export SECURITY_MODE=jwt
\`\`\``
);
expect(results[2].problems[0]).to.equal(
`Trim out this whitespace\n\`\`\`suggestion
export CAT="pants"
\`\`\``
);
});
});
|
const path = require('path')
const HtmlPlugin = require('html-webpack-plugin')
module.exports = {
entry: './src/main.ts',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.ts$/,
loader: 'ts-loader'
},
{
test: /\.(svg|png|mp3|ogg)$/,
loader: 'file-loader',
options: {
name: '[name].[hash].[ext]'
}
},
]
},
plugins: [
new HtmlPlugin({ template: './src/assets/index.html' })
],
resolve: {
extensions: ['.js', '.ts', '.json']
},
devtool: 'source-map'
}
|
'use strict';
angular.module('app.channels')
.controller('ChannelsCtrl', ['$state', 'Socket', 'Channels', 'Users', 'auth', 'users', 'channels', 'user',
function($state, Socket, Channels, Users, auth, users, channels, user) {
var self = this;
self.users = users;
self.channels = channels;
self.user = user;
self.getGravatar = function(user) {
return '//www.gravatar.com/avatar/' + user.emailHash;
};
self.newChannel = {
name: ''
};
self.logout = function() {
auth.logout();
$state.go('home');
};
self.createChannel = function() {
Channels.save({
name: self.newChannel.name
}, function(channel) {
Socket.emit('channel:created', channel);
self.channels.push(channel);
self.newChannel.name = '';
});
};
}]);
|
import React from "react";
import styled from "styled-components";
import { Button, Header, Container, Divider, Icon } from "semantic-ui-react";
import { FacebookButton, GmailButton, EmailButton } from "../SocialNetButtons";
import RegisterForm from "./Form/Container";
import facebook from "../../../assets/facebook.svg";
import google from "../../../assets/google.svg";
import Modal from "../Modal/Container";
const Title = styled(Header)`
&&&& {
text-align: left;
font-size: 24px;
font-weight: 800;
border-bottom: none;
margin: 24px 0;
}
`;
const ButtonsBox = styled(Container)`
&&&& {
width: 100%;
}
`;
const StyledDivider = styled(Divider)`
&&& {
margin: 22px 0;
}
`;
const Image = styled.img`
&&& {
align-self: self-start;
height: 18px;
width: 18px;
margin-right: 12px;
}
`;
const Footer = styled.p`
&&& {
font-size: 16px;
color: #4f4b65;
font-weight: 400;
}
`;
const RegisterHeader = styled.p`
&&& {
text-align: center;
font-size: 14px;
color: #4f4b65;
font-weight: 700;
}
`;
const LoginAction = styled.a`
font-weight: 700;
color: #483df6;
margin: 0 8px;
cursor: pointer;
&:hover {
color: #483df6;
text-decoration: underline;
text-decoration-color: #483df6;
}
`;
const Register = ({
handleEmailClick,
isEmailClicked,
handleGoogleAuth,
handleFacebookAuth,
handleRegisterModalToggle,
isLogin,
reference
}) => (
<Modal name="Registrate" isLogin={isLogin} ref={reference}>
{isEmailClicked ? (
<React.Fragment>
<RegisterHeader>
<span>Regístrate con </span>
<a style={{ color: "#3a91aa", cursor: "pointer" }}> Facebook </a>
<span> o </span>
<a style={{ color: "#3a91aa", cursor: "pointer" }}> Google </a>
</RegisterHeader>
<StyledDivider horizontal>
<span style={{ color: "#767676", fontSize: "10px" }}>o</span>
</StyledDivider>
<ButtonsBox>
<RegisterForm />
<StyledDivider />
<Footer>
<span>¿Ya tienes una cuenta en Pandora?</span>
<LoginAction onClick={handleRegisterModalToggle}>Inicia sesion</LoginAction>
</Footer>
</ButtonsBox>
</React.Fragment>
) : (
<React.Fragment>
<Title>¡Crea una cuenta gratis!</Title>
<ButtonsBox>
<FacebookButton onClick={handleFacebookAuth}>
<Image src={facebook} />
<span style={{ alignSelf: "flex-end" }}>
Registrarse con Facebook
</span>
</FacebookButton>
<GmailButton onClick={handleGoogleAuth}>
<Image src={google} />
<span>Registrarse con Google</span>
</GmailButton>
<StyledDivider horizontal>
<span style={{ color: "#767676", fontSize: "12px" }}>o</span>
</StyledDivider>
<EmailButton onClick={handleEmailClick}>
<Icon
name="mail outline"
style={{ color: "#fff", fontSize: "18px" }}
/>
<span style={{ alignSelf: "flex-end" }}>
Registrarse con un correo electrónico
</span>
</EmailButton>
<StyledDivider />
<Footer>
<span>¿Ya tienes una cuenta en Pandora?</span>
<LoginAction onClick={handleRegisterModalToggle}>Inicia sesion</LoginAction>
</Footer>
</ButtonsBox>
</React.Fragment>
)}
</Modal>
);
export default Register;
|
import React, { useState } from "react";
import "antd/dist/antd.css";
import ContactList from "./ContactList";
import { ContactService } from "../../api/contactService";
const Contact = () => {
const [contact, setContact] = useState({
loading: false,
contactList: [],
});
ContactService.contacts().then((data) => {
setContact({
loading: true,
contactList: data,
});
});
return (
<div>
<ContactList
loading={contact.loading}
contactList={contact.contactList}
/>
</div>
);
};
export default Contact;
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
View,
ScrollView,
StyleSheet,
YellowBox,
Dimensions,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
import HomeContent from '../../containers/home/content';
/**
*
* @HomeView Layout component
*
*/
class HomeView extends Component {
constructor(props) {
super(props);
YellowBox.ignoreWarnings([
'Warning: componentWillMount is deprecated',
'Warning: componentWillReceiveProps is deprecated'
]);
this.state = {
vw: 0,
vh: 0,
isTablet: false,
isLandScape: false,
};
}
detectLayout = () => {
const { width, height } = Dimensions.get('screen');
let vw = width / 100;
let vh = height / 100;
let isLandScape = width > height ? true : false;
let isTablet =
(isLandScape && width / height > 1.6) ||
(!isLandScape && height / width > 1.6) ? false : true;
this.setState({ vw: vw, vh: vh, isTablet: isTablet, isLandScape: isLandScape });
}
componentDidMount() {
this.detectLayout();
}
render() {
const { headerStep } = this.props;
const { vw, vh, isTablet, isLandScape } = this.state;
return(
<View style={[
styles.homeContainer,
headerStep === 0 && { flex: 1 },
headerStep !== 0 && { height: 0 }
]} onLayout={this.detectLayout}>
<ScrollView style={{width: '100%'}}>
<HomeContent vw={vw} vh={vh}
isTablet={isTablet} isLandScape={isLandScape} />
</ScrollView>
</View>
);
}
}
/* Home Page Content Style */
const styles = StyleSheet.create({
homeContainer: {
width: '100%',
backgroundColor: '#eff3f8',
flexWrap: 'nowrap',
alignItems: 'center',
justifyContent: 'flex-start',
},
});
const mapStateToProps = (state, props) => {
return {
headerStep: state.navigator.stage,
};
};
export default connect(mapStateToProps)(HomeView);
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsInvertColors = {
name: 'invert_colors',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M17.66 7.93L12 2.27 6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31A7.98 7.98 0 0012 21.58c2.05 0 4.1-.78 5.66-2.34 3.12-3.12 3.12-8.19 0-11.31zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/></svg>`
};
|
'use strict';
/**
* based on buggy Angucomplete
*/
angular.module('angucomplete', [])
.directive('angucomplete', ['$timeout', function($timeout) {
return {
restrict : 'EA',
scope : {
'id' : '@id',
'placeholder' : '@placeholder',
'selectedObject' : '=selectedobject',
'dataField' : '@datafield',
'titleField' : '@titlefield',
'descriptionField' : '@descriptionfield',
'inputClass' : '@inputclass',
'userPause' : '@pause',
'localData' : '=localdata',
'searchFields' : '@searchfields',
'minLengthUser' : '@minlength',
'matchClass' : '@matchclass',
'searchText' : '@searchtext',
'noResultText' : '@noresulttext',
'limit' : '@limit',
'joinTitlesChar' : '@jointitleschar',
},
template :
'<div class="angucomplete-holder">' +
'<input id="{{id}}_value" ng-model="searchStr" type="text" placeholder="{{placeholder}}" class="{{inputClass}}" ' +
'onmouseup="this.select();" ng-focus="resetHideResults()" ng-blur="hideResults()"/>' +
'<div id="{{id}}_dropdown" class="angucomplete-dropdown" ng-if="showDropdown && searchStr && searchStr.length > 0" role="navigation">' +
'<div class="angucomplete-searching" ng-show="searching">{{searchText}}</div>' +
'<div class="angucomplete-searching" ng-show="!searching && (!results || results.length == 0)">{{noResultText}}</div>' +
'<div class="angucomplete-row" ng-repeat="result in results" ng-click="selectResult(result)" ng-mouseover="hoverRow()"' +
'ng-class="{\'angucomplete-selected-row\': $index === currentIndex}">' +
'<div ng-if="imageField" class="angucomplete-image-holder">' +
'<img ng-if="result.image" ng-src="{{result.image}}" class="angucomplete-image"/>' +
'<div ng-if="!result.image" class="angucomplete-image-default"></div>' +
'</div>' +
'<div class="angucomplete-title">' +
'<span ng-bind-html="result.title"></span>' +
'</div>' +
'<div ng-if="result.description" class="angucomplete-description">' +
'<span ng-bind-html="result.description"></span>' +
'</div>' +
'</div>' +
'</div>',
link : function($scope, elem) {
var lastSearchTerm = null;
var searchTimer = null;
var hideTimer = null;
var pause = 500;
var minLength = 3;
var limit = 5;
var titleFields = [];
var matchClass = 'match';
var joinTitlesChar = ' – ';
var searchFields = $scope.searchFields.split(',');
$scope.currentIndex = null;
$scope.searching = false;
$scope.searchStr = null;
if ($scope.minLengthUser) {
minLength = $scope.minLengthUser;
}
if ($scope.userPause) {
pause = $scope.userPause;
}
if ($scope.titleField) {
titleFields = $scope.titleField.split(',');
}
if ($scope.limit) {
limit = $scope.limit;
}
if ($scope.matchClass) {
matchClass = $scope.matchClass;
}
if ($scope.joinTitlesChar) {
joinTitlesChar = $scope.joinTitlesChar;
}
var isNewSearchNeeded = function(newTerm, oldTerm) {
return newTerm.length >= minLength && newTerm !== oldTerm;
};
var replaceMatchInValue = function(value, re, match) {
return value.replace(re, '<span class="' + $scope.matchClass + '">' + match[0] + '</span>');
};
var processResults = function(responseData, str) {
$scope.results = [];
if (responseData && responseData.length > 0) {
var re = new RegExp(str, 'i');
var titles, title, match, item;
var processTitleField = function(titleField) {
title = item[titleField];
if (!match) {
match = title.match(re);
if (match) {
title = replaceMatchInValue(title, re, match);
}
}
titles.push(title);
};
for (var i = 0; i < responseData.length; i++) {
item = responseData[i];
titles = [];
match = undefined;
angular.forEach(titleFields, processTitleField);
var description = '';
if ($scope.descriptionField) {
description = item[$scope.descriptionField];
if (!match) {
match = description.match(re);
if (match) {
description = replaceMatchInValue(description, re, match);
}
}
}
titles[0] = '<span class="name">' + titles[0] + '</span>';
$scope.results.push({
title : titles.join(' – '),
description : description,
image : '',
name : item[titleFields[0]],
originalObject : item
});
}
}
};
var searchTimerComplete = function(str) {
if (str.length >= minLength) {
var matches = [], match, item;
str = str.toLowerCase();
for (var i = 0; i < $scope.localData.length && matches.length < limit; i++) {
item = $scope.localData[i];
match = false;
for (var j = 0; j < searchFields.length && !match; j++) {
match = item[searchFields[j]].toLowerCase().indexOf(str) >= 0;
}
if (match) {
matches.push(item);
}
}
$scope.searching = false;
processResults(matches, str);
}
};
$scope.hideResults = function() {
hideTimer = $timeout(function() {
$scope.showDropdown = false;
}, pause);
};
$scope.resetHideResults = function() {
if (hideTimer) {
$timeout.cancel(hideTimer);
}
};
$scope.hoverRow = function(index) {
$scope.currentIndex = index;
};
var keyPressed = function(event) {
if (!(event.which === 38 || event.which === 40)) {
if (!$scope.searchStr) {
$scope.showDropdown = false;
lastSearchTerm = null;
} else if (isNewSearchNeeded($scope.searchStr, lastSearchTerm) ||
(event.which === 13 && ($scope.currentIndex === undefined || $scope.currentIndex < 0))) {
lastSearchTerm = $scope.searchStr;
$scope.showDropdown = true;
$scope.currentIndex = 0;
$scope.results = [];
if (searchTimer) {
$timeout.cancel(searchTimer);
}
$scope.searching = true;
searchTimer = $timeout(function() {
searchTimerComplete($scope.searchStr);
}, pause);
}
} else {
event.preventDefault();
}
};
$scope.selectResult = function(result) {
lastSearchTerm = null;
$scope.searchStr = result.name;
$scope.selectedObject = result;
$scope.showDropdown = false;
$scope.results = [];
};
var inputField = elem.find('input');
inputField.on('keyup', keyPressed);
elem.on('keyup', function(event) {
if (event.which === 40) {
if ($scope.results && $scope.results.length > 0) {
if ($scope.currentIndex + 1 < $scope.results.length) {
$timeout(function() {
$scope.currentIndex++;
}, 0);
} else {
$timeout(function() {
$scope.currentIndex = 0;
}, 0);
}
event.preventDefault();
event.stopPropagation();
}
} else if (event.which === 38) {
if ($scope.results && $scope.results.length > 0) {
if ($scope.currentIndex > 0) {
$timeout(function() {
$scope.currentIndex--;
}, 0, true);
} else {
$timeout(function() {
$scope.currentIndex = $scope.results.length - 1;
}, 0);
}
event.preventDefault();
event.stopPropagation();
}
} else if (event.which === 13) {
if ($scope.results && $scope.currentIndex >= 0 && $scope.currentIndex < $scope.results.length) {
$timeout(function() {
$scope.selectResult($scope.results[$scope.currentIndex]);
}, 0);
} else {
$timeout(function() {
$scope.results = [];
}, 0);
}
event.preventDefault();
event.stopPropagation();
} else if (event.which === 27) {
$timeout(function() {
$scope.results = [];
$scope.showDropdown = false;
}, 0);
} else if (event.which === 8) {
$timeout(function() {
$scope.selectedObject = null;
}, 0);
}
});
}
};
}]);
|
const AirtableSync = require("@evdhiggins/airtable-sync");
/**
* For airtable-sync v0.2.4
*/
const airtableConfig = {
apiKey: "keyxxxxxxxxxxxxxx",
baseId: "appxxxxxxxxxxxxxx",
};
const databaseConfig = {
name: "postgresql",
options: {
databaseUrl: "postgres://USER:PASS@HOST:PORT/DB",
},
};
const itemSync = {
name: "Items",
airtable: {
tableId: "tblxxxxxxxxxxxxxx",
},
local: {
tableName: "items",
syncFlag: {
columnName: "to_sync",
true: "T",
false: "F",
},
idColumns: {
local: "id",
airtable: "record_id",
},
},
columns: [
{
localColumn: "id",
airtableColumn: "Item ID",
},
{
localColumn: "name",
airtableColumn: "Item Name",
},
{
localColumn: "price",
airtableColumn: "Price",
},
],
};
const salesSync = {
name: "Sales",
airtable: {
tableId: "tblxxxxxxxxxxxxxx",
lookupByPrimaryKey: true,
},
local: {
tableName: "sales",
syncFlag: {
columnName: "to_sync",
true: true,
false: false,
},
idColumns: {
airtable: "record_id",
local: "id",
},
},
columns: [
{
localColumn: "id",
airtableColumn: "ID",
},
{
localColumn: "total_sales_value",
airtableColumn: "Total Sales",
},
{
localColumn: "total_sales_qty",
airtableColumn: "Total Qty Sold",
},
],
};
(async () => {
const sync = AirtableSync({
airtable: airtableConfig,
database: databaseConfig,
});
sync.addSync(itemSync);
sync.addSync(salesSync);
const results = await sync.run();
console.log(results);
})();
|
var searchData=
[
['mouthcontroller_80',['mouthController',['../d0/d61/class_eye_poke_handler.html#ab0828f7b5481ae0abec599b2cc06941e',1,'EyePokeHandler']]]
];
|
import en from "../locales-js/en";
import de from "../locales-js/de";
import fr from "../locales-js/fr";
import es from "../locales-js/es";
import pt from "../locales-js/pt";
import ja from "../locales-js/ja";
import zh from "../locales-js/zh";
const locales = {
en: en.en,
de: de.de,
fr: fr.fr,
es: es.es,
pt: pt.pt,
ja: ja.ja,
zh: zh.zh
};
export default locales;
|
import React from "react"
const PizzaForm = (props) => {
return(
<div className="form-row">
<div className="col-5">
<input type="text" className="form-control" placeholder="Pizza Topping" value={
//Pizza Topping Should Go Here
props.selectedPizza ? props.selectedPizza.topping : ''
} onChange={props.handleToppingChange}/>
</div>
<div className="col">
<select value={props.selectedPizza ? props.selectedPizza.size : "Small"} onChange={props.handleSizeChange}className="form-control">
<option value="Small">Small</option>
<option value="Medium">Medium</option>
<option value="Large">Large</option>
</select>
</div>
<div className="col">
<div className="form-check">
<input className="form-check-input" type="radio" value="Vegetarian" onChange={props.handleVegetarianChange} checked={props.selectedPizza && props.selectedPizza.vegetarian ? true : false}/>
<label className="form-check-label">
Vegetarian
</label>
</div>
<div className="form-check">
<input className="form-check-input" type="radio" value="Not Vegetarian" onChange={props.handleVegetarianChange} checked={props.selectedPizza && props.selectedPizza.vegetarian ? false : true}/>
<label className="form-check-label">
Not Vegetarian
</label>
</div>
</div>
<div className="col">
<button type="submit" className="btn btn-success" onClick={props.handleSubmit}>Submit</button>
</div>
</div>
)
}
export default PizzaForm
|
// pages/resume-edit/languageAbility/languageAbility.js
const APP = getApp();
const { saveResume, deleteResume } = require('../../common/common.js');
Page({
/**
* 页面的初始数据
*/
data: {
languageTypes: ['英语', '日语', '韩语', '法语', '德语', '西班牙语', '葡萄牙语', '意大利语', '阿拉伯语', '俄语'],
languageLevel: ['一般', '良好', '熟练', '精通'],
chooseLanguageIndex: -1,
chooseLevelIndex: -1,
isInfoLegal: false,
isLanguageChoosePicker: false,
isLevelChoosePicker: false
},
// showLanguageChoosePicker: function() {
// this.changeStatus('isLanguageChoosePicker', true)
// },
// showLevelChoosePicker: function(){
// this.changeStatus('isLevelChoosePicker', true)
// },
// hiddenLanguageChoosePicker: function(){
// this.changeStatus('isLanguageChoosePicker', false)
// },
// hiddenLevelChoosePicker: function(){
// this.changeStatus('isLevelChoosePicker', false)
// },
changeStatus: function(types, status) {
this.setData({
[types]: status
})
},
// 选择语言种类和程度
changePickerValue:function (e) {
const { types, value } = e.detail;
this.setData({
[types]: value
})
this.checkBtnStatus()
},
// 判断按钮状态
checkBtnStatus: function(){
const { chooseLanguageIndex, chooseLevelIndex } = this.data;
this.setData({
isInfoLegal: chooseLanguageIndex >=0 && chooseLevelIndex >= 0 && true
})
},
// 点击保存
saveAction: function() {
const { _id, isEdit, languageTypes, languageLevel, chooseLanguageIndex, chooseLevelIndex } = this.data,
language = {
name: languageTypes[chooseLanguageIndex],
level: languageLevel[chooseLevelIndex]
},
saveStatus = isEdit >= 0 ? _id : '0';
saveResume('campus', language, 'language', saveStatus)
},
// 删除本条语言能力
deleteAction: function(){
const { _id } = this.data
deleteResume('campus', 'language', _id, '语言能力')
},
fetchIndex: function(arr,name,Index, self){
arr.forEach((item, index) => {
if (item == name){
self.setData({
[Index]: index
})
}
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
const { index } = options
this.setData({
isEdit: index,
isShowDeleteBtn: index >= 0 ? true : false
})
if(index >= 0) {
const { name, level,_id } = APP.globalData.schoolResume.language[index],
{ languageTypes, languageLevel } = this.data;
this.fetchIndex(languageTypes, name, 'chooseLanguageIndex',this)
this.fetchIndex(languageLevel, level, 'chooseLevelIndex',this)
this.setData({
_id
})
this.checkBtnStatus()
}
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
})
|
var assert = require('assert');
var cc = require('../index');
var hex = cc.hex;
describe('hex', function() {
describe('#hex', function() {
it('should construct hex {abbr: \'#123456\', val: \'#123456\'}', function() {
var target = {
abbr: '#123456',
val: '#123456'
}
assert.deepEqual(target, hex('#123456'));
assert.deepEqual(target, hex('123456'));
assert.deepEqual(target, hex(' 123456 '));
});
it('should construct hex {abbr: \'#abc\', val: \'#aabbcc\'}', function() {
var target = {
abbr: '#abc',
val: '#aabbcc'
}
assert.deepEqual(target, hex('#aabbcc'));
assert.deepEqual(target, hex('aabbcc'));
assert.deepEqual(target, hex('abc'));
assert.deepEqual(target, hex('#abc'));
assert.deepEqual(target, hex(' abc '));
assert.deepEqual(target, hex(' aabbcc '));
});
});
describe('#str', function() {
it('should be \'#123456\' for both abbr and val', function() {
assert.equal('#123456', hex('#123456').str());
assert.equal('#123456', hex('#123456').str(true));
});
it('should be \'#ace\' for abbr and \'#aaccee\' for val', function() {
assert.equal('#ace', hex('#ace').str(true));
assert.equal('#aaccee', hex('#ace').str());
});
});
describe('#rgba', function() {
it('should be rgba {r: 18, g: 205, b: 239, a:1}', function() {
assert.deepEqual({
r: 18,
g: 205,
b: 239,
a: 1
}, hex('#12cdef').rgba());
});
});
describe('#rgb', function() {
it('should be rgb {r: 18, g: 205, b: 239}', function() {
assert.deepEqual({
r: 18,
g: 205,
b: 239
}, hex('#12cdef').rgb());
});
});
describe('#hsla', function() {
it('shoule be hsla {h: 210, s: 65, l: 13, a: 1}', function() {
assert.deepEqual({
h: 210,
s: 65,
l: 13,
a: 1
}, hex('#0c2238').hsla());
});
});
describe('#hsl', function() {
it('shoule be hsl {h: 210, s: 65, l: 13}', function() {
assert.deepEqual({
h: 210,
s: 65,
l: 13
}, hex('#0c2238').hsl());
});
});
});
|
import React from "react";
import Router from "react-router-dom/BrowserRouter";
import Route from "react-router-dom/Route";
import PortfolioWrapper from "./components/topbar/handling/portfolioWrapper";
import Main from "./components/main components/main";
import SidebarAnimationWrapper from "./components/topbar/handling/sidebarAnimationSettings";
import ParticlesData from "./data-config/particles.config.json";
import { Particles } from "react-particles-js";
import "./css/gridStyles.scss";
import "./css/styles.scss";
import "./css/mobile.scss";
import "./css/slides.scss";
import "./css/libraries/press.css";
import "./css/libraries/normalize.css";
const App = () => {
return (
<div className="App">
<Particles
width={"100vw"}
height={"100vh"}
params={ParticlesData.configuration}
style={ParticlesData.style}
/>
<Router id="router">
<div>
<div className="l-main-layout">
<Main />
</div>
<SidebarAnimationWrapper />
<Route path="/portfolio" component={PortfolioWrapper} />
</div>
</Router>
</div>
);
};
export default App;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _initialize = require('./initialize');
var _initialize2 = _interopRequireDefault(_initialize);
var _express = require('express');
var _express2 = _interopRequireDefault(_express);
var _bodyParser = require('body-parser');
var _bodyParser2 = _interopRequireDefault(_bodyParser);
var _morgan = require('morgan');
var _morgan2 = _interopRequireDefault(_morgan);
var _http = require('http');
var _http2 = _interopRequireDefault(_http);
var _socket = require('socket.io');
var _socket2 = _interopRequireDefault(_socket);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _globals = require('../globals');
var _socket3 = require('./socket');
var jsSocket = _interopRequireWildcard(_socket3);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _restBase = require('./restBase');
var _restBase2 = _interopRequireDefault(_restBase);
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var app = (0, _express2.default)();
var accessLogStream = _fs2.default.createWriteStream(_globals.config.logFile, { flags: 'a' });
app.set('views', _path2.default.join(__dirname, '/views')); // eslint-disable-line
app.set('view engine', 'ejs');
app.use(_bodyParser2.default.json()); // for parsing application/json */
app.use(_bodyParser2.default.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded*/
app.use((0, _morgan2.default)('combined', { stream: accessLogStream })); // create log and append to logger file*/
app.use((0, _morgan2.default)('dev')); // display it and only dev*/
app.use('/public', _express2.default.static(_path2.default.join(__dirname, '/views/public'))); // eslint-disable-line
app.use('/son-goku', _restBase2.default);
app.get('/socketPage', function (req, res) {
res.sendFile(_path2.default.join(__dirname, '/views/public/socketpage.html')); // eslint-disable-line
});
app.use('/', function (req, res) {
res.render('index');
});
var server = _http2.default.createServer(app);
var io = (0, _socket2.default)(server);
server.listen(process.env.PORT || _initialize2.default.get('api:port'), function () {
console.log('----Server API getway at port :' + _initialize2.default.get('api:port') + ' and domain: ' + _initialize2.default.get('api:host') + '....');
console.log('----Database run at ' + _globals.config.dbGenUrl(_initialize2.default.get('db')));
});
jsSocket.socketBase(io);
exports.default = app;
|
/*
* Route: /apps/:appId/notifications/:appNotificationId?
*/
const AppNotificationModel = rootRequire('/models/AppNotification');
const AppDeviceModel = rootRequire('/models/AppDevice');
const userAuthorize = rootRequire('/middlewares/users/authorize');
const appAuthorizeOwnership = rootRequire('/middlewares/apps/authorizeOwnership');
const appDeviceAuthorize = rootRequire('/middlewares/apps/devices/authorize');
const router = express.Router({
mergeParams: true,
});
/*
* GET
*/
router.get('/', appDeviceAuthorize);
router.get('/', (request, response, next) => {
const { appId, appNotificationId } = request.params;
const { appDevice } = request;
if (appNotificationId) {
AppNotificationModel.find({
where: {
id: appNotificationId,
appId,
appDeviceId: appDevice.id,
},
}).then(appNotification => {
if (!appNotification) {
throw new Error('The app notification does not exist.');
}
response.success(appNotification);
}).catch(next);
} else {
AppNotificationModel.findAll({
where: {
appId,
appDeviceId: appDevice.id,
},
order: [['id', 'DESC']],
}).then(appNotifications => {
response.success(appNotifications);
}).catch(next);
}
});
/*
* POST
*/
router.post('/', userAuthorize);
router.post('/', appAuthorizeOwnership);
router.post('/', (request, response, next) => {
const { app } = request;
const { title, message } = request.body;
let url = (!request.body.url.includes('http')) ? `http://${request.body.url}` : request.body.url;
app.sendGlobalNotification(null, url, title, message).then(() => {
response.success();
}).catch(next);
});
/*
* PATCH
*/
router.patch('/', appDeviceAuthorize);
router.patch('/', (request, response, next) => {
const { appId, appNotificationId } = request.params;
const { appDevice } = request;
const { read } = request.body;
let where = { id: appNotificationId, appId };
where.appDeviceId = appDevice.id;
AppNotificationModel.find({
where: {
id: appNotificationId,
appId,
appDeviceId: appDevice.id,
},
}).then(appNotification => {
if (!appNotification) {
throw new Error('The app notification does not exist.');
}
appNotification.read = read || appNotification.read;
return appNotification.save();
}).then(appNotification => {
response.success(appNotification);
}).catch(next);
});
/*
* Export
*/
module.exports = router;
|
import { useHistory } from "react-router-dom";
import restringido from "../assets//restringido.svg";
import Button from "react-bootstrap/Button";
const SinAutorizacion = () => {
const history = useHistory();
return (
<div className="d-flex justify-content-center mt-5">
<img className="mb-4" src={restringido} alt="" width="300" height="100" />
<div>
<h1>Sin autorización</h1>
<h3>Por favor contactar al adminsitrador para validar su usuario</h3>
<span className="tag">soportedigytos@udea.com</span>
<br />
<br />
<div>
<Button
variant="primary"
onClick={() => {
history.goBack();
}}
>
Regresar al sitio
</Button>
</div>
</div>
</div>
);
};
export default SinAutorizacion;
|
import React, { Component } from 'react';
class SearchBar extends Component {
constructor() {
super();
this.state = { term: ''};
}
render() {
return (
<div className="search-bar">
<h1>Nkululeko Youtube</h1>
<label htmlFor="search">Search</label>
<input
id="search"
value={this.state.term}
onChange={e => this.onInputChange(e.target.value) } type="text"/>
<i class="fa fa-search" aria-hidden="true"></i>
</div>
);
}
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term);
}
}
export default SearchBar;
|
import React, { useState } from "react";
import { Route, Switch } from "react-router-dom";
import "./MainBody.css";
import Home from "./Home/Home";
import Watch from "./Watch/Watch";
import Friends from "./Friends/Friends";
import MyProfile from "./MyProfile/MyProfile";
import Chat from "./Chat/Chat";
import ChatBubble from "./Chat/ChatBubble/ChatBubble";
import useStateContext from "../../context/DataLayer";
function MainBody() {
const [{ chatBoxOpen }, dispatch] = useStateContext();
return (
<div className="mainBody">
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/watch" component={Watch} />
<Route exact path="/friends" component={Friends} />
<Route exact path="/profile" component={MyProfile} />
</Switch>
<div className="mainBody__chatBubblesContainer">
<ChatBubble />
</div>
{chatBoxOpen && <Chat />}
</div>
);
}
export default MainBody;
|
import React, { Component } from "react";
export class IndexHome extends Component{
render(){
return (
<div className="container">
<div className="jumbotron text-center">
<h1><span className="fa fa-lock"></span> Node Authentication</h1>
<p>Login or Register with:</p>
<a href="/flicks/login" className="btn btn-default"><span className="fa fa-user"></span> Local Login</a>
<a href="/flicks/signup" className="btn btn-default"><span className="fa fa-user"></span> Local Signup</a>
<a href="/flicks/auth/google" className="btn btn-danger"><span className="fa fa-google-plus"></span> Google</a>
</div>
</div>
);
}
}
|
exports.up = function(knex) {
return knex.schema.table('blogposts', t=>{
t.string('facebook_link')
t.string('instagram_link')
t.string('youtube_link')
})
};
exports.down = function(knex) {
return knex.schema.table('blogposts', t=>{
t.dropColumn('facebook_link')
t.dropColumn('instagram_link')
t.dropColumn('youtube_link')
})
};
|
import React, { Component } from 'react';
import { Redirect } from 'react-router-dom';
import {Link} from 'react-router-dom'
import Header from './header';
class Dashboard extends Component {
state = {
user1: "",
email1: "",
password1: "",
phoneNumber1: "",
isRedirect: false
}
reDirectdata = (e) => {
e.preventDefault();
this.setState({
isRedirect: true
})
return
}
render() {
console.log(this.props);
return (
<div>
<Header />
<div className="container">
<div className="row">
<div className="col-md-6">
<img className=" split-person" src="https://dx0qysuen8cbs.cloudfront.net/assets/fat_rabbit/drawings/person-orange-132756aba0816bfed6540e25d57d59f6900f36b6854ef71b361ac24d7db53d39.png" alt="jbh" />
</div>
<div className="col-md-6">
<h1> <img src={require('../assets/splitwise.png')} alt="split" className="dashboard-spli" />
Welcome to Splitwise!</h1>
<div><p>What would you like to do first?</p></div>
<div><a className="btn btn-large btn-warning apart-btn"><i className=" fa fa-home"><Link to='/Apartment-group'>Add Your Apartment</Link></i></a></div>
<div><a className="btn btn-large btn-warning apart-btn"><i className=" fa fa-globe">Add group Trip</i></a></div>
<div><a className="btn btn-large btn-light apart-btn">
Skip setup for now</a></div>
</div>
</div>
</div>
{this.state.isRedirect ? <Redirect to={{
pathname: '/Account',
state: { user: this.props.location.state }
}} /> : null}
</div>
)
}
}
export default Dashboard;
|
const express = require('express');
const bodyParser = require('body-parser');
const fetch = require('node-fetch');
const fs = require('fs');
const app = express();
const cors = require('cors');
const port = 7777;
app.use(express.json());
// app.use(bodyParser.urlencoded({ extended: true }));
app.use(cors());
const readFavourites = () => {
let rawdata = fs.readFileSync('favourites.json');
return JSON.parse(rawdata);
};
const writeFavourites = (data) => {
fs.writeFileSync('favourites.json', JSON.stringify(data));
};
const findFavourite = (favourites, favourite_id) =>
favourites.some(
(favourite) => parseInt(favourite.id, 10) === parseInt(favourite_id, 10)
);
const fetchFavourite = async (favourites, isRandom, favourite_id) => {
return await fetch(
`http://api.icndb.com/jokes/${
isRandom ? 'random' : favourite_id
}?escape=javascript`
)
.then((r) => r.json())
.then((response) => {
if (response.type === 'success') {
//if we get a joke
let exists = findFavourite(favourites, favourite_id);
if (exists) {
//but we already have it
return {
success: false,
message: 'favourite_already_exists',
joke: null,
};
} else {
//and it isnt already saved
const new_favourites = favourites.concat(response.value);
writeFavourites(new_favourites);
return {
success: true,
message: 'favourite_saved',
joke: response.value,
};
}
} else {
return {
success: false,
message: 'joke_server_could_not_connect',
};
}
});
};
app.route('/favourites')
.get((req, res) => {
let favourites = readFavourites();
res.send({
data: favourites,
success: true,
});
})
.post(async (req, res) => {
let isRandom = /true/i.test(req.query.is_random);
let favourite_id = parseInt(req.query.joke_id);
let favourites = readFavourites();
if (favourites.length < 10) {
const result = await fetchFavourite(
favourites,
isRandom,
favourite_id
);
res.send(result);
} else {
res.send({
success: false,
message: 'maximum_reached',
joke: null,
});
}
});
app.route('/favourites/:id').delete((req, res) => {
let favourite_id = req.params.id;
let favourites = readFavourites();
const new_arr = favourites.filter((favourite) => {
return favourite.id !== parseInt(favourite_id, 10);
});
writeFavourites(new_arr);
res.send({
success: true,
message: 'favourite_deleted',
});
});
app.listen(port, () => {
console.log(`Favourites server: http://localhost:${port}`);
});
|
/**
* @license
*
* Copyright IBM Corp. 2020, 2021
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { render } from 'react-dom';
import ArrowRight20 from '@carbon/icons-react/es/arrow--right/20.js';
import DDSLeadspace from '@carbon/ibmdotcom-web-components/es/components-react/leadspace/leadspace';
import DDSLeadspaceHeading from '@carbon/ibmdotcom-web-components/es/components-react/leadspace/leadspace-heading';
import DDSLeadspaceImage from '@carbon/ibmdotcom-web-components/es/components-react/leadspace/leadspace-image';
import DDSButtonGroup from '@carbon/ibmdotcom-web-components/es/components-react/button-group/button-group';
import DDSButtonGroupItem from '@carbon/ibmdotcom-web-components/es/components-react/button-group/button-group-item';
import DDSImageItem from '@carbon/ibmdotcom-web-components/es/components-react/image/image-item';
import './index.css';
const App = () => (
<DDSLeadspace alt="Image alt text">
<DDSLeadspaceHeading>Heading can go on two lines max</DDSLeadspaceHeading>
Use this area for a short line of copy to support the title
<DDSButtonGroup slot="action">
<DDSButtonGroupItem href="https://www.example.com">
<ArrowRight20 slot="icon" />
Button 1
</DDSButtonGroupItem>
<DDSButtonGroupItem href="https://www.example.com">
<ArrowRight20 slot="icon" />
Button 2
</DDSButtonGroupItem>
</DDSButtonGroup>
<DDSLeadspaceImage
slot="image"
default-src="https://picsum.photos/id/1076/1056/480"
className="bx--image"
alt="Image alt text">
<DDSImageItem media="(min-width: 672px)" srcset="https://picsum.photos/id/1076/672/400"></DDSImageItem>
<DDSImageItem media="(min-width: 0)" srcset="https://picsum.photos/id/1076/320/370"></DDSImageItem>
</DDSLeadspaceImage>
</DDSLeadspace>
);
render(<App />, document.getElementById('root'));
|
"use strict";
App
.filter('timeFormat',function(){
/* 时间过滤 */
return function(time){
return time * 1000;
}
})
.filter('search',function(){
/* 搜索 */
return function(data){
return "";
}
})
.filter('plus',function(){
/* $index+1 */
return function(data){
return data = Number(data) + 1;
}
})
.filter('setMB',function(){
return function(data){
return data = data / 1024 / 1024;
}
})
.filter('cutstr',function(){
return function(data){
return data = data.substr(0,20) + "...";
}
})
|
module.exports = {
totalTokens(quantity, price) {
let total = quantity * price
return total
},
removeBalance(balance, quantity, price) {
let total = quantity * price
let accountBalance = balance - total
return accountBalance
},
repay(quantity, balance, price) {
let refund = quantity * price
let total = balance + refund
return total
},
capitalized: (string) => string[0].toUpperCase() + string.slice(1).toLowerCase(),
toDate: (date) => {
date = new Date(date).toISOString().slice(0, 10)
console.log(date)
return date
}
}
|
import React, { Component } from "react";
// class NavBar extends Component {
// render() {
// return (
// <nav class="navbar navbar-light bg-light">
// <a class="navbar-brand" href="#">
// <span className="badge badge-pill badge-secondary">
// {this.props.counterTotal}
// </span>
// </a>
// </nav>
// );
// }
// }
// export default NavBar;
const NavBar = ({ counters }) => {
return (
<nav className="navbar navbar-light bg-light">
<a className="navbar-brand" href="#">
Item:{" "}
<span className="badge badge-pill badge-secondary m-2">
{counters.filter(c => c.value > 0).length}
</span>
Number:
<span className="badge badge-pill badge-secondary m-2">
{counters.map(c => c.value).reduce((acc, item) => acc + item)}
</span>
</a>
</nav>
);
};
export default NavBar;
|
;(function() {
$(document).ready( function() {
//start ready
let timerId = setInterval( function () {
$('.slider__list').each( function() {
let currIndex = $('.slider__list').data('item');
let prevIndex = currIndex;
currIndex++;
currIndex >= $(this).children().length ? currIndex = 0 : currIndex = currIndex;
if ( $(this).data('bullit') == '') {
$('.slider__list').children().eq(prevIndex).fadeOut();
} else {
let prevBullitIndex = $(this).data('bullit');
$('.slider__list').children().eq(prevBullitIndex).fadeOut();
$(this).data('bullit', '');
};
$(this).data('item', currIndex);
$(this).children().eq(currIndex).fadeIn();
let navigation = $(this).parent().next().children();
navigation.removeClass('active');
navigation.removeClass('prevActive');
navigation.eq(currIndex).addClass('active');
navigation.eq(prevIndex).addClass('prevActive');
});
}, 4000);
$('.slider__navigation').children().click( function() {
let list = $(this).parent().prev().children().eq(0);
if ($(this).data('index') == '') {
let listData = list.data('item');
$(this).parent().data('index', listData);
}
$(this).parent().children().removeClass('active');
$(this).parent().children().removeClass('prevActive');
let prevIndData = $(this).parent().data('index');
list.children().eq(prevIndData).fadeOut();
let currIndex = $(this).index();
list.children().eq(currIndex).fadeIn();
$(this).parent().data('index', currIndex);
list.data('bullit', currIndex);
$(this).parent().children().eq(prevIndData).addClass('prevActive');
$(this).addClass('active');
});
//end ready
});
})();
|
'use strict';
describe('GalleryThumbs directive', function() {
var scope,
isolatedScope,
template,
element,
$rs;
beforeEach(module('FEF-Angular-UI'));
// beforeEach(module('templates/directives/gallery-thumbs.html'))
beforeEach(inject(function($rootScope, $compile, $templateCache) {
/**
* instead of using the usual html2js pattern and declaring the template as a module (commented out above for eg)
* have added the template to the cache here manually so that we can force the width of elements using
* inline style, otherwise it would have involved rendering the document etc, which would be slower
*/
$templateCache.put("templates/gallery-thumbs.html",
"<div class=\"gallery-thumbs-previous\" ng-click=\"previousThumbs()\"><i class=\"icon-chevron-left\"></i></div>\n" +
"<div class=\"gallery-thumbs-next\" ng-click=\"nextThumbs()\"><i class=\"icon-chevron-right\"></i></div>\n" +
"<ul class=\"gallery-thumbs-runner\">\n" +
" <li style=\"width: 120px;\" ng-repeat=\"slide in slides\" repeat-done=\"thumbRepeaterId\" ng-click=\"loadThumb($index)\">\n" +
" <div class=\"highlight\"></div>\n" +
" <img width=\"120\" alt=\"{{ slide.alt }}\" ng-src=\"{{ slide.src }}\">\n" +
" </li>\n" +
"</ul>");
$rs = $rootScope;
scope = $rootScope.$new();
scope.data = [
{
"id":1,
"src":"img/wagamama.jpg",
"alt":"some image"
},
{
"id":2,
"src":"img/wahaca.jpg",
"alt":"some image"
},
{
"id":3,
"src":"img/tayyabs.jpg",
"alt":"some image"
},
{
"id":4,
"src":"img/byron.jpg",
"alt":"some image"
},
{
"id":5,
"src":"img/giraffe.jpg",
"alt":"some image"
},
{
"id":6,
"src":"img/GBK.jpg",
"alt":"some image"
},
{
"id":7,
"src":"img/pizza-express.jpg",
"alt":"some image"
},
{
"id":8,
"src":"img/jamies-italian.jpg",
"alt":"some image"
}
];
template = '<div gallery-thumbs slides="data"></div>';
element = angular.element(template);
element.width('300px');
$compile(element)(scope);
isolatedScope = element.scope();
isolatedScope.$apply();
}));
var $thumbs, $runner, $previous, $next;
beforeEach(function() {
$thumbs = element.find('.gallery-thumbs-runner li');
$runner = element.find('.gallery-thumbs-runner');
$previous = element.find('.gallery-thumbs-previous');
$next = element.find('.gallery-thumbs-next');
});
describe('init', function () {
// TODO: investigate how to test isolated scope in 1.2 once more docs / samples have surfaced
xit("should attach slides to isolated scope", function() {
expect(isolatedScope.slides.length).toBe(8);
});
it('should create thumb elements', function() {
expect($thumbs.length).toBe(8);
});
it('should create next and previous navigation elements', function () {
expect($next.length).toBe(1);
expect($previous.length).toBe(1);
});
it("should highlight the first thumb", function() {
expect($thumbs.first().hasClass('selected')).toBeTruthy();
});
it("should disable the previous button", function() {
var slideIndicator = element.find('.slider-indicators li:first-child');
expect($previous.hasClass('disabled')).toBeTruthy();
});
});
describe('sliding', function() {
it("should load the next set of thumbs when the next button is clicked", function() {
expect($runner.css('left')).toEqual('0px');
$next.click();
expect($runner.css('left')).toEqual('-240px');
});
it("should load the previous set of thumbs when the previous button is clicked", function() {
expect($runner.css('left')).toEqual('0px');
$next.click();
expect($runner.css('left')).toEqual('-240px');
$previous.click();
expect($runner.css('left')).toEqual('0px');
});
it("should disable the previous button when at the start", function() {
$next.click();
$previous.click();
expect($previous.hasClass('disabled')).toBeTruthy();
});
it("should disable the next button when at the end", function() {
$next.click(); // 300
$next.click(); // 600
$next.click(); // 900
expect($next.hasClass('disabled')).toBeTruthy();
});
// TODO: investigate how to test isolated scope in 1.2 once more docs / samples have surfaced
xit("should fire a 'set_slide' event when a thumb is clicked", function() {
spyOn(isolatedScope, '$emit');
$thumbs.eq(2).click();
expect(isolatedScope.$emit).toHaveBeenCalledWith('set_slide', 2);
});
it("should highlight the thumb when highlight_thumb event is received", function() {
var index = 2;
$rs.$broadcast('highlight_thumb', index);
expect($thumbs.eq(2).hasClass('selected')).toBeTruthy();
});
});
afterEach(function() {
scope.$destroy();
});
});
|
import React, { Component } from 'react';
import { Form } from 'antd';
import { type, scope, changeitem, selectType, createhistory } from '../constants/enumtype';
import {halfFourColLayout,fourColLayout} from "components/layout/formLayout";
const FormItem = Form.Item;
export default class OtherInfo extends Component {
constructor(props) {
super(props);
}
render() {
return (
<Form inline>
<FormItem label='名称:' {...halfFourColLayout}>{this.props.baseData.attrCode}</FormItem>
<FormItem label='作用范围:' {...halfFourColLayout}>{scope(this.props.baseData.scope)}</FormItem>
<FormItem label='数据类型:' {...halfFourColLayout}>{type(this.props.baseData.attrType)}</FormItem>
<FormItem label='生成历史记录:' {...halfFourColLayout}>{createhistory(this.props.baseData.createHistory)}</FormItem>
<FormItem label='描述:' {...fourColLayout}>{this.props.baseData.describe}</FormItem>
</Form>
)
}
}
|
function signIn() {
console.log("Attempting to sign in...");
var provider = new firebase.auth.GithubAuthProvider();
provider.addScope('repo'); // Request access to user's repos
provider.setCustomParameters({
'allow_signup': false
});
firebase.auth().signInWithPopup(provider).then(function(result) {
var username = result.additionalUserInfo.username;
var token = result.credential.accessToken;
console.log("Successfully signed in with user " + username + ".");
// Store data in session and redirect to main page.
sessionStorage.setItem('username', username);
sessionStorage.setItem('token', token);
location.href = "github-insite.html";
}).catch(function(error) {
console.log(error);
});
}
function signOut() {
console.log("Attempting to sign out...");
firebase.auth().signOut().then(function() {
console.log("Sign out successful.");
// Clear session & redirect user back to login page.
sessionStorage.clear();
location.href = "index.html";
}).catch(function(error) {
console.log(error);
});
}
|
var %BUNDLE%;
var deps=%DEPS%;
var getRequire = (function(){
return function getRequire(a){
return function atomRequire(m){
return require(deps[a][m])
}
}
})();
(function start (entryAtomName, derefs) {
var ATOMS = {};
function translate (word) {
// TODO import whole wisp
return word.replace(/(-[a-zA-Z])/g,
function (x) { return x[1].toUpperCase() })
}
function deref (atom) {
console.log("deref", atom);
if (!atom.value) {
atom.value = require('vm').runInNewContext(
atom.compiled, makeContext(atom.name));
}
return atom.value;
}
function makeContext (atomName) {
var context =
{ require: getRequire(atomName)
, script: document.getElementsByTagName("script")[0] // TODO
, deref: deref };
ATOMS[translate(atomName)].derefs.map(function (i) {
context[i] = ATOMS[i];
});
console.log(context);
return context;
};
var req = new XMLHttpRequest();
req.onload = function () {
var atoms = JSON.parse(this.responseText);
[entryAtomName].concat(derefs).map(function (atomName) {
console.log("install", atomName);
ATOMS[atomName] = atoms[atomName];
})
console.log(ATOMS);
ATOMS[entryAtomName].value = require('vm').runInNewContext(
ATOMS[entryAtomName].compiled, makeContext(entryAtomName));
}
req.open("get", "/atoms", true);
req.send();
})("%ATOM%", %DEREFS%);
|
'use strict';
angular
.module('emailInput')
.component('emailInput', {
templateUrl : 'email-input/email-input.template.html',
controller : function emailInputController () {
//Messages
var messages = {
'startingMessage' : 'Your email goes here.',
'nameOverflowMessage' : 'I am afraid that email is too long.',
'invalidNameMessage' : 'There is a problem with that email.',
'validNameMessage' : 'Nice email.'
}
//User Object
this.user = {
'email' : 'jazz@smooth.jams',
'emailStatus' : function () {
//check email is defined
if(this.email === undefined) {
return 'undefined';
}
//Check length
if(this.email.length > 50) {
return 'overflow';
}
else {
return 'valid';
}
},
'message' : function () {
if (this.emailStatus() === 'valid') {
return messages.validNameMessage;
}
if (this.emailStatus() === 'overflow') {
return messages.nameOverflowMessage;
}
if (this.emailStatus() === 'undefined') {
return messages.invalidNameMessage;
}
return 'Huh? We don\'t have a message for this'
}
}
}
});
|
/*
* Copyright 2000-2012 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Created with IntelliJ IDEA.
* User: Natalia.Ukhorskaya
* Date: 3/29/12
* Time: 1:56 PM
*/
var HighlighterDecorator = (function () {
function HighlighterDecorator() {
var currentHighlighter = null;
var instance = {
getHighlighting:function (configurationType, programText, callback) {
if (currentHighlighter != null) {
currentHighlighter.getHighlighting(configurationType, programText, callback);
}
},
onHighlight:function (data) {
},
setHighlighter:function (highlighter) {
if (currentHighlighter != null) {
currentHighlighter.onHighlight = null;
currentHighlighter.onFail = null;
}
currentHighlighter = highlighter;
currentHighlighter.onHighlight = function (data, callback) {
instance.onHighlight(data);
callback(data);
};
currentHighlighter.onFail = function (exception) {
instance.onFail(exception);
};
},
onFail:function (message) {
}
};
return instance;
}
return HighlighterDecorator;
})();
/*var arrayOfHighlighters = [];
arrayOfHighlighters.push(Configuration.mode.CLIENT.highlighter);
arrayOfHighlighters.push(Configuration.mode.SERVER.highlighter);
var i = 0;
for (i = 0; i < arrayOfHighlighters.length; ++i) {
arrayOfHighlighters[i].onHighlight = function (data, callback) {
instance.onHighlight(data);
callback(data);
};
arrayOfHighlighters[i].onFail = function (exception) {
instance.onFail(exception);
};
}*/
|
'use strict';
const bcrypt = require('bcryptjs')
module.exports = (sequelize, DataTypes) => {
const User = sequelize.define('User', {
name: DataTypes.STRING,
username: {
type : DataTypes.STRING,
validate:{
isUnique(){
return User.findAll()
.then(data=>{
data.forEach(element=>{
if(element.username==this.username){
throw new Error ('Email sudah ada')
}
})
})
}
}
},
password: DataTypes.STRING
}, {
hooks:{
beforeCreate:(user, option)=>{
let salt = bcrypt.genSaltSync(10)
user.password = bcrypt.hashSync(user.password,salt)
},
beforeSave:(user, option)=>{
let salt = bcrypt.genSaltSync(10)
user.password = bcrypt.hashSync(user.password,salt)
}
}
});
User.associate = function(models) {
// associations can be defined here
User.hasMany(models.Restaurant, {foreignKey: 'ownerId'})
User.hasMany(models.Review, {foreignKey: 'CreatorId' })
// models.User.belongsToMany(models.Restaurant, {through: Review, foreignKey: 'CreatorId' })
};
return User;
};
|
import React, { Component } from 'react';
import GroceryListContainer from '../containers/GroceryListContainer';
import AddGroceryContainer from '../containers/AddGroceryContainer';
import SortContainer from '../containers/SortContainer';
class App extends Component {
render() {
return (
<div className="App">
<h1>Grocery List</h1>
<SortContainer />
<br />
<GroceryListContainer />
<br />
<AddGroceryContainer />
</div>
);
}
}
export default App;
|
import styled from "styled-components";
export default styled.div`
height: 30px;
width: 30px;
background: url(${props => props.url}) no-repeat center;
background-size: cover;
border-radius: 50%;
margin-right: 12px;
cursor: pointer;
`;
|
export const users=[
{
"id": 1,
"username": "_LinaJiang",
"firstName": "Lina",
"lastName": "Jiang",
"email": "jianglina0914@gmail.com",
"isAdmin": true,
"twoots": [
{"id": 1, "content": "Twotter is Amazing!"},
{"id": 2, "content": "Don't forget to subscriber to The Earth is Square!"}
]
},
{
"id": 2,
"username": "_LingMing",
"firstName": "Ling",
"lastName": "Ming",
"email": "lingming0316@gmail.com",
"isAdmin": false,
"twoots": []
},
{
"id": 3,
"username": "MariaMa",
"firstName": "Maria",
"lastName": "Ma",
"email": null,
"isAdmin": false,
"twoots": []
},
{
"id": 4,
"username": "MingliangCui",
"firstName": "Mingliang",
"lastName": "Cui",
"email": null,
"isAdmin": false,
"twoots": []
}
]
|
/**
* @author ashutosh
* @type type
*/
var procedure = require('../models/procedure.js');
var policy = require('../models/policy.js');
var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
var legislation = require('../models/legislation.js');
var fs = require('fs');
var officegen = require('officegen');// for the doc file generator
var docx = officegen('docx'); // for the doc file generator
var http = require('http');
var procedurecontroller = function() {
};
procedurecontroller.prototype = {
'addprocedure': function(req, res, done) {
var newlprocedure = new procedure();
newlprocedure.procedurename = req.body.procedurename;
newlprocedure.proceduretext = req.body.proceduretext;
newlprocedure.legislation = req.body.legislation;
newlprocedure.policy = req.body.policy;
process.nextTick(function() {
newlprocedure.save(function(err) {
if (err) {
console.log("Error! Couldn't insert data successfully.");
}
else {
console.log("You have submitted the data");
}
});
});
}, 'getdatabyproid': function(req, res) { // get all procedure data
process.nextTick(function() {
procedure.find({'_id': req.params.uid}, function(err, data) {
res.render('addresearchedit', {'resultprocedure': data, layout: "login"});
});
});
},
'generatedoc': function(req, res) { // get legislation data by id
process.nextTick(function() {
procedure.findOne({'_id': req.params.uid}, function(err, data) {
console.log('data');
console.log(data);
console.log(req.params.uid);
docx.on('finalize', function(written) {
console.log('Finish to create Word file.\nTotal bytes created: ' + written + '\n');
});
docx.on('error', function(err) {
console.log(err);
});
var pObj = docx.createP({align: 'center'});
pObj.addText('Procedure Data', {bold: true, underline: true});
//pObj.addImage ( path.resolve(__dirname, 'images_for_examples/image3.png' ) );
//docx.putPageBreak();
//1st
var pObj = docx.createListOfNumbers();
pObj.addText('Procedure Name:', {bold: true});
pObj.options.align = 'left';
pObj.addText(' ' + data.procedurename);
//2nd
var pObj = docx.createListOfNumbers();
pObj.addText('Procedure Text:', {bold: true});
pObj.options.align = 'left';
pObj.addText(' ' + data.proceduretext);
var wordrand = Math.floor((Math.random() * 100000) + 1000000);// generate the random number for the doc file
var out = fs.createWriteStream(wordrand + 'out.docx');
out.on('error', function(err) {
console.log(err);
});
docx.generate(out);
console.log(out.path);
// var request = http.get("http://localhost:3300/"+out.path, function(response) {
// response.pipe(out);
// out.on('finish', function() {
// out.close();
// });
// });
});
});
},
'deletedatabylid': function(req, res) {
process.nextTick(function() {
procedure.remove({'_id': req.params.uid}, function(err, data) {
console.log(data);
//es.render('addresearchedit', {'lresult': data, layout: "login"});
});
});
}, 'updatedatabylid': function(req, res) {
process.nextTick(function() {
procedure.update({'_id': req.body.id}, {$set: {'procedurename': req.body.procedurename, 'proceduretext': req.body.proceduretext, 'legislation': req.body.legislation, 'policy': req.body.policy}}, function(err, results) {
});
});
}, 'getupdatedata': function(req, res) { // get all legislative data by id
var alldata = [];
process.nextTick(function() {
policy.find({}, function(err, policydata) {
alldata['podata'] = policydata;
});
procedure.find({}, function(err, proceduredata) {
alldata['prodata'] = proceduredata;
});
legislation.find({}, function(err, d) {
alldata['ldata'] = d;
});
procedure.findOne({'_id': req.params.uid}, function(err, sdata) {
if (sdata.legislation) {
var asdfghk=[];
var spldata = sdata.legislation.split(',');
var j=0;
for (i in spldata) {
// console.log(i);
legislation.findOne({'_id': spldata[i]}, function(err, seldata) {
// console.log(seldata.policyname);
localStorage.setItem('mainheadinga',seldata.mainheading);
});
asdfghk[j]=localStorage.getItem('mainheadinga');
// console.log(j);
localStorage.removeItem('mainheadinga');
j++;
}
}
if (sdata.policy) {
var asdfghkpro=[];
var spldata = sdata.policy.split(',');
var j=0;
for (i in spldata) {
// console.log(i);
policy.findOne({'_id': spldata[i]}, function(err, seldata) {
// console.log(seldata.policyname);
localStorage.setItem('pa',seldata.policyname);
});
asdfghkpro[j]=localStorage.getItem('pa');
// console.log(j);
localStorage.removeItem('pa');
j++;
}
}
// console.log(asdfghk);
alldata['selectdata']=asdfghk;
alldata['selectprodata']=asdfghkpro;
});
procedure.findOne({'_id': req.params.uid}, function(err, sdata) {
alldata['sldata'] = sdata;
// alldata['expldata']=sdata.policy.split(',');
//console.log(sdata.policy);
res.render('addresearchupdateprocedure', {'result': alldata, layout: "login"});
});
});
}
};
module.exports = new procedurecontroller();
|
import { API_KEY } from '../constants'
import { REQUEST_MOVIES, REQUEST_MOVIE_DETAILS, RECEIVE_MOVIES, RECEIVE_MOVIE_DETAILS } from './types'
function requestMovies() {
return {
type: REQUEST_MOVIES
}
}
function receiveMovies(json) {
return {
type: RECEIVE_MOVIES,
movies: json.results.map(movie => movie)
}
}
function requestMovieDetails() {
return {
type: REQUEST_MOVIE_DETAILS
}
}
function receiveMovieDetails(json) {
return {
type: RECEIVE_MOVIE_DETAILS,
details: json
}
}
export function fetchMovies(movieTitle) {
return (dispatch) => {
dispatch(requestMovies())
return fetch(
`https://api.themoviedb.org/3/search/movie?api_key=${API_KEY}&language=en-US&query=${movieTitle}`
)
.then(response => response.json())
.then(json => dispatch(receiveMovies(json)))
}
}
export function fetchMovieDetails(id, moveTitle) {
return (dispatch) => {
dispatch(requestMovieDetails())
const movie = fetch(
`https://api.themoviedb.org/3/movie/${id}?api_key=${API_KEY}&language=en-US`
).then(response => response.json())
const wiki = fetch(
`https://en.wikipedia.org/w/api.php?action=query&origin=*&prop=extracts&exintro=&explaintext=&format=json&titles=${moveTitle}`
).then(response => response.json())
const combinedData = {
movie: {},
wiki: {}
}
Promise.all([movie, wiki]).then((results) => {
combinedData.movie = results[0]
const pageId = Object.keys(results[1].query.pages)[0]
combinedData.wiki = results[1].query.pages[pageId]
dispatch(receiveMovieDetails(combinedData))
})
}
}
|
../../../../../../shared/src/App/MainHeader/Search/actions.js
|
module.exports = {
collectCoverage: true,
collectCoverageFrom: [
'**/server/**/*.js',
'!**/server/server.js',
'!**/tests/**',
],
};
|
setInterval(updateIcon(), 5000);
updateIcon();
|
import VueFetch, { $fetch } from '../../plugins/fetch'
export function getComments(fanficId, isActive) {
return $fetch(`comments-list/?fanfic=${fanficId}&active=${isActive}/`)
.then(res => res)
.catch(err => {
console.log(err);
throw err;
});
}
export function getAllComments() {
return $fetch(`comments-list/`)
.then(res => res)
.catch(err => {
console.log(err);
throw err;
});
}
export function postComment (name, email, body, fanfic, chapter) {
return $fetch('comments/', {
method: 'post',
body: JSON.stringify({
name: name,
email: email,
body: body,
fanfic: fanfic,
chapter: chapter
})
})
.then(res => res)
.catch(err => console.log(err))
}
|
function kreni() {
var opcija = document.lista.izbor.selectedIndex;
var url = document.lista.izbor.options[opcija].value;
if ((opcija != 0) || (opcija != 8))
window.location = url;
}
|
/*Create a new website with external js file
Add a button (e.g. 'click me') that when clicked console.logs 'you clicked me!'
Create a function that fetches from The Github API. For example from [this page] (https://api.github.com/orgs/HackYourFuture/repos) (the one we used last week). For help on this check this SO post
Display the data that you get from the Github API on your web page.
Now link the two together: When you click the button -> get the data from the Github API and display it on your website
Make all the repositories link their own page in Github. Use the value of the key: name to make this work (hint: Github urls always look like this https://api.github.com/repos/HackYourFuture/[repositoryName] where [repositoryName] would be replaced by the actual name of the repository, for example CommandLine). Make sure the link opens in a new tab.
*/
const mybutton = document.querySelector('button');
mybutton.addEventListener('click', function() {
console.log("you clicked me!")
});
const myButtonClick = function(){
const fetchUrl = "https://api.github.com/orgs/HackYourFuture/repos";
const listRepos = document.querySelector('.list_repos');
listRepos.innerHTML = "";
const req = new XMLHttpRequest();
req.addEventListener('load', function(data) {
if (this.status === 200) {
const responseText = req.responseText;
const data = JSON.parse(responseText);
console.log(data.name);
data.forEach(function(repo) {
const liElement = document.createElement('li');
const dataUrl = 'https://api.github.com/repos/HackYourFuture/' + repo.name;
liElement.innerHTML = '<a href="' + dataUrl + '" target="_blank">' + dataUrl + '</a>';
listRepos.appendChild(liElement);
});
}
else {
console.log('Something is probably wrong with the url');
}
});
req.open('GET', fetchUrl);
req.send();
}
mybutton.addEventListener("click", myButtonClick)
|
(function() {
"use strict";
// レコード一覧画面
kintone.events.on(['app.record.index.show', 'app.record.detail.show'], function(event) {
var manager = new KintoneRecordManager;
manager.getRecords(function(records) {
// レコード取得後の処理
console.log('KintoneRecordManager');
console.log(records);
});
RelatedRecordsFieldManager.prototype.getFieldProperties().then(function(){
var relatedRecordsField = new RelatedRecordsFieldManager('販売情報');
event.records.forEach(function(record, index){
relatedRecordsField.getRecords(record).then(function(records){
if(records.length){
kintone.app.getFieldElements('製番')[index].innerText = 1;
} else {
kintone.app.getFieldElements('製番')[index].innerText = 0;
}
console.log('RelatedRecordsFieldManager');
console.log(records);
});
});
});
return event;
});
/**
* kintoneと通信を行うクラス
*/
var KintoneRecordManager = (function() {
KintoneRecordManager.prototype.records = []; // 取得したレコード
KintoneRecordManager.prototype.appId = null; // アプリID
KintoneRecordManager.prototype.query = ''; // 検索クエリ
KintoneRecordManager.prototype.limit = 100; // 一回あたりの最大取得件数
KintoneRecordManager.prototype.offset = 0; // オフセット
function KintoneRecordManager() {
this.appId = kintone.app.getId();
this.records = [];
}
// すべてのレコード取得する
KintoneRecordManager.prototype.getRecords = function(callback) {
kintone.api(
kintone.api.url('/k/v1/records', true),
'GET',
{
app: this.appId,
query: this.query + (' limit ' + this.limit + ' offset ' + this.offset)
},
(function(_this) {
return function(res) {
var len;
Array.prototype.push.apply(_this.records, res.records);
len = res.records.length;
_this.offset += len;
if (len < _this.limit) { // まだレコードがあるか?
_this.ready = true;
if (callback !== null) {
callback(_this.records); // レコード取得後のcallback
}
} else {
_this.getRecords(callback); // 自分自身をコール
}
};
})(this)
);
};
console.log('records');
console.log(KintoneRecordManager.prototype.records);
console.log('query');
console.log(KintoneRecordManager.prototype.query);
console.log('appId');
console.log(KintoneRecordManager.prototype.appId);
console.log('limit');
console.log(KintoneRecordManager.prototype.limit);
console.log('offset');
console.log(KintoneRecordManager.prototype.offset);
return KintoneRecordManager;
})();
var RelatedRecordsFieldManager = (function(fieldCode){
function RelatedRecordsFieldManager(fieldCode) {
this.fieldCode = fieldCode;
this.targetAppId = kintone.app.getRelatedRecordsTargetAppId(fieldCode);
this.property = this.fieldProperties[fieldCode].referenceTable;
}
RelatedRecordsFieldManager.prototype = {
selfAppId: kintone.app.getId(),
records: [],
limit: 1,
query: '',
//limit: 500,
offset: 0,
getFieldProperties: function(){
return kintone.api(kintone.api.url('/k/v1/app/form/fields', true), 'GET', {
app: RelatedRecordsFieldManager.prototype.selfAppId,
}).then(function(response){
RelatedRecordsFieldManager.prototype.fieldProperties = response.properties;
});
},
query: function(record){
return (
this.property.condition.relatedField +
'="' +
record[this.property.condition.field].value +
(this.property.filterCond ? '" and ' : '"') +
this.property.filterCond
);
},
getRecords: function(record){
var _this = this;
return kintone.api(kintone.api.url('/k/v1/records', true), 'GET', {
app: this.targetAppId,
query:
this.query(record) +
' order by ' + this.property.sort +
' limit ' + this.limit +
' offset ' + this.offset
}).then(function(response){
return response.records;
/*_this.records = _this.records.concat(response.records);
_this.offset += response.records.length;
if(response.records.length === _this.limit){
return _this.getRecords(record);
}else{
return _this.records;
}*/
});
}
}
console.log('query');
console.log(RelatedRecordsFieldManager.prototype.query);
console.log('records');
console.log(RelatedRecordsFieldManager.prototype.records);
console.log('appId');
console.log(RelatedRecordsFieldManager.prototype.selfAppId);
console.log('limit');
console.log(RelatedRecordsFieldManager.prototype.limit);
console.log('offset');
console.log(RelatedRecordsFieldManager.prototype.offset);
return RelatedRecordsFieldManager;
})();
})();
|
import test from 'ava';
import React from 'react';
import {
mount,
shallow
} from 'enzyme';
import sinon from 'sinon';
import injectCss from 'src/index';
import * as utils from 'src/utils';
const Component = () => {
return (
<div/>
);
};
test('if injectCss will throw an error if the incorrect values are passed', (t) => {
t.throws(() => {
injectCss();
});
});
test('if injectCss returns a function', (t) => {
const result = injectCss({
css: 'foo',
id: 'bar',
selectors: {}
});
t.true(typeof result === 'function');
});
test('if injectCss returns a function that receives a component and returns a HOC', (t) => {
const decorator = injectCss({
css: 'foo',
id: 'bar',
selectors: {}
});
const result = decorator(Component);
t.true(React.Component.isPrototypeOf(result));
});
test('if injectCss will call injectStyleTag when mounted', (t) => {
const decorator = injectCss({
css: 'foo',
id: 'bar',
selectors: {}
});
const stub = sinon.stub(utils, 'injectStyleTag');
const WrappedComponent = decorator(Component);
mount(<WrappedComponent/>);
t.true(stub.calledOnce);
stub.restore();
});
test('if injectCss will return a component that will have the selectors as props', (t) => {
const selectors = {
foo: 'bar'
};
const decorator = injectCss({
css: 'foo',
id: 'bar',
selectors
});
const WrappedComponent = decorator(Component);
const wrapper = shallow(<WrappedComponent/>);
t.deepEqual(wrapper.props(), {
selectors
});
});
|
var Sumalib = require('libreria-deber/lib/area');
var respuesta = Sumalib(8, 5,2);
console.log('la respuesta es :', respuesta);
|
import mongoose from 'mongoose'
const Schema = mongoose.Schema
// create a schema
const tagSchema = new Schema({
nodeId: { type: String, required: true, unique: true },
watch: { type: Boolean, default: false },
})
// the schema is useless so far
// we need to create a model using it
const Tag = mongoose.model('Tag', tagSchema)
// make this available to our users in our Node applications
export default Tag
|
const BrowserStack = require('../api/browserstack');
module.exports = {
'init': init
}
var browserstack = undefined;
function init(cfg) {
if (!cfg.browserstack || !cfg.browserstack.api){
throw Error('BrowserStack credentials not passed with config');
}
return browserstack = {
'client': BrowserStack.createClient(cfg.browserstack.api),
'automateClient': BrowserStack.createAutomateClient(cfg.browserstack.api),
'screenshotClient': BrowserStack.createScreenshotClient(cfg.browserstack.api)
};
}
|
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { compose } from 'redux';
import get from 'lodash.get';
import { Button, Form, Icon, Input, message } from 'antd';
import buttonStyle from '../../../antdTheme/button/style/index.less';
import formStyle from '../../../antdTheme/form/style/index.less';
import iconStyle from '../../../antdTheme/icon/style/index.less';
import inputStyle from '../../../antdTheme/input/style/index.less';
import messageStyle from '../../../antdTheme/message/style/index.less'; // eslint-disable-line
import { connect } from '../../../store/redux';
import { commonReducer } from '../../../store/common.reducer';
import { commonAction } from '../../../store/common.action';
import Query from '../../../components/Query';
import ScrollArea from '../../../components/ScrollBar/js/ScrollAreaWithCss';
import moment from 'moment/moment';
import s from './Auditing.css';
const StateName = 'supplierAuditing';
const defaultState = {
test: 'default',
};
const InputTextArea = Input.TextArea;
const FormItem = Form.Item;
// 多行文本输入框
class AuditingTextArea extends React.Component {
// 触发标签事件的函数声明
handleSubmit = status => {
this.props.form.validateFields(async (err, values) => {
if (!err) {
let result;
try {
result = await this.query.fetch({
data: {
buIdSecret: this.props.buIdSecret,
// userId: get(
// this.props.runtime,
// 'user.userId',
// 'zhouyidong@chinasofti.com',
// ),
status,
contactPhone: this.props.contactPhone,
...values,
},
});
} catch (ex) {
message.error('提交失败,请重试。');
}
if (result) {
if (get(result, 'code', '') === 200) {
if (get(result, 'data.resultType', '') === '200') {
message.success('审核提交成功');
this.handleClose();
this.props.successCallBack();
} else {
message.error(get(result, 'data.msg', '审核提交失败!'));
}
} else {
message.error(get(result, 'message', '审核失败!'));
}
}
}
});
};
handleClose() {
const actionOpts = { type: `supplierExamList.drawer`, isGlobal: true };
this.props.commonAction({ visible: false }, actionOpts);
}
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form style={{ marginBottom: 20 }}>
<Query
onRef={query => {
this.query = query;
}}
auto={false}
url={`{apiUrl}/op/v1/supplier/saveApply`}
statePath={`${StateName}.submitData`}
/>
<div className="section">
<span>备注</span>
</div>
<FormItem style={{ marginTop: 20 }}>
{getFieldDecorator('note', {})(
<InputTextArea
rows={4}
maxLength={250}
placeholder="当退出时,该信息将通知申请人"
/>,
)}
</FormItem>
<Button
type="primary"
size="large"
onClick={() => {
this.handleSubmit(1);
}}
>
审核通过
</Button>
<Button
size="large"
onClick={() => {
this.handleSubmit(2);
}}
>
审核不通过
</Button>
</Form>
);
}
}
const WrappedAuditingTextArea = Form.create()(AuditingTextArea);
class SupplierAuditing extends React.Component {
render() {
const { buIdSecret, auditStatus } = this.props;
const detail = get(this.props.detail, 'data.data.contactInfo') || {};
const auditLogList = get(this.props.detail, 'data.data.auditLogList') || [];
const serviceAccount =
get(this.props.detail, 'data.data.serviceAccount') || {};
const sfzzmUrl = get(detail, 'idCardObverse')
? `${get(this.props.runtime, 'config.apiUrl', '').replace(
/\/\w*\/?$/,
'/yjusers',
)}/buauth/download/${buIdSecret}/${detail.idCardObverse}`
: './images/sfzzm.png';
const sfzfmUrl = get(detail, 'idCardReverse')
? `${get(this.props.runtime, 'config.apiUrl', '').replace(
/\/\w*\/?$/,
'/yjusers',
)}/buauth/download/${buIdSecret}/${detail.idCardReverse}`
: './images/sfzfm.png';
const yyzzUrl = get(detail, 'licImg')
? `${get(this.props.runtime, 'config.apiUrl', '').replace(
/\/\w*\/?$/,
'/yjusers',
)}/buauth/download/${buIdSecret}/${detail.licImg}`
: './images/yyzz.png';
return (
<div>
<Query
url="{apiUrl}/op/v1/supplier/getSuppluerAuditDetails"
data={{
buIdSecret,
}}
statePath={`${StateName}.detail`}
/>
<div className="detail-sub-title">
<span style={{ color: '#4a4a4a', fontSize: 16, fontWeight: 500 }}>
{detail.buName}
</span>
<span style={{ marginLeft: 20 }}>
<Icon type="idcard" />
<span style={{ fontSize: 12 }}>认证资料</span>
</span>
<span className={s.topBarMsg}>
<span>姓名:</span>
<span>{detail.juridicalPerson}</span>
</span>
<span className={s.topBarMsg}>
<span>账户:</span>
<span>{detail.userId}</span>
</span>
<span className={s.topBarMsg}>
<span>手机号:</span>
<span>{detail.contactTel}</span>
</span>
</div>
<ScrollArea
stopScrollPropagation
smoothScrolling="true"
speed={10}
className="detail-container"
style={{
position: 'absolute',
top: 111,
left: 0,
right: 0,
bottom: 0,
}}
>
<table style={{ width: '80%' }} className="detail-table">
<tbody>
<tr style={{ height: 30 }}>
<td style={{ width: 180 }}>港澳台及外国企业入驻:</td>
<td>{detail.overeeas === 0 ? '否' : '是'}</td>
<td style={{ width: 180 }}>法定代表人姓名:</td>
<td>{detail.juridicalPerson}</td>
</tr>
<tr style={{ height: 30 }}>
<td>企业法人名称:</td>
<td>{detail.buName}</td>
<td>法定代表人身份证号:</td>
<td>{detail.jurCode}</td>
</tr>
<tr style={{ height: 30 }}>
<td>统一社会信用代码:</td>
<td colSpan={3}>{serviceAccount.bulicenseCode}</td>
</tr>
<tr valign="top">
<td>法人代表身份证:</td>
<td colSpan={3}>
<div className={s.eachImgDiv}>
<img src={sfzzmUrl} alt="身份证正照" />
</div>
<div
className={s.eachImgDiv}
style={{
marginLeft: 40,
}}
>
<img src={sfzfmUrl} alt="身份证反照" />
</div>
</td>
</tr>
<tr valign="top">
<td>营业执照</td>
<td colSpan={3}>
<div className={s.eachImgDiv}>
<img src={yyzzUrl} alt="营业执照图片" />
</div>
</td>
</tr>
</tbody>
</table>
<div className="section">
<span>平台审核</span>
</div>
<div className={s.platformAuditSteps}>
<table>
<tbody>
{auditLogList.length > 0
? auditLogList.map(item => (
<tr>
<td>
{moment(item.auditTime).format('YYYY-MM-DD HH:mm:ss')}
</td>
<td>{item.actorName}</td>
<td>{item.action}</td>
</tr>
))
: '暂无审核'}
</tbody>
</table>
</div>
{auditStatus === 0 && (
<div>
<WrappedAuditingTextArea
contactPhone={detail.contactTel}
commonAction={this.props.commonAction}
buIdSecret={this.props.buIdSecret}
successCallBack={this.props.successCallBack}
/>
</div>
)}
</ScrollArea>
</div>
);
}
}
const mapState = state => ({
runtime: state.runtime,
...state[StateName],
});
const mapDispatch = {
commonAction: commonAction(StateName),
};
export default compose(
withStyles(s, buttonStyle, formStyle, iconStyle, inputStyle, messageStyle),
connect(
StateName,
commonReducer(StateName, defaultState),
mapState,
mapDispatch,
),
)(SupplierAuditing);
|
describe('pixi/Pixi', function () {
'use strict';
var expect = chai.expect;
it('Module exists', function () {
expect(global).to.have.property('PIXI').and.to.be.an('object');
});
});
|
/**
* @param {number} input
* @return {number}
*/
// 10 -> 1010 -> 0101 -> 5
// 9090 -> 10001110000010 -> 01000001110001
const reverseBits = (input) => {
// convert decimal to binary
// divide until we have result = 0
// append remaining to binary number
// 5 / 2 = 2 remaining = 1
// 2 / 2 = 1 remaining = 0
// 1 / 2 = 0 remaining = 1
// 4 / 2 = 2 remaining = 0
// 2 / 2 = 1 remaining = 0
// 1 / 2 = 0 remaining = 1
let binary = decimalToBinary(input);
// [1, 0, 1]
// reverse binary
// convert binary to decimal
let decimal = binaryToDecimal(binary);
return decimal;
};
// [0, 0, 1] = 4 (reverse)
function binaryToDecimal(binary) {
let result = 0;
let multiplier = 1;
for (let i = binary.length - 1; i >= 0; i--) {
result += binary[i] * multiplier;
multiplier *= 2;
}
return result;
}
function decimalToBinary(input) {
// 0
let result = [];
while (true) {
let division = Math.floor(input / 2);
let remaining = input % 2;
result.push(remaining);
if (division === 0) {
return result;
}
input = division;
}
}
// console.log(reverseBits(0));
// console.log(reverseBits(1));
console.log(reverseBits(9090));
|
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
Button,
ScrollView,
TextInput,
KeyboardAvoidingView,
Picker,
TouchableOpacity,
Dimensions,
} from 'react-native';
import {connect} from 'react-redux';
import {bindActionCreators } from 'redux';
import navigateTo from '../../actions/NavigationAction';
import { Container, Content, Form, Item, Input } from 'native-base';
import uStyles from '../../styles';
import Icon from 'react-native-vector-icons/Entypo';
import UploadImageComponent from '../UploadImageComponent';
import getAllPublications from '../../actions/publication/getAllPublications';
import createHeadlineAction from '../../actions/headlines/createHeadlineAction';
import LoaderComponent from '../LoaderComponent';
import getAllPerspectives from '../../actions/perspective/getAllPerspectives';
import nullFyImageuploadUrlAction from '../../actions/ImageUpload/nullFyImageuploadUrlAction';
import insertImageUploadUrlAction from '../../actions/ImageUpload/insertImageUploadUrlAction';
const {height,width}=Dimensions.get('window');
class EditHeadlineComponent extends React.Component{
constructor(){
super();
this.state={
publication_id:'',
section_id:'',
heading:'',
sub_heading:'',
note:'',
perspective_id:'',
showLoader:false
};
}
static navigationOptions = ({ navigation }) => ({
headerTitle:'Edit Headline',
headerStyle: { backgroundColor: '#0D47A1'},
headerRight:(
<TouchableOpacity onPress={() => navigation.navigate('DrawerOpen')} style={uStyles.hambergerMenu}>
<Icon name="menu" size={30} color="#fff" />
</TouchableOpacity>
)
});
componentWillMount (){
this.setState({
publication_id:this.props.selectedHeadline.publication_id,
section_id:this.props.selectedHeadline.section_id,
heading:this.props.selectedHeadline.heading,
sub_heading:this.props.selectedHeadline.subheading,
note:this.props.selectedHeadline.briefnote,
perspective_id:this.props.selectedHeadline.perspective_id,
},()=>{
console.log('state',this.state)
});
}
componentDidMount(){
this.props.insertImageUploadUrlAction(this.props.selectedHeadline.image_url);
}
editHeadLine(){
this.setState({
showLoader:true,
});
let url='';
if(this.props.imageUploadReducer!==null){
url=this.props.imageUploadReducer.split('/');
url=url[url.length-1];
}
let data={
publication_id:this.state.publication_id,
section_id:this.state.section_id,
heading:this.state.heading,
sub_heading:this.state.sub_heading,
note:this.state.note,
perspective_id:this.state.perspective_id,
image_url:url,
user_id:this.props.userData[0].id
};
let send=this.props.createHeadlineAction(data);
send.then((x)=>{
if(x){
this.setState({
showLoader:false,
});
this.props.nullFyImageuploadUrlAction();
}
})
}
render(){
const perspectives=()=>{
if (this.props.allPerspectivesReducer!==null){
return this.props.allPerspectivesReducer.map((data,index)=>{
return(
<Picker.Item label={data.perspective_name} value={data.id} key={index} />
)
});
}else {
return(
<Picker.Item label='' value='' enabled={false}/>
)
}
};
const publications=()=>{
if (this.props.allPublications!==null){
return this.props.allPublications.map((data,index)=>{
return(
<Picker.Item label={data.publication_name} value={data.id} key={index} />
)
});
}else {
return(
<Picker.Item label='' value='' enabled={false}/>
)
}
};
const showSubmitLoader=()=>{
if(this.state.showLoader){
return(
<LoaderComponent/>
)
}
};
const submitButton=()=>{
if(this.state.publication_id!=='' && this.state.heading!=='' && this.state.section_id!=='' && this.state.note!==''){
return(
<View style={uStyles.buttonContainer}>
<View style={uStyles.buttonSubContainer}>
<TouchableOpacity style={uStyles.dashBoardbutton} onPress={()=>this.editHeadLine()}>
<Text style={uStyles.dashBoardButtonText}>Edit Headlines</Text>
</TouchableOpacity>
</View>
</View>
)
}else{
return(
<View style={uStyles.buttonContainer}>
<View style={uStyles.buttonSubContainer}>
<TouchableOpacity style={uStyles.disabledDashButton}>
<Text style={uStyles.dashBoardButtonText}>Edit Headlines</Text>
</TouchableOpacity>
</View>
</View>
)
}
};
return(
<ScrollView style={[uStyles.mainView,localStyles.mainView]} keyboardShouldPersistTaps="always">
<View style={[uStyles.container,localStyles.container]}>
<View style={uStyles.picker}>
<Picker
selectedValue={this.state.publication_id}
onValueChange={(itemValue, itemIndex) => this.setState({publication_id:itemValue})}
>
<Picker.Item label='Select Publication' value='' enabled={false}/>
{publications()}
</Picker>
</View>
<View style={uStyles.picker}>
<Picker
selectedValue={this.state.perspective_id}
onValueChange={(itemValue, itemIndex) => this.setState({perspective_id:itemValue})}
>
<Picker.Item label='Select Perspective' value=''/>
{perspectives()}
</Picker>
</View>
<View style={uStyles.picker}>
<Picker
selectedValue={this.state.section_id}
onValueChange={(itemValue, itemIndex) => this.setState({section_id:itemValue})}
>
<Picker.Item label='Select Section' value='' enabled={false}/>
<Picker.Item label='Front Page' value={1}/>
<Picker.Item label='Middle Page' value={2}/>
<Picker.Item label='Last Page' value={3}/>
</Picker>
</View>
<View style={[localStyles.textInput,uStyles.textInput]}>
<TextInput
placeholder="Heading"
underlineColorAndroid="#fff"
keyboardType='default'
value={this.state.heading}
onChange={(event) => this.setState({heading:event.nativeEvent.text})}
/>
</View>
<View style={[localStyles.textInput,uStyles.textInput]}>
<TextInput
placeholder="Sub Heading"
underlineColorAndroid="#fff"
keyboardType='default'
value={this.state.sub_heading}
onChange={(event) => this.setState({sub_heading:event.nativeEvent.text})}
/>
</View>
<View style={[localStyles.textInput,uStyles.textinputMultiline]}>
<TextInput
multiline = {true}
maxLength = {200}
editable={true}
placeholder="Brief Note"
underlineColorAndroid="#fff"
keyboardType='default'
value={this.state.note}
onChange={(event) => this.setState({note:event.nativeEvent.text})}
/>
</View>
<UploadImageComponent/>
{showSubmitLoader()}
{submitButton()}
</View>
</ScrollView>
)
}
}
const localStyles=StyleSheet.create({
mainView:{
backgroundColor:'#fff'
},
container:{
},
logoContainer:{
},
textInput:{
}
});
function mapStateToProps(state) {
return {
allPublications:state.allPublicationsReducerState,
imageUploadReducer:state.imageUploadReducer,
allPerspectivesReducer:state.allPerspectivesReducer,
userData:state.userDataReducer,
selectedHeadline:state.selectedHeadline,
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(
{
navigateTo:navigateTo,
getAllPublications:getAllPublications,
createHeadlineAction:createHeadlineAction,
getAllPerspectives:getAllPerspectives,
nullFyImageuploadUrlAction:nullFyImageuploadUrlAction,
insertImageUploadUrlAction:insertImageUploadUrlAction
},dispatch)
}
export default connect(mapStateToProps,mapDispatchToProps)(EditHeadlineComponent)
|
ui.GalleryEdit = function() {
ui.GalleryEdit.base.constructor.call(this);
this.userClass = "";
this.images = {};
this.meAdd = wr.bind(this, this.onAdd);
};
wr.inherit(ui.GalleryEdit, wr.View);
ui.GalleryEdit.prototype.create = function() {
this.thumbs = wr.div_c("ui_galleryedit_thumbs");
this.buttonAdd = ui.create(ui.Upload, {userClass: "ui_galleryedit_buttonadd", multiple: true, userText: "Добавить"});
this.node = wr.div_cc("ui_galleryedit", [
this.thumbs,
wr.div_cc("buttons", [
this.buttonAdd.node
])
]);
wr.addClass(this.node, this.userClass);
};
ui.GalleryEdit.prototype.enter = function() {
ui.GalleryEdit.base.enter.call(this);
this.buttonAdd.enter();
this.buttonAdd.eventChange.listen(this.meAdd);
for (var name in this.images) {
this.images[name].enter();
}
};
ui.GalleryEdit.prototype.exit = function() {
ui.Gallery.base.exit.call(this);
this.buttonAdd.exit();
this.buttonAdd.eventChange.unlisten(this.meAdd);
for (var name in this.images) {
this.images[name].exit();
}
};
ui.GalleryEdit.prototype.empty = function() {
var child = this.thumbs.firstChild;
var next;
while (child) {
next = child.nextSibling;
wr.removeChild(this.thumbs, child);
child = next;
}
};
ui.GalleryEdit.prototype.add = function(url) {
var image = ui.create(ui.Image, {userClass: "ui_galleryedit_thumb", src: url});
this.images[url] = image;
wr.appendChild(this.thumbs, image.node);
if (this.isEnter) {
image.enter();
}
};
ui.GalleryEdit.prototype.onAdd = function(files) {
};
|
const INC = 'inc';
const DEC = 'dec';
const reducer = (state = 0, action) => {
switch (action.type) {
case INC:
state + action.amount;
break;
case DEC:
state - action.amount;
break;
default:
}
return state;
}
const store = Redux.createStore(reducer);
const increment = {
type: INC,
amount: 1
}
const decrement = {
type: DEC,
amount: 1
}
function render() {
const counterEl = document.getElementById('counter');
const state = store.getState;
counterEl.innerHTML = state;
}
render();
store.subscribe(render);
document.getElementById('increment').addEventListener('click', (e)=>{
store.dispatch(increment);
})
document.getElementById('decrement').addEventListener('click', (e)=>{
store.dispatch(decrement);
})
|
export default {
'filter': true,
};
|
/*-------------------------------- Constants --------------------------------*/
const winCom =
[[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 4, 8], [2, 4, 6], [0, 3, 6], [1, 4, 7], [2, 5, 8]]
/*---------------------------- Variables (state) ----------------------------*/
//1) Define the required variables used to track the state of the game:
let turn
let board = []
let isWinner
/*------------------------ Cached Element References ------------------------*/
//Store cached element references on the page that will be accessed in code more than once in variables to make code more concise, readable, and performanullfirstSquare = document.querySelector("#sq0")
let square = document.querySelectorAll(".quadrangle")
let boardElement = document.querySelector(".board")
let reset = document.querySelector(".reset-btn")
let message = document.querySelector("#message")
/*----------------------------- Event Listeners -----------------------------*/
boardElement.addEventListener("click", handleClick)
reset.addEventListener("click", initial)
/*-------------------------------- Functions --------------------------------*/
initial()
function initial() {
board =
[null, null, null,
null, null, null,
null, null, null]
turn = 1
isWinner = null
render()
}
function render() {
square.forEach((quadrangle, idx) => {
quadrangle = square[idx]
if (board[idx] === 1) { // and element is clicked)
quadrangle.style.backgroundColor = "black"
quadrangle.innerText = "X"
quadrangle.style.color = "white"
quadrangle.innerText.justifyContent = "center"
} else if (board[idx] === -1) {
quadrangle.style.backgroundColor = "black"
quadrangle.innerText = "O"
quadrangle.style.color = "white"
} else if (board[idx] === null) {
quadrangle.style.backgroundColor = "black"
quadrangle.innerText = ""
}
})
if (!isWinner) {
message.innerText = ` It's time for ${turn === 1 ? "X" : "O"} to play`
} else if (isWinner === `T`) {
message.innerText = `It's a tie! Try Again!`
} else if (isWinner === 1) {
message.innerText = `X is the winner`
}else if (isWinner === -1) {
message.innerText = `O is the winner`
}
}
function handleClick(evt, idx) {
if (board[(evt.target.id.replace("sq", ""))] === 1 ||
board[(evt.target.id.replace("sq", ""))] === -1) {
return
} else if (isWinner !== null) {
return
}
board[(evt.target.id.replace("sq", ""))] = turn
turn = turn * -1
let winner = getWinner()
function getWinner() {
winCom.forEach(function (idxInArr) {
let idx1 = idxInArr[0]
let idx2 = idxInArr[1]
let idx3 = idxInArr[2]
let realWinner = board[idx1]
let sum = Math.abs(board[idx1] + board[idx2] + board[idx3])
if (sum === 3) {
isWinner = realWinner
return realWinner
} else if (board.includes(null)) {
return null
} else {
isWinner = "T"
return isWinner
}
})
render()
}
}
// render()
// sumOfComb = 0
// sumOfComb += idx
// if (absValueOfSum === 3 ) {
// return `We have a winner!`
// } else if (absValueOfSum !== 3) {
|
module.exports = {
beep: require('./beep'),
ping: require('./ping'),
clean: require('./cleanChannel'),
test: require('./test'),
play: require('./music/play'),
pause: require('./music/pause'),
resume: require('./music/resume'),
leave: require('./music/leave'),
volumedown: require('./music/volumeDown'),
volumeup: require('./music/volumeUp'),
volumeset: require('./music/volumeSet'),
stop: require('./music/stop')
}
|
var menu = {
init: function() {
var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
// Si la viewport est inférieure à 768px
if (viewportWidth <= 768) {
//on exécute les fonctions
menu.displayMenu();
menu.removeMenu();
}
menu.smoothScroll();
},
/* ---------------DISPLAY MENU--------------- */
displayMenu: function() {
$burgerButtonElement = $('.nav-link.burger');
$burgerButtonElement.on('click', menu.handleDisplayMenu);
},
handleDisplayMenu: function() {
// Définitions des elements
$navElement = $('.nav-list');
$removeElement = $('.remove');
// Add class
$navElement.addClass('is-active');
$removeElement.addClass('is-active');
// Css burger icon
$burgerButtonElement = $('.nav-link.burger');
$burgerButtonElement.css('display', 'none');
},
/* ---------------REMOVE MENU--------------- */
removeMenu: function() {
$removeButtonElement = $('.remove');
$liElement = $('.nav-list > li > a');
// Pour chaque élément li dans nav-list
$liElement.each(function(index) {
// Je retire la nav-list au clic
$(this).on('click', menu.handleRemoveMenu);
});
// Au clic sur l'icone "remove" je retire la nav-list
$removeButtonElement.on('click', menu.handleRemoveMenu);
},
handleRemoveMenu: function() {
// Définitions des elements
$navElement = $('.nav-list');
$removeElement = $('.remove');
// Remove class
$navElement.removeClass('is-active');
$removeElement.removeClass('is-active');
// Css burger icon
$burgerButtonElement = $('.nav-link.burger');
$burgerButtonElement.css('display', 'inline');
},
smoothScroll: function() {
$('a[href^="#"]').on('click', function(event) {
let target = $(this.getAttribute('href'));
let fadInBottomElement = $('.fadInBottom');
if( target.length ) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: target.offset().top - $('.header').height()
}, 1000);
fadInBottomElement.css({transform : 'none', opacity : 1});
}
});
}
};
$(menu.init);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.