text
stringlengths
7
3.69M
import NumResolver from "@class/resolver/NumericResolver" export default { template: `<div> <div class="represntative" @click="move_to"> <img :src="item.url"> <div class="sale_rate" v-if="sale"> <span> {{ item.sale_rate + ' %' }} </span> </div> <div class="new_rate" v-if="item.new_rate!=0"> <span> new </span> </div> <div class="like_btn"></div> </div> <div class="product_name"> {{ item.product_name }} </div> <div class="style"> {{ style }} </div> <div class="price"> <span class="raw"> <span>{{ item.price }}</span> <span class="unit"> 원 </span> </span> <span class="not_raw"> {{ saled_price }} </span> <slot name="like"></slot> </div> </div>`, props: { item: { }, sale: { default : false } }, data(){ return { } }, computed: { style(){ return `[${this.item.style_main}] ${this.item.style_time}` }, saled_price(){ let price_rate = (100-NumResolver.to_num(this.item.sale_rate))/100 let item_price = NumResolver.to_num(this.item.price) return NumResolver.to_won( price_rate * item_price ) } }, methods: { move_to(){ } } }
import React from 'react'; import Next from './Next'; export const Section2APropos = () => ( <section id="section2" className="section sectionAPropos rel"> <div className="chevron abs haut1 larg1" onClick={Next}> <i className="chevronBas fas fa-chevron-down"></i> </div> <div className="flex-h haut1 larg100 rel"> <div className="bord larg1 coul0"> </div> <div className="bord larg1 coul2 haut1 abs car1"> </div> <div className="bord larglogo coul0"></div> <div className="bord larg1 coul0 inv5 raj"></div> <div className="bord larg1logo inv2 coul0"></div> <div className="haut1 fg"></div> <div className="bord larg1 coul0 inv1"></div> <div className="larg1 inv1"></div> <div className="bord larg1 coul2"></div> <div className="bord larg1 coul0"></div> </div> <div className="text flex-v rel"> <div className="bord larg1 coul0 haut1 car2 abs inv5"> </div> <div className="bord larg2 coul0 haut1 titre abs coul1"><h2>A Propos</h2> </div> <div className="bord larg1 coul0 haut1 car4 abs inv5"> </div> <div className="bord larg2 coul0 haut1 car5 abs coul0 inv3"></div> <p> Bonjour,<br/> Architecte de formation, j’ai longtemps été mère au foyer de 4 enfants. Actuellement, les enfants devenus grands, je désire prendre une autre direction et celle-ci m’a été confirmée lors de ma dernière formation. Le dévelopement Web est, pour moi, amusement, découvertes et défis à dépasser ! Accepteriez-vous de faire partie de mon parcours ? N'hésitez pas à me contacter ! </p> <blockquote> <cite>" Un voyage de mille kilomètres commence toujours par un premier pas" </cite> <p> Lao Tseu</p> </blockquote> <div className=" larg1 haut1 car6 abs inv4"> </div> </div> </section> );
import { default as ContributionHunk } from '../contribution-hunk'; import { default as utils } from '../utils'; import { default as Color } from 'color'; const Snapshot = class { constructor (prevSnapshot = Snapshot.root(), data = null) { if (prevSnapshot === null) { this.prevSnapshot = null; this.tracker = [null]; this.hunks = []; } else { this.prevSnapshot = prevSnapshot; this.tracker = prevSnapshot.tracker.slice(0); this.hunks = prevSnapshot.hunks.map(d => ContributionHunk.clone(d)); } this.data = this._parse(data); } static with (prevSnapshot, data) { return new Snapshot(prevSnapshot, data); } static root () { return new Snapshot(null); } isRoot () { return !this.prevSnapshot; } prev () { return this.prevSnapshot; } _parse (data) { let parsedData, color; if (!data) { return null; } parsedData = Object.assign({}, data); parsedData.timestamp = utils.ISO8601toNativeDate(parsedData.timestamp); color = Color(parsedData.color); parsedData.flowColor = color.rgb().opaquer(-0.5); return parsedData; } transact (commands) { let deleted, added, delta = 0; commands.forEach(command => { deleted = command[1]; added = command[3]; this ._atomicRemoveTransaction(command[0], deleted, delta) ._atomicAdditionTransaction(command[2], added, delta); delta += (-deleted + added); }); this.hunks = ContributionHunk.merge(this.hunks); this.tracker = this.hunks.reduce((acc, hunk, i) => { return acc.concat(Array(hunk.range[1] - hunk.range[0] + 1).fill(i)); }, [null]); return this; } _atomicRemoveTransaction (start, change, delta) { let startHunkIndex, endHunkIndex, hunk, hunkTop, hunkBottom, end; if (!change) { return this; } start += delta; startHunkIndex = this.tracker[start]; endHunkIndex = this.tracker[end = start + change - 1]; if (startHunkIndex === endHunkIndex) { hunk = this.hunks[startHunkIndex]; this.hunks = this.hunks .slice(0, startHunkIndex + 1) .concat(ContributionHunk.of(start, end).removable(true)) .concat(ContributionHunk.cloneWithRange(hunk, end + 1)) .concat(this.hunks.slice(startHunkIndex + 1)); hunk.updateRange(undefined, start - 1); } else { hunkTop = this.hunks[startHunkIndex]; hunkBottom = this.hunks[endHunkIndex]; this.hunks = this.hunks .slice(0, startHunkIndex + 1) .concat(ContributionHunk.of(start, hunkTop.range[1]).removable(true)) .concat(this.hunks.slice(startHunkIndex + 1, endHunkIndex).map(h => h.removable(true))) .concat(ContributionHunk.cloneWithRange(hunkBottom, undefined, end).removable(true)) .concat(ContributionHunk.cloneWithRange(hunkBottom, end + 1)) .concat(this.hunks.slice(endHunkIndex + 1)); hunkTop.updateRange(undefined, start - 1); hunkBottom.updateRange(end + 1); } this.hunks.reduce((acc, _hunk, i) => { if (!_hunk.removeFlag) { _hunk.shift(-acc.delta); } else { acc.delta += _hunk.range[1] - _hunk.range[0] + 1; acc.removables.push(i); } return acc; }, { delta: 0, removables: [] }); this.hunks = this.hunks.filter(_hunk => !_hunk.removeFlag); this.tracker = this.hunks.reduce((acc, _hunk, i) => { return acc.concat(Array(_hunk.range[1] - _hunk.range[0] + 1).fill(i)); }, [null]); return this; } _atomicAdditionTransaction (start, change) { let index, hunk, indexToHunk, end; if (!change) { return this; } if (this.tracker.length - 1 < start) { index = this.hunks.push(ContributionHunk.of(start, start + change - 1, this.data)); this.tracker = this.tracker.concat(Array(change).fill(index - 1)); } else { indexToHunk = this.tracker[start]; hunk = this.hunks[indexToHunk]; if(hunk.range[0] !== start) { end = hunk.range[1]; hunk.updateRange(undefined, start - 1); this.hunks = this.hunks .slice(0, indexToHunk + 1) .concat(ContributionHunk.cloneWithRange(hunk, start, end)) .concat(this.hunks.slice(indexToHunk + 1)); this.tracker = this.tracker .slice(0, start) .concat(this.tracker.slice(start).map(d => d + 1)); indexToHunk++; } this.hunks = this.hunks .slice(0, indexToHunk) .concat(ContributionHunk.of(start, start + change - 1, this.data)) .concat( this.hunks .slice(indexToHunk) .map((_hunk) => _hunk.shift(change)) ); this.tracker = this.tracker .slice(0, start) .concat(Array(change).fill(indexToHunk)) .concat( this.tracker .slice(start) .map(d => d + 1) ); } return this; } getMax () { return this.hunks[this.hunks.length - 1].range[1]; } }; export { Snapshot as default };
(function() { 'use strict'; /** * Create the module and call the requires */ var app = angular.module('ideasmanagement', [ 'ngRoute', 'ngCookies', 'ui.bootstrap' ]); app.filter('searchAllIdeasFor', function(){ return function(arr, searchString){ if (!searchString) { return arr; } var result = []; searchString = searchString.toLowerCase(); angular.forEach(arr, function(item) { if (item.ideatitle.toLowerCase().indexOf(searchString) !== -1 || item.ideadescription.toLowerCase().indexOf(searchString) !== -1 || item.name.toLowerCase().indexOf(searchString) !== -1) { result.push(item); } }); return result; }; }); app.filter('searchMyIdeasFor', function(){ return function(arr, searchString){ if (!searchString) { return arr; } var result = []; searchString = searchString.toLowerCase(); angular.forEach(arr, function(item) { if (item.ideatitle.toLowerCase().indexOf(searchString) !== -1 || item.ideadescription.toLowerCase().indexOf(searchString) !== -1) { result.push(item); } }); return result; }; }); app.filter('filterByCategory', function() { return function(ideas, selectedCategory) { var outIdeas = []; console.log("selectedCategory:" + selectedCategory); console.log("ideas:" + ideas); if(selectedCategory == "" || typeof selectedCategory == 'undefined') { outIdeas = ideas; } else { for (var i = ideas.length - 1; i >= 0; i--) { if( (selectedCategory == "Health" && ideas[i].health =='1') || (selectedCategory == "Social" && ideas[i].social =='1') || (selectedCategory == "Economic" && ideas[i].economic =='1') || (selectedCategory == "Finance" && ideas[i].finance =='1') || (selectedCategory == "Personal" && ideas[i].personal =='1') || (selectedCategory == "Business" && ideas[i].business =='1') || (selectedCategory == "Scientific" && ideas[i].cientific =='1') || (selectedCategory == "Educational" && ideas[i].educational =='1') ) { outIdeas.push(ideas[i]); } } } return outIdeas; } }); app.filter('filterByUser', function() { return function(ideas, selectedUser) { var outIdeas = []; console.log("selectedUser:" + selectedUser); if(selectedUser == null || typeof selectedUser == 'undefined') { outIdeas = ideas; } else { for (var i = ideas.length - 1; i >= 0; i--) { if(selectedUser.name==ideas[i].name) { outIdeas.push(ideas[i]); } } } return outIdeas; } }); /** * Configure the Routes */ app.config(function($routeProvider, $locationProvider) { $routeProvider .when("/", { templateUrl: "app/views/home.html", controller: "HomeCtrl", css: "styles/home.css" }) .when("/home", { templateUrl: "app/views/home.html", controller: "HomeCtrl", css: "styles/home.css" }) .when("/menuadmin", { templateUrl: "app/views/menuadmin.html", controller: "HomeCtrl", css: "styles/home.css" }) .when("/menu", { templateUrl: "app/views/menu.html", controller: "HomeCtrl", css: "styles/home.css" }) .when("/listmyideas", { templateUrl: "app/views/listideas.html", controller: "ListideasCtrl", css: "styles/home.css" }) .when("/list_all_ideas", { templateUrl: "app/views/list_all_ideas.html", controller: "ListAllIdeasCtrl", css: "styles/home.css" }) .when("/addidea", { templateUrl: "app/views/addidea.html", controller: "AddideaCtrl", css: "styles/addIdea.css" }) .when("/manageideas", { templateUrl: "app/views/manageideas.html", controller: "ManageideasCtrl", css: "styles/home.css" }) .when("/list_all_users", { templateUrl: "app/views/list_all_users.html", controller: "ListAllUsersCtrl", css: "styles/home.css" }) .when("/forbidden", { templateUrl: "app/views/forbidden.html", controller: "HomeCtrl", css: "styles/home.css" }) .otherwise({ redirectTo: '/forbidden' }); // Enabling HTML5 mode so that the URL doesn't show up with hashtags //$locationProvider.html5Mode({ enabled: true, requireBase: false }); $locationProvider.html5Mode(true); }); }());
import { motion } from 'framer-motion' import 'twin.macro' import Dictionary from '../Dictionary' export default function Permutation({ state }) { const { __done: done, __returnValue, windowStart, windowEnd, patternFrequencies, pattern, } = state const isActive = (index) => done && !__returnValue ? true : index >= windowStart && index <= windowEnd const step = done ? __returnValue ? 'Done! 🥳' : 'Not found 😢' : windowEnd < pattern.length ? `Building window 🚧` : `Sliiide 🏂` return ( <> <p tw="font-semibold text-center text-gray-500">{step}</p> <h1 tw="text-4xl font-serif text-center my-10"> {[...state.str].map((char, index) => ( <motion.span key={`${char}-${index}`} tw="inline-block" animate={{ opacity: isActive(index) ? 1 : 0.1, y: isActive(index) ? 0 : 4, }} > {char} </motion.span> ))} </h1> <section tw="text-center"> <code tw="block mb-4">Pattern: {pattern}</code> <Dictionary tw="w-1/2 mx-auto mb-4 md:w-1/3" entries={patternFrequencies} /> </section> </> ) }
import axios from "axios"; export const signUp = (body) => { return axios.post("/api/1.0/users", body); }; export const signIn = (body) => { return axios.post("/api/1.0/auth", {}, { auth: body }); };
const express = require('express'); const csrf = require('csurf'); const bodyParser = require('body-parser') const app = express(); const cookieParser = require('cookie-parser') const session = require('express-session') app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser()); app.use(session({ secret: 'mySecret', resave: false, saveUninitialized: true, cookie: { secure: false } })) app.use(csrf()); app.get('/', (req, res) => { res.send(`<form action="/transferMoney" method="post"> <input name="amount" placeholder="Enter Money Amount to transfer" /> <input type="hidden" name="to" value="123456" /> <input type="hidden" name="_csrf" value="${req.csrfToken()}" /> <input type="submit" value="submit" /> </form>`) }) app.post('/transferMoney', (req, res) => { res.send(`Money ${req.body.amount} transfered succefully to ${req.body.to}`) }) app.listen(3000, () => console.log('app listening on 3000'))
let button = document.getElementById("button"); button.addEventListener('click', function (e) { e.preventDefault(); let password1 = document.getElementById("password1"); let password2 = document.getElementById("password2"); if (password1.value == password2.value) { password1.style.borderColor = "green"; password2.style.borderColor = "green"; } else { document.getElementById("password1").style.borderColor = "red"; document.getElementById("password2").style.borderColor = "red"; } });
module.exports = function(QuestionType) { };
import { Component } from 'react'; import { connect } from 'react-redux'; import { push } from 'react-router-redux'; export default class TagFilter extends Component { constructor(props) { super(props); this.goHome = this.goHome.bind(this); } initQueryFilter() { const { loadCategories, loadTags } = this.props; loadCategories(); loadTags(); } goHome() { const { dispatch } = this.props; dispatch(push('/')); } getFilteredPosts(categoryInput, tagInput, searchInput) { const { dispatch, loadPosts } = this.props; let fullUrl = ''; let params = {}; // if there is no input, then show all posts again, if not, then show posts filtered by queries if (searchInput.value !== '' || tagInput.value !== '' || categoryInput.value !== '') { if (categoryInput.value !== '') { fullUrl += `/category/${categoryInput.value}`; params.category = categoryInput.value; } if (tagInput.value !== '') { fullUrl += `/tag/${tagInput.value}`; params.tag = tagInput.value; } if (searchInput.value !== '') { fullUrl += `/search/${searchInput.value}`; params.search = searchInput.value; } dispatch(push(fullUrl)); loadPosts(fullUrl, params, false); } else { dispatch(push('/')) loadPosts('/', params, false); } } componentDidMount() { this.initQueryFilter(); } render() { let categoryInput; let tagInput; let searchInput; return ( <div> <form className="query-filter" onSubmit={e => { e.preventDefault(); this.getFilteredPosts(categoryInput, tagInput, searchInput); }}> <i className="header__icon [ icon ion-trash-b ] [ hide-mobile hide-palm ]" onClick={this.goHome}></i> <select className="query-filter__select query-filter__select--category" ref={node => { categoryInput = node}}> <option value="">Categories</option> {Object.keys(this.props.categories).length ? Object.values(this.props.categories).map(category => <option key={category.slug} value={category.slug}>{category.slug}</option>) : <option value="">Loading...</option> } </select> <select className="query-filter__select query-filter__select--tag" ref={node => { tagInput = node}}> <option value="">Tags</option> {Object.keys(this.props.tags).length ? Object.values(this.props.tags).map(tag => <option key={tag.slug} value={tag.slug}>{tag.slug}</option>) : <option value="">Loading...</option> } </select> <input className="query-filter__input query-filter__input--search" type="text" placeholder="search" ref={node => { searchInput = node; }}/> <button className="query-filter__button query-filter__button--submit" type="submit"></button> </form> </div> ) } } export default connect()(TagFilter);
const { Movie } = require('../models') module.exports = { async index(req, res) { try { const movielink = await MovieLink.findOne({ where: { tmdbId : tmdbId } }) res.send(movielink) } catch (err) { res.status(500).send({ error: 'An error has occured trying to fetch the movies' }) } }, }
const express = require("express"); const router = express.Router(); const auth = require("../../middlewares/auth.js"); // Set Chat Route router.get("/", auth.checkLogin, (req, res) => { res.render("./dashboard/chat", { user: req.session.user, chat: req.session.chat }); }); router.get("/room-enter", auth.checkLogin, (req, res) => { res.render("./dashboard/room_enter", { watermark: 'social', url_1: 'deactive', url_2: 'deactive', url_3: 'deactive', url_4: 'deactive', user: req.session.user }); }); router.get("/room-enter/room", auth.checkLogin, (req, res) => { res.render("./dashboard/rooms", { user: req.session.user }); }); module.exports = router;
import index from './index'; import newsletter from './newsletter'; import search from './search'; export default { index, newsletter, search, }
var keystone = require('keystone'); var Types = keystone.Field.Types; /** * Banner Model * ============= */ var Banner = new keystone.List('Banner', { autokey: { from: 'name', path: 'key', unique: true }, track: true }); Banner.add({ name: { type: String, required: true, index: true }, publishedDate: { type: Date, default: Date.now }, imageUrl: { type: Types.Text, initial: true }, HausaImageUrl: { type: Types.Text, initial: true }, YourubeImageUrl: { type: Types.Text, initial: true }, igboImageUrl: { type: Types.Text, initial: true }, description: { type: Types.Text, initial: true }, /*image: { type: Types.CloudinaryImage }, images: { type: Types.CloudinaryImages },*/ }); Banner.register();
import React from "react"; import { EmailIcon, FacebookIcon, LinkedinIcon } from "react-share"; import { withFirebase, storage } from "../Firebase"; //import storage from "../Firebase/firbaseStorage" import { compose } from "recompose"; import { withRouter } from "react-router-dom"; import { AuthUserContext, withAuthorization, withEmailVerification, } from "../Session"; import { Link } from "react-router-dom"; import * as ROUTES from "../../constants/routes.js"; import SignOut from "../SignOut"; import Setting from "../../containers/Account"; // const options = ["username", "profile", "setting"]; class Userprofile extends React.Component { constructor(props) { // console.log("this is the props value:" + props) super(props); this.state = { article: [], username: "", //photoUrl: " ", name: "", email: "", selectedFile: null, image: null, progress: 0, crewDirectory: [], file: "", pics: [], url: "", }; } togglePopup = () => { this.setState({ showPopup: !this.state.showPopup, }); }; onUrlChange = (e) => { this.setState({ url: e.target.value, }); }; upload = (e, authUser) => { e.preventDefault(); console.log("my new url", authUser.uid); const autherId = authUser.uid; this.props.firebase.user(autherId).update({ photoUrl: this.state.url, }); this.setState({ showPopup: false }); }; cancleButton = (e) => { this.setState({ showPopup: false }); }; render() { const { url } = this.state; console.log("pics1", url); let imgPreview; let id; if (this.state.file) { imgPreview = <img src={this.state.file} alt="" />; } return ( <AuthUserContext.Consumer> {(authUser) => ( <div> <div className="dropdown"> <div className="dropbtn"> <i style={{ Color: "#fae596" }}> {" "} <img src={authUser.photoUrl} className="user-profile1" /> </i>{" "} <i className="fa fa-caret-down" style={{ Color: "#fae596" }} /> <div className="dropdown-content"> <div> <span> <img src={authUser.photoUrl} className="user-profile11" /> <div className="PhotoCamera"> <span> <i className="fa fa-camera" aria-hidden="true" onClick={this.togglePopup} /> </span> {this.state.showPopup ? ( <div className="profilewraper"> <div className="prfilecard"> <div> {" "} <button className="canclebutton" onClick={(e) => this.cancleButton(e)} > x </button> </div> <br /> <div className="uploadimage"> <input className="imageinput" type="url" placeholder="Drage and drop your Image-URl" value={this.state.url} onChange={this.onUrlChange} required /> <button className="imageupload" onClick={(e) => this.upload(e, authUser)} > upload Image </button> </div> <br /> <img src={ this.state.url || "http://via.placeholder.com/100x100" } alt="Uploaded images" // height="100" //width="100" /> </div> </div> ) : null} </div> </span> <br /> <br /> <p>{authUser.username}</p> <p>{authUser.email}</p> </div> <div className="AccountsignOut"> <Link to={ROUTES.ACCOUNT}> {" "} <i className="fal fa-cog" style={{ Color: "#fae596" }} /> {" "} UserSetting{" "} </Link> {/* <Link to={ROUTES.SIGNOUT}> {" "} <i class="fa fa-sign-out" aria-hidden="true" style={{ Color: "#fae596" }} ></i> {" "} SignOut{" "} </Link> */} <span> <SignOut/> </span> </div> </div> </div> </div> </div> )} </AuthUserContext.Consumer> ); } } export default withFirebase(Userprofile);
$(function () { $("#tableExcel tr").each(function () { var _this = $(this); // 删除 _this.find(".delpayConfig").click(function () { var id = $(this).attr('data-value'); if (confirm("你确定要把配置,编号为" + id + "删除么?")) { $.ajax({ type: 'POST', url: 'delConfig', data: 'id=' + id, dataType: 'json', success: function (result) { alert(result.msg); if (result.errcode == 0) { window.location.reload(); } }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert(XMLHttpRequest.status); alert(XMLHttpRequest.readyState); alert(errorThrown); alert(textStatus); // paser error; } }); } }); // 编辑 _this.find(".editpayConcif").click(function () { var id = $(this).attr('data-value'); var form = $("#editpayconfigForm").serializeArray(); for (var i = 0; i < form.length; i++) { var name = form[i].name; if (name == null || name == "") { continue; } if(name=="channel_id") { value = $(this).parent().parent().find('[data-name=channel_id]').text(); //(value); optionVerifySet("channelId",parseInt(value)); } value = $(this).parent().parent().find('[data-name=' + name + ']').text(); $("#editpayconfigForm [name=" + name + "]").val(value); } $("#EditConfigModal").modal({backdrop: "static"}).modal('show'); }); }); $("#editPayBtn").click(function () { var Formdata = $("#editpayconfigForm").serializeArray(); $.ajax({ type: 'POST', url: 'editConfig', data: Formdata, dataType: 'json', success: function (result) { alert(result.msg); if (result.errcode == 0) { window.location.reload(); //window.location.href = window.location.href; } } }); }); function optionVerifySet(byid = null, type = null, display = false, serverId = null) { var count = $("#" + byid + " option").length; for (var i = 0; i < count; i++) { var optionstr = $("#" + byid).get(0).options[i].value; if (optionstr == type) { $("#" + byid).get(0).options[i].selected = true; break; } } } // $(".loadConfig").click(function () { var id = $(this).attr('data-value'); $.ajax({ type: 'POST', url: 'loadConfig', data: "id=" + id, dataType: 'json', success: function (result) { alert(result.msg); if (result.errcode == 0) { window.location.reload(); //window.location.href = window.location.href; } } }); }) $("#addPayCofnigBtn").click(function () { var Formdata = $("#addPayConfigForm").serializeArray(); $.ajax({ type: 'POST', url: 'addConfig', data: Formdata, dataType: 'json', success: function (result) { alert(result.msg); if (result.errcode == 0) { //window.location.reload(); window.location.href = 'index'; } } }); }); //请求状态信息 $("#tableExcel tr").each(function() { var _this = $(this); _this.find(".serverInfo").click(function() { var form = $("#logInfoForm").serializeArray(); for(var i=0;i<form.length;i++){ var name = form[i].name; if(name ==null ||name =="") { continue; } var value = $(this).parent().parent().find('[data-name='+name+']').text(); $("#logInfoForm [name="+name+"]").val(value); } //$("#serverinfoModal input[name=id]").val(_this.attr("id")); $("#loginfoModal").modal({backdrop:"static"}).modal('show'); }); }); });
//搜索的初始化,默认初始化一下变量 var url = "http://www.chijiao.org/"; var charset = "gbk"; //var searchTpye = "article"; //实现搜索,触发该方法,跳出搜索结果页面 function getSearchPage(searchTpye, keyword){ switch(searchTpye){ case 'article': url = "ArticleSearch.do?act=search&orderby=pubdate desc&keyword="; charset = "gbk"; break; case 'video': url = "VideoSearch.do?act=search&orderby=pubdate desc&keyword="; charset = "gbk" break; default: url = "AskSearch.do?act=search&orderby=pubdate desc&keyword="; charset = "gbk"; } switch(charset){ case 'utf-8': url = url + urlDecode(keyword); //window.location.href = encodeURI(url); window.open(encodeURI(url)); break; case 'gbk': url = url + urlDecode(keyword); //window.location.href = url; window.open(url); break; default: url = url + escape(keyword); //window.location.href = url; window.open(url); } } // function urlDecode(str){ var ret = ""; for(var i= 0;i<str.length;i++){ var chr = str.charAt(i); if(chr == "+") ret += " "; else if(chr == "%"){ var asc = str.substring(i + 1, i + 3); if(parseInt("0x" + asc) > 0x7f){ ret += asc2str(parseInt("0x" + asc + str.substring(i + 4, i + 6))); i += 5; }else{ ret += asc2str(parseInt("0x" + asc)); i += 2; } }else{ ret += chr; } } return ret; } //响应搜索时候的回车事件,按下回车键相当于点击搜索按钮 function EnterSubmit(){ var _key; document.onkeyup = function(e){ if (e == null) { // ie _key = event.keyCode; } else { // firefox _key = e.which; } if(_key == 13){ document.getElementById("searchSubmit").click(); } } }
//grabs the html div with the id of submit, and adds //a click event listener to it document.getElementById('submit').addEventListener('click', function() { //grabs the value of the input with id num1 var number1 = Number(document.getElementById('num1').value); //grabs the value of the input with id num2 var number2 = Number(document.getElementById('num2').value); //grabs the value of the input with id operation var operation = document.getElementById('operation').value; //grabs the div with the id answer var answer = document.getElementById('answer'); //this is a conditional check to see if operation is //equal to the string 'add'. If true, the code inside //the brackets will be run, if false, it will be skipped //over. your challenge is to finish the code. if (operation === 'add') { //this will add a value to the div answer.innerHTML = // write your code here reset(); return; } if (operation === 'subtract') { //this will add a value to the div answer.innerHTML = // write your code here reset(); return; } if (operation === 'divide') { //this will add a value to the div answer.innerHTML = // write your code here reset(); return; } if (operation === 'multiply') { //this will add a value to the div answer.innerHTML = // write your code here reset(); return; } if (operation === 'modulo') { //this will add a value to the div answer.innerHTML = // write your code here reset(); return; } }) //this simply resets the input fields back to empty function reset() { var number1 = document.getElementById('num1').value = ' '; var number2 = document.getElementById('num2').value = ' '; }
import React from 'react'; import { ScrollView, StyleSheet, View,Image, ImageBackground, AsyncStorage,TouchableOpacity,Alert, SafeAreaView,Linking,Platform,BackHandler } from 'react-native'; import { Container ,Header, StyleProvider,Textarea, Form ,Item,Left,Right,Title,Input, Label,Content,List,CheckBox,Body,ListItem,Text,Button} from 'native-base'; import * as COLOR_CONSTS from '../constants/color-consts'; import * as ROUTE_CONSTS from '../constants/route-consts'; import * as APP_CONSTS from '../constants/app-consts'; import * as API_CONSTS from '../constants/api-constants'; import getTheme from '../../native-base-theme/components'; import material from '../../native-base-theme/variables/platform'; import SubmitButton from '../components/submitButtonSqr'; import Loader from '../components/loader'; import { RNCamera } from 'react-native-camera'; import ImagePicker from 'react-native-image-picker' import { RNS3 } from 'react-native-aws3'; import DocumentPicker from 'react-native-document-picker'; import { NavigationEvents } from 'react-navigation'; import {check, PERMISSIONS, RESULTS} from 'react-native-permissions'; export default class CreatePostScreen extends React.Component { constructor(props){ super(props); this.state = { loading:false, videoSelected: true, photoSelected: false, cameraModeFront: true, camera: true, timer: 0, maxTimer: 61.0, cancle: false, start: true } this.openTextShare = this.openTextShare.bind(this) this.openVideoShare = this.openVideoShare.bind(this) this.openPhotoShare = this.openPhotoShare.bind(this) this.openSurveyShare = this.openSurveyShare.bind(this) this.toggleCamera = this.toggleCamera.bind(this) this.newPost = this.newPost.bind(this) this.pickDocument = this.pickDocument.bind(this) this.pickAudio = this.pickAudio.bind(this) this.closeButtonTapped = this.closeButtonTapped.bind(this) this.updateStart = this.updateStart.bind(this) } componentDidMount(){ BackHandler.addEventListener('hardwareBackPress', this.handleBackButton); } componentWillUnmount = () => { BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton); } handleBackButton() { // ToastAndroid.show('Back button is pressed'); BackHandler.exitApp() return true; } updateStart(){ this.setState({ start:true }) } closeButtonTapped(){ if(this.camera) { this.camera.stopRecording() } clearInterval(this.interval); this.setState({ timer: 0, cancle: true, start:true, camera: false }) this.props.navigation.navigate('Home') } checkPermission(){ if(Platform.OS == "ios") { this.setState({ start:true, camera: true, cancle: false }) check(PERMISSIONS.IOS.CAMERA) .then(result => { switch (result) { case RESULTS.UNAVAILABLE: console.log( 'This feature is not available (on this device / in this context)', ); break; case RESULTS.DENIED: console.log( 'The permission has not been requested / is denied but requestable', ); alert("Uvii needs to access your camera for uploading posts and videos, \n Please go to settings and turn on camera permissions") break; case RESULTS.GRANTED: console.log('The permission is granted'); break; case RESULTS.BLOCKED: console.log('The permission is denied and not requestable anymore'); Alert.alert('Message','Uvii needs to access your camera for uploading posts and videos, \n Please go to settings and turn on camera permissions', [ {text: 'OK', onPress: () =>this.setState ({loading:false}, function(){ // this.forceUpdate() // this.props.navigation.navigate('Home') Linking.canOpenURL('app-settings:').then(supported => { if (!supported) { console.log('Can\'t handle settings url'); } else { return Linking.openURL('app-settings:'); } }).catch(err => console.error('An error occurred', err)); })} ]) break; } }) .catch(error => { // … }); } else{ setTimeout(() => {this.setState({ start:true, camera: true, cancle: false }, function(){ this.forceUpdate() })}, 100) } } newPost(){ // this.props.navigation.navigate(ROUTE_CONSTS.NEW_POST) // alert("Please select options first") } openTextShare(){ this.props.navigation.navigate(ROUTE_CONSTS.ASK_QUESTION) } openSurveyShare(){ this.props.navigation.navigate(ROUTE_CONSTS.CREATE_SURVEY) } pickDocument = async() =>{ try { const res = await DocumentPicker.pick({ type: [DocumentPicker.types.allFiles], }); console.log(res) console.log( res.uri, res.type, // mime type res.name, res.size ); // Platform.OS === 'ios' ? this.uploadDoc( res.uri, res.name, res.type); //: this.uploadAndroidDoc(res) } catch (err) { if (DocumentPicker.isCancel(err)) { // User cancelled the picker, exit any dialogs or menus and move on } else { throw err; } } } pickAudio = async() => { try { const res = await DocumentPicker.pick({ type: [DocumentPicker.types.audio], }); console.log(res) console.log( res.uri, res.type, // mime type res.name, res.size ); this.uploadAudio(res.uri, res.name, res.type); } catch (err) { if (DocumentPicker.isCancel(err)) { // User cancelled the picker, exit any dialogs or menus and move on } else { throw err; } } } uploadAudio(audio, name, type) { this.setState({ loading: true }); var timeStamp = Math.floor(Date.now() / 1000); const file = { uri: audio, name: timeStamp + '.aac', type: type, }; const options = { keyPrefix: 'photos/', bucket: 'photosuvii', region: 'us-east-1', accessKey: 'AKIARHYAPDNBPCVVZPKM', secretKey: '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', successActionStatus: 201, awsUrl: 's3-accelerate.amazonaws.com', useAccelerateEndpoint: true, }; RNS3.put(file, options).then(response => { console.log('response', response) this.setState({ loading: false}); if (response.status !== 201) { throw new Error('Failed to upload audio to S3', response); } console.log('*** BODY ***', response.body); var audioResponse = response.body.postResponse; var audioLocation = audioResponse.location; console.log('*** AUDIO PATH LOCATION ***', audioLocation); this.props.navigation.navigate(ROUTE_CONSTS.NEW_POST, {image:audioLocation, localImage: this.state.image ,type: 6 }) }) .catch(error => { this.setState({ loading: false }); console.log('error',error) }); } openVideoShare(){ this.setState({ videoSelected: true, photoSelected: false, }) } openPhotoShare(){ this.setState({ videoSelected: false, photoSelected: true, }) } toggleCamera(){ this.setState({ cameraModeFront: !this.state.cameraModeFront }) } takePicture = async() => { if (this.camera) { const options = { quality: 0.5, base64: true }; const data = await this.camera.takePictureAsync(options); console.log(data.uri); // this.uploadImage(data.uri) this.props.navigation.navigate(ROUTE_CONSTS.UPLOAD_PHOTO,{image: data}) } else{ alert("Uvii needs to access your camera for uploading posts and videos, \n Please go to settings and turn on camera permissions") } }; _pickImage = async () => { ImagePicker.openPicker({ width: 300, height: 400, cropping: true }).then(image => { // // // this.uploadImage(image) console.log(image); this.props.navigation.navigate(ROUTE_CONSTS.UPLOAD_PHOTO,{image: image}) }); } uploadDoc(doc,name,type){ this.setState({ loading: true }); var timeStamp = Math.floor(Date.now() / 1000); const file = { uri: doc, name: timeStamp + name, type: type, }; const options = { keyPrefix: 'photos/', bucket: 'photosuvii', region: 'us-east-1', accessKey: 'AKIARHYAPDNBPCVVZPKM', secretKey: '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', successActionStatus: 201, awsUrl: 's3-accelerate.amazonaws.com', useAccelerateEndpoint: true, }; RNS3.put(file, options).then(response => { console.log('response', response) if (response.status !== 201) { throw new Error('Failed to upload image to S3', response); } console.log('*** BODY ***', response.body); var imageresponse = response.body.postResponse; var imageLocation = imageresponse.location; // this.state.profileImage = imageLocation; console.log('*** DOC PATH LOCATION ***', imageLocation); // // // let image = this.state.image // image.push(imageLocation) this.setState({ // image: image, currentDoc: imageLocation, loading: false }) this.props.navigation.navigate(ROUTE_CONSTS.NEW_POST, {image:imageLocation, localImage: this.state.image ,type: 3 }) }) .catch(error => { this.setState({ loading: false }); console.log('error',error) }); } // uploadAndroidDoc(res){ // this.setState({ loading: true }); // console.log(global.token) // let url = API_CONSTS.API_BASE_URL+API_CONSTS.API_UPLOAD_FILE; // var formData = new FormData(); // formData.append('file', { // uri: res.uri, // name: res.name, // type: res.type // }); // console.log(url) // fetch(url, {method: 'POST', // headers: { // 'Content-Type': 'multipart/form-data', // }, // body: formData, // },) // .then((response) => { // return response.json() // }) // .then(responseJson => { // this.setState({ loading:false }) // if (response.code === 200) { // console.log('responseJson',responseJson) // this.props.navigation.navigate(ROUTE_CONSTS.NEW_POST, {image:responseJson.documentUrl, localImage: this.state.image ,type: 3 }) // } // }) // .catch((error) => { // alert(JSON.stringify(error.message)) // this.setState({ // loading:false // }) // }); // } uploadImage(image) { var timeStamp = Math.floor(Date.now() / 1000); const file = { uri: image, name: timeStamp + '.png', type: 'image/png' }; const options = { keyPrefix: 'photos/', bucket: 'photosuvii', region: 'us-east-1', accessKey: 'AKIARHYAPDNBPCVVZPKM', secretKey: '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', successActionStatus: 201, awsUrl: 's3-accelerate.amazonaws.com', useAccelerateEndpoint: true }; RNS3.put(file, options).then(response => { console.log('response', response) if (response.status !== 201) { throw new Error('Failed to upload image to S3', response); } console.log('*** BODY ***', response.body); var imageresponse = response.body.postResponse; var imageLocation = imageresponse.location; // this.state.profileImage = imageLocation; console.log('*** IMAGE PATH LOCATION ***', imageLocation); // // // let image = this.state.image // image.push(imageLocation) this.setState({ // image: image, currentImage: imageLocation }) // this.updateProfileDeatils() }); } takeVideo = async() => { // if (this.camera) { // const options = { quality: 0.5, base64: true }; // const data = await this.camera.takePictureAsync(options); // console.log("Thumb Video: " + data.uri); // this.setState({ // videoThumb: data.uri // }) // } if (this.camera) { if(this.state.timer > 0 ) { console.log("STOP") this.camera.stopRecording() clearInterval(this.interval); this.setState({ timer: 0, cancle: false, start:false }) } else{ if(this.state.start) { this.setState({ start:false }) this.interval = setInterval( () => this.setState((prevState)=> ({ timer: prevState.timer + 1 })), 1000 ); console.log("START") const options = {quality: RNCamera.Constants.VideoQuality['480p'],videoBitrate: 1*1024*1024,maxDuration:this.state.maxTimer ,base64: true }; const data = await this.camera.recordAsync(options) console.log(data.uri); clearInterval(this.interval); this.setState({ timer: 0, }) if(this.state.cancle){ } else{ console.log("MOVE TO NEXT") this.props.navigation.navigate(ROUTE_CONSTS.UPLOAD_VIDEO,{video: data, videoThumb: this.state.videoThumb,onGoBack: this.updateStart }) } } } } else{ alert("Uvii needs to access your camera for uploading posts and videos, \n Please go to settings and turn on camera permissions") } }; GetSelectedPickerItemNew = async () => { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, mediaType:'video', storageOptions: { skipBackup: true, }, }; // GetSelectedPickerItem // mediaType:'mixed', ImagePicker.launchImageLibrary(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { let source = { uri: response.uri }; // You can also display the image using data: // let source = { uri: 'data:image/jpeg;base64,' + response.data }; console.log("Selected Video Details") console.log(response) console.log(response.uri) // let url = this.uploadImage(response.uri) // this.uploadDoc(response) // .then(url => { console.log(url); this.setState({profilePic: url,loading:false,avatarSource: url,flag:true}) }) // .catch(error => console.log(error)) if(response.type == undefined) { this.props.navigation.navigate(ROUTE_CONSTS.UPLOAD_VIDEO,{video: source, videoThumb: source.uri,onGoBack: this.updateStart}) this.setState({ // avatarSource: source, loading: false }); } else{ // this.props.navigation.navigate(ROUTE_CONSTS.UPLOAD_PHOTO,{image: source}) // this.setState({ // // avatarSource: source, // loading: false // }); this.props.navigation.navigate(ROUTE_CONSTS.UPLOAD_VIDEO,{video: source, videoThumb: source.uri,onGoBack: this.updateStart}) this.setState({ // avatarSource: source, loading: false }); } } }); } GetSelectedPickerItem = async () => { const options = { quality: 1.0, maxWidth: 500, maxHeight: 500, mediaType: 'photo', storageOptions: { skipBackup: true, }, }; // GetSelectedPickerItem ImagePicker.launchImageLibrary(options, (response) => { console.log('Response = ', response); if (response.didCancel) { console.log('User cancelled photo picker'); } else if (response.error) { console.log('ImagePicker Error: ', response.error); } else if (response.customButton) { console.log('User tapped custom button: ', response.customButton); } else { let source = { uri: response.uri }; // You can also display the image using data: // let source = { uri: 'data:image/jpeg;base64,' + response.data }; console.log(response.uri) // let url = this.uploadImage(response.uri) // this.uploadDoc(response) // .then(url => { console.log(url); this.setState({profilePic: url,loading:false,avatarSource: url,flag:true}) }) // .catch(error => console.log(error)) this.props.navigation.navigate(ROUTE_CONSTS.UPLOAD_PHOTO,{image: source}) this.setState({ // avatarSource: source, loading: false }); } }); } render() { return ( <StyleProvider style={getTheme(material)}> <Container style={styles.container}> <NavigationEvents onWillFocus={() => { this.checkPermission() }} /> <Loader loading={this.state.loading} /> {this.state.camera ? <TouchableOpacity style={{flex:1}} onPress={()=>{console.log("Test")}}> {this.state.cameraModeFront ? <RNCamera ref={ref => { this.camera = ref; }} captureQuality={'480p'} defaultVideoQuality={RNCamera.Constants.VideoQuality["480p"]} style={styles.preview} type={RNCamera.Constants.Type.front} flashMode={RNCamera.Constants.FlashMode.off} androidCameraPermissionOptions={{ title: 'Permission to use camera', message: 'We need your permission to use your camera', buttonPositive: 'Ok', buttonNegative: 'Cancel', }} androidRecordAudioPermissionOptions={{ title: 'Permission to use audio recording', message: 'We need your permission to use your audio', buttonPositive: 'Ok', buttonNegative: 'Cancel', }} // onGoogleVisionBarcodesDetected={({ barcodes }) => { // console.log(barcodes); // }} /> : <RNCamera ref={ref => { this.camera = ref; }} style={styles.preview} type={RNCamera.Constants.Type.back} flashMode={RNCamera.Constants.FlashMode.off} captureQuality={'480p'} defaultVideoQuality={RNCamera.Constants.VideoQuality["480p"]} androidCameraPermissionOptions={{ title: 'Permission to use camera', message: 'We need your permission to use your camera', buttonPositive: 'Ok', buttonNegative: 'Cancel', }} androidRecordAudioPermissionOptions={{ title: 'Permission to use audio recording', message: 'We need your permission to use your audio', buttonPositive: 'Ok', buttonNegative: 'Cancel', }} // onGoogleVisionBarcodesDetected={({ barcodes }) => { // console.log(barcodes); // }} /> } {/* <View style={{ flex: 0.2, flexDirection: 'row', justifyContent: 'center' }}> <TouchableOpacity onPress={this.takePicture.bind(this)} style={styles.capture}> <Text style={{ fontSize: 14 }}> SNAP </Text> </TouchableOpacity> </View> */} <View style={{height:60,backgroundColor:COLOR_CONSTS.APP_SEMI_TRANSPARENT_COLOR, flexDirection:'row',position:'absolute',top:0,width:'100%',marginTop:20,padding:10}}> <Left> <View style={{ padding: 10, marginTop: 0, alignItems: "flex-start" }}> <TouchableOpacity onPress={this.closeButtonTapped}> <Image source={require('../../assets/close.png')} style={{ width: 20, height: 20, resizeMode: 'contain' }} /> </TouchableOpacity> </View> </Left> <Body style={{flex:3}}> {this.state.videoSelected && this.state.timer < 10 ? <Title style={styles.title}>00:00:0{this.state.timer}</Title> : this.state.videoSelected && this.state.timer > 9 && this.state.timer <= 59 ? <Title style={styles.title}>00:00:{this.state.timer}</Title> : this.state.videoSelected && this.state.timer == 60 ? <Title style={styles.title}>00:01:00</Title> : null} </Body> <Right> {/* <TouchableOpacity onPress={this.newPost}> <Image source={require('../../assets/arrowFw.png')} style={{ width: 20, height: 20, resizeMode: 'contain' }} /> </TouchableOpacity> */} </Right> </View> <View style={{height:110,backgroundColor:COLOR_CONSTS.APP_SEMI_TRANSPARENT_COLOR,flexDirection:'column',position:'absolute',bottom:0,width:'100%'}}> {this.state.timer == 0 ? <View style={{flexDirection:'row',backgroundColor:'transparent',height:40,justifyContent:'center'}}> <ScrollView horizontal={true} > {this.state.photoSelected ? <Button transparent onPress={this.GetSelectedPickerItem} style={{marginLeft:-10}}> <Text style={{color:COLOR_CONSTS.APP_WHITE_COLOR,fontSize:11}}>LIBRARY</Text> </Button> : <Button transparent onPress={this.GetSelectedPickerItemNew} style={{marginLeft:-10}}> <Text style={{color:COLOR_CONSTS.APP_WHITE_COLOR,fontSize:11}}>LIBRARY</Text> </Button> } <Button transparent onPress={this.openSurveyShare}> <Text style={{color:COLOR_CONSTS.APP_WHITE_COLOR,fontSize:11}}>SURVEY</Text> </Button> <Button transparent onPress={this.openVideoShare}> {this.state.videoSelected ? <Text style={{color:COLOR_CONSTS.APP_ORANGE_COLOR,fontSize:11}}>VIDEO</Text> : <Text style={{color:COLOR_CONSTS.APP_WHITE_COLOR,fontSize:11}}>VIDEO</Text> } </Button> <Button transparent onPress={this.openPhotoShare} style={{marginRight:-10}}> {this.state.photoSelected ? <Text style={{color:COLOR_CONSTS.APP_ORANGE_COLOR,fontSize:11}}>PHOTO</Text> : <Text style={{color:COLOR_CONSTS.APP_WHITE_COLOR,fontSize:11}}>PHOTO</Text> } </Button> <Button transparent onPress={this.pickDocument} style={{marginRight:-10}}> <Text style={{color:COLOR_CONSTS.APP_WHITE_COLOR,fontSize:11}}>DOCUMENT</Text> </Button> <Button transparent onPress={this.pickAudio} style={{marginRight:-10}}> <Text style={{color:COLOR_CONSTS.APP_WHITE_COLOR,fontSize:11}}>AUDIO</Text> </Button> </ScrollView > </View> : <View style={{flexDirection:'row',backgroundColor:'transparent',height:40,justifyContent:'center',alignItems:'center'}}> <Text style={{color:COLOR_CONSTS.APP_ORANGE_COLOR,fontSize:11}}>VIDEO</Text> </View> } <View style={{flexDirection:'row',justifyContent:'space-between',margin:10,marginLeft:43,marginTop:-15,backgroundColor:'transparent',height:90,alignItems:'center'}}> {this.state.photoSelected ? <TouchableOpacity style={{}} onPress={this.GetSelectedPickerItem}> {/* <Image source={require('../../assets/gallery.jpg')} style={{ width: 35, height: 35, resizeMode: 'stretch' }} /> */} </TouchableOpacity> : <TouchableOpacity style={{}} onPress={this.GetSelectedPickerItemNew}> {/* <Image source={require('../../assets/gallery.jpg')} style={{ width: 35, height: 35, resizeMode: 'stretch' }} /> */} </TouchableOpacity> } {this.state.photoSelected ? <TouchableOpacity style={{borderWidth:2,borderRadius:24,padding:1,borderColor:'white'}} onPress={this.takePicture.bind(this)}> <View style={{ width: 46, height: 46, backgroundColor:'white', borderRadius:23 }} /> </TouchableOpacity> : this.state.timer == 0 ? <TouchableOpacity style={{borderWidth:2,borderRadius:24,padding:1,borderColor:'white'}} onPress={this.takeVideo.bind(this)}> <View style={{ width: 46, height: 46, backgroundColor:'red', borderRadius:23 }} /> </TouchableOpacity> : <TouchableOpacity style={{borderWidth:2,borderRadius:24,padding:10,borderColor:'white'}} onPress={this.takeVideo.bind(this)}> <View style={{ width: 30, height: 30, backgroundColor:'red', borderRadius:5 }} /> </TouchableOpacity> } <TouchableOpacity style={{}} onPress={this.toggleCamera}> { this.state.timer == 0 ? <Image source={require('../../assets/cameraToggle.png')} style={{ width: 35, height: 35, resizeMode: 'contain' }} /> : <View style={{ width: 35, height: 35, resizeMode: 'contain' }}></View> } </TouchableOpacity> </View> </View> </TouchableOpacity> : null} </Container> </StyleProvider> ); } } const styles = StyleSheet.create({ container: { backgroundColor:COLOR_CONSTS.APP_OFF_WHITE_COLOR, flex:1 }, headerStyle:{ backgroundColor:COLOR_CONSTS.APP_BLACK_COLOR }, title:{ color:COLOR_CONSTS.APP_WHITE_COLOR, fontSize: 18, fontWeight:'bold' }, preview: { flex: 1, justifyContent: 'flex-end', alignItems: 'center', }, capture: { flex: 0, backgroundColor: '#fff', borderRadius: 5, padding: 15, paddingHorizontal: 20, alignSelf: 'center', margin: 20, }, });
var searchData= [ ['main',['main',['../main_8cpp.html#ae66f6b31b5ad750f1fe042a706a4e3d4',1,'main.cpp']]], ['med',['med',['../class_student.html#a38b3e368f66757d5ab99fea91e579024',1,'Student']]], ['medcalc',['medCalc',['../class_student.html#a3d9abf4e847a325a49ba91e07d6f9594',1,'Student::medCalc()'],['../funk_8h.html#abbe2127df5bad35ec0e6edcb484fe829',1,'medCalc():&#160;funk.h']]] ];
import Layout from "../../../components/Layout"; import axios from "axios"; import {useEffect, useState} from "react"; import {env} from "../../../next.config"; import Link from "next/link"; import reactHtml from "react-render-html"; import moment from "moment"; import InfiniteScroll from 'react-infinite-scroller'; import withAdmin from "../../withAdmin"; import {getCookie} from '../../../helpers/auth'; import Router from "next/router"; const Links = ({links, totalLinks, linksLimit, linkSkip, token}) => { const [setLinks, setLinksState] = useState(links); // to determine load more or not const [setLimit, setLimitState] = useState(linksLimit); const [setSkip, setSkipState] = useState(0); const [setSize, setSizeState] = useState(totalLinks); const checkDelete = (event, id) => { event.preventDefault(); const popUpConfirm = window.confirm("Do yo want to delete category?"); if (popUpConfirm) { handleDelete(id); } } const handleDelete = async (id) => { try { const response = await axios.delete(`${env.API}/link/admin/${id}`, { headers: { Authorization: `Bearer ${token}` } }); console.log("Link delete successfully: ", response); // once deleted link, it still in browser; unless refetch from backend process.browser && window.location.reload(); } catch(error) { console.log("link delete failed: ", error); } } const allLinks = () => { return ( setLinks.map((link, index) => { return ( <div className="row"> <div className="col-md-8 filter-drop-shadow box"> <a className="custom text-secondary" href={link.url} target="_blank"> <h3 onClick={() => handleClick(link._id)} className="title-width">{link.title}</h3> </a> <div className="col-md-4"> <span className="badge text-dark">{moment(link.createdAt).fromNow()} added by {link.postedBy.name}</span> {/* <span className="badge text-dark">{moment(link.createdAt).fromNow()} added by </span> */} </div> <div className="col-md-12"> <span className="badge text-dark"> {link.type} </span> <span className="badge text-dark"> {link.medium} </span> {link.categories.map((link, index) => { return <span className="badge text-dark">{link.name}</span> })} </div> <span className="badge text-dark">{link.views} views</span> <span onClick={(event) => checkDelete(event, link._id)} className="badge text-dark">Delete</span> <Link href={`/user/link/${link._id}`}> <a className="custom"><span className="badge text-dark">Update</span></a> </Link> </div> </div> ) }) ) } const handleLoad = async () => { let Skips = setSkip + setLimit; const response = await axios.post(`${env.API}/links/`, {skip: Skips, limit: setLimit}, { headers: { Authorization: `Bearer ${token}` } }) setLinksState([...setLinks, ...response.data]) setSizeState(response.data.length); setSkipState(Skips); } // const loadButton = () => { // return ( // setSize > 0 && setSize >= setLimit && ( // <div className="text-center"> // <button onClick={handleLoad} className="btn btn-lg btn-secondary">Load more links</button> // </div> // ) // ) // } return ( <Layout> <div className="row"> <div className="col-md-12"> <h1>All links</h1> </div> </div> <br/> <div className="row" style={{"paddingTop": "150px"}}> <div className="col-md-4"> <h2>top trending</h2> <p>show links</p> </div> <div className="col-md-8"> {allLinks()} {/* {loadButton()} */} </div> <div className="row"> <div className="col-md-4"></div> <div className="col-md-8 text-center"> <InfiniteScroll pageStart={0} loadMore={handleLoad} hasMore={setSize > 0 && setSize >= setLimit } // loader={<div className="loader" key={0}>Loading ...</div>} loader={<img key={0} className="custom-image" src="/static/images/loading.gif" alt="loading" />} > </InfiniteScroll> </div> </div> </div> </Layout> ) }; Links.getInitialProps = async ({req}) => { let skip = 0; let limit = 2; const token = getCookie("token", req) // get slug from query const response = await axios.post(`${env.API}/links/`, {skip, limit}, { headers: { Authorization: `Bearer ${token}` } }) return { links: response.data, totalLinks: response.data.length, linksLimit: limit, linkSkip: skip, token } } export default withAdmin(Links);
var express = require('express'), router = express.Router(), mongoose = require('mongoose'), Team = mongoose.model('Team'); module.exports = function(app) { app.use('/', router); }; router.get('/', function(req, res, next) { res.render('index', { "title": "API SmartBoxTV" }); }); router.get('/api/teams/', function(req, res, next) { Team.find(function(err, teams) { if (err) return next(err); res.json(teams); }); }); router.get('/api/teams/:idTeam/players', function(req, res, next) { Team.findById(req.params.idTeam).populate('players').exec(function(err, team) { if (err) return next(err); res.json({ "team": team.name, "players": team.players }) }); }); router.get('/api/active_teams/players', function(req, res, next) { Team.getActives().populate('players').exec(function(err, teams) { if (err) return next(err); res.json(teams); }); });
class MovingBlock { position = {x: 0, y: 0, z: 0}; mesh = null; shape = null; type = null; boundingBox = null; scene = null; constructor(scene, boundingBox) { this.boundingBox = boundingBox; this.scene = scene; } rotate = (x, y, z) => { // converting angles to radians this.mesh.rotation.x += x * Math.PI / 180; this.mesh.rotation.y += y * Math.PI / 180; this.mesh.rotation.z += z * Math.PI / 180; for (let i = 0; i < this.shape.length; i++) { let vector = Utils.cloneVector(SHAPES[this.type][i]); this.shape[i] = new THREE.Vector3(vector.x, vector.y, vector.z).applyEuler(this.mesh.rotation); Utils.roundVector(this.shape[i]); } if (this.checkCollision(false) === COLLISION.WALL) { this.rotate(-x, -y, -z); } }; move = (x ,y, z) => { this.mesh.position.x += x * CUBE.size; this.mesh.position.y += y * CUBE.size; this.mesh.position.z += z * CUBE.size; this.position.x += x; this.position.y += y; this.position.z += z; switch(this.checkCollision(z != 0)) { case COLLISION.WALL: this.move(-x, -y, 0); break; case COLLISION.GROUND: this.hitBottom(); break; } this.boundingBox.checkIfLevelCompleted(); }; convertToStatic = () => { for(let i = 0 ; i < this.shape.length; i++) { this.boundingBox.addStaticBlock(this.position.x + this.shape[i].x, this.position.y + this.shape[i].y, this.position.z + this.shape[i].z); this.boundingBox.blocks[this.position.x + this.shape[i].x][this.position.y + this.shape[i].y][this.position.z + this.shape[i].z] = FIELD.STATIC; } }; checkCollision = (ground_check) => { for(let i = 0; i < this.shape.length; i++) { if ( this.shape[i].x + this.position.x < 0 || this.shape[i].x + this.position.x >= BOUNDING_BOX.splitX || this.shape[i].y + this.position.y < 0 || this.shape[i].y + this.position.y >= BOUNDING_BOX.splitY ) return COLLISION.WALL; if (this.boundingBox.blocks[this.position.x + this.shape[i].x][this.position.y + this.shape[i].y][this.position.z + this.shape[i].z - 1] === FIELD.STATIC) { return ground_check ? COLLISION.GROUND : COLLISION.WALL; } if (this.shape[i].z + this.position.z <= 0) { return COLLISION.GROUND; } } }; generate = () => { this.type = Math.floor(Math.random() * SHAPES.length); this.shape = []; for (let i = 0; i < SHAPES[this.type].length; i++) { this.shape[i] = Utils.cloneVector(SHAPES[this.type][i]); } let geometry = new THREE.CubeGeometry(CUBE.size, CUBE.size, CUBE.size); for(let i = 1 ; i < this.shape.length; i++) { let tmpGeometry = new THREE.Mesh(new THREE.CubeGeometry(CUBE.size, CUBE.size, CUBE.size)); tmpGeometry.position.x = CUBE.size * this.shape[i].x; tmpGeometry.position.y = CUBE.size * this.shape[i].y; THREE.GeometryUtils.merge(geometry, tmpGeometry); } this.mesh = Utils.createMultiMaterialObject( geometry, [ new THREE.MeshBasicMaterial({color: 0x000000, flatShading: true, wireframe: true, transparent: true}), new THREE.MeshBasicMaterial({color: 0x9c4406}) ] ); this.position = { x: Math.floor(BOUNDING_BOX.splitX / 2) - 1, y: Math.floor(BOUNDING_BOX.splitY / 2) - 1, z: 16 }; this.mesh.position.x = (this.position.x - BOUNDING_BOX.splitX / 2) * CUBE.size / 2; this.mesh.position.y = (this.position.y - BOUNDING_BOX.splitY / 2) * CUBE.size / 2; this.mesh.position.z = (this.position.z - BOUNDING_BOX.splitZ / 2) * CUBE.size + CUBE.size / 2; this.mesh.overdraw = true; if(this.checkCollision(true) === COLLISION.GROUND) { isGameOver = true; document.getElementById('game-over').style.display = 'flex'; } this.scene.add(this.mesh); } hitBottom = () => { this.convertToStatic(); this.scene.remove(this.mesh); this.generate(); }; }
import React from 'react'; import Prism from '../Prism'; import LiLink from '../LiLink'; import Droids from '../../../../src'; import { Label } from 'react-bootstrap'; import { IndexLink } from 'react-router'; class ApiDocs extends React.Component { renderHome() { return ( <div> <Prism className="language-jsx"> { `import MyReactComponent from 'my-react-component';` } </Prism> <p>&nbsp;</p> <p className="lead">Examples:</p> <div className="panel panel-default"> <div className="panel-heading"> <h3 className="panel-title">Default mode</h3> </div> <div className="panel-body"> <Droids /> </div> <div className="panel-footer"> <Label bsSize="small">Code:</Label> <Prism className="language-jsx"> { `<MyReactComponent />` } </Prism> </div> </div> <div className="panel panel-default"> <div className="panel-heading"> <h3 className="panel-title">Disable display name</h3> </div> <div className="panel-body"> <Droids name={ false } /> </div> <div className="panel-footer"> <Label bsSize="small">Code:</Label> <Prism className="language-jsx"> { `<MyReactComponent name={ false } />` } </Prism> </div> </div> </div> ); } renderSidebar() { return ( <ul className="ascii fixed"> <li> <IndexLink activeClassName="active" to="/api_docs">MyReactComponent</IndexLink> <ul> <LiLink to="/api_docs/set_config">setConfig</LiLink> </ul> </li> </ul> ); } render() { return ( <div id="top"> <p>&nbsp;</p> <div className="container"> <div className="row"> <div className="col-xs-3 ascii"> { this.renderSidebar() } </div> <div className="col-md-9"> { this.props.children || this.renderHome() } </div> </div> </div> </div> ); } } export default ApiDocs;
import React from 'react'; import JobDetailsForm from '../forms/job-details-form'; const JobDetailsArea = ({item}) => { return ( <> <div className="job-details-info pt-120 pb-100"> <div className="container"> <div className="row"> <div className="col-xl-6 col-lg-6"> <div className="jobdetails"> <div className="jobdetails__subtitle"> <h5 className="jb-subtitle">Ongoing</h5> </div> <div className="jobdetails__title"> <h4 className="job-title pb-10">{item?.title}</h4> <span>Product Management</span> </div> <div className="jobdetails__paragraph"> <p className="pb-20">{"We're"} looking for a new Product Manager to join our 14-people Product Management team. Check out our {"Team's"} expert blog here. :) </p> <p className="pb-30">Since last year, {"we've"} been building a new team of <b>Product Managers.</b> Our goal is to build world-class products, elevate the product strategy and execution support we deliver to our clients. </p> </div> <div className="jobdetails__feature"> <ul> <li> <i className="fal fa-check"></i> <span>Salary :</span> base salary + salary review every 6 months</li> <li> <i className="fal fa-check"></i> <span>Perks : </span> + 1 000 PLN home office bonus, Multisport card, private health insurance, discounts on Apple products, development budget, and more!</li> <li> <i className="fal fa-check"></i> <span>B2B : </span> +16 paid days off</li> <li> <i className="fal fa-check"></i> <span>Required skills :</span> 2-year experience in managing complex digital products; C1+ English; experience in Agile</li> <li> <i className="fal fa-check"></i> <span>B2B :</span> +16 paid days off</li> <li> <i className="fal fa-check"></i> <span>Location : </span> Poznań, remotely in Poland, remotely in the EU </li> </ul> </div> <div className="jobdetails__img"> <img src="/assets/img/job/job-1.jpg" alt="" /> </div> <div className="jobdetails__title"> <h4 className="job-title pb-20">Your responsibilities :</h4> </div> <div className="jobdetails__paragraph"> <p className="mb-30">Our mission at Nerox is to help entrepreneurs and innovators shape the world through beautiful software. We care about trust, taking ownership, and transparency. As a Certified B Corporation®, we offer a safe, inclusive and productive environment for all team members, and we’re always open to feedback.</p> </div> <div className="jobdetails__feature jobdetails__feature-2"> <ul> <li> <i className="fal fa-check"></i> <span>Supporting Nerox’s clients in developing a viable vision, strategy, and roadmap for their products.</span> Working on product discovery and development in order to increase the {"client's"} business value.</li> <li> <i className="fal fa-check"></i> <span>Gaining a deep understanding of our customers’ needs, requirements, and objectives</span> through taking part in market research, experimentation, user testing, implementing continuous feedback systems, and performing data analysis.</li> <li> <i className="fal fa-check"></i> <span>Supporting Nerox’s clients in developing a viable vision, strategy, and roadmap for their products.</span> Working on product discovery and development in order to increase the {"client's"} business value.</li> <li> <i className="fal fa-check"></i> <span>Required skills :</span> 2-year experience in managing complex digital products; C1+ English; experience in Agile</li> <li> <i className="fal fa-check"></i> <span>Gaining a deep understanding of our customers’ needs, requirements, and objectives</span> through taking part in market research, experimentation, user testing, implementing continuous feedback systems, and performing data analysis.</li> <li> <i className="fal fa-check"></i> <span>Location : </span> Poznań, remotely in Poland, remotely in the EU </li> </ul> </div> <div className="jobdetails__title"> <h4 className="job-title pb-15">All About Collax </h4> </div> <div className="jobdetails__paragraph"> <p>Our mission at Netguru is to help entrepreneurs and innovators shape the world through beautiful software. We care about trust, taking ownership, and transparency. As a Certified B Corporation®, we offer a safe, inclusive and productive environment for all team members, and we’re always open to feedback. </p> </div> </div> </div> <div className="col-xl-6 col-lg-6"> <div className="tpcontact"> <div className="tpcontact__form tpcontact__form-2"> <JobDetailsForm/> </div> </div> </div> </div> </div> </div> </> ); }; export default JobDetailsArea;
const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const CrittersPlugin = require('critters-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); module.exports = { entry: { main: './src/js/main.js' }, output: { path: path.resolve(__dirname, 'dist'), filename: '[name].[chunkhash].js' }, module: { rules: [{ test: /\.(sass|scss|css)$/i, use: [{ loader: MiniCssExtractPlugin.loader }, { loader: 'css-loader', }, { loader: 'sass-loader', options: { includePaths: ['node_modules'] } }] }] }, plugins: [ new CleanWebpackPlugin('dist'), new HtmlWebpackPlugin({ template: './src/index.html', chunks: ['main'], minify: { removeRedundantAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true } }), new MiniCssExtractPlugin({ filename: "[name].[contenthash].css", chunkFilename: "[id].[contenthash].css", }), new CrittersPlugin() ] };
appicenter.factory('loginService', ['$firebaseSimpleLogin', function($firebaseSimpleLogin) { var ref = new Firebase('https://appicenter.firebaseio.com/'); return $firebaseSimpleLogin(ref); }]);
import React from 'react'; import {Panel, Image} from 'react-bootstrap'; import PostActions from './PostActions'; import parseDate from '../../helpers/date'; class Post extends React.Component{ render(){ let {post} = this.props; return ( <Panel className="post"> <Panel.Heading> <div className="author"> <Image className="photo" src={post.author.photo} circle /> <span className="name">{post.author.name}</span> </div> <div className="post-date"> {parseDate(post.date)} </div> </Panel.Heading> <Panel.Body> {post.publication} </Panel.Body> <PostActions post={post} reloadPost={()=>this.props.reloadPost()} /> </Panel> )} } export default Post;
import { get, post, upload } from "../http"; export async function popular() { return get("/trending"); } export async function top(type) { return get(type === "movie" ? "/top/movies" : "/top/shows"); } export async function history(user_id, type) { return post("/history", { id: user_id, type }); } export async function getBandwidth() { return get("/history/bandwidth"); } export async function getServerInfo() { return get("/history/server"); } export async function getCurrentSessions() { return get("/sessions"); } export async function get_plex_media(id, type) { return get(`/plex/lookup/${type}/${id}`); } export async function movie(id = false, minified) { if (!id) return Promise.resolve(false); return get(`/movie/lookup/${id}${minified ? "/minified" : ""}`); } export async function series(id = false, minified) { if (!id) return Promise.resolve(false); return get(`/show/lookup/${id}${minified ? "/minified" : ""}`); } export async function person(id = false) { if (!id) return Promise.resolve(false); return get(`/person/lookup/${id}`); } export async function search(title = false) { return get(`/search/${encodeURIComponent(title)}`); } export async function actor(id = false) { if (!id) return Promise.resolve(false); return get(`/person/lookup/${id}`); } export async function checkConfig() { return get("/config"); } export async function saveConfig(config) { return post(`/setup/set`, config); } export async function updateConfig(config) { return post(`/config/update`, config); } export async function sonarrConfig() { return get(`/services/sonarr/config`); } export async function saveSonarrConfig(config) { return post(`/services/sonarr/config`, config); } export async function testSonarr(id) { return get(`/services/sonarr/test/${id}`); } export async function sonarrPaths(id) { return get(`/services/sonarr/paths/${id}`); } export async function sonarrProfiles(id) { return get(`/services/sonarr/profiles/${id}`); } export async function sonarrTags(id) { return get(`/services/sonarr/tags/${id}`); } export async function radarrConfig() { return get(`/services/radarr/config`); } export async function radarrPaths(id) { return get(`/services/radarr/paths/${id}`); } export async function radarrProfiles(id) { return get(`/services/radarr/profiles/${id}`); } export async function radarrTags(id) { return get(`/services/radarr/tags/${id}`); } export async function testRadarr(id) { return get(`/services/radarr/test/${id}`); } export function saveRadarrConfig(config) { return post(`/services/radarr/config`, config); } export function saveEmailConfig(config) { return post(`/mail/create`, { email: config }); } export function getEmailConfig() { return get(`/mail/config`); } export function getConfig() { return get(`/config/current`); } export function testEmail() { return get(`/mail/test`); } export function testDiscord() { return get(`/hooks/discord/test`); } export function testTelegram() { return get(`/hooks/telegram/test`); } export async function getUser(id) { return get(`/user/${id}`); } export async function allUsers() { return get(`/user/all`); } export function testServer(server) { return post(`/setup/test_server`, { server }); } export function testMongo(mongo) { return post(`/setup/test_mongo`, { mongo }); } export function getIssues() { return get(`/issue/all`); } export function createUser(user) { return post(`/user/create_custom`, { user }); } export function getProfiles() { return get(`/profiles/all`); } export function saveProfile(profile) { return post(`/profiles/save_profile`, { profile }); } export function deleteProfile(profile) { return post(`/profiles/delete_profile`, { profile }); } export function editUser(user) { return post(`/user/edit`, { user }); } export function deleteUser(user) { return post(`/user/delete_user`, { user }); } export function bulkEditUser(data) { return post(`/user/bulk_edit`, data); } export function removeReq(request, reason) { return post(`/request/remove`, { request, reason }); } export function updateReq(request, servers) { return post(`/request/update`, { request, servers }); } export function getConsole() { return get(`/logs/stream`); } export function getReviews() { return get(`/review/all`); } export function removeIssue(id, message) { return post(`/issue/remove`, { id, message }); } export function updateFilters(movie, tv) { return post(`/filter/update`, { movie, tv }); } export function getFilters() { return get(`/filter`); } export function uploadThumb(data, id) { return upload(`/user/thumb/${id}`, data); } export function testPlex() { return get(`/plex/test_plex`); } export function updatePlexToken() { return get(`/plex/update_token`); }
var carrinhos = []; var cervo; var elefante; var frango; var tartaruga; var girafa; var kermit; var ourico; var ovelha; var pinguim; var ursoNatal; var urso; var hipopotamo; function Produto(codigo, nome, preco, peso){ this.codigo = codigo; //this.foto; this.nome = nome; //this.descricao; this.preco = preco; this.peso = peso; this.getNome = function(){ return this.nome; } this.getCodigo = function(){ return this.codigo; } this.getPreco = function(){ return this.preco; } this.getPeso = function(){ return this.peso; } /*this.getDescricao = function(){ return this.descricao; } this.getFoto = function(){ return this.foto; } */ } function Carrinho(dono){ this.dono = dono; this.produtos = []; } function Entrar(){ var carrinho; var nome = document.getElementById('nomeLogin').value; var x = carrinhos.length; if(x > 0){ for(var i = 0; i < x; i++){ if(clientes[i].getNome() == nome){ carrinho = carrinhos[i]; carrinhos.splice(i, 1); }else{ carrinho = new Carrinho(nome); } } }else{ carrinho = new Carrinho(nome); } console.log(carrinho); } function listaDeProdutos(){ cervo = new Produto(1, 'Cervo', 'R$ 39.90', 1); elefante = new Produto(2, 'Elefante', 'R$ 49.90', 2); frango = new Produto(3, 'Frango', 'R$ 29.90', 1); tartaruga = new Produto(4, 'Tartaruga', 'R$ 59.90', 1); girafa = new Produto(5, 'Girafa', 'R$ 59.90', 1); kermit = new Produto(6, 'Sapo Kermit', 'R$ 59.90', 1); ourico = new Produto(7, 'Ouriço', 'R$ 39.90', 1); ovelha = new Produto(8, 'Ovelha', 'R$ 49.90', 1); pinguim = new Produto(9, 'Pinguim', 'R$ 49.90', 1); ursoNatal = new Produto(11, 'Urso Natalino', 'R$ 29.90', 1); urso = new Produto(12, 'Urso Doentinho', 'R$ 29.90', 1); hipopotamo = new Produto(12, 'Hopopótamo', 'R$ 39.90', 2); console.log(cervo); document.getElementById("cervo-nome").innerHTML = cervo.getNome(); //document.getElementById("cervo-preco").innerHTML = cervo.getPreco(); //document.getElementById("elefante-nome").innerHTML = elefante.getNome(); //document.getElementById("elefante-preco").innerHTML = elefante.getPreco(); //document.getElementById('numberMatch').innerHTML; //document.getElementById('numberMatch').innerHTML; //document.getElementById('numberMatch').innerHTML; //document.getElementById('numberMatch').innerHTML; //document.getElementById('numberMatch').innerHTML; //document.getElementById('numberMatch').innerHTML; //document.getElementById('numberMatch').innerHTML; //document.getElementById('numberMatch').innerHTML; //document.getElementById('numberMatch').innerHTML; } function CalcularTotal(){ } listaDeProdutos();
var login = new Vue({ el:'#login-div-id', delimiters: ['[[', ']]'], data: { register1: false, username: '', password: '', errors: false, errortext: '', username1: '', email: '', password1: '', password2: '', }, methods: { close: function(){ this.errors = false; }, registeron: function(){ this.register1 = !this.register1; }, login: function(){ axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; const url = address+'/rest-auth/login/'; const bodyFormData = new FormData(); bodyFormData.append('username', this.username); bodyFormData.append('password', this.password); axios.post(url,bodyFormData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then( response => { window.location.href = address+"/"; } ) .catch(function (error) { login.errors = true; if (error.response.request.response == '{"password":["This field may not be blank."]}'){ login.errortext = 'Password field can not be blank'; } else if (error.response.request.response == '{\"non_field_errors\":[\"Unable to log in with provided credentials.\"]}') { login.errortext = 'Username and password do not match. '; } else if (error.response.request.response == '{\"non_field_errors\":[\"Must include \\\"username\\\" and \\\"password\\\".\"]}') { login.errortext = 'You must enter an username. '; } else { login.errortext = 'Some errors occurred. '; } }); }, register: function(){ axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken'; const url = address+'/rest-auth/registration/'; const bodyFormData = new FormData(); bodyFormData.append('username', this.username1); bodyFormData.append('email', this.email); bodyFormData.append('password1', this.password1); bodyFormData.append('password2', this.password2); axios.post(url,bodyFormData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then( response => { window.location.href = address+"/"; } ) .catch(function (error) { login.errors = true; if (error.response.request.response == "{\"non_field_errors\":[\"The two password fields didn't match.\"]}"){ login.errortext = 'The two password fields did not match.'; } else if (error.response.request.response == "{\"email\":[\"Enter a valid email address.\"]}") { login.errortext = 'Enter a valid email address.'; } else if (error.response.request.response == "{\"password1\":[\"This password is too short. It must contain at least 8 characters.\"]}") { login.errortext = 'This password is too short. It must contain at least 8 characters.'; } else if (error.response.request.response == "{\"username\":[\"A user with that username already exists.\"]}") { login.errortext = 'A user with that username already exists.'; } else if (error.response.request.response == "{\"email\":[\"A user is already registered with this e-mail address.\"]}") { login.errortext = 'A user is already registered with this e-mail address.'; } else { login.errortext = 'Some errors occurred.'; } }) }, }, })
import React from "react"; import Grid from "@material-ui/core/Grid"; import { FormattedMessage } from "react-intl"; import GithubIcon from "../GithubIcon"; import { fileOnGithub } from "../../utils"; import Tray from "../Tray"; import Breadcrumbs from "../Breadcrumbs"; import TocIcon from "@material-ui/icons/Bookmark"; export default props => { return ( <React.Fragment> <Breadcrumbs via={props.frontmatter.breadcrumbs}> {props.frontmatter.title} </Breadcrumbs> <Grid container direction="row" justify="flex-start" wrap="wrap-reverse"> <Grid item xs={12} sm={10} md={7} lg={6} xl={6}> <h1> {props.frontmatter.title} &nbsp;&nbsp; <a href={fileOnGithub(props.fileAbsolutePath)}> <GithubIcon color={"#2979ff"} /> </a> </h1> <article dangerouslySetInnerHTML={{ __html: props.html }} /> {props.pleaseTranslate} </Grid> <Grid item xs={false} sm={false} md={false} lg={1} xl={1} /> <Grid item xs={12} sm={10} md={5} lg={5} xl={4} className="align-self-stretch pl1nsm" > {props.languageNotAvailable} {props.measurementsBox} <Tray className="mb1 stick" icon={<TocIcon />} title={<FormattedMessage id="app.contents" />} > <div className="toc" dangerouslySetInnerHTML={{ __html: props.tableOfContents }} /> </Tray> </Grid> </Grid> </React.Fragment> ); };
import { csvParseRows, csvParse } from 'd3-dsv'; import { timeParse } from 'd3-time-format'; import { stack } from 'd3-shape'; import { range } from 'd3-array'; import { getUniqueDateValues } from './utils'; /** * Data parsing module. Takes a CSV and turns it into an Object, and optionally determines the formatting to use when parsing dates. * @module utils/dataparse */ export function inputDate(scaleType, defaultFormat, declaredFormat) { if (scaleType === 'time' || scaleType === 'ordinal-time') { return declaredFormat || defaultFormat; } else { return undefined; } } export function parse(csv, inputDateFormat, index, stacked) { let val; const firstVals = {}; const headers = csvParseRows(csv.match(/^.*$/m)[0])[0]; const data = csvParse(csv, (d, i) => { const obj = {}; if (inputDateFormat) { const dateFormat = timeParse(inputDateFormat); obj.key = dateFormat(d[headers[0]]); } else { obj.key = d[headers[0]]; } obj.series = []; for (let j = 1; j < headers.length; j++) { const key = headers[j]; if (d[key] === 0 || d[key] === '') { d[key] = '__undefined__'; } if (index) { if (i === 0 && !firstVals[key]) { firstVals[key] = d[key]; } if (index === '0') { val = ((d[key] / firstVals[key]) - 1) * 100; } else { val = (d[key] / firstVals[key]) * index; } } else { val = d[key]; } obj.series.push({ val: val, key: key }); } return obj; }); const seriesAmount = data[0].series.length; let stackedData; if (stacked && headers.length > 2) { const stackFn = stack().keys(headers.slice(1)); stackedData = stackFn(range(data.length).map(i => { const o = {}; o[headers[0]] = data[i].key; for (let j = 0; j < data[i].series.length; j++) { if (!data[i].series[j].val || data[i].series[j].val === '__undefined__') { o[data[i].series[j].key] = '0'; } else { o[data[i].series[j].key] = data[i].series[j].val; } } return o; })); } const uniqueDayValues = inputDateFormat ? getUniqueDateValues(data, 'day') : undefined; const uniqueMonthValues = inputDateFormat ? getUniqueDateValues(data, 'month') : undefined; const uniqueYearValues = inputDateFormat ? getUniqueDateValues(data, 'year') : undefined; return { csv: csv, data: data, seriesAmount: seriesAmount, keys: headers, stackedData: stackedData, uniqueDayValues: uniqueDayValues, uniqueMonthValues: uniqueMonthValues, uniqueYearValues: uniqueYearValues }; }
function register(env) { env.addFilter("root", handler); } function handler(input) { return Math.sqrt(input); } export { handler, register as default };
(function (document) { if (document.getElementById('yummlyYumletConfirmClose')) { return false; } var siteTitle = document.title, siteProtocol = document.location.protocol, yDiv = document.createElement('div'), yIFrame = document.createElement('iframe'), body = document.getElementsByTagName('body')[0], pageScripts = document.getElementsByTagName('script'), pageWidth = document.documentElement.clientWidth, thisScriptURL = pageScripts[pageScripts.length - 1].src, scriptSearch = thisScriptURL.split('?')[1] || '', siteImage, siteUrl, url; yIFrame.setAttribute('scrolling', 'no'); yIFrame.setAttribute('style', 'position:absolute; z-index:2147483646; top:0; left:0;'); yIFrame.setAttribute('frameBorder', '0'); if (pageWidth >= 480) { yDiv.setAttribute('style', 'position:fixed; z-index:2147483647; width: 600px; height: 500px; top:10px; right:10px; box-shadow: 0 0 8px rgba(0, 0, 0, 0.18);'); yIFrame.setAttribute('width', '600'); yIFrame.setAttribute('height', '500'); } else { yDiv.setAttribute('style', 'position:fixed; z-index:2147483647; width: 300px; height: 440px; top:10px; left:10px;'); yIFrame.setAttribute('width', '300'); yIFrame.setAttribute('height', '440'); } yDiv.innerHTML = '<a href="javascript:void(0);" id="yummlyYumletConfirmClose" style="text-decoration: none; position:absolute; color: #fff; top:10px; right: 15px; font-size: 23px; font-weight: bold; font-family: sans-serif; z-index:2147483647;">&times;</a>'; function getSiteUrl() { var links = document.head.getElementsByTagName('link'); for (var i = 0; i < links.length; i++) { if (links[i].getAttribute('rel') === 'canonical') { var testUrl = links[i].getAttribute('href'), testReg = /^https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/i; if(testUrl.match(testReg)) { return testUrl; } } } return document.URL; } function getMetaImage() { var metaTags = document.getElementsByTagName('META'), imageTest = new Image(), imageUrl, testUrl; for (var i=0; i<metaTags.length; i++) { if (metaTags[i].getAttribute('property') && metaTags[i].getAttribute('property').toLowerCase() === 'og:image') { testUrl = metaTags[i].getAttribute('content'); break; } } if (testUrl) { imageTest.onload = function () { if (imageTest.width >= 220 && imageTest.height >= 220) { siteImage = testUrl; } }; imageTest.src = testUrl; } return testUrl; } function getMicroFormatImage() { var recipeMicro = document.getElementsByClassName('h-recipe')[0] || document.getElementsByClassName('hRecipe')[0]; if (recipeMicro) { return recipeMicro.getElementsByClassName('u-photo')[0] || recipeMicro.getElementsByClassName('photo')[0]; } else { return null; } } function getFirstImage() { var images = document.getElementsByTagName('img'), imageUrl = null; for (var i=0; i<images.length; i++) { var elem = images[i]; if (elem.width >= 220 && elem.height >= 220) { while (elem && (elem.getAttribute('id') !== 'header') && (elem.className.split(' ').indexOf('header') === -1) && (elem.tagName !== 'header') ) { elem = elem.parentElement; } if (!elem) { imageUrl = images[i].src; break; } } } return imageUrl; } function loadIFrame() { siteImage = siteImage || getMicroFormatImage() || getFirstImage() || ''; url += '&image=' + encodeURIComponent(siteImage); yIFrame.setAttribute('src', url); yDiv.appendChild(yIFrame); body.appendChild(yDiv); document.getElementById('yummlyYumletConfirmClose').onclick = function () { yDiv.removeChild(yIFrame); body.removeChild(yDiv); }; } siteUrl = getSiteUrl(); url = siteProtocol + '//' + thisScriptURL.split('//')[1].split('/')[0] + '/urb/verify?url=' + encodeURIComponent(siteUrl) + '&title=' + encodeURIComponent(siteTitle) + '&urbtype=bookmarklet' + (scriptSearch ? '&' + scriptSearch : ''); if (getMetaImage()) { /* wait for image test*/ setTimeout(loadIFrame, 1000); } else { loadIFrame(); } }(window.document));
import ShortcutIconRow from './ShortcutIconRow'; export default ShortcutIconRow;
// CURRENTLY NOT IN USE const Message = require('../message'); const message = new Message(); message .setup() .then(() => { console.log('Database setup complete.'); }) .catch(err => { console.log('Database setup error: ', err); });
let Temp = require('./Temp.vue') module.exports = Temp
import { shallowMount } from "@vue/test-utils"; import Project from "@/components/Project.vue"; describe("Project", () => { describe("project image", () => { it("renders the project image", () => { const wrapper = shallowMount(Project); expect(wrapper.find(".project__image img").exists()).toBe(true); }); it("includes alt text", () => { const wrapper = shallowMount(Project); expect(wrapper.find(".project__image img").element.alt).toEqual( "A monitor with code displayed" ); }); it("includes title", () => { const wrapper = shallowMount(Project); expect(wrapper.find(".project__image img").element.title).toEqual( "Joseph Banass Project Logo" ); }); }); describe("content", () => { describe("header", () => { it("has a text content stating 'PROJECTS'", () => { const wrapper = shallowMount(Project); expect( wrapper.find(".project__header").element.textContent.trim() ).toEqual("Projects"); }); }); describe("subheader", () => { it("has a text content stating 'All talk and no show?'", () => { const wrapper = shallowMount(Project); expect( wrapper.find(".project__subheader").element.textContent.trim() ).toEqual("All talk and no show?"); }); }); describe("description", () => { it("includes the proper content for the description", () => { const wrapper = shallowMount(Project); expect( wrapper.find(".project__description").element.textContent.trim() ).toEqual( "Not quite. Check out my GitHub for an assortment of projects and scripts I'm in the middle of!" ); }); describe("anchor link", () => { it("includes an anchor link", () => { const wrapper = shallowMount(Project); expect(wrapper.find(".project__description a").exists()).toBe(true); }); it("links out to my GitHub", () => { const wrapper = shallowMount(Project); expect(wrapper.find(".project__description a").element.href).toEqual( "https://github.com/jbanass" ); }); }); }); }); });
"use strict"; var async = require('async'); var Rate = require('../database/rate'); var utils = require('../utils'); var rateController = module.exports; rateController.get = function (req, res, next) { Rate.findById(req.params.uuid, function (err, rate) { if (err) return next(err); return res.json({code: 200, msg: rate}); }); }; rateController.create = function (req, res, next) { var rate = { cid: req.body.cid, csid: req.body.csid, rate: req.body.rate, ip: req.body.ip }; Rate.create(rate, function (success) { if (!success) return next(new Error('create rate error')); return res.json({code: 200, msg: "success"}); }); }; rateController.patch = function (req, res, next) { var rate = {rate: req.body.rate}; var condition = {uuid: req.params.uuid}; Rate.update(rate, condition, function (err, data) { if (err) return next(err); return res.json({code: 200, msg: 'success update'}); }); }; rateController.delete = function (req, res, next) { var condition = {uuid: req.params.uuid}; Rate.delete(condition, function (err, data) { if (err) return next(err); return res.json({code: 200, msg: 'success delete'}); }); }; rateController.list = function (req, res, next) { var cid = req.params.cid; var csid = req.params.csid; var condition = {}; if (cid) condition.cid = cid; if (csid) condition.csid = csid; var order = [['createdAt', 'DESC']]; var pageNum = utils.parsePositiveInteger(req.query.pageNum); var pageSize = 10; Rate.listAndCount(condition, order, pageSize, pageNum, function (err, data) { if (err) return next(err); return res.json({code: 200, msg: data}); }); }; rateController.search = function (req, res, next) { var condition = {}; if (req.query.csid) condition.csid = req.query.csid; if (req.query.rate) condition.rate = req.query.rate; if (req.query.createdAtStart || req.query.createdAtEnd) { condition.createdAt = {}; if (req.query.createdAtStart) condition.createdAt["$gte"] = req.query.createdAtStart; if (req.query.createdAtEnd) condition.createdAt["$lte"] = req.query.createdAtEnd; } var order = [['createdAt', 'DESC']]; if (req.query.sortField) order = [[req.query.sortField, req.query.sortOrder === 'ascend' ? 'ASC' : 'DESC']]; var pageNum = utils.parsePositiveInteger(req.query.pageNum); var pageSize = 10; return Rate.listAndCount(condition, order, pageSize, pageNum, function (err, data) { if (err) return next(err); return res.json({code: 200, msg: data}); }); };
import React from 'react'; import { Grid, Paper, Typography } from '@material-ui/core' import weatherImg from '../images/weatherImage.jpg' import WeatherList from './WeatherList'; import FavoriteItem from './FavoriteItem'; import { useSelector, useDispatch } from 'react-redux' const Favorites = () => { const _favorites = useSelector(state => state.favoritesState.favorits.map((obj, i) => { return <FavoriteItem title={obj.title} key={i} temp={obj.Temperature.Value + obj.Temperature.Unit} desc={obj.WeatherText} /> })); return ( <Grid item justify="center" md={9} xs={8}> <WeatherList listItems={_favorites} /> </Grid> ) } export default Favorites
import React,{Component} from 'react'; import {connect} from 'react-redux' import {fetchList} from '../actions' import { Pagination, PaginationItem, PaginationLink , Breadcrumb , BreadcrumbItem} from 'reactstrap'; import { NavLink } from 'react-router-dom' var PAGE=1; const mapStateToProps = (state)=>{ return { ...state.product } } class Product extends Component{ componentDidMount(){ this.props.fetchList(); } //显示一页产品 showPro(){ var list=this.props.list.pageData if(list.length > 0){ var jxt=[]; for(let i=0;i<list.length;i++){ var url=`/product/${i}`; jxt.push( <NavLink to={url} key={i} style={{color:"#000"}}> <div className="col-sm-6 col-md-4" key={i} > <div className="thumbnail" style={{backgroundColor:"#f5f5f5",padding:"10px"}}> <img src={list[i].img} style={{width:"200px",height:"150px"}}/> <div className="caption" style={{textAlign:"center"}}> <h4>{list[i].name}</h4> <p style={{color:"#f40"}}>¥{list[i].price}</p> </div> </div> </div> </NavLink> ) } return jxt; }else{ return null; } } render(){ const {list,fetchList}=this.props; return ( <div style={{overflow:"hidden",fontSize:"1.5rem"}}> <div style={{overflow:"hidden"}}> <div className="panel panel-success" style={{fontSize:"1.5rem"}}> <div className="panel-body"> {this.showPro()} </div> </div> </div> </div> ) } } export default connect(mapStateToProps,{fetchList})(Product);
const Colors = { primary: '#F6F6FC', secondary: '#FFFFFF', accent: '#6F16E3', danger: '#bb2124', sucess: '#22bb33', warning: '#f0ad4e', inActive: '#cdd0cb', dark: '#433d3c' } export default Colors;
$(function() { // 显示语言切换 $(".language-box > button").bind("click", function() { if($(".dropdown-menu").is(":hidden")){ $(".dropdown-menu").show(); }else { $(".dropdown-menu").hide(); } }); // 手机端下显示头部信息 $(".open-header").bind("click", function() { $("#pc-navigation").addClass("show-header"); $(".drawer-backdrop").show(); }); // 隐藏信息 $(".drawer-backdrop").bind("click", function() { $("#pc-navigation").removeClass("show-header"); $("#container > nav").removeClass("show-nav"); $(".dropdown-menu").hide(); $(this).hide(); }); // 显示手机端下导航栏 $(".open-tags > button").bind("click", function() { $("#container > nav").toggleClass("show-nav"); }); });
import styled from 'styled-components' const Input = styled.input` color: green; font-size: 20px; font-weight: bold; `; export default Input;
import http from 'http'; var rp = require('request-promise'); var request = require("request"); const MongoClient = require('mongodb').MongoClient; const dbUrl = 'mongodb://egursoy:Forever9@ds129030.mlab.com:29030/webscraper' // const dbUrl = 'mongodb://localhost:27017/local'; var db; export default function stocks(req) { const tempUrl = 'http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.quotes where symbol in ("YHOO,GOOG,FB,NOW,SBUX")&format=json&env=store://datatables.org/alltableswithkeys' return new Promise((resolve, reject)=>{ // request({url:tempUrl, json:true}, function (err, res, body) { // if (err) { // return reject(err); // } else if (res.statusCode !== 200) { // err = new Error("Unexpected status code: " + res.statusCode); // err.res = res; // return reject(err); // } if(req.session.user){ console.log('BACKEND HIT ' + req.session.user.name); var userObj = req.session.user; MongoClient.connect(dbUrl, (err, database) => { if (err) { console.log('error'); } else { db = database; db.collection('users').findOne({name: userObj.name}, function(userErr, userData){ if(userErr){ reject('user information not found'); } else{ var tickerValues = []; for(var i=0; i<userData.tickers.length; i++){ tickerValues.push(userData.tickers[i].Symbol); } db.collection('tickers2').aggregate([ { "$match": { symbol: { $in: tickerValues } } }, { $lookup: { from: "tickers", localField: "symbol", foreignField: "Symbol", as: "mergedTickers" } } ], function(err, results){ if(!err){ req.session.stockList = results; resolve(results); } }) } }) } }); } else{ reject('user is not logged in'); } //resolve(body); // }); }); }
import propTypes from 'prop-types'; import NavItem from './NavItem.js'; import logo from'../tamaiti_logo.png'; function NavBar(props) { return ( <ul className="navbar-nav bg-gradient-primary sidebar sidebar-dark accordion" id="accordionSidebar"> <a className="sidebar-brand d-flex align-items-center justify-content-center" href="/"> <div className="sidebar-brand-icon"> <img src={logo} className="img-fluid px-3 px-sm-4 mt-3 mb-4" alt="logo"/> </div> </a> <hr className="sidebar-divider my-0" /> <li className="nav-item active"> <a className="nav-link" href="/"> <i className="fas fa-fw fa-tachometer-alt"></i> <span>Dashboard</span></a> </li> <hr className="sidebar-divider" /> <div className="sidebar-heading">Tienda Online</div> <NavItem enlace="Usuarios listado" icono="fas fa-fw fa-chevron-right" enlaceUrl="#listadoUsuarios"/> <NavItem enlace="Productos listado" icono="fas fa-fw fa-chevron-right" enlaceUrl="#listadoProductos"/> <hr className="sidebar-divider d-none d-md-block"/> </ul> ); } NavBar.propTypes ={ enlaces:propTypes.array } export default NavBar;
var counter = 0; $(".row1").click(function() { if(counter % 2 === 0){ $( this ).append( "<img src='https://cdn0.iconfinder.com/data/icons/basic-ui-elements-plain/385/010_x-512.png' alt='Smiley face' height='42' width='42'>" ); counter++ }else{ $( this ).append( "<img src='http://circlesfordialogue.com/wp-content/uploads/2014/12/LAURA-LET%C2%B4S-CIRCLE-UP-2014-12-08.jpg' alt='Smiley face' height='42' width='42'>" ); counter++ } }); $(".row2").click(function(){ if(counter % 2 === 0){ $( this ).append( "<img src='https://cdn0.iconfinder.com/data/icons/basic-ui-elements-plain/385/010_x-512.png' alt='Smiley face' height='42' width='42'>" ); counter++ }else{ $( this ).append( "<img src='http://circlesfordialogue.com/wp-content/uploads/2014/12/LAURA-LET%C2%B4S-CIRCLE-UP-2014-12-08.jpg' alt='Smiley face' height='42' width='42'>" ); counter++ } }); $(".row3").click(function(){ if(counter % 2 === 0){ $( this ).append( "<img src='https://cdn0.iconfinder.com/data/icons/basic-ui-elements-plain/385/010_x-512.png' alt='Smiley face' height='42' width='42'>" ); counter++ }else{ $( this ).append( "<img src='http://circlesfordialogue.com/wp-content/uploads/2014/12/LAURA-LET%C2%B4S-CIRCLE-UP-2014-12-08.jpg' alt='Smiley face' height='42' width='42'>" ); counter++ } });
var json = [ tmas, satcom, radiowave, optic, noise, modulation, microwave, digicom, broadcast, antenna, acoustic] var data = { tmas:{name:"Transmission Media and Antenna Systems", description:"",type:"subject", data:tmas}, satcom:{name:"Satellite Communications", description:"", type:"subject", data:satcom}, radio:{name:"Radio Wave Propagation", description:"", type:"subject", data:radiowave}, optic:{name:"Optics", description:"", data:optic}, noise:{name:"Noise", description:"", data:noise}, modulation:{name:"Modulation", description:"", type:"subject", data:modulation}, microwave:{name:"Microwave", description:"", type:"subject", data:microwave}, digicom:{name:"Digital Communications", description:"", type:"subject", data:digicom}, broadcast:{name:"Broadcasting", description:"", type:"subject", data:broadcast}, antenna:{name:"Antennas", description:"", type:"subject", data:antenna}, acoustic:{name:"Acoustics", description:"", type:"subject", data:acoustic}, } var HASH = Date.now(); var count= 0; tokenize = (token)=>{ return { hash:++HASH, question:token.question, answer:token.answer, choices:token.choices, explanation:"", image:"none" } } convert=(json)=>{ temp = (JSON.parse(json)); temp = temp.map(token=>{ return tokenize(token); }) count+=temp.length return temp } window.onload = ()=>{ main = document.getElementById('main') Object.keys(data).map(d=>{ data[d].data = convert(data[d].data) main.innerHTML += `<h3>${d}<h3> <textarea>${JSON.stringify(data[d])}</textarea> <br><br> ` }) main.innerHTML+='<h1>'+count+'</h1>' }
// returns a string with a message that contains the name of the person shopping, and // the total amount they will pay function calculateHEBDiscount(shopperName, groceryTotal, discountPercent){ var price = 200; var discount = 100; var result; if(groceryTotal>price){ discountPercent = groceryTotal-discount; result= shopperName + " amount before discount " + groceryTotal + " amount after discount " + discountPercent } else{ result= shopperName + " No discount" } return result } var yes= calculateHEBDiscount('bryan', 300, 500); console.log(yes); // will take in two strings, and randomly pick one of the two strings to return function decideBetweenOptions(theFirstOption, theSecondOption) { var yes; (flipACoin===0)? yes=theFirstOption : yes=theSecondOption; return yes } var flipACoin = Math.floor(Math.random()* 2) var wow= decideBetweenOptions('great', 'its ok' ) console.log(wow); // will take in a lucky number and a total, and return the new total // applying a discount based on the lucky number (possibly none at all) function applyLuckyNumberDiscount (luckyNumber, totalBeforeDiscount) { var totalBeforeDiscount; var result; switch (luckyNumber) { case 0: afterdiscount = totalBeforeDiscount; result="you will have to pay: " + afterdiscount; break; case 1: discount = 0.1 afterdiscount = totalBeforeDiscount-(totalBeforeDiscount*discount); result = "you will have to pay: " + afterdiscount; break; case 2: discount = 0.25 afterdiscount = totalBeforeDiscount-(totalBeforeDiscount*discount); result = "you will have to pay: " + afterdiscount; break; case 4: discount = 0.4 afterdiscount = totalBeforeDiscount-(totalBeforeDiscount*discount); result = "you will have to pay: " + afterdiscount; break; case 5: afterdiscount = 'nothing'; result = "you will have to pay: " + afterdiscount; break; default: result = "There's nothing "; } return result } var luckyNumber = Math.floor(Math.random()* 6) var priceAfterDiscount = applyLuckyNumberDiscount(luckyNumber, 60); console.log( priceAfterDiscount); // will take in a number and return a string that is the corresponding month name function convertMonthNumberToName(Month) { var Month = Math.floor(Math.random()* 13) var result; switch (Month) { case 1: result = Month + " January"; break; case 2: result = Month + " February"; break; case 3: result = Month + " March"; break; case 4: result = Month + " April"; break; case 5: result = Month + " May"; break; case 6: result = Month + " June"; break; case 7: result = Month + " july"; break; case 8: result = Month + " August"; break; case 9: result = Month + " September"; break; case 10: result = Month + " October"; break; case 11: result = Month + " November"; break; case 12: result = Month + " December"; break; default: result = "Is not a month"; } return result } var months = convertMonthNumberToName('Month'); console.log(months); // will take in a starting number of cones and simulate customers coming and buying cones var coneInventory = Math.floor(Math.random() * 50) + 50; console.log(coneInventory); function sellCones(coneInventory) { var conesToSell; var result; result = 'Yeah I sold all cones.'; while (coneInventory > 0) { conesToSell = Math.floor(Math.random() * 5) + 1; if (conesToSell <= coneInventory) { result = 'Selling ' + conesToSell + ' cones...'; coneInventory -= conesToSell; } else { result = 'I can\'t sell you ' + conesToSell + ', I only have ' + coneInventory; } return result } } var seller = sellCones('coneInventory'); console.log(seller); // will take in a number and generate multiplication tables for it function generateMultiplicationTables(Number){ var Number = Math.floor(Math.random()* 11); var result; for (var i = 1; i < 11; i++) { result = Number + " x " + i + " = " + Number*i console.log(result); } return result } generateMultiplicationTables(Number); // will count down from the start number to the stop number // by step // console.log is okay here // ex. countDown(6, 0, 2); output is below // 6 // 4 // 2 // 0 function countDown(num1, num2, num3) { var num1 ; var num2 ; var num3 ; var result; if (num1 > (num2 && num3)) { if (num2 > num3) { result = num1 + ',' + num2 + ',' + num3 } else{ result = num1 +',' + num3 + ',' + num2 } } else if (num2>(num1 && num3)) { if (num1 > num3) { result = num2 + ','+ num1 + ','+ num3 } else { result = num2 + ','+ num3 + ',' + num1 } } else if (num3 > (num1 && num2)) { if (num1 > num2) { result = num3 + ',' + num1 + ','+ num2 } else { result = num3 + ',' + num2 + ',' + num1 } } return result } var resultnumber = countDown(12,3,27); console.log(resultnumber);
const state = { key: 'API_KEY', version: 'ENGESV', currentBook: 'Luke', currentBookId: 'Luke', currentChapter: 1, books: {}, timestamps: [], } document.addEventListener('DOMContentLoaded', app); async function app() { const booksList = await fetchBooks(state.key, state.version); const bookData = state.books[`${state.currentBookId}`]; const damId = bookData.dam_id; navbar(damId, booksList, bookData); text(damId); } const navbar = async (damId, booksList, bookData) => { audioPlayer(damId); selectors(booksList, bookData); } const text = async (damId) => { const text = await fetchText(damId); displayText(text); handleTextClick(); handleTextHighlighting(); } const audioPlayer = async (damId) => { const audioData = await fetchAudio(damId); state.timestamps = await fetchVerseTimestamps(damId); const audio = document.querySelector('#listener'); setAudioSrc(audio, audioData); handleAudioPlayerChange(audio); } const selectors = (booksList, bookData) => { const { currentBookId, currentChapter } = state; setCurrentBook(currentBookId); setCurrentChapter(currentChapter); displayBooks(booksList); displayChapters(bookData); handleChapterChange(); } const displayText = (textArray) => { const paragraph = document.querySelector('#paragraph'); paragraph.innerHTML = ''; textArray.forEach(text => { if (isArabic()) paragraph.setAttribute('dir', 'rtl'); if (isFrench()) text.verse_id = ` ${text.verse_start}`; paragraph.innerHTML += `<span id='${text.verse_id}'' class='clickMe'>${text.verse_id} ${text.verse_text}</span>`; }); } const displayBooks = (booksList) => { const dropdown = document.querySelector('.dropdown-content'); dropdown.innerHTML = ''; booksList.forEach((book) => { const string = String(book.book_id); dropdown.innerHTML += `<a class='bookName ${book.dam_id}' id='${book.book_id}' onclick=updateCurrentBook(\'${string}\')>${book.book_name}</a>` }); } const displayChapters = (currentBookData) => { const dropdown = document.querySelector('.dropdown-contentCH'); dropdown.innerHTML = ''; const chapterList = currentBookData.chapters.split(','); chapterList.forEach((chapter) => { dropdown.innerHTML += `<a class='chapterID' onclick=updateCurrentChapter('${chapter}')>${chapter}</a>` }); } const setCurrentBook = (bookId) => { const currentBook = document.querySelector('#book'); state.currentBookId = bookId; state.currentBook = state.books[`${bookId}`].book_name; currentBook.textContent = state.currentBook; } const setCurrentChapter = chapter => { const currentChapter = document.querySelector('#chapter'); state.currentChapter = chapter; currentChapter.textContent = state.currentChapter; } const setAudioSrc = (audio, audioData) => { audio.currentTime = 0; audio.src = `https://fcbhabdm.s3.amazonaws.com/mp3audiobibles2/${audioData.path}`; } const fetchBooks = async (key, version) => { const url = getBooksEndpoint(key, version); const books = await fetchData(url); books.forEach(book => { state.books[`${book.book_id}`] = book; }); return books; } const fetchText = async (damId, chapter = 1) => { if (isFrench()) { const url = getFrenchTextEndpoint(state.version, chapter) const text = await fetchData(url); return text.data; } const url = getTextEndpoint(damId, chapter, state.version) const text = await fetchData(url); return text; } const fetchAudio = async (damId, chapter = 1) => { const url = getAudioEndpoint(damId, chapter) const audioData = await fetchData(url); return audioData[0]; } const fetchVerseTimestamps = async (damId, chapter = 1) => { if (!isEnglish()) return; const url = getVerseTimestampsEndpoint(damId, chapter); const timestamps = await fetchData(url); return timestamps; } const getBooksEndpoint = (key, version) => { return `https://dbt.io/library/book?key=${key}&dam_id=${version}&v=2` } const getTextEndpoint = (damId, chapter, version) => { return `https://dbt.io/text/verse?key=${state.key}&dam_id=${damId}2ET&book_id=${state.currentBookId}&chapter_id=${chapter}&v=2`; } const getFrenchTextEndpoint = (version, chapter) => { return `https://api.v4.dbt.io/bibles/filesets/${version}/${state.currentBookId}/${chapter}?key=52e62d4c-f7c8-4a8b-9008-8634d0fbddb0&v=4`; } const getAudioEndpoint = (damId, chapter) => { return `https://dbt.io/audio/path?key=${state.key}&dam_id=${damId}2DA&book_id=${state.currentBookId}&chapter_id=${chapter}&v=2`; } const getVerseTimestampsEndpoint = (damId, chapter) => { return `https://dbt.io/audio/versestart?key=${state.key}&dam_id=${damId}2DA&osis_code=${state.currentBook}&chapter_number=${chapter}&v=2`; } const fetchData = async (url) => { try { const response = await fetch(url); const data = await response.json(); return data; } catch (err) { console.log('Could not fetch data'); console.log(err); } } const updateCurrentBook = (bookId = 'Luke') => { setCurrentBook(bookId); updateCurrentChapter(); } const updateCurrentChapter = (chapter = 1) => { const { currentBookId } = state; const bookData = state.books[`${currentBookId}`]; setCurrentChapter(chapter); displayChapters(bookData); updateAudioSrc(chapter); updateText(chapter); } const updateText = async (chapter = 1) => { const { currentBookId } = state; const damId = state.books[`${currentBookId}`].dam_id; const text = await fetchText(damId, chapter); displayText(text); } const updateAudioSrc = async (chapter = 1) => { const { currentBookId } = state; const damId = state.books[`${currentBookId}`].dam_id; const audioData = await fetchAudio(damId, chapter); const audio = document.querySelector('#listener'); setAudioSrc(audio, audioData); } const handleChapterChange = () => { prevChapter(); nextChapter(); } const handleAudioPlayerChange = (audio) => { audioPlaybackDisplay(audio); playButton(audio); progressBar(audio); skipButtons(audio); volumeControl(audio); playbackSpeed(audio); } const handleTextClick = () => { const section = document.querySelector('section'); const whatsapp = document.querySelector('#side_button'); whatsappHighlight(section); shareButton(section, whatsapp); } const handleTextHighlighting = () => { const audio = document.querySelector('#listener'); audio.addEventListener('timeupdate', () => highlightText(audio)); } const prevChapter = () => { const prev = document.querySelector('#reverseBtn'); prev.addEventListener('click', () => { if (isFirstChapter(state.currentBook, Number(state.currentChapter) - 1)) return; updateCurrentChapter(Number(state.currentChapter) - 1); }); function isFirstChapter(currentBook, chapter) { const chapters = state.books[`${currentBook}`].chapters; const [ firstChapter ] = chapters.split(',')[0]; if (chapter < Number(firstChapter)) return true; return false; } } const nextChapter = () => { const next = document.querySelector('#forwardBtn'); next.addEventListener('click', () => { if (isLastChapter(state.currentBook, Number(state.currentChapter) + 1)) return; updateCurrentChapter(Number(state.currentChapter) + 1); }); function isLastChapter(currentBook, chapter) { const chapters = state.books[`${currentBook}`].chapters; const [ lastChapter ] = chapters.split(',').slice(-1); if (chapter > Number(lastChapter)) return true; return false; } } const audioPlaybackDisplay = audio => { audio.addEventListener('canplay', () => { handleProgress(); displayCurrentTime(); displayAudioDuration(); }); audio.addEventListener('timeupdate', () => { handleProgress(); displayCurrentTime(); }); function handleProgress() { const progressBar = document.querySelector('.progressFiller'); const percentComplete = (audio.currentTime / audio.duration) * 100; progressBar.style.flexBasis = `${percentComplete}%`; } function displayCurrentTime() { const currentTime = document.querySelector('#currentTime'); const minutes = getMinutes(audio.currentTime); const seconds = getSeconds(audio.currentTime); currentTime.innerHTML = `${minutes}:${(seconds < 10) ? `0${seconds}` : seconds}`; } function displayAudioDuration() { const duration = document.querySelector('#duration'); const minutes = getMinutes(audio.duration); const seconds = getSeconds(audio.duration); if (minutes !== 0 || seconds !== 0) duration.innerHTML = ''; duration.innerHTML = `${minutes}:${(seconds < 10) ? `0${seconds}` : seconds}`; } function getMinutes(time) { return Math.floor(parseInt(time) / 60); } function getSeconds(time) { return parseInt(time) % 60; } } const playButton = audio => { const toggle = document.querySelector('#toggle'); toggle.addEventListener('click', togglePlay); function togglePlay() { const method = audio.paused ? 'play' : 'pause'; audio[method](); updateButton(); } function updateButton() { const icon = audio.paused ? '►' : '❚❚'; toggle.textContent = icon; } } const progressBar = audio => { const progress = document.querySelector('.progress'); let mousedown = false; progress.addEventListener('click', scrub); progress.addEventListener('mousemove', (e) => mousedown && scrub(e)); progress.addEventListener('mousedown', () => mousedown = true); progress.addEventListener('mouseup', () => mousedown = false); function scrub(e) { const scrubTime = (e.offsetX / progress.offsetWidth) * audio.duration; audio.currentTime = scrubTime; } } const skipButtons = audio => { const skipButtons = document.querySelectorAll('[data-skip]'); skipButtons.forEach(button => button.addEventListener('click', skip)); function skip() { audio.currentTime += parseFloat(this.dataset.skip); } } const volumeControl = audio => { const volume = document.querySelector('.slider'); volume.addEventListener('change', handleVolumeChange); volume.addEventListener('mousemove', handleVolumeChange); function handleVolumeChange() { audio[this.name] = this.value; } } const playbackSpeed = audio => { const speed = document.querySelector('.playSpeed'); speed.addEventListener('click', changeSpeed); function changeSpeed() { if (speed.textContent == '1x') { speed.textContent = '1.5x'; audio.playbackRate = 1.5; } else if (speed.textContent == '1.5x') { speed.textContent = '.75x'; audio.playbackRate = 0.75; } else { speed.textContent = '1x'; audio.playbackRate = 1; } } } const whatsappHighlight = section => { section.addEventListener('click', event => { if (event.target.classList.contains('clickMe')) { clickToHighlight(event); } }); function clickToHighlight(event) { if (isAudioPlaying()) return; toggleWhatsappHighlight(event); } function isAudioPlaying() { return toggle.textContent == '❚❚'; } function toggleWhatsappHighlight(event) { if (isVerseHighlighted(event)) { removeWhatsappHighlight(event); } else { addWhatsappHighlight(event); } } function isVerseHighlighted(event){ return event.target.classList.contains('highlight2'); } function removeWhatsappHighlight(event) { event.target.className = event.target.className.replace(' highlight2', ''); event.target.style.background = '#ffffff'; event.target.style.color = 'black'; } function addWhatsappHighlight(event) { event.target.className += ' highlight2'; event.target.style.background = '#1e9544'; event.target.style.color = 'white'; } } const shareButton = (section, whatsapp) => { section.addEventListener('click', event => { if (event.target.classList.contains('clickMe')) { display(whatsapp); } }); function display(whatsapp) { const verseSelection = selectHighlightedVerses(); if (verseSelection == 'https://wa.me/?text=') { showShareButton(whatsapp); } else { removeShareButton(whatsapp, verseSelection); } } function selectHighlightedVerses() { let verseSelection = 'https://wa.me/?text='; paragraph.querySelectorAll('.highlight2').forEach(verse => { verseSelection += verse.innerText }); verseSelection = verseSelection.split(' ').join('%20'); return verseSelection; } function showShareButton(whatsapp) { whatsapp.removeAttribute('href'); whatsapp.removeAttribute('xlink:href'); whatsapp.classList.add('show'); } function removeShareButton(whatsapp, verseSelection) { whatsapp.setAttribute('href', verseSelection); whatsapp.setAttribute('xlink:href', verseSelection); whatsapp.classList.remove('show'); } } const highlightText = (audio) => { if (!isEnglish()) return; const { timestamps } = state; const lastVerse = timestamps.length; timestamps.forEach((timestamp, index, array) => { const currentVerse = timestamp.verse_id; if (isCorrectTimeframe(audio, {timestamp, index, array})) { highlightVerse(currentVerse, array); } else if (areTimestampsIncorrect(audio, array)) { highlightVerse(lastVerse, array); unhighlightVerse(lastVerse - 1, array); } else { unhighlightVerse(currentVerse, array); } }); function isCorrectTimeframe(audio, {timestamp, index, array}) { const isGreaterThanCurrentVerse = audio.currentTime >= timestamp.verse_start; const isLessThanNextVerse = audio.currentTime < array[index + 1].verse_start; const isLessThanDuration = audio.currentTime < audio.duration - 1; return isGreaterThanCurrentVerse && isLessThanNextVerse && isLessThanDuration; } function areTimestampsIncorrect(audio, timestamps) { const areTimestampsTooShort = audio.currentTime >= timestamps[timestamps.length - 1].verse_start; const isThereStillAudioToPlay = audio.currentTime <= audio.duration - 1; return areTimestampsTooShort && isThereStillAudioToPlay; } function highlightVerse(index, timestamps) { document.getElementById(timestamps[index - 1].verse_id).style.background = "#f9e93d"; document.getElementById(timestamps[index - 1].verse_id).style.color = 'black'; } function unhighlightVerse(index, timestamps) { document.getElementById(timestamps[index - 1].verse_id).style.background = "#ffffff"; document.getElementById(timestamps[index - 1].verse_id).style.color = 'black'; } } const isEnglish = () => { return state.version == 'ENGESV'; } const isArabic = () => { return state.version == 'ARBAS1'; } const isFrench = () => { return state.version == 'FRNPDV'; }
'use strict'; module.exports = function (sequelize, DataTypes) { var Character = sequelize.define('Character', { id: { type: DataTypes.BIGINT.UNSIGNED, field: 'character_id', primaryKey: true }, name: { type: DataTypes.STRING, field: 'name' }, factionId: { type: DataTypes.INTEGER, field: 'faction_id' }, worldId: { type: DataTypes.INTEGER, field: 'world_id' }, battleRank: { type: DataTypes.INTEGER, field: 'battle_rank' }, battleRankPercentToNext: { type: DataTypes.INTEGER, field: 'battle_rank_percent_to_next' }, certsEarned: { type: DataTypes.INTEGER.UNSIGNED, field: 'certs_earned' }, titleId: { type: DataTypes.INTEGER, field: 'title_id' } }, { tableName: 'character', classMethods: { associate: function (models) { Character.hasOne(models.CharacterTime, { as: 'times', constraints: true, foreignKey: { field: 'character_id', primaryKey: true }, onDelete: 'CASCADE', onUpdate: 'NO ACTION' }); Character.hasMany(models.CharacterStat, { constraints: true, foreignKey: { field: 'character_id', primaryKey: true }, onDelete: 'CASCADE', onUpdate: 'NO ACTION' }); Character.hasMany(models.CharacterStatByFaction, { constraints: true, foreignKey: { field: 'character_id', primaryKey: true }, onDelete: 'CASCADE', onUpdate: 'NO ACTION' }); Character.hasMany(models.CharacterWeaponStat, { constraints: true, foreignKey: { field: 'character_id', primaryKey: true }, onDelete: 'CASCADE', onUpdate: 'NO ACTION' }); Character.hasMany(models.CharacterWeaponStatByFaction, { constraints: true, foreignKey: { field: 'character_id', primaryKey: true }, onDelete: 'CASCADE', onUpdate: 'NO ACTION' }); Character.hasMany(models.CharacterIviStat, { constraints: true, foreignKey: { field: 'character_id', primaryKey: true }, onDelete: 'CASCADE', onUpdate: 'NO ACTION' }); Character.hasOne(models.OutfitMember, { constraints: false, foreignKey: 'characterId' }); Character.belongsTo(models.World, { constraints: false, foreignKey: 'worldId' }); Character.belongsTo(models.Title, { constraints: false, foreignKey: 'titleId' }); Character.belongsTo(models.Faction, { constraints: false, foreignKey: 'factionId' }); } } }); return Character; };
const canvas = document.createElement('canvas'); canvas.width = 500; canvas.height = 500; canvas.style.width = canvas.width + 'px'; canvas.style.height = canvas.height + 'px'; canvas.style.border = '1px solid black'; document.body.appendChild(canvas); /** * @type {CanvasRenderingContext2D} */ const ctx = canvas.getContext('2d'); let cameraX = 0; let cameraY = 0; canvas.addEventListener('mousemove', function(e) { if (e.buttons == 1) { cameraX += e.movementX; cameraY += e.movementY; } }); let elements = []; const debugElements = { center: (_=>{const center = { x: canvas.width / 2, y: canvas.height / 2, draw: function() { ctx.beginPath(); ctx.fillStyle = 'red'; ctx.ellipse(cameraX + center.x, cameraY + center.y, 10, 10, 0, 0, Math.PI * 2); ctx.closePath(); ctx.fill(); } };return center})() }; function scale(num, in_min, in_max, out_min, out_max) { return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } function createRectangle(x, y, width, height, color) { const rect = {x, y, width, height, color}; rect.draw = function() { ctx.fillStyle = rect.color; ctx.fillRect(cameraX + rect.x, cameraY + rect.y, rect.width, rect.height); } return rect; } function randomColor() { let r = Math.round(scale(Math.random(), 0, 1, 50, 200)); let g = Math.round(scale(Math.random(), 0, 1, 50, 200)); let b = Math.round(scale(Math.random(), 0, 1, 50, 200)); return `rgb(${r}, ${g}, ${b})`; } function generateElementsSet(size = 1000) { elements = []; for (let i = 0; i < size; i++) { let width = Math.round(scale(Math.random(), 0, 1, 100, 200)); let height = Math.round(scale(Math.random(), 0, 1, 100, 200)); let x = Math.round(scale(Math.random(), 0, 1, 0, canvas.width - width)); let y = Math.round(scale(Math.random(), 0, 1, 0, canvas.height - height)); let color = randomColor(); elements.push(createRectangle(x, y, width, height, color)); } } const inputSetSize = document.createElement('input'); document.body.appendChild(inputSetSize); inputSetSize.type = 'number'; inputSetSize.min = 10; inputSetSize.max = 10000; inputSetSize.value = 1000; const btnGenerateElementSet = document.createElement('button'); btnGenerateElementSet.innerHTML = 'Generate Elements'; btnGenerateElementSet.addEventListener('click', e => {generateElementsSet(inputSetSize.valueAsNumber)}); document.body.appendChild(btnGenerateElementSet); generateElementsSet(); function vectorLength(x, y) { return Math.sqrt(x * x + y * y); } function displace(toDisplace, collider, vector) { let displaced = false; const rect1 = toDisplace; const rect2 = collider; let x1 = rect1.x + rect1.width - rect2.x; let x2 = rect2.x + rect2.width - rect1.x; let y1 = rect1.y + rect1.height - rect2.y; let y2 = rect2.y + rect2.height - rect1.y; const magnitude = 10; if (x1 > 0 && x2 > 0 && y1 > 0 && y2 > 0) { toDisplace.x += vector.x * magnitude; toDisplace.y += vector.y * magnitude; displace(toDisplace, collider, vector); displaced = true; } return displaced; } function resolveIntersections() { let time = performance.now(); const references = []; let lowX = Infinity, lowY = Infinity, highX = -Infinity, highY = -Infinity; for (let node of elements) { let reference = { node, length: vectorLength(node.x, node.y) } if (lowX > node.x) { lowX = node.x; } if (highX < node.x) { highX = node.x; } if (lowY > node.y) { lowY = node.y; } if (highY < node.y) { highY = node.y; } references.push(reference); } let centerX = ((highX - lowX) / 2) + lowX; let centerY = ((highY - lowY) / 2) + lowY; debugElements.center.x = centerX; debugElements.center.y = centerY; function distance(pos1, pos2) { let x = Math.abs(pos1.x - pos2.x); let y = Math.abs(pos1.y - pos2.y); let d = Math.sqrt(x * x + y * y); return d; } const sortedFromCenter = [...references].sort(function(ref1, ref2) { return distance({x: ref1.node.x, y: ref1.node.t}, {x: centerX, y: centerY}) - distance({x: ref2.node.x, y: ref2.node.t}, {x: centerX, y: centerY}); }); function normalize({x, y}) { let a = Math.sqrt((x * x) + (y * y)); let u = {x: x / a, y: y / a}; return u; } function direction(pos1, pos2) { let x = pos2.x - pos1.x; let y = pos2.y - pos1.y; return normalize({x, y}); } for (let i = 1; i < sortedFromCenter.length; i++) { let toDisplace = sortedFromCenter[i].node; let displaced = false; do { displaced = false; for (let j = 0; j < i; j++) { let collider = sortedFromCenter[j].node; let vector = direction({x: centerX, y: centerY}, {x: toDisplace.x + toDisplace.width / 2, y: toDisplace.y + toDisplace.height / 2}); if (displace(toDisplace, collider, vector)) { displaced = true; } } } while (displaced); } console.log('time: ', performance.now() - time); // const sortedByLength = [...references].sort(function(ref1, ref2) { // return ref1.length - ref2.length; // }); // let centerIndex = Math.round(sortedByLength.length / 2) - 1; // let centerNode = sortedByLength[centerIndex]; } const btnResolveIntersections = document.createElement('button'); btnResolveIntersections.innerHTML = 'Resolve Intersections'; btnResolveIntersections.addEventListener('click', e => {resolveIntersections()}); document.body.appendChild(btnResolveIntersections); //LOOP///////////////////////////////////////////////// function loop() { ctx.clearRect(0, 0, canvas.width, canvas.height); for (let node of elements) { node.draw(); } for (let name in debugElements){ debugElements[name].draw(); } ctx.font = '20px sans-serif'; ctx.fillStyle = 'black'; ctx.strokeStyle = 'white'; ctx.strokeText(`x: ${cameraX}, y: ${cameraY}`, 20, 20); ctx.fillText(`x: ${cameraX}, y: ${cameraY}`, 20, 20); requestAnimationFrame(loop); } requestAnimationFrame(loop);
module.exports = function () { return { app: "./src/app.js", scripts: "./src/**/*.js", assets: "./src/assets/**/*", styles: "./src/**/*.scss", appStyle: "./src/styles.scss", index: './src/index.html', dist: "./dist" } }
export default { state: { server: '', expire_at: 0, code: undefined, session: undefined }, namespaced: true, mutations: { setCode (state, payload) { state.code = payload localStorage.setItem('network/code', payload) }, setServer (state, payload) { state.server = payload }, setSession (state, payload) { state.session = payload localStorage.setItem('network/session', payload) }, setExpireAt (state, payload) { state.expire_at = payload localStorage.setItem('network/expire_at', payload) } }, actions: { setCode: ({commit}, value) => { commit('setCode', value) }, setServer: ({commit}, value) => { commit('setServer', value) }, setSession: ({commit}, value) => { commit('setSession', value) }, setExpireAt: ({commit}, value) => { commit('setExpireAt', value) } }, getters: { code: state => state.code, server: state => state.server, session: state => state.session, expire_at: state => state.expire_at } }
const compose = (...fns) => (...args) => fns.reduceRight((s, fn) => [fn.call(null, ...s)], args)[0]; const map = (f) => (arr) => arr.map(f); const arrayTransformer = ([k, v]) => ([k, parseInt(v, 10)]); const fromEntries = (arr) => arr .reduce((acc, pair) => (pair.length === 2 ? { ...acc, [pair[0]]: pair[1] } : {}), {}); const transformToInt = compose( fromEntries, map(arrayTransformer), Object.entries, ); const range = (from, count, arr) => arr.slice(from, from + count); const handlePaginationRequest = (query, responseData) => { const { currentItemID, itemsToFetch } = transformToInt(query); const responseItems = currentItemID && itemsToFetch ? range(currentItemID + 1, itemsToFetch, responseData) : range(0, 4, responseData); const itemsLeft = responseItems.length - responseItems[responseItems.length - 1].id; const response = { responseItems, itemsLeft, }; return response; } const defaultGet = (data) => (_, res) => res.status(200).send(data); const DefaultPaginationGet = (data) => (req, res) => res.status(200).send(handlePaginationRequest(req.query, data)) const exportDefaultImports = (dirName, fileName) => { const { join, basename, parse } = require('path'); return require('fs') .readdirSync(dirName) .reduce((acc, f) => f !== basename(fileName) ? {...acc, [parse(f).name]: require(join(dirName, f))} : acc , {}); } module.exports = { DefaultPaginationGet, defaultGet, exportDefaultImports }
var indexSectionsWithContent = { 0: "_abcdefghilmnoprstuvwxy", 1: "_alnps", 2: "acfilnoprstuv", 3: "abcdefghilmnoprstuvwxy", 4: "abcdfghilmnoprstwxy", 5: "ilnst", 6: "el", 7: "bclvw", 8: "agmrstu", 9: "cdfhinost", 10: "dhsu" }; var indexSectionNames = { 0: "all", 1: "classes", 2: "files", 3: "functions", 4: "variables", 5: "typedefs", 6: "enums", 7: "enumvalues", 8: "defines", 9: "groups", 10: "pages" }; var indexSectionLabels = { 0: "All", 1: "Classes", 2: "Files", 3: "Functions", 4: "Variables", 5: "Typedefs", 6: "Enumerations", 7: "Enumerator", 8: "Macros", 9: "Modules", 10: "Pages" };
import { Navigation } from 'react-native-navigation'; import configureStore from './src/store/configureStore'; import InviteScreen from './src/screens/invite/InviteScreen'; import OfferScreen from './src/screens/offers/OfferScreen'; import RewardScreen from './src/screens/rewards/RewardScreen'; import SettingScreen from './src/screens/settings/SettingScreen'; import Icon from 'react-native-vector-icons/Ionicons'; const store = configureStore(); Navigation.registerComponent( 'CashOut.InviteScreen', () => InviteScreen, ); Navigation.registerComponent( 'CashOut.OfferScreen', () => OfferScreen, ); Navigation.registerComponent( 'CashOut.RewardScreen', () => RewardScreen, ); Navigation.registerComponent( 'CashOut.SettingScreen', () => SettingScreen, ); Promise.all([ Icon.getImageSource("ios-apps-outline", 30), Icon.getImageSource("ios-person-add-outline", 30), Icon.getImageSource("ios-card-outline", 30), Icon.getImageSource("ios-settings-outline", 30), ]).then(sources => { Navigation.startTabBasedApp({ tabs: [ { screen: 'CashOut.OfferScreen', label: 'Offers', title: "Offers", icon: sources[0], navigatorStyle: { statusBarColor: 'lightcyan', navBarBackgroundColor: 'lightcyan', navBarTextColor: 'black', navBarNoBorder: true, navBarHidden: true } }, { screen: 'CashOut.InviteScreen', label: 'Invite', title: "Invite", icon: sources[1], navigatorStyle: { navBarBackgroundColor: 'lightcyan', navBarTextColor: 'black', navBarNoBorder: true, navBarHidden: true } }, { screen: 'CashOut.RewardScreen', label: 'Rewards', title: "Rewards", icon: sources[2], navigatorStyle: { navBarBackgroundColor: 'lightcyan', navBarTextColor: 'black', navBarNoBorder: true, navBarHidden: true } }, { screen: 'CashOut.SettingScreen', label: 'Settings', title: "Settings", icon: sources[3], navigatorStyle: { statusBarColor: 'lightcyan', navBarBackgroundColor: 'lightcyan', navBarTextColor: 'black', navBarNoBorder: true, navBarHidden: true } }, ] }); });
WMS.module("Commissions.List", function(List, WMS, Backbone, Marionette) { var Views = _.extend({}, WMS.Common.Views, List.Views); List.Controller = Marionette.Controller.extend({ prefetchOptions: [ { request: 'get:commission:list', name: 'commissions', options:['from', 'to'] }, ], regions: [ { name: "titleRegion", View: Views.Title, options: { title: "Commesse" } }, { name: 'filterRegion', View: Views.FilterView, options : { clientId: "@clientId", from : "@from", to : "@to" }, events: { 'search': 'filterCommissions' } }, { name: 'panelRegion', viewName: '_panel', View: List.Views.Panel, options: { criterion: "@criterion" }, events: { "commissions:new": 'newCommission' } }, { name: 'masterRegion', viewName: '_commissions', View: List.Views.List, options: { collection: "@commissions", from : "@from", to : "@to", }, events: { 'commission:selected': 'selectCommission', }, }, { name: 'paginatorRegion', viewName: '_paginator', View: List.Views.Paginator, options: { collection: "@commissions", }, }, ], initialize: function() { var self = this; this.listenTo(WMS.vent, "commission:created", function(commission) { self.options.commissions.add(commission); }); this.listenTo(WMS.vent, "commission:updated", function(commission) { var model = self.options.commissions.find({ id: commission.get("id") }); if (model) { model.set(commission.attributes); } }); }, listCommissions: function(from, to) { this.options.from = from; this.options.to = to; var self = this; this.start().then(function() { if (self._layout && !self._layout.isDestroyed) { self.setupRegions(self._layout); } else { self._layout = new Views.Layout(); self._layout.on('show', function() { self.setupRegions(self._layout); }); WMS.mainRegion.show(self._layout); } }); }, filterCommissions: function(args) { var c = this._commissions.collection; Object.keys(args.model.attributes).forEach(function(k) { c.attr(k, typeof args.model.get(k) === 'undefined' ? null : args.model.get(k)); }); c.fetch(); }, newCommission: function() { var klass = WMS.Models.Commission; if (klass.canCreate()) { var model = new klass() , view = new WMS.Commissions.Forms.New({ model: model }); WMS.showModal(view); } else { WMS.showError('Operazione non consentita!'); } }, /* , editCommission: function(childView, args) { var commission = args.model; if (commission.canUpdate()) { var view = new WMS.Commissions.Forms.Edit({ model: commission }); WMS.showModal(view); } else { WMS.showError('Operazione non consentita!'); } } , deleteCommssion: function(childView, args) { var commission = args.model; if (commission.canDestroy()) { if (confirm("Eliminare commessa " + commission + "?")) { commission.destroy(); } } else { WMS.showError('Operazione non consentita!'); } } */ selectCommission: function(childView) { var commission = childView.model; if (commission.canRead()) { WMS.trigger("commissions:show", commission.get("id")); } }, }); });
/** * Created by patrick conroy on 2/3/18. */ module.exports = { firebaseServerAuthCreds:{ "type": "service_account", "project_id": "XXXXX", "private_key_id": "xxxxxxxxxxxxxxxxxx", "private_key": "" "client_email": "XXXXX" "client_id": "XXXXX", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "XXXXXX" }, session:{ secret:"XXXXXXXXXX", storagePath:"/tmp/mlblog-distillant/sessions" } };
import React, { useState, useEffect, useContext } from "react"; import { userContext } from "./utils/Context.js"; import { BrowserRouter, Route, Switch } from "react-router-dom"; import API from "./utils/API.js"; //import pages import About from './pages/About'; import SignUp from './pages/SignUp'; import Login from './pages/Login'; import Discover from './pages/Discover'; import AddShelf from './pages/AddShelf'; import Shelf from './pages/Shelf'; import NoMatch from './pages/NoMatch'; //import logo from "./logo.svg"; //components import Nav from './components/Nav' import Footer from './components/Footer' import Wrapper from './components/Wrapper'; function App(){ const [currentUser, setCurrentUser] = useState(""); useEffect(() => { API.userLoggedIn().then(response => { //the current user will go here console.log(response) if(response.data !== 'no user'){ const reqId = response.data.id //this returns the right object const currentuser=response.data; API.userShelves({id:reqId}).then((resshelves)=> { currentuser.shelves=resshelves.data }).then(()=>{ setCurrentUser(currentuser); }) } }) }, []); function handleLogout(e){ e.preventDefault(); API.userLogout().then((res)=>{ setCurrentUser(''); window.location='/'; }); } return ( <BrowserRouter> <userContext.Provider value={[currentUser, setCurrentUser]}> <Wrapper> <Nav logout = {handleLogout} user = {currentUser.id} /> <Switch> <Route exact path={['/', '/about']}> <About /> </Route> <Route exact path='/signup'> <SignUp /> </Route> <Route exact path='/login'> <Login /> </Route> <Route exact path='/discover'> <Discover /> </Route> <Route exact path='/addshelf'> <AddShelf /> </Route> <Route exact path='/shelves/:id'> <Shelf /> </Route> <Route> <NoMatch /> </Route> </Switch> </Wrapper> <Footer></Footer> </userContext.Provider> </BrowserRouter> ) } export default App; // nav and router switch inside wrapper, footer outside
const rimraf = require("rimraf"); const path = require("path"); const fs = require("fs"); const tymlogger = require("tymlogger"); const log = new tymlogger(); const BUILD_DIRECTORY = path.resolve(process.cwd(), "Build"); const BUILD_LOG = path.resolve(process.cwd(), "Build.log"); const PROJECT_FILE = path.resolve(process.cwd(), "Project.json"); module.exports = function () { if (fs.existsSync(PROJECT_FILE)) { log.write("Clean..."); rimraf.sync(BUILD_DIRECTORY); rimraf.sync(BUILD_LOG); } else { log.error("No Elizabeth project!"); } }
import React, { useRef, useEffect } from "react"; import styled from "styled-components"; import { useSelector } from "react-redux"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { faAward } from "@fortawesome/free-solid-svg-icons/faAward"; import { defaultPlayerNames } from "../../constants/players"; import { getGameState, getPlayer, getPlayers } from "../../selectors"; import { getColor, getPlayerColor, getRadius, getSize, } from "../../utils/theme"; import { play } from "../../utils/sound"; import playerJoined from "../../sound/playerJoined.mp3"; const Score = () => { const { activePlayer, winner, scores } = useSelector(getGameState); const players = useSelector(getPlayers); const prevPlayers = useRef([]); const currentPlayer = useSelector(getPlayer); useEffect(() => { if ( players.length > 1 && players.length - prevPlayers.current.length === 1 ) { play(playerJoined); } prevPlayers.current = players; }, [players]); return ( <> {players.map((name, player) => ( <PlayerScore key={player} player={player} isActive={activePlayer === player} > <Player current={player === currentPlayer}> {name || defaultPlayerNames[player]}{" "} {winner === player && <Winner icon={faAward} />} </Player> <strong>{scores[player]}</strong> </PlayerScore> ))} </> ); }; const Winner = styled(FontAwesomeIcon)` margin-left: ${getSize(2)}; color: ${getColor("gold")}; `; const Player = styled.span` overflow: ellipsis; flex-grow: 1; whitespace: no-wrap; margin-right: ${getSize(2)}; font-weight: ${(props) => (props.current ? "bold" : "normal")}; `; const PlayerScore = styled.span` background-color: ${(props) => props.isActive && getColor("subtleBg")}; display: flex; align-items: center; border-radius: ${getRadius("rounded")}; margin-right: ${getSize(5)}; margin-bottom: ${getSize(2)}; width: 100%; padding: ${getSize(2)} ${getSize(4)} ${getSize(2)} ${getSize(3)}; &:before { border-radius: ${getRadius("rounded")}; display: inline-block; content: ""; height: ${getSize(4)}; width: ${getSize(4)}; margin-right: ${getSize(3)}; background-color: ${(props) => getPlayerColor(props.player)}; } &:last-child { margin-right: 0; } `; export default Score;
/* Creator : ABDUL BASITH A */ /* Email : ambalavanbasith@gmail.com */ /* github : abdulbasitha */ /* More Info : https://techzia.in */ import React, { Component } from "react"; import { View, Text, StyleSheet, Button, TouchableOpacity, TextInput, Image, SafeAreaView, Alert, TouchableWithoutFeedback, TouchableHighlight } from "react-native"; // import cio from 'cheerio-without-node-native'; import firebase, { auth } from "firebase"; import config from '../config/firebase'; import { Drawer } from "react-native-router-flux"; import { readBuilderProgram } from "typescript"; import Login from "./LoginScreen"; import Geolocation from '@react-native-community/geolocation'; import Geocoder from 'react-native-geocoding'; import { ScrollView } from "react-native-gesture-handler"; class NearPlace extends Component { state ={ data:[] } componentWillMount(){ let arr =this.props.navigation.getParam('data',[]) this.setState({ data:arr }) console.log("sdsdsds",arr[0].image_url) } renderdata = ()=>{ return this.props.navigation.getParam('data',[]).map((data)=>{ return( <View style={{height:160,width:160,marginTop:20,marginLeft:20,borderWidth:0.5,borderColor:"#dddddd"}}> <TouchableHighlight underlayColor='rgba(73,182,77,1,0.9)' style={{flex:2}} onPress={()=>this.props.navigation.navigate("SignlePlace",{link:data.view_more})}> <View style={{flex:2}}> <View style={{flex:2}}> <Image style={{flex:1, width:null, height:null, resizeMode:"cover"}} source={{uri: data.image_url}}/> </View> <View style={{flex:1,alignItems:"center",paddingTop:20}}> <Text>{data.place_name}</Text> </View> </View> </TouchableHighlight> </View> ) }) } render() { return ( <SafeAreaView style={styles.container}> <View style={{alignItems:"center"}}> <TextInput placeholderTextColor={'#797C80'} placeholder={'Search destinations'} style={styles.emailField} /> </View> {/* <TouchableOpacity onPress={()=>{this.getData()}}> <Text>Address</Text> </TouchableOpacity> */} <Text style={styles.Text}>Nearby Places</Text> <ScrollView horizontal={true} > {this.renderdata()} </ScrollView> <View> <Text style={styles.Text}>Other Sevices</Text> </View> <View style={{flex:10,flexDirection: "row"}}> <TouchableOpacity style={styles.signButton} activeOpacity={0.5}> <Text style={styles.btnTxt}> Road Assistance </Text> </TouchableOpacity> <TouchableOpacity style={styles.signButton} activeOpacity={0.5}> <Text style={styles.btnTxt}>Rental</Text> </TouchableOpacity> </View> <Text style={styles.footerTxt}>WeGo</Text> </SafeAreaView> ); } signout=() =>{ firebase.auth().signOut() this.props.navigation.navigate('Login') } } export default NearPlace; const styles = StyleSheet.create({ container: { flex: 1, // alignItems: 'center', //justifyContent: 'center' }, SquareShapeView: { marginHorizontal: 0, height: 100, paddingHorizontal:10, backgroundColor: '#0000ff', borderBottomEndRadius: 20, borderBottomStartRadius: 20, }, textProp: { fontFamily: 'Montserrat-Bold', fontSize: 38, color: '#ffffff', marginTop: 32, marginBottom: 0, marginRight: 0, marginLeft: 37, alignSelf: 'flex-start', }, emailField: { fontFamily: 'Montserrat-Light', fontSize: 14, color: '#86898E', width: 330, height: 50, backgroundColor: '#E1E6EC', borderRadius: 30, paddingLeft: 22, marginTop: 10, marginBottom: 10, marginLeft: 0, marginRight: 0, }, pwdField: { fontFamily: 'Montserrat-Light', fontSize: 14, color: '#BDC7D4', width: 286, height: 60, backgroundColor: '#314256', borderRadius: 30, paddingLeft: 22, marginTop: 36, marginBottom: 0, marginLeft: 0, marginRight: 0, }, btnTxt: { fontFamily: 'Montserrat-Bold', fontSize: 14, textAlign: 'center', color: '#000000', backgroundColor: '#BDC7D4', padding: 0, alignContent: 'space-between', marginHorizontal: 5, marginBottom: 0.5, marginTop: 0, paddingTop: 15, paddingBottom: 15, borderRadius: 30, left: 0, bottom: 0, width: 138, height: 52, }, signButton: { // alignSelf: 'center', marginTop: 10, marginLeft: 0, marginRight: 0, marginBottom: 0, }, bodyTxt: { fontFamily: 'Montserrat-Regular', fontSize: 14, color: '#ffffff', marginTop: 58, marginBottom: 0, marginRight: 0, marginLeft: 0, alignSelf: 'center', }, signUpTxt: { fontFamily: 'Montserrat-Bold', fontSize: 14, color: '#0176FB', alignSelf: 'center', }, footerTxt: { fontFamily: 'Montserrat-Bold', fontSize: 20, alignSelf: 'center', color: '#314256', marginTop: 90, marginBottom: 16, marginRight: 0, marginLeft: 0, }, Text: { fontFamily: 'Montserrat-Bold', fontSize: 20, marginLeft: 10, marginRight: 0, color: '#314256', marginHorizontal: 0, marginTop: 40, }, texttap: { fontFamily: 'Montserrat-Regular', fontSize: 16, marginLeft: 0, marginRight: 0, color: '#314256', marginHorizontal: 0, marginTop: 60, } });
roleDefender = { Tick: function(creep){ if (creep.spawning){return} roomName = creep.memory.originroom; room = Game.rooms[roomName]; hostiles = taskManager.getHostiles(roomName); if (hostiles.length < 0){ nearestHostile = creep.pos.findClosestByRange(hostiles); hostileRange = creep.pos.getRangeTo(nearestHostile); if (hostileRange > 3){ creep.moveTo(nearestHostile); } if (hostileRange < 3){ creep.rangedAttack(nearestHostile); let path = PathFinder.search(creep, nearesthostile, {flee: true}); creep.moveByPath(path); } } } } module.exports = roleDefender;
const last = arr => arr[arr.length - 1]; //let a = [11,12,13] -> 13
let url = "https://jsonplaceholder.typicode.com/users/1"; function getResponse(response) { return new Promise(function (resolve, reject) { if (!response) { reject(Error("getResponse")); } else { console.log("getResponse: ", response); resolve(response.json()); } }); } function parseName(data) { return new Promise(function (resolve, reject) { if (!data) { reject(Error("parseName error")); } else { console.log("parseName: ", data.name); resolve(data.name); } }); } function authName(name) { return new Promise(function (resolve, reject) { if (!name || name !== "Leanne Graham") { reject(Error("authName error")); } else { console.log("authName: ", name); resolve(name); } }); } function displayName(name) { return new Promise(function (resolve, reject) { if (!name) { reject(Error("displayName error")); } else { console.log("displayName: ", name); resolve(1); } }); } fetch(url) .then(getResponse) .then(parseName) .then(authName) .then(displayName) .catch((err) => { console.error(err); });
const CopyWebpackPlugin = require('copy-webpack-plugin'); const ServiceWorkerWebpackPlugin = require('serviceworker-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const VueLoaderPlugin = require('vue-loader/lib/plugin') const path = require('path'); const title = "Spoonfeedr"; module.exports = { mode: "development", entry: "./src/index.js", devtool: 'inline-source-map', output: { path: path.resolve(__dirname, 'dist'), filename: "[name].[hash].bundle.js" }, devServer: { contentBase: path.join(__dirname, 'dist') }, plugins: [ new CleanWebpackPlugin(['dist']), new ServiceWorkerWebpackPlugin({ entry: path.join(__dirname, '/src/sw.js') }), new VueLoaderPlugin(), new HtmlWebpackPlugin({ title, template: path.resolve(__dirname, 'public', 'index.html') }), new CopyWebpackPlugin([{ from: 'public', to: './', // note: 'to' is relative to the output path (in our case the dist folder) toType: 'dir', ignore: ['.DS_Store'], }]) ], module: { rules: [{ test: /\.less$/, use: [ {loader: 'style-loader'}, // creates style nodes from JS strings {loader: 'css-loader'}, // translates CSS into CommonJS {loader: 'postcss-loader'}, // runs some transformations on the css like adding vendor prefixes {loader: 'less-loader'} // compiles Less to CSS ] }, { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ["@babel/preset-env"] } } }, { test: /\.vue$/, loader: 'vue-loader', options: { hotReload: true } }, { test: /\.(png|jpe?g|gif|webp)(\?.*)?$/, use: [ { loader: 'url-loader', options: { limit: 4096, fallback: { loader: 'file-loader', options: { name: 'assets/images/[name].[hash:8].[ext]' } } } } ] }, { test: /\.(svg)(\?.*)?$/, use: [ { loader: 'file-loader', options: { name: 'assets/images/[name].[hash:8].[ext]' } } ] }, { test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/, use: [ { loader: 'url-loader', options: { limit: 4096, fallback: { loader: 'file-loader', options: { name: 'assets/media/[name].[hash:8].[ext]' } } } } ] }, { test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/i, use: [ { loader: 'url-loader', options: { limit: 4096, fallback: { loader: 'file-loader', options: { name: 'assets/fonts/[name].[hash:8].[ext]' } } } } ] }] } };
(function() { var OtpView, _type, _status, _query, _table, _page, _resendOtp; var _menu = BackendAdminPayDee._menu; var _datepicker = BackendAdminPayDee._datepicker; var _notifyForUser = BackendAdminPayDee._notifyForUser; var _pageCommon = BackendAdminPayDee._page; _menu.activeMenu('otp-menu'); _datepicker.init('fromDate'); _datepicker.init('toDate'); OtpView = window.OtpView = {}; OtpView.Type = (function() { function Type() { this.current = undefined; this.otpTypeEl = $('select[name="otpType"]'); this.otpTypeEl.on("select2:select", function () { _type.current = _type.otpTypeEl.val(); console.log(_type); }); this.init(); } Type.prototype.init = function() { var data = [ { id: -1, text: 'Loại OTP' }, { id: 0, text: 'Giao dịch' }, { id: 1, text: 'Kích hoạt tài khoản' }, { id: 2, text: 'Resend' }, { id: 3, text: 'Reset mật khẩu' } ]; this.otpTypeEl.select2({ data: data }); this.current = this.otpTypeEl.select2('data')[0].id; }; Type.prototype.toText = function(type) { switch(type){ case 0: return "Giao dịch"; case 1: return "Kích hoạt tài khoản"; case 2: return "Resend"; case 3: return "Reset mật khẩu"; default: return ""; } }; return Type; })(); OtpView.Status = (function() { function Status() { this.current = undefined; this.statusEl = $('select[name="status"]'); this.statusEl.on("select2:select", function () { _status.current = _status.statusEl.val(); console.log(_status); }); this.init(); } Status.prototype.init = function() { var data = [ { id: -1, text: 'Trạng thái' }, { id: 0, text: 'Chờ xác nhận' }, { id: 1, text: 'Thành công' }, { id: 2, text: 'Hết hạn' } ]; this.statusEl.select2({ data: data }); this.current = this.statusEl.select2('data')[0].id; }; Status.prototype.toText = function(status) { switch(status){ case 0: return "Chờ xác nhận"; case 1: return "Thành công"; case 2: return "Hết hạn"; default: return ""; } }; return Status; })(); OtpView.Query = (function() { function Query() { this.fromDate = $('input[name="fromDate"]'); this.toDate = $('input[name="toDate"]'); this.keyword = $('input[name="keyword"]'); this.btnSearch = $('button[name="search-otp"]'); this.btnExport = $('button[name="export-otp"]'); this.btnReset = $('button[name="reset-otp"]'); this.btnExport.on('click', { context: this }, function(e) { _pageCommon.resetNumber(); e.data.context.exportData(); }); this.btnSearch.on('click', { context: this }, function(e) { _pageCommon.resetNumber(); e.data.context.search(); }); this.btnReset.on('click', {context: this}, function(e){ _pageCommon.resetNumber(); e.data.context.reset(); }); } Query.prototype.makeRequest = function () { _query.request = { fromDate: _query.fromDate.val(), toDate: _query.toDate.val(), otpType: _type.current, keyword: _query.keyword.val(), status: _status.current, pageNumber: (_pageCommon.number < 1) ? 1 : (_pageCommon.number + 1), pageSize: _pageCommon.defaultSize } }; Query.prototype.validateRequest = function() { return _datepicker.validateDuration(_query.fromDate.val(), _query.toDate.val()); }; Query.prototype.exportData = function() { if(!_query.validateRequest()) return; _query.makeRequest(); console.log(_query.request); console.log("Fetching Data Of Page: " + _query.pageNumber); var url = BASE_URL + "/otp/export"; console.log("charging export with url: " + url); $.ajax({ url: url, type: 'POST', contentType : 'application/json', async: true, data : JSON.stringify(_query.request) }).done(function(data) { console.log(data); if(data === null || data === '' || data !== 'done') { _notifyForUser.error("Thực hiên xuất thất bại!"); } else { _notifyForUser.ok("Thực hiên xuất thành công!"); } _notifyForUser.show(); }).fail(function(data) { console.log(data); console.log("Đã xảy ra lỗi khi thực hiện xuất "); _notifyForUser.error('Đã xảy ra lỗi khi thực hiện xuất !'); _notifyForUser.show(); }).always(function() { console.log("Complete Call Ajax: Export OTP" ); }) }; Query.prototype.search = function() { if(!_query.validateRequest()) return; _query.makeRequest(); _page.loadData(_query.request); }; Query.prototype.reset = function() { console.log("call function reset()"); $('#fromDate').val(''); $('#toDate').val(''); $('#keyword').val(''); _type.otpTypeEl.val("-1").trigger('change.select2'); _status.statusEl.val("-1").trigger('change.select2'); }; return Query; })(); OtpView.Table = (function() { function Table() { this.el = $('#search-otp-table'); this.data = []; this.tableEl = this.el.find('table'); } Table.prototype.makeTable = function() { this.tableEl.children('tbody').remove(); this.tableEl.append(this.makeBody()); }; Table.prototype.makeBody = function() { var tbody = $('<tbody>'); $.each(this.data, function(idx, obj) { var _actionMenu = new BackendAdminPayDee.ActionMenu(); // Phải khởi tạo đối tượng mới. if (obj.otpType === 1 && (obj.status === 0 || obj.status === 2)) { _actionMenu.addMenu('fa-repeat', "Gửi lại", '#', 'OtpView._resendOtp.confirm("' + obj.receiveName + '", "' + obj.receivePhoneNumber + '", "' + obj.reference + '")'); } tbody.append($('<tr>') .append($('<td>', {"class": "text-nowrap"}).append(idx + 1 + _pageCommon.number * _pageCommon.defaultSize)) .append($('<td>', {"class": "text-nowrap"}).append(obj.sendTime)) .append($('<td>', {"class": "text-nowrap"}).append("<strong>" + obj.receiveName + "</strong>")) .append($('<td>', {"class": "text-nowrap"}).append("<strong>" + obj.receivePhoneNumber + "</strong>")) .append($('<td>', {"class": "text-nowrap"}).append(_type.toText(obj.otpType))) .append($('<td align=\'right\'>', {"class": "text-nowrap"}).append("<strong>" + obj.count + "</strong>")) .append($('<td>', {"class": "text-nowrap"}).append(_status.toText(obj.status))) .append($('<td>').append((obj.otpType == 1 && (obj.status == 0 || obj.status == 2)) ? _actionMenu.toHtml() : ''))); }); return tbody; }; return Table; })(); OtpView.Page = (function() { function Page() { this.paginationEl = _table.el.find('ul.pagination'); } Page.prototype.loadData = function() { var url = BASE_URL + "/otp/search"; var self = this; $.ajax({ async: true, url: url, method: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(_query.request), dataType: "json" }).done(function(data) { console.log(data); _pageCommon.number = data.pageNumber; _pageCommon.total = data.pagesAvailable; _pageCommon.list = _pageCommon.calculatePage(data.pageNumber, data.pagesAvailable); _table.data = data.pageItems; _table.makeTable(); _pageCommon.pagination(self.paginationEl, OtpView._query); }).fail(function() { console.log("Đã xảy ra lỗi khi thực hiện tìm kiếm mã OTP!"); _notifyForUser.error('Đã xảy ra lỗi khi thực hiện tìm kiếm mã OTP!'); _notifyForUser.show(); }).always(function() { console.log("Complete Call Ajax: Search OTP!" ); }); }; return Page; })(); OtpView.ResendOtp = (function() { function ResendOtp() {} ResendOtp.prototype.confirm = function(receiveName, receivePhoneNumber, reference) { var confirmMessage = '<h4>Bạn có chắc chắn gửi lại tin nhắn này cho <strong>' + receiveName + ' - ' + receivePhoneNumber + '</strong> không?</h4>'; var self = this; bootbox.confirm({ title: "<strong>Chú ý!</strong>", message: confirmMessage, buttons: { confirm: { label: 'Đồng ý', className: 'btn-success' }, cancel: { label: 'Hủy', className: 'btn-danger' } }, callback: function(result) { if (! result) return; var request = { data: reference }; console.log(request); self.resend(request); } }); }; ResendOtp.prototype.resend = function(request) { var url = BASE_URL + "/otp/resend-otp"; $.ajax({ async: true, url: url, method: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(request), dataType: "text" }).done(function(data) { console.log(data); if (data !== null && data.length > 0) { _notifyForUser.ok('Gửi lại tin nhắn thành công!'); _notifyForUser.show(); } }).fail(function() { console.log("Đã xảy ra lỗi khi gửi lại tin nhắn!"); _notifyForUser.error('Đã xảy ra lỗi khi gửi lại tin nhắn!'); _notifyForUser.show(); }).always(function() { console.log("Complete Call Ajax: Resend OTP!" ); }); }; return ResendOtp; })(); _type = new OtpView.Type(); _status = new OtpView.Status(); _query = new OtpView.Query(); _table = new OtpView.Table(); _page = new OtpView.Page(); _resendOtp = new OtpView.ResendOtp(); OtpView._query = _query; OtpView._resendOtp = _resendOtp; _query.search(); }).call(this);
export { default } from 'ember-sunny-days/components/sunny-day';
(function () { 'use strict'; $('.mask-cellphone').mask('(00) 00000-0000'); })();
import { GET_OAUTH_GITHUB_TOKEN_START, GET_OAUTH_GITHUB_TOKEN_SUCCESS, GET_OAUTH_GITHUB_TOKEN_ERROR } from '../../consts/actionTypes' import { GITHUB_TOKEN } from '../../consts' import get from 'lodash/get' import { saveData } from '../../utils/storage' const initialState = {} export default function(state = initialState, action) { switch (action.type) { case GET_OAUTH_GITHUB_TOKEN_START: return { ...state } // break case GET_OAUTH_GITHUB_TOKEN_SUCCESS: // const githubToken = action.loginResponse.data.githubToken) const githubToken = get(action, "loginResponse.data.githubToken") saveData(GITHUB_TOKEN, githubToken) return { ...state, githubToken: githubToken} // break case GET_OAUTH_GITHUB_TOKEN_ERROR: return { ...state, error: true } // break default: return { ...state } } }
import express from 'express'; import assetCtrl from '../controllers/assetCtr'; const router = express.Router(); router.route('/api/assets') .get(assetCtrl.getAssData) .put(assetCtrl.updateAssData) router.route('/api/assets/inincome') .put(assetCtrl.infIncome) router.route('/api/assets/payroll') .put(assetCtrl.payrollSalary) export default router
const { completeTransaction } = require("./utils/general"); /** * @dev Constant flow agreement v1 helper class */ module.exports = class ConstantFlowAgreementV1Helper { /** * @dev Create new helper class * @param {Framework} sf Superfluid Framework object * * NOTE: You should first call async function Framework.initialize to initialize the object. */ constructor(sf) { this._sf = sf; this._cfa = sf.agreements.cfa; } /** * @dev Create a new flow * @param {tokenParam} superToken superToken for the flow * @param {addressParam} sender sender of the flow * @param {addressParam} receiver receiver of the flow * @param {flowRateParam} flowRate the flowrate of the flow * @param {Buffer} userData the user data passed to the callbacks * @param {Function} onTransaction function to be called when transaction hash has been generated * @return {Promise<Transaction>} web3 transaction object */ async createFlow({ superToken, sender, receiver, flowRate, userData, onTransaction = () => null }) { const superTokenNorm = await this._sf.utils.normalizeTokenParam( superToken ); const senderNorm = await this._sf.utils.normalizeAddressParam(sender); const receiverNorm = await this._sf.utils.normalizeAddressParam( receiver ); const flowRateNorm = this._sf.utils.normalizeFlowRateParam(flowRate); userData = userData || "0x"; console.debug( `Create flow from ${sender} to ${receiver} at ${flowRate} ...` ); const tx = await completeTransaction({ sf: this._sf, args: [ this._cfa.address, this._cfa.contract.methods .createFlow( superTokenNorm, receiverNorm, flowRateNorm, "0x" ) .encodeABI(), userData ], sender: senderNorm, method: this._sf.host.callAgreement, onTransaction }); this._sf._pushTxForGasReport(tx, "createFlow"); console.debug("Flow created."); return tx; } /** * @dev Update a new flow with a new flow rate * @param {tokenParam} superToken superToken for the flow * @param {addressParam} sender sender of the flow * @param {addressParam} receiver receiver of the flow * @param {flowRateParam} flowRate the flowrate of the flow * @param {Buffer} userData the user data passed to the callbacks * @param {Function} onTransaction function to be called when transaction hash has been generated * @return {Promise<Transaction>} web3 transaction object */ async updateFlow({ superToken, sender, receiver, flowRate, userData, onTransaction = () => null }) { const superTokenNorm = await this._sf.utils.normalizeTokenParam( superToken ); const senderNorm = await this._sf.utils.normalizeAddressParam(sender); const receiverNorm = await this._sf.utils.normalizeAddressParam( receiver ); const flowRateNorm = this._sf.utils.normalizeFlowRateParam(flowRate); userData = userData || "0x"; console.debug( `Update flow from ${sender} to ${receiver} to ${flowRate} ...` ); const tx = await completeTransaction({ sf: this._sf, args: [ this._cfa.address, this._cfa.contract.methods .updateFlow( superTokenNorm, receiverNorm, flowRateNorm, "0x" ) .encodeABI(), userData ], sender: senderNorm, method: this._sf.host.callAgreement, onTransaction }); this._sf._pushTxForGasReport(tx, "updateFlow"); console.debug("Flow updated."); return tx; } /** * @dev Delete a existing flow * @param {tokenParam} superToken superToken for the flow * @param {addressParam} sender sender of the flow * @param {addressParam} receiver receiver of the flow * @param {addressParam} by delete flow by a third party (liquidations) * @param {Buffer} userData the user data passed to the callbacks * @param {Function} onTransaction function to be called when transaction hash has been generated * @return {Promise<Transaction>} web3 transaction object */ async deleteFlow({ superToken, sender, receiver, by, userData, onTransaction = () => null }) { const superTokenNorm = await this._sf.utils.normalizeTokenParam( superToken ); const senderNorm = await this._sf.utils.normalizeAddressParam(sender); const receiverNorm = await this._sf.utils.normalizeAddressParam( receiver ); const byNorm = (by && (await this._sf.utils.normalizeAddressParam(by))) || senderNorm; userData = userData || "0x"; console.debug( `Delete flow from ${sender} to ${receiver} by ${by || byNorm} ...` ); const tx = await completeTransaction({ sf: this._sf, args: [ this._cfa.address, this._cfa.contract.methods .deleteFlow(superTokenNorm, senderNorm, receiverNorm, "0x") .encodeABI(), userData ], sender: byNorm, method: this._sf.host.callAgreement, onTransaction }); this._sf._pushTxForGasReport(tx, "deleteFlow"); console.debug("Flow deleted."); return tx; } /** * @dev Get information of a existing flow * @param {tokenParam} superToken superToken for the flow * @param {addressParam} sender sender of the flow * @param {addressParam} receiver receiver of the flow * @return {Promise<object>} Informationo about the flow: * - <Date> timestamp, time when the flow was last updated * - <string> flowRate, flow rate of the flow * - <string> deposit, deposit of the flow * - <string> owedDeposit, owed deposit of the flow */ async getFlow({ superToken, sender, receiver //unit }) { const superTokenNorm = await this._sf.utils.normalizeTokenParam( superToken ); const senderNorm = await this._sf.utils.normalizeAddressParam(sender); const receiverNorm = await this._sf.utils.normalizeAddressParam( receiver ); const result = await this._cfa.getFlow( superTokenNorm, senderNorm, receiverNorm ); return this.constructor._sanitizeflowInfo(result); } /** * @dev Get information of the net flow of an account * @param {tokenParam} superToken superToken for the flow * @param {addressParam} account the account for the query * @return {Promise<string>} Net flow rate of the account */ async getNetFlow({ superToken, account //unit }) { const superTokenNorm = await this._sf.utils.normalizeTokenParam( superToken ); const accountNorm = await this._sf.utils.normalizeAddressParam(account); const netFlow = await this._cfa.getNetFlow(superTokenNorm, accountNorm); return netFlow.toString(); } /** * @dev Get information of the net flow of an account * @param {tokenParam} superToken superToken for the flow * @param {addressParam} account the account for the query * @return {Promise<string>} Net flow rate of the account */ async getAccountFlowInfo({ superToken, account //unit }) { const superTokenNorm = await this._sf.utils.normalizeTokenParam( superToken ); const accountNorm = await this._sf.utils.normalizeAddressParam(account); const result = await this._cfa.getAccountFlowInfo( superTokenNorm, accountNorm ); return this.constructor._sanitizeflowInfo(result); } static _sanitizeflowInfo({ timestamp, flowRate, deposit, owedDeposit }) { return { timestamp: new Date(Number(timestamp.toString()) * 1000), flowRate: flowRate.toString(), deposit: deposit.toString(), owedDeposit: owedDeposit.toString() }; } async getFlowEvents({ token, receiver = null, sender = null }) { let flows; if (this._sf.agreements.cfa.getPastEvents) { flows = await this._sf.agreements.cfa.getPastEvents("FlowUpdated", { fromBlock: 0, toBlock: "latest", filter: { token, receiver, sender } }); } else { const filter = this._sf.agreements.cfa.filters.FlowUpdated( token, sender, receiver ); flows = await this._sf.agreements.cfa.queryFilter(filter); } return Object.values( flows.reduce((acc, i) => { acc[i.args.sender + ":" + i.args.receiver] = i; return acc; }, {}) ).filter((i) => i.args.flowRate.toString() != "0"); } /** * @dev List flows of the account * @param {tokenParam} superToken superToken for the flow * @param {addressParam} account the account for the query * @return {Promise<[]>} */ async listFlows({ superToken, account, onlyInFlows, onlyOutFlows //unit }) { const superTokenNorm = await this._sf.utils.normalizeTokenParam( superToken ); const accountNorm = await this._sf.utils.normalizeAddressParam(account); const result = {}; if (!onlyOutFlows) { result.inFlows = ( await this.getFlowEvents({ receiver: accountNorm, token: superTokenNorm }) ).map((f) => ({ sender: f.args.sender, receiver: f.args.receiver, flowRate: f.args.flowRate.toString() })); } if (!onlyInFlows) { result.outFlows = ( await this.getFlowEvents({ token: superTokenNorm, sender: accountNorm }) ).map((f) => ({ sender: f.args.sender, receiver: f.args.receiver, flowRate: f.args.flowRate.toString() })); } return result; } };
// This app depends of the fact that wp-json is installed on the server var websiteLocation = 'https://steinbring.net'; var data = {mainDetails:'',pages:{projects:'',resume:'',about:''},selected:'home',posts:'',currentPost:''}; var getMainDetails = function(){ var request = new XMLHttpRequest(); request.open('GET', websiteLocation+'/wp-json', false); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! // Set mainDetails to equal the query results data.mainDetails = JSON.parse(request.responseText); // Now that we have a value from the server, cache the value for later localStorage.setItem("mainDetails", JSON.stringify(data.mainDetails)); } else { // We reached our target server, but it returned an error } }; request.onerror = function() { // There was a connection error of some sort }; request.send(); }; var getPages = function(){ var request = new XMLHttpRequest(); request.open('GET', websiteLocation+'/wp-json/pages', false); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! // Set pages to equal the query results // Add target to each link, to make sure it opens in an external browser withTargetAdded = request.responseText.replace(new RegExp('a href', 'g'), 'a target=\'_blank\' href'); var tempPages = JSON.parse(withTargetAdded); for (var i = tempPages.length - 1; i >= 0; i--) { if(tempPages[i].slug == 'projects') data.pages.projects = tempPages[i]; if(tempPages[i].slug == 'resume') data.pages.resume = tempPages[i]; if(tempPages[i].slug == 'about') data.pages.about = tempPages[i]; }; // Now that we have a value from the server, cache the value for later localStorage.setItem("pages", JSON.stringify(data.pages)); } else { // We reached our target server, but it returned an error } }; request.onerror = function() { // There was a connection error of some sort }; request.send(); } var getPosts = function(){ var request = new XMLHttpRequest(); request.open('GET', websiteLocation+'/wp-json/posts', false); request.onload = function() { if (request.status >= 200 && request.status < 400) { // Success! // Set pages to equal the query results // Add target to each link, to make sure it opens in an external browser withTargetAdded = request.responseText.replace(new RegExp('a href', 'g'), 'a target=\'_blank\' href'); data.posts = JSON.parse(withTargetAdded); } else { // We reached our target server, but it returned an error } // Now that we have a value from the server, cache the value for later localStorage.setItem("posts", JSON.stringify(data.posts)); // Close the "loading" screen $('#loadingDialog').modal('hide'); }; request.onerror = function() { // There was a connection error of some sort }; request.send(); } var getOldValues = function(){ // Only set the values if there is something there to set if(localStorage.getItem("pages") != null) data.pages = JSON.parse(localStorage.getItem("pages")); if(localStorage.getItem("posts") != null) data.posts = JSON.parse(localStorage.getItem("posts")); if(localStorage.getItem("mainDetails") != null) data.mainDetails = JSON.parse(localStorage.getItem("mainDetails")); } // Out of the box, Rivets.js can't do comparisons. This gives you a way. rivets.formatters.eq = function (value, args) { return value === args; }; // This is needed for the navigation links var toggle = function(tab){ data.selected = tab; if(tab != 'blog') data.currentPost = ''; }; // This is needed for blog navigation var toggleBlog = function(postSlug){ for (var i = data.posts.length - 1; i >= 0; i--) { if(data.posts[i].slug == postSlug) data.currentPost = data.posts[i]; } } // Prepopulate the values with anything previously downloaded getOldValues(); // Is the user online? If they are, refresh the data. if (navigator.onLine) { // Open the "Loading" screen $('#loadingDialog').modal('show'); getMainDetails(); getPages(); getPosts(); } // If the user is offline, don't bother offering them the twitter link else{ document.getElementById('twitterLink').style.display = 'none'; } var longFormatDate = function(date){ var monthNames = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ]; var date = new Date(date); var day = date.getDate(); var monthIndex = date.getMonth(); var year = date.getFullYear(); return monthNames[monthIndex] + ' ' + day+ ', ' + year } rivets.formatters.longDate = function(value) { return longFormatDate(value); }; // Bind the data to part of the DOM var el = document.getElementById('data'); rivets.bind(el, {data: data});
// get the client const mysql = require('mysql2'); // create the connection to database const connection = mysql.createConnection({ host: '192.168.1.141', port:"3306", user:"root", password: "123456" }); // simple query connection.query( 'show databases;', function (err, results, fields) { console.log("err",err) console.log("results",results); // results contains rows returned by server console.log("fields",fields); // fields contains extra meta data about results, if available } );
import {createGUI} from './helpers.mjs'; const supportedMethods = ['get', 'post', 'put', 'patch', 'delete'] const body = document.body; body.appendChild(createGUI(supportedMethods)); // const config = { // 'tagName': 'button', // 'tagText': 'ala ma kota', // 'tagClass': 'send', // 'tagId': 'send', // 'tagAttr': { // 'key': 'placeholder', // 'val': 'endpoint' // }, // 'tagEvent': { // 'type': 'click', // 'cb': () => { // console.log('text'); // } // } // } // const methodList = document.querySelector('#methods'); // const endpoint = document.querySelector('#endpoint'); // const sendBtn = document.querySelector('#send');
const express = require('express') const mongoose = require('mongoose') const axios = require('axios') const { connectDb } = require('./helpers/db') const { port, host, db, authApiUrl } = require('./configuration') const app = express() const postSchema = new mongoose.Schema({ name: String }) const Post = mongoose.model('Post', postSchema) const startServer = () => { app.listen(port, () => { console.log(`Server listening on ${port}`) console.log(`On host ${host}`) console.log(`Our db ${db}`) Post.find(function (err, posts) { if (err) return console.error(err); console.log(posts); }) const silence = new Post({name: "silence"}) silence.save((function (err, savedPost) { if(err) return console.error(err) console.log('save post:', savedPost) })) }) } app.get('/test', (req, res) => { res.send('Its works') }) app.get('/testwithcurrentuser', async (req, res) => { console.log(authApiUrl + '/currentUser') const result = await axios.get(authApiUrl + '/currentUser') res.json({ testwithcurrentuser: true, currentUserFromAuth: result.data }) }) app.get('/api/testapidata', (req, res) => { res.json({ message: "Hello Man" }) }) connectDb() .on('error', console.log) .on('disconnect', connectDb) .once('open', startServer)
const cv = () => { return ( <h1>cv</h1> ) } export default cv
// Dedié à la partie header de la page : patrimoine function myFunction(imgs) { var expandImg = document.getElementById("expandedImg"); var imgText = document.getElementById("imgtext"); expandImg.src = imgs.src; imgText.innerHTML = imgs.alt; expandImg.parentElement.style.display = "block"; } // Dédié à la page guide_voyage formulaire (function() { 'use strict'; window.addEventListener('load', function() { var forms = document.getElementsByClassName('needs-validation'); var validation = Array.prototype.filter.call(forms, function(form) { form.addEventListener('submit', function(event) { if (form.checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.classList.add('was-validated'); }, false); }); }, false); })();
import * as Yup from 'yup'; import Plan from '../models/Plan'; class PlanController { async store(req, res) { const schema = Yup.object().shape({ title: Yup.string().required(), price: Yup.number() .positive() .required(), duration: Yup.number() .positive() .required(), }); if (!(await schema.isValid(req.body))) { return res.status(400).json({ error: 'Validation failed.' }); } const planExists = await Plan.findOne({ where: { title: req.body.title, deleted: false, }, }); if (planExists) { return res.status(400).json({ message: 'Please use another title.', }); } const { id, title, duration, price } = await Plan.create(req.body); return res.status(201).json({ message: 'Plan created sucessfully!', plan: { id, title, duration, price, }, }); } async index(req, res) { const plans = await Plan.findAll({ where: { deleted: false }, attributes: ['title', 'duration', 'price'], }); return res.json(plans); } async update(req, res) { const schema = Yup.object().shape({ title: Yup.string(), price: Yup.number().positive(), duration: Yup.number().positive(), }); if (!(await schema.isValid(req.body))) { return res.status(400).json({ error: 'Validation failed.' }); } const plan = await Plan.findByPk(req.params.id); if (!plan) { return res .status(404) .json({ error: 'This plan does not exists.' }); } if (plan.deleted) { return res .status(401) .json({ error: 'You cant change a deleted plan.' }); } if (req.body.title && req.body.title !== plan.title) { const planExists = await Plan.findOne({ where: { title: req.body.title, deleted: false, }, }); if (planExists) { return res.status(400).json({ message: 'Please use another title.', }); } } const { id, title, duration, price } = await plan.update(req.body); return res.status(200).json({ message: 'Plan updated sucessfully!', plan: { id, title, duration, price }, }); } async delete(req, res) { const plan = await Plan.findByPk(req.params.id); if (!plan) { return res .status(404) .json({ error: 'This plan does not exists.' }); } if (plan.deleted) { return res .status(400) .json({ error: 'This plan is already deleted.' }); } plan.deleted = true; await plan.save(); return res .status(200) .json({ message: 'Plan deleted sucessully', plan }); } } export default new PlanController();
export default function ({app}) { if (!app.$cookies.get('s')) { app.$cookies.set('s', 'Morocco', { path: '/' }) } }
const db = require('../model/transactions') const insert = (req, res) => { db.create({ buyer: req.headers.auth.id, goods: req.headers.goods, address: req.body.address, telp: req.body.telp }) .then(response => { res.send(response) }) .catch(err => { res.send(err) }) } const all = (req, res) => { db.find({ _id: req.params.id }) .populate('buyer') .populate('goods') .then(response => { res.send(response) }) .catch(err => { res.send(err) }) } module.exports = { all, insert }
import React, { Fragment } from 'react'; import convertReaderToDataUri from '../utils/convertReaderToDataUri'; import { FileInputStyle } from './styles/FileUploadStyles'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import { setDataUri } from '../redux/actions/image'; const FileInput = ({ setDataUri }) => { const handleFile = async (e) => { const file = e.target.files[0]; const uriString = await convertReaderToDataUri(file); setDataUri(uriString); }; return ( <Fragment> <p className="lead text-primary"> Choose a File To Upload <br /> to Our AI! </p> <FileInputStyle type="file" name="file" id="file" onChange={handleFile} /> <label htmlFor="file">Upload</label> </Fragment> ); }; FileInput.propTypes = { setDataUri: PropTypes.func.isRequired, }; export default connect(null, { setDataUri })(FileInput);
import React from 'react'; import { BrowserRouter as Router, Route } from 'react-router-dom'; import Test1 from './Test1'; import Test2 from './Test2'; import index from './'; import TestF from './TestF'; import TestFunc from './TestFunc'; const Routes = () => ( <Router> <Route path="/" component={index} /> <Route path="/class" component={Test1} /> <Route path="/func" component={Test2} /> <Route path="/reduxclasscounter" component={TestF} /> <Route path="/reduxfunccounter" component={TestFunc} /> </Router> ); export default Routes;
import { renderString } from '../../src/index'; describe(`Returns a Blog by id`, () => { it(`unnamed case 0`, () => { const html = renderString(`{{ blog_by_id(123) }}`); }); });
// 判断两个对象的相等 // 就是在判断成员是否相等 // 简单对象演示( 复杂对象 ) function compare_plain_obj( obj1, obj2 ) { if ( obj1 === obj2 ) return true; // 地址不相同 // 什么是两个对象相同? // 对象1 中的所有属性, 在 对象2 中都有. 而且值都相同 => 对象1 包含 在对象2 中 // 如果对象2 中的所有成员, 在 对象1 中也都有. 而且值相等 => 对象2 包含在对象 1 中 for ( var k in obj2 ) { // if ( 是不是引用类型 ) { // 递归 // } if ( obj1[ k ] !== obj2[ k ] ) { return false; // obj2 中有一个成员 在 obj1 中不存在 // null, undefined 需要单独讨论 } } // 如果代码走到这里, 说明 obj2 包含在 obj1 中 for ( var k in obj1 ) { if ( obj1[ k ] !== obj2[ k ] ) { return false; // obj1 中有一个成员 在 obj2 中不存在 } } // 说明互相包含 return true; } var o1 = { name: 'jim', age: 19, gender: '男' }; var o2 = { name: 'jim', age: '19', gender: '男' }; console.log( compare_plain_obj( o1, o2 ) );
(function(){ /** Class representing a color */ class Color{ /** * Creates a Color object. * @param {string} cssStr - String of css color value */ constructor(cssStr){ this.rbg = parseRGB(rbg_str) this.r = r this.g = g this.b = b } /** * Parses the RBG value from a string representing the css color. * @param {number} str - color string * @returns {array} An array containg the rbg values in thei respective order. */ parseRGB(str){ //TODO: check if hex or rbg return str.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); } /** * Return the hex value of a RBG digit * @param {number} x - digit of RBG 8 bit value * @returns {array} An array containg the rbg values in resptive order. */ hex(x) { return ("0" + parseInt(x).toString(16)).slice(-2) } /** * Covert the color RBG value to Hex * @param {number} x - digit of RBG 8 bit value * @returns {array} An array containg the rbg values in resptive order. */ rgbToHex(rgb){ return "x" + hex(rbg[1]) + hex(rgb[2]) + hex(rgb[3]) } /** * Calculate the brightness(luminance) of the color. * @param {number} x - digit of RBG 8 bit value * @returns {array} An array containg the rbg values in resptive order. */ calculateBrightness(){ let L = 0.2126 * this.r + 0.7152 * this.g + 0.0722 * this.b return L } } /** Class representing the Relative Lumainance. */ class RelativeLuminance{ /** * Set the defualts for this * @param {obj} conf - Configuration object containing the background color, text color and the text size */ constructor(conf){ this.backgroundColor = null this.textColor = null this.textSize = null Object.keys().foreach(function(propName){ this[propName] = conf[propName] }, this); } /* Comapre the text color with the background color * @param {string} L1 - Relative Luminance of the text color. * @param {string} L2 - Relative Luminance of the background color. * @returns {number} The contrast ratio. */ compare(L1, L2){ let constrast_ratio = (L1 + 0.05) / (L2 + 0.05) return constrast_ratio } /* Get the relative Luminance of a 8 bit RBG color. * @returns {number} The luminance of the colr. */ relativeLuminance(){ r = this.textColor.r/255 g = this.textColor.g/255 b = this.textColor.b/255 r = (r <= 0.03928) ? r/12.92 : Math.pow(((RsRGB+0.055)/1.055), 2.4) g = (g <= 0.03928) ? g/12.92 : Math.pow(((g+0.055)/1.055), 2.4) b = (b <= 0.03928) ? b = b/12.92 : Math.pow(((b+0.055)/1.055), 2.4) let luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b return luminance } } })();
// Global Name for Screens // Login export const LOGIN = 'sta.login'; // Main Stack export const CALENDAR = 'sta.calendar'; export const HOME = 'sta.home'; export const PHOTOS = 'sta.photos'; export const TOOLS = 'sta.tools'; // Tools export const CURRENCY = 'sta.currency'; export const JOURNAL = 'sta.journal'; export const SETTINGS = 'sta.settings'; export const TODOS = 'sta.todos';
'use strict'; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var e = React.createElement; var MeasuresList = function (_React$Component) { _inherits(MeasuresList, _React$Component); function MeasuresList(props) { _classCallCheck(this, MeasuresList); var _this = _possibleConstructorReturn(this, (MeasuresList.__proto__ || Object.getPrototypeOf(MeasuresList)).call(this, props)); _this.state = { error: null, isLoaded: false, data: [] }; return _this; } _createClass(MeasuresList, [{ key: 'componentDidMount', value: function componentDidMount() { var _this2 = this; axios.get('/api/measures').then(function (result) { var data = result.data; _this2.setState({ error: null, data: data, isLoaded: true }); }, function (error) { _this2.setState({ error: error }); }); } }, { key: 'render', value: function render() { var _state = this.state, error = _state.error, isLoaded = _state.isLoaded, data = _state.data; if (error) { return React.createElement( 'div', null, 'Error: ', error ); } if (!isLoaded) { return React.createElement( 'div', null, 'Please wait' ); } return React.createElement( 'div', null, data.items.map(function (d, idx) { return React.createElement( 'li', { key: idx }, d.measureValue ); }) ); } }]); return MeasuresList; }(React.Component); ReactDOM.render(e(MeasuresList), document.querySelector('#itemsList'));
shapely.geom = function( coords, type ){ var type = type; var coords = coords; var geom = { area: area, length: length } function area(){ return 0.0; } function length(){ return 0.0; } return geom; };
import React from 'react'; import {Container, Card, Row, Col } from 'react-bootstrap' const ServiceItems = (props) => ( <div> <Card> <Container className="dark-text service"> <Row className="service"> Milage: {props.item.milage} </Row> <Row className="service"> Service Done: {props.item.service}</Row> <Row className="service"> Comments: {props.item.note}</Row> <Row className="service"> Cost: ${props.item.cost}</Row> </Container> </Card> </div> ) export default ServiceItems;
import React ,{useState} from 'react'; import {Link} from "react-router-dom"; const CourseCard = ( { course, lastModified="1/1/2021", owner="who knows?", deleteCourse, updateCourse }) => { const [editing, setEditing] = useState(false) const [title, setTitle] = useState(course.title) const saveCourse = () => { setEditing(false) const newCourse = { ...course, title: title } updateCourse(newCourse) } return ( <div className="col-xl-2 col-lg-3 col-md-4 col-sm-6 col-xs-1"> <div className="card" > {<img className="card-img-top" src="https://picsum.photos/300/200" />} <div className="card-body" > <h5 className="card-title"> {!editing && <a href={`/courses/grid/edit/${course._id}`}> {course.title} </a> } {editing && <input className="form-control " onChange={(e) => setTitle(e.target.value)} value={title}/> } </h5> <p className="card-text">Some Description</p> <p>{course.owner}</p> <p>{course.lastModified}</p> <div> {editing && <i onClick={() => deleteCourse(course)} className="fas fa-trash"></i> } { editing && <i onClick={() => saveCourse()} className="fas fa-check"></i> } { !editing && <i onClick={() => setEditing(true)} className="fas fa-edit"></i> } </div> </div> </div> </div> )} export default CourseCard
var mocks = require('./mocks.js'); var request = require('supertest'); var jade = require('jade'); var should = require('should'); var app = require('../app')(mocks); var views = __dirname + '/../views/'; describe('App', function() { describe('/', function() { beforeEach(function() { mocks.db.err = null; }); it('should return rendered main page without content', function(done) { request(app).get('/') .expect(200) .expect('Content-Type', 'text/html; charset=utf-8') .end(function(err, res) { if (err) throw err; var pattern = app.engines['.jade'](views + 'index.jade', { title: 'Мой дом', basedir: __dirname + "/../public" }); res.text.should.equal(pattern); done(); }); }); it('should return array of rendered ads', function(done) { var ad1 = { id: 1, name: "name", second_name: "second", header: "header", description: "description", price: 12, price_type: 'per_hour' }; mocks.db.ads = [ad1]; request(app) .get('/adsReq?lo_lat=55.646&lo_lng=37.757&hi_lat=55.647&hi_lng=37.759') .expect(200) .expect('Content-Type', 'application/json; charset=utf-8') .end(function(err, res) { if (err) throw err; res.body.should.length(1); res.body[0].html.should.equal(app.engines['.jade'](views + 'ad.jade', ad1)); res.body[0].id.should.be.exactly(1); done(); }); }); it('should return err when ads requested', function(done) { mocks.db.err = new Error("test error"); request(app).get('/adsReq') .expect(500) .expect('Content-Type', 'text/html; charset=utf-8') .end(function(err, res) { if (err) throw err; res.error.text.should.containEql("<h1>test error</h1>"); done(); }); }); it('should return array of tags', function(done) { mocks.db.tags = ["tag1", "tag2"]; request(app) .get('/tagsReq') .expect(200) .expect('Content-Type', 'application/json; charset=utf-8') .end(function(err, res) { if (err) throw err; res.body.should.length(2); res.body.should.eql(mocks.db.tags); done(); }); }); it('should return err when ads requested', function(done) { mocks.db.err = new Error("test error"); request(app).get('/tagsReq') .expect(500) .expect('Content-Type', 'text/html; charset=utf-8') .end(function(err, res) { res.error.text.should.containEql("<h1>test error</h1>"); done(); }); }); }); describe('other', function() { it('should return 404 error', function(done) { request(app).get('/somePath') .expect(404) .expect('Content-Type', 'text/html; charset=utf-8') .end(function(err, res) { if (err) throw err; done(); }); }); }); });
const express = require("express"); const bbGController = require("../../Controllers/BebidasControl/BebidaGaseosa"); const api = express.Router(); api.post("/agregar-BebidaGaseosa", bbGController.guardarBG); api.get("/gaseosa", bbGController.getGaseosas); api.put("/updateBebGas/:id", bbGController.updateBebGas); api.delete("/deleteBebGas/:id", bbGController.deleteBebGas); module.exports = api;
import styled from 'styled-components' const SearchBarWrapper = styled.div` display: flex; align-items: center; width: 1040px; margin: 0 auto; ` const SearchBarForm = styled.form` width: 100%; `; const SearchBarButton = styled.a` border: 1px solid #fff; height: 50px; line-height: 50px; cursor: pointer; padding: 0 10px; ` const SearchBarInput = styled.input` border: 0; font-size: 18px; width: 100%; height: 50px; padding: 0 17px; ` export { SearchBarWrapper, SearchBarForm, SearchBarButton, SearchBarInput }
module.exports = function (params) { const keys = Object.keys(params); for (let i = 0; i < keys.length; i++) { if (!params[keys[i]]) { return false; } } return true; };
import React, { Component } from "react"; import { Link } from "react-router-dom"; import PropTypes from "prop-types"; // Redux import { connect } from "react-redux"; import { setDetailsMovie, addMovieToCollection, removeMovieFromCollection } from "../../../actions/movieActions"; class TrendingMovie extends Component { onClick = e => { e.preventDefault(); const movie = { movie: this.props.movie }; this.props.setDetailsMovie(movie); }; render() { const { isAuthenticated } = this.props.auth; const { myMovies } = this.props.movies; const { title, vote_average, release_date, poster_path, id } = this.props.movie; let shortTitle; const year = release_date.slice(0, 4); if (title.length > 13) { shortTitle = title.substring(0, 12) + "..."; } else { shortTitle = title; } let likeButton; if (isAuthenticated) { if (myMovies.some(movie => parseInt(movie.movie_id) === id)) { likeButton = likeButton = ( <button type="button" className="button button-red button-add" onClick={() => this.props.removeMovieFromCollection(id)} > Remove </button> ); } else { likeButton = ( <button type="button" className="button button-green button-add" onClick={() => this.props.addMovieToCollection(this.props.movie)} > ADD </button> ); } } else { likeButton = ( <Link to="/login" style={{ marginLeft: "auto", color: "black" }}> <button type="button" className="button button-green"> ADD </button> </Link> ); } return ( <div onClick={this.onClick} className="carousel-container"> <img src={`http://image.tmdb.org/t/p/w185/${poster_path}`} alt="" className="carousel-image" /> <p className="vote">{vote_average}</p> <div className="carousel-info"> <Link to="/details" style={{ textDecoration: "none" }} > <h4 className="carousel-info-title"> {shortTitle} ({year}) </h4> </Link> {likeButton} </div> </div> ); } } TrendingMovie.propTypes = { auth: PropTypes.object.isRequired, movies: PropTypes.object.isRequired, setDetailsMovie: PropTypes.func.isRequired, addMovieToCollection: PropTypes.func.isRequired, removeMovieFromCollection: PropTypes.func.isRequired }; const mapStateToProps = state => ({ auth: state.auth, profile: state.profile, movies: state.movies }); export default connect( mapStateToProps, { setDetailsMovie, addMovieToCollection, removeMovieFromCollection } )(TrendingMovie);
$(document).ready(function() { $('#test').on('click', function (e) { console.log("event",event); console.log("this", $(this)); console.log("this not jq", this); }); }); // this.a = 37 // console.log(window.a); // var fubar = "42"; // function baz() { // console.log("baz"); // bar(); // } // function bar() { // console.log("bar"); // foo(); // } // function foo() { // console.log("foo"); // var fubar = 13; // console.log("this", this); // foo // console.log("fubar", this.fubar); // 13 // } // baz(); var a = 3; function foo() { console.log("this", this); // obj for (key in this) { console.log(this.key); } console.log("a", this.monkey); // 2 } var obj = { a: 2, monkey: foo }; obj.monkey();
function inArray(value,array){ if(Array.prototype.indexOf){ return array.indexOf(value) !== -1; }else{ var has = 0; for(var i=0,len=array.length; i<len;i++){ if(value === array[i]){ has = 1; break; } } return has; } } _.difference = function(array,values){ var tempArr = []; for(var i=0 ,len=array.length;i<len;i++){ if(inArray(array[i],values)){ tempArr.push(array[i]); } } return tempArr; } /* console.log(_.difference([1,2,4,6,8],[1,6,9,8])); */