text
stringlengths 7
3.69M
|
|---|
import React, { Component } from "react"
import "./Mapview.scss"
import { loadModules } from "react-arcgis"
// import { loadModules } from "../../../../../public/data/data"
var data = [ //json数据
{
"name":"长城",
"x":116.016033,
"y":40.364233,
"desc":"长城(Great Wall),又称万里长城,是中国古代的军事防御工程,是一道高大、坚固而连绵不断的长垣,用以限隔敌骑的行动。长城不是一道单纯孤立的城墙,而是以城墙为主体,同大量的城、障、亭、标相结合的防御体系。",
"type":"cultureHeritage"
},
{
"name":"莫高窟",
"x":94.815602,
"y":40.048747,
"desc":"莫高窟,俗称千佛洞,坐落在河西走廊西端的敦煌。它始建于十六国的前秦时期,历经十六国、北朝、隋、唐、五代、西夏、元等历代的兴建,形成巨大的规模,有洞窟735个,壁画4.5万平方米、泥质彩塑2415尊,是世界上现存规模最大、内容最丰富的佛教艺术地。",
"type":"cultureHeritage"
},
{
"name":"故宫",
"x":116.403414,
"y":39.924091,
"desc":"北京故宫是中国明清两代的皇家宫殿,旧称为紫禁城,位于北京中轴线的中心,是中国古代宫廷建筑之精华。北京故宫以三大殿为中心,占地面积72万平方米,建筑面积约15万平方米,有大小宫殿七十多座,房屋九千余间。是世界上现存规模最大、保存最为完整的木质结构古建筑之一。",
"type":"cultureHeritage"
},
{
"name":"秦始皇陵及兵马俑坑",
"x":109.289337,
"y":34.392294,
"desc":"秦始皇陵是中国历史上第一个皇帝——秦始皇帝的陵园,也称骊山陵。兵马俑坑是秦始皇陵的陪葬坑,位于陵园东侧1500米处。其规模之大、陪葬坑之多、内涵之丰富,为历代帝王陵墓之冠。",
"type":"cultureHeritage"
},
{
"name":"周口店北京人遗址",
"x":115.938822,
"y":39.696296,
"desc":"周口店遗址博物馆坐落在北京城西南房山区周口店龙骨山脚下,是一座古人类遗址博物馆,始建于1953年。1929年,中国古人类学家裴文中先生在龙骨山发掘出第一颗完整的“北京猿人”头盖骨化石,震撼了全世界。",
"type":"cultureHeritage"
},
{
"name":"拉萨布达拉宫历史建筑群",
"x":91.125103,
"y":29.660384,
"desc":"布达拉宫(藏文:??????,藏语拼音:bo da la,威利:po ta la),坐落于于中国西藏自治区的首府拉萨市区西北玛布日山上,是世界上海拔最高,集宫殿、城堡和寺院于一体的宏伟建筑,也是西藏最庞大、最完整的古代宫堡建筑群。",
"type":"cultureHeritage"
},
{
"name":"峨眉山-乐山大佛",
"x":103.450213,
"y":29.575827,
"desc":"峨眉山(Mount Emei)山头位于中国四川省乐山市峨眉山市境内,是中国“四大佛教名山”之一,地势陡峭,风景秀丽,素有“峨眉天下秀”之称,山上的万佛顶最高,海拔3099米,高出峨眉平原2700多米。《峨眉郡志》云:“云鬘凝翠,鬒黛遥妆,真如螓首蛾眉,细而长,美而艳也,故名峨眉山。”",
"type":"doubleHeritage"
},
{
"name":"九寨沟国家级自然保护区",
"x":103.925277,
"y":33.273815,
"desc":"九寨沟:世界自然遗产、国家重点风景名胜区、国家AAAAA级旅游景区、国家级自然保护区、国家地质公园、世界生物圈保护区网络,是中国第一个以保护自然风景为主要目的的自然保护区。",
"type":"natureHeritage"
}
];
export default class MapVIew extends Component {
componentDidMount() {
}
mapDom() {
loadModules(["esri/Map",
"esri/views/MapView",
"esri/views/SceneView",
"esri/widgets/Search",
"esri/layers/TileLayer",
"esri/geometry/Point",
"esri/layers/GraphicsLayer",
"esri/Graphic",
"dojo/_base/Color",
"dojo/domReady!"
]).then(([Map, MapView, SceneView, Search,TileLayer,Point,GraphicsLayer,Graphic,Color]) => {
var switchButton = this.input
var appConfig = {
mapView: null,
sceneView: null,
activeView: null,
container: this.viewDiv // use same container for views
};
var initialViewParams = {
zoom: 12,
center : [ 120.160338, 32.325512 ],
container: appConfig.container
};
var map = new Map({
basemap: "streets",
ground: "world-elevation"
});
console.log("hello world...")
var tiled = new TileLayer("https://server.arcgisonline.com/ArcGIS/rest/services/Reference/World_Transportation/MapServer",{"id":"tiled"});
map.add(tiled);
// var mapCenter = new Point(103.847, 36.0473, {"wkid":4326});
// map.centerAndZoom(mapCenter,3);
var gLyr = new GraphicsLayer({"id":"gLyr"});
map.add(gLyr);
var gLyrLbl = new GraphicsLayer({"id":"gLyrLbl"});
map.add(gLyrLbl);
map.on("load",function(){
for(var i=0;i<data.length;i++){
var pt = new Point(data[i].x,data[i].y,{"wkid":4326});
var pms;
if (data[i].type=="natureHeritage") {
pms = new esri.symbol.PictureMarkerSymbol(require("../../../../image/env/weather/10.png"),30,30);
}else if (data[i].type=="cultureHeritage") {
pms = new esri.symbol.PictureMarkerSymbol(require("../../../../image/env/weather/10.png"),30,30);
}else if (data[i].type=="doubleHeritage") {
pms = new esri.symbol.PictureMarkerSymbol(require("../../../../image/env/weather/10.png"),30,30);
}
var gImg = new Graphic(pt,pms,data[i]);
gLyr.add(gImg);
var gLbl = new esri.Graphic(pt,data[i]);
gLyrLbl.add(gLbl);
}
gLyr.on("mouse-over",function(e){
var attr = e.graphic.attributes;
showInfo(attr);
});
});
function showInfo(attr){
var pt=new Point(attr.x,attr.y,{"wkid":4326});//WGS84的点
map.infoWindow.setTitle(attr.name);
map.infoWindow.setContent(attr.desc);
map.infoWindow.show(pt);
}
// create 2D view and and set active
appConfig.mapView = createView(initialViewParams, "2d");
appConfig.mapView.map = map;
appConfig.activeView = appConfig.mapView;
// create 3D view, won't initialize until container is set
initialViewParams.container = null;
initialViewParams.map = map;
appConfig.sceneView = createView(initialViewParams, "3d");
// switch the view between 2D and 3D each time the button is clicked
switchButton.addEventListener("click", function () {
switchView();
});
// Switches the view from 2D to 3D and vice versa
function switchView() {
var is3D = appConfig.activeView.type === "3d";
// remove the reference to the container for the previous view
appConfig.activeView.container = null;
if (is3D) {
appConfig.mapView.viewpoint = appConfig.activeView.viewpoint.clone();
appConfig.mapView.container = appConfig.container;
appConfig.activeView = appConfig.mapView;
switchButton.value = "3D";
} else {
appConfig.sceneView.viewpoint = appConfig.activeView.viewpoint.clone();
appConfig.sceneView.container = appConfig.container;
appConfig.activeView = appConfig.sceneView;
switchButton.value = "2D";
}
}
// convenience function for creating a 2D or 3D view
function createView(params, type) {
var view;
var is2D = type === "2d";
if (is2D) {
view = new MapView(params);
} else {
view = new SceneView(params);
}
search(view)
return view;
}
// search
function search (view) {
var searchWidget = new Search({
view: view
});
view.ui.add(searchWidget, {
position: "top-right"
});
}
})
return (
<div>
<div
ref={(dom) => { this.viewDiv = dom }}
className="viewDiv"
style={{ width: "100%", height: "100vh" }}
>
</div>
<div id="infoDiv">
<input className="esri-component esri-widget--button esri-widget esri-interactive"
type="button"
id="switch-btn"
value="3D"
ref={(input) => { this.input = input }}
/>
</div>
</div>
)
}
render() {
return (
<div>
{this.mapDom()}
</div>
)
}
}
|
import React from 'react';
const ErrorIcon = () => (
<svg
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<circle cx="12" cy="12" r="9" fill="#CF176C" />
<path
d="M12 2C6.48 2 2 6.48 2 12C2 17.52 6.48 22 12 22C17.52 22 22 17.52 22 12C22 6.48 17.52 2 12 2ZM13 17H11V15H13V17ZM13 13H11V7H13V13Z"
fill="#F9DAE9"
/>
</svg>
);
export default ErrorIcon;
|
import React from "react";
import './index.css';
import { Button, Tooltip, message} from "antd";
import {CopyOutlined } from '@ant-design/icons';
export default class Getandcopy extends React.Component {
constructor(props) {
super(props);
this.copyRef = React.createRef();
this.state = {
content:''
}
}
getcontent = ()=>{
this.props.getcontent && this.props.getcontent((content)=>{
this.setState({
content
});
});
};
copyClick = ()=>{
if (!this.state.content){
message.destroy();
message.warning('内容为空,复制失败!');
return;
}
this.copyRef.current.value = this.state.content; // 修改文本框的内容
this.copyRef.current.select(); // 选中文本
document.execCommand("copy");
message.destroy();
message.success('复制成功!');
};
render() {
return (
<div className='get-copy-box'>
<Button
onClick={this.getcontent}
size='small'
type="primary"
disabled={this.props.disabled}
>
{this.props.btntext}
</Button>
<Tooltip title='复制'>
<CopyOutlined onClick={this.copyClick}/>
</Tooltip>
<textarea ref={this.copyRef}></textarea>
<p>{this.state.content}</p>
</div>
);
}
}
|
import React from 'react';
import {gestureHandlerRootHOC} from 'react-native-gesture-handler';
import {Navigation} from 'react-native-navigation';
import {Provider} from 'react-redux';
import SplashScreen from './SplashScreen';
import DetailsScreen from './src/Components/Details';
console.ignoredYellowBox = [
'Warning: Each',
'Warning: Failed',
"Warning: Can't perform",
];
import store from './src/store';
Navigation.registerComponentWithRedux(
'Details',
() => gestureHandlerRootHOC(DetailsScreen),
Provider,
store,
);
Navigation.registerComponentWithRedux(
'Home',
() => gestureHandlerRootHOC(SplashScreen),
Provider,
store,
);
Navigation.events().registerAppLaunchedListener(async () => {
await Navigation.setRoot({
root: {
stack: {
id: 'HomeStack', // This is the id we're going to use when interacting with the stack
children: [
{
component: {
id: 'details',
name: 'Details',
},
},
{
component: {
id: 'home',
name: 'Home',
},
},
],
},
},
});
});
Navigation.setDefaultOptions({
animations: {
push: {
waitForRender: true,
},
setRoot: {
waitForRender: true
}
},
});
|
$(document).ready(function() {
// Using translate.js <https://github.com/tinoni/translate.js>
// Part 1 of 2 of translate.js: Constructing the dictionary
var dict = {
"Proximos Eventos": { // Translations for "Tour"
es: "Proximos Eventos",
en: "Upcoming Events"
},
"Próximamente": { // Translations for "Coming Soon"
es: "Próximamente",
en: "Coming Soon"
},
"Discografía": { // Translations for "Discography"
es: "Discografía",
en: "Discography"
},
"VER MAS": { // Translations for "Read More"
es: "VER MAS",
en: "READ MORE"
},
"Biografía": { // Translations for "Biography"
es: "Biografía",
en: "Biography"
},
"Benito Antonio Martínez Ocasio, conocido en el mundo de la música como Bad Bunny, es un cantante y compositor puertorriqueño de hip-hop en español, rap, trap y otros ritmos urbanos. Nació en San Juan, Puerto Rico el 10 de marzo de 1994 y es reconocido por ser un artista creativo y versátil": {
es: "Benito Antonio Martínez Ocasio, conocido en el mundo de la música como Bad Bunny, es un cantante y compositor puertorriqueño de hip-hop en español, rap, trap y otros ritmos urbanos. Nació en San Juan, Puerto Rico el 10 de marzo de 1994 y es reconocido por ser un artista creativo y versátil",
en: "Benito Antonio Martínez Ocasio, known in the world of music as Bad Bunny, is a Puerto Rican singer and songwriter (He also has American nationality) of hip-hop in Spanish, rap, trap and other urban rhythms. He was born in San Juan, Puerto Rico on March 10, 1994, and is recognized as a creative and versatile artist"
}
};
// Part 2 of 2 of translate.js: Enabling buttons to start translation
$("#esp").click(function() {
var translator = $("body").translate({lang: "es", t: dict}); // translating to Spanish
});
$("#eng").click(function() {
var translator = $("body").translate({lang: "en", t: dict}); // translating to English
});
$(".tile").mouseenter(function() {
$(this).removeClass("unselected");
$(this).addClass("selected");
});
$(".tile").mouseleave(function() {
$(this).removeClass("selected");
$(this).addClass("unselected");
});
}); // end of JavaScript code
|
let commands = require('../../../src/commands');
describe('clap slash command', () => {
test('function exists', () => {
expect(typeof commands.clap).toBe('function')
})
})
describe('save slash command', () => {
test('function exists', () => {
expect( typeof commands.save).toBe('function')
})
})
|
/**
* Created by duoyi on 2017/3/8.
*/
const Koa = require('koa')
const path = require('path')
const staticSever = require('koa-static')
// 处理URL
const router = require('koa-router')()
// api编写
const START = require('./router')
// 处理返回参数体
const bodyParser = require('koa-bodyparser')
// rest
const rest = require('./middleware/rest')
const app = new Koa()
app.use(bodyParser())
app.use(rest.restify())
app.use(staticSever(path.join(__dirname, 'WEB/dist')))
START(router)
app.use(router.routes())
app.listen(3000)
console.log('app started at port 3000...')
|
class staticObject{
constructor(vPos, vDim, oOptions){
this.pos = vPos || new vector(0,0);
this.dim = vDim || new vector(16,16);
this.swiss(oOptions, "all");
//game.renderer.push(this);
}
}
staticObject.prototype.centerOver = function(oObj){
this.pos = (oObj.getCenter()).subtract(this.dim.scalar(0.5));
}
staticObject.prototype.rotateZ = function(){
}
staticObject.prototype.update = function(nDelta){
switch (this.constructor.name) {
case "sprite":
}
}
staticObject.prototype.sides =()=>{
return [this.pos.x, this.pos.x + thos.dim.x, this.pos.y, this.pos.y + this.dim.y]
}
overlapX = function(obj1, obj2){
this.left = null;
this.right = null;
if(obj1.pos.x > obj2.pos.x){
this.left = obj1.x;
}
else{
this.left = obj2.pos.x;
}
if(obj1.pos.x + obj1.dim.x < obj2.pos.x + obj2.dim.x){
this.right = obj1.pos.x + obj1.dim.x;
}
else{
this.right = obj2.pos.x + obj2.dim.x;
}
return {
left: this.left,
right: this.right
}
}
overlapY = function(obj1, obj2){
this.top = null;
this.bottom = null;
if(obj1.pos.y > obj2.pos.y){
this.top = obj1.pos.y;
}
else{
this.top = obj2.pos.y;
}
if(obj1.pos.y + obj1.dim.y < obj2.pos.y + obj2.dim.y){
this.bottom = obj1.y + obj1.dim.y;
}
else{
this.bottom = obj2.pos.y + obj2.dim.y;
}
return {
top: this.top,
bottom: this.bottom
}
}
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
var stone, rubber, hammer, plane;
function setup() {
createCanvas(800, 700);
engine = Engine.create();
world = engine.world;
plane = new Plane(400, 690, 800, 20);
hammer = new Hammer(100, 20);
rubber = new Rubber(650, 600, 5);
stone = new Stone(450, 600, 10, 10);
}
function draw() {
background("aqua");
Engine.update(engine);
plane.display();
hammer.display();
rubber.display();
stone.display();
}
|
'use strict';
let Layout = Reach.component('Layout.BaseLayout');
let theme = require('../theme.js');
export default class BaseView extends React.Component {
render () {
return (
<Layout theme={theme} />
);
}
}
|
module.exports = function (app) {
app.directive('quizLogin', [quizLogin]);
function quizLogin() {
return {
template: require('./login.template.html'),
scope: {
user: "=",
},
controller: function ($scope, $mdDialog) {
$scope.choosingStrategy = false;
$scope.chooseStrategy = function () {
$scope.choosingStrategy = !$scope.choosingStrategy;
};
}
};
}
};
|
sap.ui.define([
"sap/ui/core/mvc/Controller",
"sap/ui/core/routing/History",
"sap/ui/core/UIComponent"
], function(Controller, History, UIComponent) {
"use strict";
return Controller.extend("sap.f.sample.ShellBarWithSplitApp.controller.BaseController", {
USER_SESSION_PATH: "currentUser",
getRouter() {
return UIComponent.getRouterFor(this);
},
getServerUrl() {
let base = [];
let serve = this.getOwnerComponent().getMetadata().getConfig().serviceUrl;
base.push(serve);
for (let index = 0; index < arguments.length; index++) {
const element = arguments[index];
base.push(element);
}
return base.join('/');
},
getModel(sName) {
return this.getView().getModel(sName);
},
setModel(oModel, sName) {
return this.getView().setModel(oModel, sName);
},
onNavBack() {
var oHistory, sPreviousHash;
oHistory = History.getInstance();
sPreviousHash = oHistory.getPreviousHash();
if (sPreviousHash !== undefined) {
window.history.go(-1);
} else {
this.getRouter().navTo("appHome", {}, true /*no history*/);
}
},
getUserSession() {
return this.getItem(this.USER_SESSION_PATH);
},
setUserSession(userData) {
delete userData.Password;
this.setItem(this.USER_SESSION_PATH, userData)
},
destroyUserSession() {
this.removeItem(this.USER_SESSION_PATH);
},
setItem(path, data) {
localStorage.setItem(path, JSON.stringify(data));
},
getItem(path) {
let strData = localStorage.getItem(path)
if (!strData || strData == '') return null;
return JSON.parse(strData);
},
removeItem(path) {
localStorage.removeItem(path);
},
});
});
|
import React from 'react'
import Auth from 'AuthService'
import Avatar from 'components/Avatar'
import { Button, Input } from 'forms/material/Material'
import { Grid, Cell } from 'Grid'
var Register = React.createClass({
getInitialState() {
return {
email: '',
first_name: '',
last_name: '',
password: '',
passwordRepeat: '',
error: false,
loading: false,
registerButton: 'Ga Verder',
emailIsValid: false,
firstNameIsValid: false,
lastNameIsValid: false,
passwordIsValid: false,
passwordRepeatIsValid: false
}
},
register(event) {
event.preventDefault()
let { email, first_name, last_name, password, passwordRepeat } = this.state
let user = {
email, first_name, last_name, password, passwordRepeat
}
this.setState({
registerButton: 'Bezig met registreren...',
loading: true
})
Auth.register(user, (res, err) => {
if (err) {
this.setState({
registerButton: 'Uh Oh, er ging wat mis...',
error: true,
loading: false,
email: '',
first_name: '',
last_name: '',
password: '',
passwordRepeat: ''
})
setTimeout(() => {
this.setState({
registerButton: 'Ga Verder',
error: false
})
}, 2500)
}
})
},
setEmail(event) {
this.setState({
email: event.target.value
})
},
setFirstName(event) {
this.setState({
first_name: event.target.value
})
},
setLastName(event) {
this.setState({
last_name: event.target.value
})
},
setPassword(event) {
this.setState({
password: event.target.value
})
},
setPasswordRepeat(event) {
this.setState({
passwordRepeat: event.target.value
})
},
validateEmail(result) {
this.setState({
emailIsValid: result
})
},
validateFirstName(result) {
this.setState({
firstNameIsValid: result
})
},
validateLastName(result) {
this.setState({
lastNameIsValid: result
})
},
validatePassword(result) {
this.setState({
passwordIsValid: result
})
},
validatePasswordRepeat(result) {
this.setState({
passwordRepeatIsValid: result
})
},
render() {
let { loading, registerButton, emailIsValid, firstNameIsValid, lastNameIsValid, passwordIsValid, passwordRepeatIsValid } = this.state
let iconClass = `material-icons right ${this.state.loading ? 'icon-spin' : ''}`
let isValid = emailIsValid && firstNameIsValid && lastNameIsValid && passwordIsValid && passwordRepeatIsValid
return (
<div>
<form onSubmit={this.register}>
<Grid>
<Cell>
<Input
id="email"
label="E-mail"
name="email"
onChange={this.setEmail}
onValidate={this.validateEmail}
rules={['required', 'email', 'endsWith:@ugent.be:@student.hogent.be']}
type="email"
value={this.state.email}
/>
</Cell>
<Cell width={6/12}>
<Input
id="first_name"
label="Voornaam"
name="first_name"
onChange={this.setFirstName}
onValidate={this.validateFirstName}
rules={['required']}
type="text"
value={this.state.first_name}
/>
</Cell>
<Cell width={6/12}>
<Input
onValidate={this.validateLastName}
rules={['required']}
label="Achternaam"
type="text"
id="last_name"
name="last_name"
value={this.state.last_name}
onChange={this.setLastName}
/>
</Cell>
<Cell>
<Input
onValidate={this.validatePassword}
rules={['required']}
label="Wachtwoord"
type="password"
id="password"
name="password"
value={this.state.password}
onChange={this.setPassword}
/>
</Cell>
<Cell>
<Input
onValidate={this.validatePasswordRepeat}
rules={['required']}
label="Herhaal Wachtwoord"
type="password"
id="password_repeat"
name="password_repeat"
value={this.state.passwordRepeat}
onChange={this.setPasswordRepeat}
/>
</Cell>
</Grid>
<div className="right-align">
<Button disabled={ ! isValid} className={this.state.error ? 'red' : ''} large>
<i className={iconClass}>{loading ? 'loop' : 'send'}</i>{registerButton}
</Button>
</div>
</form>
</div>
)
}
})
export default Register
|
$(document).ready(function(){
verificar_editar();
verificar_borrar();
});
function verificar_editar(){
$.ajax({
url: '/cuentas/notificar_editar_empresa/',
dataType: 'json',
success : function(response){
if (response.result == true){
showNotificationSuccess('top','right','Se ha modificado la empresa exitosamente');
}else if (response.result == false){
showNotificationDanger('top','right','Ha ocurrido un error, inténtelo de nuevo más tarde');
}else{
}
}
});
}
function verificar_borrar(){
$.ajax({
url: '/cuentas/notificar_borrar_empresa/',
dataType: 'json',
success : function(response){
if (response.result == true){
showNotificationSuccess('top','right','Se ha eliminado la empresa exitosamente');
}else if (response.result == false){
showNotificationDanger('top','right','Ha ocurrido un error, inténtelo de nuevo más tarde');
}else{
}
}
});
}
|
var compare = require('../lib/index.cjs.js');
var expect = require('chai').expect;
describe('版本号比较测试', function () {
it('v1大于v2', function () {
expect(compare('11.23.2', '11.21.2')).to.be.equal(true);
});
it('v1大于v2', function () {
expect(compare('11.23.20000', '11.23.00001')).to.be.equal(true);
});
it('v1小于v2', function () {
expect(compare('11.23.2', '11.23.20')).to.be.equal(false);
});
it('v1小于v2', function () {
expect(compare('2.7.14.2345', '2.12.8.1234')).to.be.equal(false);
});
it('v1小于v2', function () {
expect(compare('3.0.0.1', '3.0.0.1.1')).to.be.equal(false);
})
});
|
process.env.NODE_ENV = "test"
const db = require("../db");
const request = require("supertest");
const app = require("../app");
beforeAll(async () => {
await db.query(`CREATE TABLE books ( isbn TEXT PRIMARY KEY,
amazon_url TEXT,
author TEXT,
language TEXT,
pages INTEGER,
publisher TEXT,
title TEXT,
year INTEGER)`)
});
beforeEach(async () => {
// seed with some data
await db.query(`INSERT INTO books (
isbn,
amazon_url,
author,
language,
pages,
publisher,
title,
year)
VALUES ('0691161518','http://a.co/eobPtX2','Matthew Lane','english','264','Princeton University Press','Power-Up: Unlocking the Hidden','2017')
RETURNING isbn,
amazon_url,
author,
language,
pages,
publisher,
title,
year`);
});
afterEach(async () => {
await db.query("DELETE FROM books");
});
afterAll(async () => {
await db.query("DROP TABLE books");
db.end();
});
describe("GET /", () => {
test("It should respond with an array of books", async () => {
const response = await request(app).get("/books");
expect(response.body).toEqual({
"books": [
{
"isbn": "0691161518",
"amazon_url": "http://a.co/eobPtX2",
"author": "Matthew Lane",
"language": "english",
"pages": 264,
"publisher": "Princeton University Press",
"title": "Power-Up: Unlocking the Hidden",
"year": 2017
}
]
});
expect(response.statusCode).toBe(200);
});
});
describe("GET /0691161518", () => {
test("It should respond with a book", async () => {
const response = await request(app).get("/books/0691161518");
expect(response.body).toEqual({
"book":
{
"isbn": "0691161518",
"amazon_url": "http://a.co/eobPtX2",
"author": "Matthew Lane",
"language": "english",
"pages": 264,
"publisher": "Princeton University Press",
"title": "Power-Up: Unlocking the Hidden",
"year": 2017
}
});
expect(response.statusCode).toBe(200);
});
});
describe("POST /", () => {
test("It should respond with the new book added", async () => {
const response = await request(app).post("/books").send(
{
"isbn": "0699998",
"amazon_url":"http://a.co/eifPX2",
"author": "test",
"language": "english",
"pages": 999999,
"publisher": "test",
"title": "test",
"year": 20000
}
);
expect(response.body).toEqual({
"book":
{
"isbn": "0699998",
"amazon_url": "http://a.co/eifPX2",
"author": "test",
"language": "english",
"pages": 999999,
"publisher": "test",
"title": "test",
"year": 20000
}
});
expect(response.statusCode).toBe(201);
});
test("It should respond with an error for schema validation", async () => {
const response = await request(app).post("/books").send(
{
"isbn": "0699998",
"amazon_url":"http://a.co/eifPX2",
"author": "test",
"language": "english",
"pages": "wrong",
"publisher": "test",
"title": "test",
"year": 20000
}
);
expect(response.body).toEqual({"error": ["instance.pages is not of a type(s) integer"]}
);
expect(response.statusCode).toBe(500);
});
});
describe("PATCH /", () => {
test("It should edit a book", async () => {
const response = await request(app).patch("/books/0691161518").send(
{
"isbn": "0691161518",
"amazon_url": "http://a.co/eobPtX2",
"author": "JOEL DID THIS",
"language": "english",
"pages": 264,
"publisher": "Princeton University Press",
"title": "Power-Up: Unlocking the Hidden",
"year": 2017
}
);
expect(response.body).toEqual({
"book":
{
"isbn": "0691161518",
"amazon_url": "http://a.co/eobPtX2",
"author": "JOEL DID THIS",
"language": "english",
"pages": 264,
"publisher": "Princeton University Press",
"title": "Power-Up: Unlocking the Hidden",
"year": 2017
}
});
expect(response.statusCode).toBe(200);
});
test("It should respond with an error for schema validation", async () => {
const response = await request(app).patch("/books/0691161518").send(
{
"isbn": "0691161518",
"amazon_url": "http://a.co/eobPtX2",
"author": "JOEL DID THIS",
"language": 42342,
"pages": 264,
"publisher": "Princeton University Press",
"title": "Power-Up: Unlocking the Hidden",
"year": 2017
}
);
expect(response.body).toEqual({"error": ["instance.language is not of a type(s) string"]}
);
expect(response.statusCode).toBe(500);
});
});
describe("DELETE /", () => {
test("It should delete a book", async () => {
const response = await request(app).delete("/books/0691161518");
expect(response.body).toEqual({"message":"Book deleted"})
expect(response.statusCode).toBe(200);
});
test("It should return invalid for unidentified book", async () => {
const response = await request(app).delete("/books/06sdfsdaf518");
expect(response.body).toEqual({"error": {"status": 404}, "message": "There exists no book with an isbn of '06sdfsdaf518"})
expect(response.statusCode).toBe(404);
});
});
|
const jwt = require('jsonwebtoken');
const httpEnum = require('../enum/Ehttp');
const auth = (request, response, next) => {
const authHeader = request.headers.authorization;
if (!authHeader) {
return response.status(httpEnum.httpStatusCode.UNAUTHORIZED).json({ message: 'Token is required!' });
}
const [, token] = authHeader.split(' ');
try {
jwt.verify(token, process.env.SECRET);
next()
} catch (error) {
return response.status(httpEnum.httpStatusCode.UNAUTHORIZED).json({ message: 'Token invalid!' });
}
};
module.exports = auth;
|
import { api } from "./api";
const fetchUserByName = (username) => (
api.get('users/' + username)
);
const fetchUsers = (activated = true) => (
api.get('users', {
params: {
Activated: activated
}
})
);
const deleteUser = (username)=> (
api.delete('users/' + username)
);
const createUser = (username, email, password) => (
api.post('users/', {
username,
password,
email
})
);
const updateUser = (username, email, isActivated) => (
api.put('users/', {
username,
email,
isActivated
})
);
export const usersApi = {
fetchUserByName,
fetchUsers,
deleteUser,
createUser,
updateUser
}
|
import { render, Component, zero_react_create } from './zero-react.js'
class MyComponent extends Component{
render(){
return <div><h1>zero component</h1>
{this.children}
</div>
}
}
render(<MyComponent id="a" class="c">
<div>abc</div>
<div/>
<div/>
</MyComponent>, document.body);
|
import {
applyMiddleware,
bindActionCreators,
combineReducers,
createStore
} from "redux";
import Reducer from "./reducer";
import StateConnector from "./state-connector";
import { convertDirectoryNotationToObject } from "./utils";
/* #####################################################################
Publicly exposed functional adapters for Radux components
####################################################################### */
/**
* Functional adapter for Reducer class
* @param name Name of the reducer - acts as namespace for action types
* @param initialState - initial state for reducer
*/
const reducer = (name, initialState = {}) => new Reducer(name, initialState);
/**
* Functional adapter for StateConnector class
* @param Component React Component to connect Redux state to
* @param params Object consisting of any of the following: stateFilter, actionCreators, redux "connect" options or mergeProps
* @return {StateConnector} The resulting StateConnector
*/
const stateConnector = (Component, params) =>
new StateConnector(Component, params);
/* #####################################################################
Radux global store storage
####################################################################### */
// Default store key
const DEFAULT = "default";
/**
* Radux global store object
* @type {{}}
*/
const stores = {};
/* #####################################################################
Radux global action creator registration
####################################################################### */
/**
* Radux package store for globally registered reducers
* @type {{}}
*/
let globalReducers = {};
/**
* Register action creators that will register with every radux connected Component
* @param reducer {Reducer} A Radux reducer
*/
const registerGlobalReducer = reducer =>
(globalReducers = {
...globalReducers,
[reducer.name]: reducer
});
/* #####################################################################
Radux Reducer registration and retrieval
####################################################################### */
/**
* * Radux package store for all registered reducers
* @type {Reducer}
*/
let registeredReducers = {};
/**
* Register reducer with radux - when getting the combined reducer all registered reducers will be in the result
* @param name {String} Name of the reducer; Used as namespace for all actions dispatchers and props
* @param reducer {Reducer} Radux Reducer object
* @param storeName {String} Optional store name; default store name is used if omitted
*/
const registerReducer = (name, reducer, storeName = DEFAULT) => {
if (!reducer instanceof Reducer) {
throw `registerReducer must be passed an object of type Reducer. ${type(
reducer
)} provided.`;
}
registeredReducers[storeName] = {
...registeredReducers[storeName],
...{ [name]: reducer }
};
};
/**
* Bulk reducer registration
* @param reducers {{Reducer}} Object of {name: reducer} pairs; See registerReducer for more details
* @param storeName {String} Optional store name; default store name is used if omitted
*/
const registerReducers = (reducers, storeName = DEFAULT) =>
Object.keys(reducers).forEach(r =>
registerReducer(r, reducers[r], storeName)
);
/**
* Adds and returns a store based on all registered reducers
* @returns {Store} Redux store object
* @param storeName {String} Store name
* @param newReducers {{Reducer}} Radux or Redux Reducers used to create store
* @param storeInitialState {{}} Initial state for store
* @param enhancers {{}} Enhancers (must be accepted by Redux.applyMiddleware)
*/
const addNamedStore = (
storeName,
newReducers = {},
storeInitialState = {},
...enhancers
) => {
const reducers = {
...globalReducers,
...(registeredReducers[storeName] || {}),
...newReducers
};
// Register any passed Radux Reducers
Object.keys(newReducers).forEach(
key =>
newReducers[key] instanceof Reducer &&
registerReducer(key, newReducers[key], storeName)
);
/*
If any are not Radux reducers then assume they are
Redux reducers and keep as-is in reducers object
*/
Object.keys(reducers).forEach(
key =>
reducers[key] instanceof Reducer &&
(reducers[key] = reducers[key].getReduxReducer())
);
return (stores[storeName] = createStore(
combineReducers(reducers),
storeInitialState,
applyMiddleware(...enhancers)
));
};
/**
* Returns the default store, for params see definition of addNamedStore;
* 'default' is used as store name
* @returns {Store<S>}
*/
const addStore = (...args) => {
return addNamedStore(DEFAULT, ...args);
};
/**
* Returns a store by the given name; the default store is returned if no name is supplied
* @param storeName {String} Name of store
* @returns {Store<S>}
*/
const getStore = storeName => {
return stores[storeName || DEFAULT];
};
const dispatch = (storeName, action) => {
if (!action) [storeName, action] = [null, storeName];
return getStore(storeName).dispatch(action);
};
/* ####################################################################
Redux connect argument builders
####################################################################### */
/**
* Builds mapDispatchToProps argument of Redux connect
* @param actionCreators
* @param dispatcherExtensions
*/
const buildDispatchToPropsMap = (
actionCreators = {},
dispatcherExtensions = {}
) => dispatch => {
const combinedCreators = {
...Object.keys(globalReducers).reduce((ac, reducerName) => {
return { ...ac, ...globalReducers[reducerName] };
}, {}),
...actionCreators
};
const boundActionCreators = {
...bindActionCreators(combinedCreators, dispatch)
};
Object.keys(dispatcherExtensions).map(type => {
boundActionCreators[type] = (...args) => {
dispatch(actionCreators[type](...args));
return dispatcherExtensions[type](dispatch, ...args);
};
});
return {
actions: convertDirectoryNotationToObject(boundActionCreators)
};
};
/**
* Builds mapStateToProps argument of Redux connect
* @param filters [BaseFilter] An array of filters to apply
*/
const buildStateToPropsMap = (filters = []) => state => {
const newState = filters.reduce(
(newState, filter) => ({ ...newState, ...filter.apply(state) }),
{}
);
/* Always allow our global registered reducers */
return Object.keys(globalReducers).reduce(
(finalState, key) => ({ ...finalState, [key]: state[key] }),
newState
);
};
export {
buildDispatchToPropsMap,
buildStateToPropsMap,
dispatch,
addStore,
addNamedStore,
getStore,
reducer,
registerGlobalReducer,
registerReducers,
stateConnector
};
|
// 任务类型及状态值
module.exports = {
'DEFAULT': {
name: '无任务',
},
'BUILD': {
name: '构建',
states: {
'init': '未执行',
'process': '进行中',
'failure': '失败',
'success': '成功',
}
},
'INSTALL': {
name: '安装包',
states: {
'init': '未执行',
'process': '进行中',
'failure': '失败',
'success': '成功',
}
},
'DEPLOY': {
name: '部署',
states: {
'init': '未执行',
'process': '进行中',
'failure': '失败',
'success': '成功',
}
},
'BUILDAndDEPLOY': {
name: '部署与发布',
states: {
'init': '未执行',
'process': '进行中',
'failure': '失败',
'success': '成功',
}
},
'TESTCOPY': {
name: '测试拷贝',
states: {
'init': '未执行',
'process': '进行中',
'failure': '失败',
'success': '成功',
}
}
}
exports.taskStates = () => {
return {
'init': '未执行',
'process': '执行中',
'failure': '失败',
'success': '成功',
}
}
exports.taskArray = () => {
return [
{
name: '无任务',
value: 'DEFAULT',
},
{
name: '构建',
value: 'BUILD',
states: [
{
name: '未执行',
value: 'init'
},
{
name: '进行中',
value: 'process'
},
{
name: '失败',
value: 'failure'
},
{
name: '成功',
value: 'success'
},
]
},
{
name: '安装包',
value: 'INSTALL',
states: [
{
name: '未执行',
value: 'init'
},
{
name: '进行中',
value: 'process'
},
{
name: '失败',
value: 'failure'
},
{
name: '成功',
value: 'success'
},
]
},
{
name: '打包部署',
value: 'DEPLOY',
states: [
{
name: '未执行',
value: 'init'
},
{
name: '进行中',
value: 'process'
},
{
name: '失败',
value: 'failure'
},
{
name: '成功',
value: 'success'
},
]
}
]
}
|
App.factory("Concursos", function($resource) {
return $resource("/api/concursos");
});
|
module.exports = {
// 对服务器的配置
devServer: {
host: 'localhost', // host和port设置nodejs启动服务的端口
port: 8888,
proxy:{ // 代理跨域
'/api': { // 遇到'/api'路径时进行下面的操作
target: 'http://mall-pre.springboot.cn', // 将'/api'前面的源地址换成这个,和下面的参数配合使用
changeOrigin: true,
pathRewrite: {
'/api':'' // 将最后路径中的'/api'替换成''
}
}
}
}
}
|
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import {BaristaPageCard} from "../BaristaPageCard";
import {useDispatch, useSelector} from "react-redux";
import {useEffect} from "react";
import {fetchProducts} from "../../../redux/slices/productsSlice";
import {CircularProgress} from "@material-ui/core";
export const BaristaPage = () => {
const products = useSelector(state => state.products.items)
const dispatch = useDispatch();
const isLoadingInProgress = useSelector(state => state.products.isLoading)
useEffect(() => {
dispatch(fetchProducts())
}, [dispatch])
return (
<>
<Typography paragraph variant="h4">Barista page</Typography>
{
isLoadingInProgress
? <CircularProgress />
: (
<Grid container spacing={2}>
{
products.map(product => {
return (
<BaristaPageCard
key={product.id}
product={product}
/>
)
})
}
</Grid>
)
}
</>
)
}
|
import React from "react";
import PropTypes from "prop-types";
import cn from "classnames";
const Section = ({
className,
sectionTitle,
isVisibleTitle = false,
children,
}) => {
return (
<section className={className}>
<h2 className={cn({ "visually-hidden": !isVisibleTitle })}>
{sectionTitle}
</h2>
{children}
</section>
);
};
Section.propTypes = {
className: PropTypes.string,
isVisibleTitle: PropTypes.bool,
sectionTitle: PropTypes.string.isRequired,
children: PropTypes.any,
};
export default Section;
|
/*
* Adapted from code by Brian Donohue
*/
'use strict';
const adafruitIO_username = 'example';
exports.handler = function (event, context) {
try {
console.log("event.session.application.applicationId=" + event.session.application.applicationId);
if (event.session.new) {
onSessionStarted({requestId: event.request.requestId}, event.session);
}
if (event.request.type === "LaunchRequest") {
onLaunch(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === "IntentRequest") {
onIntent(event.request,
event.session,
function callback(sessionAttributes, speechletResponse) {
context.succeed(buildResponse(sessionAttributes, speechletResponse));
});
} else if (event.request.type === "SessionEndedRequest") {
onSessionEnded(event.request, event.session);
context.succeed();
}
} catch (e) {
context.fail("Exception: " + e);
}
};
/**
* Called when the session starts.
*/
function onSessionStarted(sessionStartedRequest, session) {
console.log("onSessionStarted requestId=" + sessionStartedRequest.requestId
+ ", sessionId=" + session.sessionId);
}
/**
* Called when the user invokes the skill without specifying what they want.
*/
function onLaunch(launchRequest, session, callback) {
console.log("onLaunch requestId=" + launchRequest.requestId
+ ", sessionId=" + session.sessionId);
var cardTitle = "Welcome to the smart ventilation system!"
var speechOutput = "I can help change the temperature of your room to your preference."
callback(session.attributes,
buildSpeechletResponse(cardTitle, speechOutput, "", true));
}
/**
* Called when the user specifies an intent for this skill.
*/
function onIntent(intentRequest, session, callback) {
console.log("onIntent requestId=" + intentRequest.requestId
+ ", sessionId=" + session.sessionId);
var intent = intentRequest.intent,
intentName = intentRequest.intent.name;
// dispatch custom intents to handlers here
if (intentName == 'GetRoomTemperature') {
getRoomTemperature(intent, session, callback);
} else if (intentName == "SetRoomTemperature"){
setRoomTemperature(intent, session, callback);
}
else {
throw "Invalid intent";
}
}
/**
* Called when the user ends the session.
* Is not called when the skill returns shouldEndSession=true.
*/
function onSessionEnded(sessionEndedRequest, session) {
console.log("onSessionEnded requestId=" + sessionEndedRequest.requestId
+ ", sessionId=" + session.sessionId);
}
function getRoomTemperature(intent, session, callback) {
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://io.adafruit.com');
var targetRoomNumber = intent.slots.RoomNumber.value;
var targetRoom = 'Room ' + targetRoomNumber + " Temp";
var temp;
client.on('connect', () => {
temp = client.subscribe(adafruitIO_username + '/feeds/' + targetRoom);
});
client.on('error', (error) => {
console.log('MQTT Client Errored');
console.log(error);
});
var message = "The temperature of room " + targetRoomNumber + " is " + temp;
callback(session.attributes,
buildSpeechletResponseWithoutCard(message, "", "true"));
}
function setRoomTemperature(intent, session, callback){
var mqtt = require('mqtt');
var client = mqtt.connect('mqtt://io.adafruit.com');
var targetRoomNumber = intent.slots.RoomNumber.value;
var targetRoom = 'room' + targetRoomNumber;
var temperature = intent.slots.Temperature.value;
var command = targetRoom + ",s" + temperature;
client.on('connect', () => {
client.publish(adafruitIO_username + '/feeds/echo-commands',command); //
});
client.on('error', (error) => {
console.log('MQTT Client Errored');
console.log(error);
});
var message = "The temperature of room " + targetRoomNumber + " is now set to" + temperature;
callback(session.attributes,
buildSpeechletResponseWithoutCard(message, "", "true"));
}
// ------- Helper functions to build responses -------
function buildSpeechletResponse(title, output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
card: {
type: "Simple",
title: title,
content: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
function buildSpeechletResponseWithoutCard(output, repromptText, shouldEndSession) {
return {
outputSpeech: {
type: "PlainText",
text: output
},
reprompt: {
outputSpeech: {
type: "PlainText",
text: repromptText
}
},
shouldEndSession: shouldEndSession
};
}
function buildResponse(sessionAttributes, speechletResponse) {
return {
version: "1.0",
sessionAttributes: sessionAttributes,
response: speechletResponse
};
}
|
import React, { useRef } from 'react'
import config from "../../config"
const Header = (props) => {
const current_user = props.locals && props.locals.current_user
const inputSearchRef = useRef()
const handleKeyDown = (e) => {
if(e.keyCode === 13) {
window.open(`https://www.google.com.hk/#hl=zh-CN&q=site:cnodejs.org ${inputSearchRef.current.value}`)
}
}
return(
<div className='navbar'>
<div className='navbar-inner'>
<div className='container'>
<a className='brand' href='/'>
{ config.site_logo ? <img src={config.site_logo} /> : config.name }
</a>
<input type='text' ref={inputSearchRef} id='q' name='q' className='search-query span3' onKeyDown={handleKeyDown}/>
<ul className='nav pull-right'>
<li><a href='/'>首页</a></li>
{
current_user
? <li>
<a href='/my/messages'>
{ current_user.messages_count ? <span className='big messages_count'>{current_user.messages_count}</span> : "未读消息" }
</a>
</li>
: null
}
<li><a href='/getstart'>新手入门</a></li>
<li><a href='/api'>API</a></li>
{ (config.site_navs || []).map((nav, index) => <li key={index}><a href={nav[0]} target={nav[2]}>{nav[1]}</a></li>) }
{
current_user
? <>
<li><a href='/setting'>设置</a></li>
<li><a href='/signout' data-method="post" rel="nofollow">退出</a></li>
</>
: <>
<li><a href='/signup'>注册</a></li>
<li><a href='/signin'>登录</a></li>
</>
}
</ul>
<a className="btn btn-navbar" id="responsive-sidebar-trigger">
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</a>
</div>
</div>
</div>
)
}
export default Header
|
const express = require('express')
const router = express.Router()
router.use(express.json())
const Joi = require('joi')
const uuid = require('uuid')
const mongoose = require('mongoose')
const objectId = require('mongoose').objectid //needed to access by id
const jwt = require('jsonwebtoken')
const tokenKey = require('../../config/keys').secretOrKey
const bcrypt = require('bcryptjs');
//const objectId = require('mongoose').objectid //needed to access by id
const workshops = require('./workshops')
const fn = require('../../fn')
const EducationalOrganization = require('../../models/EducationalOrganization')
const Admin = require('../../models/Admin')
const validator = require('../../Validations/EduOrgValidations')
const passport = require('passport');//for auth trial
const nodemailer = require("nodemailer"); //notifications
router.get('/', async (req,res) => {
const educationalOrganizations = await EducationalOrganization.find()
res.json({data: educationalOrganizations})
})
//auth trial
// router.get('/profile', passport.authenticate('jwt', { session: false }),(req, res) =>{
// res.send("able to access");
// }
// );
//
//show my profile
//router.get("/:_id", (req, res) => {
router.get('/:_id', passport.authenticate('jwt', { session: false }),async(req, res) =>{
//req.user.id == id
const id = req.params._id;
const admin =await Admin.findById(req.user.id )
id2=''
if(!admin){
id2="";
}
else{
id2=admin._id;
}
console.log(id)
console.log(id2)
console.log(req.user.id)
// const id2="";
// =;admin.id
const id3=req.user.id
if(id3==id2 || id3==id) {
console.log('hiii')
EducationalOrganization.findById(id)
.exec()
.then(doc => {
if (doc) {
res.status(200).json(doc);
} else {
res
.status(404)
.json({ message: "No Educational Organization found for provided ID" });
}
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
} else {
res.status(401).json({ err: "Not authorized "});
}
});
//register
router.post('/', async (req,res) => {
try {
const isValidated = validator.createValidation(req.body)
if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const { userName, email, name, password } = req.body;
const eduOrg = await EducationalOrganization.findOne({ email }); //making sure email is unique
if (eduOrg) return res.status(400).json({ email: 'Email already exists' });
const salt = bcrypt.genSaltSync(10);
const hashedPassword = bcrypt.hashSync(password, salt);
const newEducationalOrganization = new EducationalOrganization({
userName,
password: hashedPassword,
email,
name,
});
await EducationalOrganization.create(newEducationalOrganization);
//notification trial yan
//+ token.token
console.log(newEducationalOrganization.email)
// const transporter = nodemailer.createTransport({ service: 'Sendgrid', auth: { user: process.env.SENDGRID_USERNAME, pass: process.env.SENDGRID_PASSWORD } });
// const mailOptions = { from: 'no-reply@yourwebapplication.com', to: newEducationalOrganization.email, subject: 'Account Verification Token', text: 'Hello,\n\n' + 'Please verify your account by clicking the link: \nhttp:\/\/' + req.headers.host + '\/confirmation\/' + '.\n' };
// transporter.sendMail(mailOptions, function (err) {
// if (err) { return res.status(500).send({ msg: err.message }); }
// res.status(200).send('A verification email has been sent to ' + newEducationalOrganization.email + '.');
// console.log(res.data)
// });
/////
//const newEducationalOrganization = await EducationalOrganization.create(req.body);
//const sndmail={}
require('../../services/mailer').sendMail(newEducationalOrganization).then(data => {
console.log(data)
}).catch(err => console.log(err)) ;
res.json({msg:'Educational organization was created successfully', data: newEducationalOrganization})
}
catch(error) {
// We will be handling the error later
console.log("here catch")
console.log(error)
}
});
// update Profile
//
router.put('/:id',passport.authenticate('jwt', { session: false }),async(req, res) =>{
try {
const id = req.params.id
const eduorg = await EducationalOrganization.findById(id)
const ID = {"_id":id}
if(!eduorg) return res.status(404).send({error: 'eduorg does not exist'})
const isValidated = validator.updateValidation(req.body)
if (isValidated.error) return res.status(400).send({ error: isValidated.error.details[0].message })
const updatedEduorg = await EducationalOrganization.findOneAndUpdate(ID,req.body)
res.json({msg: 'EduOrg updated successfully',data:updatedEduorg})
}
catch(error) {
// We will be handling the error later
console.log(error)
}
})
router.delete('/:id', passport.authenticate('jwt', { session: false }),async(req, res) =>{
try {
const id = req.params.id
const deletedEduOrgProfile = await EducationalOrganization.findByIdAndRemove(id)
res.json({msg:'Profile was deleted successfully', data: deletedEduOrgProfile})
}
catch(error) {
// We will be handling the error later
console.log(error)
}
})
router.get('/w/:id', async (req,res) =>{
const id = req.params.id
console.log(id)
const e = await fn.getAllWorkshops(id)
console.log(e)
res.json({msg: 'found it!!',data:e})
})
//Marina
router.get('/courses1/:id', async (req,res) =>{
const eduorgID = req.params.id;
const eduOrg = await EducationalOrganization.findById(eduorgID).populate('courses');
const string = JSON.stringify(eduOrg);
const objectValue = JSON.parse(string);
const courses = objectValue['courses'];
res.json({courses})
})
module.exports = router
// applyForCourse: async (cid, mid) => {
// const path = "http://localhost:5000/api/courses/" + cid + "/apply";
// return await axios.put(path, { applicantId: '"' + mid + '" ' });
// },
// router.get('/:id/masterclasses' ,async (req,res)=>{
// })
|
var defaultUrl = "https://mhsprod.jira.com";
document.addEventListener('DOMContentLoaded', function () {
document.querySelector('button').addEventListener('click', save);
onload();
});
function onload() {
var url = localStorage.getItem("url");
var projectKey = localStorage.getItem("projectKey");
if(url)
document.getElementById("url").value = url;
else
document.getElementById("url").value = defaultUrl;
if(projectKey)
document.getElementById("projectKey").value = projectKey;
}
function save(){
var url = document.getElementById("url").value.trim();
var projectKey = document.getElementById("projectKey").value.trim();
url = url.replace('/browse', '');
url = url.replace('/browse/', '');
localStorage.setItem("url", url);
localStorage.setItem("projectKey", projectKey);
document.getElementById('status').innerHTML = 'Saved.';
}
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var postcss = require('gulp-postcss');
var autoprefixer = require('autoprefixer');
var cssnano = require('cssnano');
var sourcemaps = require('gulp-sourcemaps');
var browserSync = require('browser-sync').create();
var paths = {
styles: {
src: "src/scss/*.scss",
main: "src/scss/app.scss",
dest: "src/css"
}
}
function style(){
return gulp
.src( paths.styles.main )
.pipe( sourcemaps.init() )
.pipe( sass() )
.on("error", sass.logError)
.pipe( postcss( [autoprefixer(), cssnano()] ))
.pipe( sourcemaps.write() )
.pipe( gulp.dest(paths.styles.dest))
.pipe( browserSync.stream());
}
function reload(){
console.log("reloading");
browserSync.reload();
}
function watch(){
browserSync.init({
server: {
baseDir: "./src"
}
});
gulp.watch(paths.styles.src, style);
gulp.watch("src/*.html").on('change', browserSync.reload );
}
exports.watch = watch;
exports.style = style;
var build = gulp.parallel( style, watch );
gulp.task('build', build);
gulp.task('default', build);
|
(function() {
'use strict'
angular
.module('atentamente')
.factory('authModal', authModal)
function authModal($uibModal, Auth) {
var service = {
openRegister: openRegister,
openLogin: openLogin,
close: close
}
var currentModal
return service
function openRegister() {
close()
currentModal = $uibModal.open({
animation: true,
templateUrl: 'auth/auth-register.html',
controllerAs: 'vm',
controller: 'AuthController'
})
return currentModal
}
function openLogin() {
close()
currentModal = $uibModal.open({
animation: true,
templateUrl: 'auth/auth-login.html',
controllerAs: 'vm',
controller: 'AuthController'
})
return currentModal
}
function close() {
if (currentModal) {
currentModal.close()
}
}
}
})()
|
import axios from 'axios';
const spotifyBaseUrl = 'https://api.spotify.com';
const clientId = '96bc7b491f9e41b694ac65c3985a6270';
const redirectUri = 'http://localhost/genre-gradient/callback';
axios({
url: `${spotifyBaseUrl}/v1/browse/categories`,
method: 'GET'
}).then(
response => {
console.log(response)
},
error => {
console.log(error)
}
);
// var playerState = {
// volume: 50,
// isPlaying: false,
// currentTrack: 0,
// timeOutReference: null
// };
//
// function generateTrackInDom() {
// var song = songs[playerState.currentTrack];
// playingSong.innerText = song.title;
// playingArtist.innerText = song.artist;
// playingAlbumYear.innerText = song.year;
// playingAlbumLabel.innerText = song.label;
// songAlbumName.innerText = song.albumName;
// // Load in the next audio track
// playingAlbumArt.setAttribute('src', song.albumSrc);
// }
//
// function resetElapsedTimeInDom() {
// scrubber.value = 0;
// songElapsedTime.innerText = '00:00';
// }
//
// function updateElapsedTimeInDom(currentTime, totalTime) {
// clearTimeout(playerState.timeOutReference);
// if (currentTime >= totalTime) {
// playerControls.onNextButtonPressed();
// } else {
// function formatElapsedTime() {
// if (parseInt(currentTime % 60).toString().length === 1) {
// return '0' + parseInt(currentTime / 60).toString() + ':0' + parseInt(currentTime % 60).toString();
// } else {
// return '0' + parseInt(currentTime / 60).toString() + ':' + parseInt(currentTime % 60).toString();
// }
// }
// songElapsedTime.innerText = formatElapsedTime();
// scrubber.max = totalTime;
// scrubber.value = currentTime;
// playerState.timeOutReference = setTimeout(updateElapsedTimeInDom.bind(null, currentTime + 1, totalTime), 1000)
// }
// }
//
// function startPlaying() {
// player.play();
// playerState.timeOutReference = setTimeout(updateElapsedTimeInDom.bind(null, 0, player.seekable.end(0)), 1000);
// }
//
// player.setAttribute('src', songs[0].src);
// document.getElementById('play_button').setAttribute('onclick', 'playerControls.onPlayButtonPressed()');
// const playerControls = {
// onPlayButtonPressed: function() {
// if (!playerState.isPlaying) {
// playerState.isPlaying = true;
// levels.setAttribute('src', 'img/levels.gif');
// status.innerText = 'playing';
// startPlaying();
// }
// },
// onPauseButtonPressed: function() {
// if (playerState.isPlaying) {
// clearTimeout(playerState.timeOutReference);
// player.pause();
// playerState.isPlaying = false;
// levels.setAttribute('src', 'img/levels.jpg');
// status.innerText = 'paused';
// }
// },
// onVolumeChanged: function(value) {
// playerState.volume = value;
// volumeBar.value = value;
// // .volume needs a value between 0 and 1
// player.volume = value / 100;
// volumeMeter.value = value;
// },
// onBackButtonPressed: function() {
// clearTimeout(playerState.timeOutReference);
// player.currentTime = 0;
// if (playerState.currentTrack === 0) {
// playerState.currentTrack = songs.length - 1;
// } else {
// playerState.currentTrack = playerState.currentTrack - 1;
// }
// player.setAttribute('src', songs[playerState.currentTrack].src);
// generateTrackInDom();
// resetElapsedTimeInDom();
// if (playerState.isPlaying) {
// player.addEventListener('canplay', startPlaying)
// }
// },
// onStopButtonPressed: function() {
// playerControls.onPauseButtonPressed();
// player.currentTime = 0;
// status.innerText = 'not playing';
// resetElapsedTimeInDom();
// },
// onNextButtonPressed: function() {
// clearTimeout(playerState.timeOutReference);
// player.currentTime = 0;
// if (playerState.currentTrack === songs.length - 1) {
// playerState.currentTrack = 0;
// } else {
// playerState.currentTrack = playerState.currentTrack + 1;
// }
// player.setAttribute('src', songs[playerState.currentTrack].src);
// generateTrackInDom();
// resetElapsedTimeInDom();
// if (playerState.isPlaying) {
// player.addEventListener('canplay', startPlaying)
// }
// },
// onScrubValueChanged: function(value) {
// clearTimeout(playerState.timeOutReference);
// player.currentTime = value;
// playerState.timeOutReference = setTimeout(updateElapsedTimeInDom.bind(this, parseInt(value), player.seekable.end(0)))
// }
// };
|
import React, { Component } from "react";
import PDFview from "../PDFview/PDFview"
import "./Documents.scss";
class Documents extends Component {
constructor(props) {
super(props);
this.state = {
documents: [],
show_pdf: false,
pdf_url: "",
};
this.handleOnClick = this.handleOnClick.bind(this);
}
async componentDidMount() {
await fetch("/api/get-documents")
.then(response => response.json())
.then(json =>
json.forEach(doc => {
JSON.stringify(doc);
let document = {
id: doc.file_title,
title: doc.file_title,
url: doc.file_URL
};
var joined = this.state.documents.concat(document);
this.setState({
documents: joined
});
})
);
}
handleOnClick(url){
this.setState({
show_pdf : true,
pdf_url: url,
});
}
render() {
const docs = this.state.documents.map((document) => {
return <li className="document-titles" onClick={() => this.handleOnClick(document.url)}>
{document.title}
</li>;
});
return (
<div id="documents-container">
<div id="documents-sidebar">
<h2 id="header"> Select a PDF </h2>
<ul>
{docs}
</ul>
</div>
<div className="pdf-viewer">
{this.state.show_pdf ? (<PDFview url={this.state.pdf_url} />) : (<div />)}
</div>
</div>
);
}
}
export default Documents;
|
import { all } from "redux-saga/effects";
import watchStories from "./stories";
import watchAutocompletes from "./autocompletes";
export default function* rootSaga() {
yield all([watchAutocompletes(), watchStories()]);
}
|
'use strict';
import React, { Component } from 'react';
import { Link } from 'react-router';
export default ({ cookie, plusItemzToCart }) => (
<div className="col-xs-18 col-sm-6 col-md-3">
<div className="thumbnail">
<div className="cookieContainer">
<img className="cookieImage" src={cookie.photo} />
</div>
<div className="caption">
{/* Handles case of Seinfeld's race relations cookie discussion */}
<h4>{cookie.name === "Black & White Cookie" ? (
<a href="https://www.youtube.com/watch?v=IlLPAIrmqvE">{cookie.name}</a>
) : (cookie.name) }</h4>
<p>{cookie.description}</p>
<p className="cookieCategory">{cookie.categories.map(category => category).join(', ')}</p>
<p><Link to="/reviews">Reviews</Link></p>
<p><span id="quantityText">Quantity: </span>
<input id={`number_of_cookie_${cookie.id}`} className="form-control quantity" name="quantity" defaultValue="1" />
<a className="btn btn-info btn-sm" role="button" onClick={(evt) => {
evt.preventDefault();
let quantity = parseInt($(`#number_of_cookie_${cookie.id}`).val());
plusItemzToCart(cookie, quantity);
alert(`Added ${quantity} ${cookie.name} to cart`);
} }>Add to cart</a>
</p>
</div>
</div>
</div>
);
|
import {useState,useEffect} from 'react'
const useStickyState = (initialState,key) => {
const [state, setState] = useState(()=> (JSON.parse(localStorage.getItem(key)) ?? initialState))
useEffect(() => {
localStorage.setItem(key,state)
}, [state])
return [state,setState]
}
export default useStickyState
|
const types = {
SET_PET: "SET_PET",
};
export const setPet = (pet) => {
return {
type: types.SET_PET,
payload: pet,
};
};
|
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
images: {
domains: ['https://kimzerovirus.github.io'],
format: ['image/png', 'image/webp', 'image/jpeg'],
},
// webpack(config) {
// config.resolve.modules.push(__dirname);
// return config;
// },
env: {
BASE_URL: process.env.BASE_URL,
},
};
module.exports = nextConfig;
|
import { FETCH_DATA } from '../actions/search_actions';
import { receiveAllTasks } from '../actions/task_actions';
import {
fetchData
} from '../util/search_api_util.js';
let defaultState = {};
const SearchMiddleware = ({ dispatch }) => next => action => {
const searchSuccess = data => {
dispatch(receiveAllTasks(data));
};
const searchError = data => {};
switch (action.type) {
case FETCH_DATA:
fetchData(action.query, searchSuccess, searchError);
default:
return next(action);
}
};
export default SearchMiddleware;
|
//https://www.hackerrank.com/challenges/utopian-tree/problem
function growthCyles(cycles) {
let total = 0
cycles++
for (index = 0; index <= cycles; index++) {
index % 2 ? total += 1 : total *= 2
}
return total
}
function utopianTreeGrowth(treeGrowth) {
const result = Array()
result.push(...treeGrowth.slice(1).map(growthCyles))
return result
}
module.exports = { growthCyles, utopianTreeGrowth };
|
/**
* Created by Brandon Garling on 12/4/2016.
*/
const Sequelize = require('sequelize');
const databaseManager = require('../user_modules/database-manager');
const configMap = require('./maps/config.map');
module.exports = {};
/**
* A Config model, this holds user information
* @type {*}
*/
const Config = databaseManager.context.define('config', {
Key: {
primaryKey: true,
allowNull: false,
type: Sequelize.STRING
},
Value: {
allowNull: false,
type: Sequelize.TEXT
}
},{
instanceMethods: {
getMap: function() {
return Config.getMap();
}
},
});
/**
* Figures out how to serialize and deserialize this model
* @returns {Object}
*/
Config.getMap = function () {
return configMap;
};
module.exports = Config;
|
import * as actionTypes from './actionTypes';
// an action creator
export const increment = () => {
return {
type: actionTypes.INCREMENT
};
};
export const decrement = () => {
return {
type: actionTypes.DECREMENT
};
};
export const add = n => {
return {
type: actionTypes.ADDITION,
addend: n
};
};
export const subtract = n => {
return {
type: actionTypes.SUBTRACTION,
subtrahend: n
};
};
|
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId());
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
// send data to LoginController
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8084/J3LP0011_YellowMoon/login');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
console.log('Signed in as: ' + xhr.responseText);
};
xhr.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
window.location.replace("http://localhost:8084/J3LP0011_YellowMoon/indexPage");
}
}
xhr.send(`email=${profile.getEmail()}&name=${profile.getName()}&password=${profile.getId()}&action=google`);
}
|
import { addPendingOrder, addConfirmedOrder } from "./actionTypes";
export const addPendingOrderAC = (pendingOder) => ({
type: addPendingOrder,
pendingOder,
});
export const addConfirmedOrderAC = (confirmedOrder) => ({
type: addConfirmedOrder,
confirmedOrder,
});
|
import logo from './logo.svg';
import './App.less';
import { Button } from 'antd';
import 'antd/dist/antd.css';
import './index.css';
import { Layout, Menu, Breadcrumb } from 'antd';
import { UserOutlined, LaptopOutlined, NotificationOutlined } from '@ant-design/icons';
const { SubMenu } = Menu;
const { Header, Content, Sider } = Layout;
function MainContent(props){
const pageState = props.pageState;
if (pageState == "Home"){
return <HomeContent />
} else if (pageState == "Course"){
return <CourseContent />
} else {
return <Lost />
}
}
function HomeContent(){
return (
<Content
className="site-layout-background"
style={{
padding: 24,
margin: 0,
minHeight: 800,
}}
>
<h2>This is the home page</h2>
</Content>
);
}
function CourseContent(){
return (
<Content
className="site-layout-background"
style={{
padding: 24,
margin: 0,
minHeight: 800,
}}
>
<h2>This is the course page</h2>
</Content>
);
}
function Lost(){
return (
<Content
className="site-layout-background"
style={{
padding: 24,
margin: 0,
minHeight: 800,
}}
>
<h2>Are you lost?</h2>
</Content>
);
}
export {
MainContent,
HomeContent,
CourseContent
}
|
import Vue from 'vue';
import Router from 'vue-router';
import TheIndex from '@/components/TheIndex';
import IssueList from '@/components/IssueList';
import AdditionalPage from '@/components/AdditionalPage';
import ColleagueList from '@/components/ColleagueList';
import AuthorList from '@/components/AuthorList';
import EditorList from '@/components/EditorList';
import NewsList from '@/components/NewsList';
import ArticleDetail from '@/components/ArticleDetail';
import ArticleList from '@/components/ArticleList/ArticleList';
import Http404 from '@/components/Http404';
Vue.use(Router);
export default new Router({
mode: 'history', // https://router.vuejs.org/en/essentials/history-mode.html
scrollBehavior(to, from, savedPosition) {
return savedPosition || { x: 0, y: 0 };
},
routes: [
{ path: '/', name: 'Index', component: TheIndex },
{ path: '/wspolpracownicy/:id?', name: 'ColleagueList', component: ColleagueList },
{ path: '/autorzy/:id?', name: 'AuthorList', component: AuthorList },
{ path: '/redaktorzy/:id?', name: 'EditorList', component: EditorList },
{ path: '/archiwum/:date?', name: 'IssueList', component: IssueList },
{ path: '/newsy/:categorySlug?', name: 'NewsList', component: NewsList }, //todo zmienic to na slug
{ path: '/artykuly/:slug', name: 'ArticleDetail', component: ArticleDetail },
{ path: '/artykuly', name: 'ArticleList', component: ArticleList },
{ path: '/dodatkowe/:pageLink', name: 'AdditionalPage', component: AdditionalPage },
{ path: '*', component: Http404 }
],
});
|
import React from 'react'
const Planet = () => {
return <div className="planet"></div>
}
export default Planet
|
// Concatenação de String
const nome = 'Nicolas'
const concatenacao = "Ola" + nome + "!" // Jeito "feio" de concatenar
const template = `Olá ${nome}!` // Usando Template
console.log(template)
// Expressões matemáticas
console.log(`1 + 1 = ${1+1}`)
// Chamando Funções
const up = texto => texto.toUpperCase()
console.log(`Ei.... ${up(nome)}, eu estou bem aqui`)
|
"use strict";
exports.getRelativeOffset = getRelativeOffset;
function getRelativeOffset(targetElement, sourceElement) {
var offset = {
left: 0,
top: 0
};
var currentElement = sourceElement;
while (currentElement && currentElement !== targetElement) {
var parentOffsetElement = currentElement.offsetParent;
var currentElementRect = currentElement.getBoundingClientRect();
var parentOffsetElementRect = parentOffsetElement.getBoundingClientRect();
offset.left += currentElementRect.left - parentOffsetElementRect.left;
offset.top += currentElementRect.top - parentOffsetElementRect.top;
currentElement = currentElement.offsetParent;
}
return offset;
}
|
let getNombre = async () => {
return 'Juan Diego Osorio Castrillón'
}
let getNombre2 = () => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve('Juan')
}, 3000);
})
}
let saludo = async () => {
let nombre = await getNombre2();
return `Hola ${nombre}`
}
saludo().then(msj => {
console.log(msj);
})
getNombre()
.then(Resp => {
console.log(Resp);
})
.catch(err => {
console.log(err);
});
console.log(getNombre());
|
/**
* @author Hamza Waqas <hamzawaqas@live.com>
* @since 4/3/15
*/
;
(function () {
'use strict';
var expect = require('chai').expect,
Clue = require('../');
describe('#clue', function() {
describe('validates', function() {
it('initialization and instance', function() {
expect(Clue).to.be.an.instanceOf(Function);
});
});
describe('executes', function() {
var path = __dirname + '/../package.json';
var clue;
beforeEach(function() {
clue = new Clue(path);
});
it('creating a new instance', function() {
var clue = new Clue(path);
expect(clue).to.be.an.instanceOf(Clue);
});
it('initialize with `path` in constructor', function() {
expect(clue).to.be.an.instanceOf(Clue);
expect(clue.__path).to.deep.equals([path]);
});
it('initialize with multiple `path` in constructor', function() {
var clue = new Clue(__dirname + '/sample1.json', __dirname + '/sample2.json');
expect(clue.get('hello')).to.equals('world');
expect(clue.get('foo')).to.equals(('bar'));
});
it('`setPath` and set path successfully', function() {
clue.reset();
expect(clue.setPath).to.be.an.instanceOf(Function);
clue.setPath(path);
expect(clue.__path).to.deep.equals([path]);
});
it('`getPath` and get path successfully', function() {
expect(clue.getPath).to.be.an.instanceOf(Function);
expect(clue.getPath()).to.deep.equals([path]);
});
describe('~`get` method', function() {
it('and return value if found', function() {
expect(clue.get).to.be.an.instanceOf(Function);
expect(clue.get('name')).to.equals('clue');
});
it('and return default value if not found', function() {
expect(clue.get('name2', 'boga')).to.equals('boga');
});
});
it('`getNotations` and return all parsed notations', function() {
expect(clue.getNotations()).to.be.an.instanceOf(Object);
});
});
});
})();
|
import React, { Component } from 'react';
import Todoinput from './Todoinput';
import Todoing from './Todoing';
import './todolist.css';
export default class Todolist extends Component {
constructor(){
super();
this.state = {
todoF:JSON.parse(localStorage.getItem('Ndone')) ||[],
todoD:JSON.parse(localStorage.getItem('done')) ||[],
}
}
addItem=(msg)=>{ //msg是input中的对象
var data = [...this.state.todoF,msg];
if(msg.done == false ){
this.setState({
todoF:data
},()=>{
localStorage.setItem('Ndone',JSON.stringify(this.state.todoF))
})
}
}
delItem=(a)=>{
var delData =[...this.state.todoF];
delData.splice(a,1);
this.setState({todoF:delData},()=>{
localStorage.setItem('Ndone',JSON.stringify(this.state.todoF));
})
}
delItem1=(a)=>{
var delData =[...this.state.todoD];
delData.splice(a,1);
this.setState({todoD:delData},()=>{
localStorage.setItem('done',JSON.stringify(this.state.todoD));
})
}
//切换
renewItem = (idx)=>{
//如果为假就放到TODO里面
var transData = [...this.state.todoF];
if(transData[idx] != undefined){
transData[idx].done = 'true';
}
var data = transData.splice(idx,1)[0];
var transData1=[...this.state.todoD,data];
this.setState({todoF:transData},()=>{
localStorage.setItem('Ndone',JSON.stringify(this.state.todoF))
})
this.setState({todoD :transData1},()=>{
localStorage.setItem('done',JSON.stringify(this.state.todoD))
})
}
renewItem1 =(idx)=>{
var transData = [...this.state.todoD];
transData[idx].done = false;
var data=transData.splice(idx,1)[0];
var transData1=[...this.state.todoF,data];
this.setState({todoD:transData},()=>{
localStorage.setItem('Ndone',JSON.stringify(this.state.todoD))
})
this.setState({todoF :transData1},()=>{
localStorage.setItem('done',JSON.stringify(this.state.todoF))
})
return;
}
render() {
return (
<div>
<Todoinput addTodo={this.addItem}/>
<Todoing todo={this.state.todo} todoF={this.state.todoF} todoD={this.state.todoD} delTodo={this.delItem} delTodo1={this.delItem1} renewTodo={this.renewItem} renewTodo1={this.renewItem1}/>
</div>
)
}
}
|
define([
'sgc-mongoose-model',
'chai'
], function(RemoteModel, chai) {
'use strict';
return function() {
var expect = chai.expect;
var Model = RemoteModel.Model;
var Collection = RemoteModel.Collection;
describe('Test Model validation ', function() {
it('test validate unknow attributes', function(){
var model = new Model();
expect(function(){
model.validate(['name']);
}).to['throw'](Error);
});
it('test undefined array, will check all submodels and collections', function(){
var model = new Model();
var validateCount = 0;
var SubModel = Model.extend({
validate: function(){
validateCount++;
return undefined;
}
});
var SubCollection = Collection.extend({
validate: function(){
validateCount++;
return undefined;
}
});
model.generateSchemaAttribute('submodel', {type:'MODEL', generator:SubModel});
model.generateSchemaAttribute('submodel1', {type:'MODEL', generator:SubModel});
model.generateSchemaAttribute('subcollection', {type:'COLLECTION', generator:SubCollection});
model.generateSchemaAttribute('subcollection1', {type:'COLLECTION', generator:SubCollection});
model.validate();
chai.assert.equal(validateCount, 4);
});
it('test validate submodel with lazy creation for children', function(done){
var model = new Model();
var SubModel = Model.extend({
configureSchema: function(){
this.generateSchemaAttribute('subsubmodel', {type:'MODEL', generator:Model});
this.generateSchemaAttribute('subsubcollection', {type:'MODEL', generator:Collection});
},
get: function(attr, options){
if (attr === 'subsubmodel') {
chai.assert.equal(options.lazyCreation, false);
}
if (attr === 'subsubcollection') {
chai.assert.equal(options.lazyCreation, false);
}
return Model.prototype.get.apply(this, arguments);
}
});
model.generateSchemaAttribute('submodel', {type:'MODEL', generator:SubModel});
model.validate();
done();
});
it('test generated error is correctly configured', function(){
var model = new Model();
var SubModel = Model.extend({
validate: function(){
return this.generateError('VERBOSE', 1) ||
Model.prototype.validate.apply(this, arguments);
}
});
model.generateSchemaAttribute('submodel', {type:'MODEL', generator:SubModel});
var error = model.validate();
expect(error).to.be.an['instanceof'](model.submodel._ModelError);
error.verbose.should.equal('VERBOSE');
error.identifier.should.equal(1);
error.model.should.equal(model.submodel);
});
it('test JSON sub format for model', function(){
var model = new Model();
var SubModel = Model.extend({
configureSchema: function(){
model.generateSchemaAttribute('anAttr1');
model.generateSchemaAttribute('anAttr2')
}
});
model.generateSchemaAttribute('submodelIn1', {type:'MODEL', generator:SubModel, jsonFormat:'_id'});
model.generateSchemaAttribute('submodelIn2', {type:'MODEL', generator:SubModel, jsonFormat:['anAttr1']});
model.set('submodelIn1', {_id:'351531'});
model.set('submodelIn2', {_id:'35153144', anAttr1:'anAttr1', anAttr2:'anAttr2'});
var res = model.toJSON();
res.submodelIn1.should.equal('351531');
res.submodelIn2.anAttr1.should.equal('anAttr1');
});
it('test JSON sub format for collection', function(){
var Collection1 = Collection.extend({
model:Model.extend({
configureSchema: function(){
this.generateSchemaAttribute('anAttr1');
this.generateSchemaAttribute('anAttr2');
Model.prototype.configureSchema.apply(this, arguments);
}
})
});
var Collection2 = Collection.extend();
var model = new (Model.extend({
configureSchema: function(){
this.generateSchemaAttribute('collection1', {type:'COLLECTION', generator:Collection1, jsonFormat:'_id'});
this.generateSchemaAttribute('collection2', {type:'COLLECTION', generator:Collection2, jsonFormat:['anAttr2']});
}
}))();
model.set('collection1', ['351', '24274']);
model.set('collection2', [{anAttr2:'anAttr2', anAttr1:'anAttr1'}]);
var res = model.toJSON();
res.collection1.length.should.equal(2);
res.collection1[0].should.equal('351');
res.collection2.length.should.equal(1);
res.collection2[0].anAttr2.should.equal('anAttr2');
});
});
};
});
|
/**
* 睡眠
*
* @export
* @param {*} millisecond 毫秒
*/
export async function sleep(millisecond) {
await (() => new Promise((resolve) => setTimeout(resolve, millisecond)))();
}
|
var player = {
pos: null,
render: true,
img: null,
scale: { width: 55, hieght: 55 },
movespeed: 3,
bounds: { x: 0, y: 0 },
animations: {},
animationFrame: 1,
animationFrameCounter: 0,
currentAnimation: 'idle',
lastAnimation: 'idle',
Spawn: function (pos) {
this.pos = pos
this.animations['attack'] = this.CreateAnimation('./img/gob/attack', '.png', 6)
this.animations['death'] = this.CreateAnimation('./img/gob/death', '.png', 7)
this.animations['idle'] = this.CreateAnimation('./img/gob/idle', '.png', 3)
this.animations['run'] = this.CreateAnimation('./img/gob/run', '.png', 6)
this.img = this.animations['idle'][0]
},
CreateAnimation: function (path, ending, length, start = 1) {
var arrayOut = []
for (var i = 1; i < length + 1; i++) {
var newImg = document.createElement('img')
newImg.src = path + i + ending
arrayOut.push(newImg)
}
return arrayOut
},
TryMove: function () {
if (this.pos === null) { return }
var keysDown = window.game.keysDown
var dir = { x: 0, y: 0 }
if (keysDown['87'] === true) dir.y -= 1 // w
if (keysDown['65'] === true) dir.x -= 1 // a
if (keysDown['83'] === true) dir.y += 1 // s
if (keysDown['68'] === true) dir.x += 1 // d
var targetPos = this.pos
if (Math.abs(dir.x) + Math.abs(dir.y) === 2) { // diagonal movement
this.currentAnimation = 'run'
targetPos.x += Math.sqrt(2) / 2 * dir.x * this.movespeed
targetPos.y += Math.sqrt(2) / 2 * dir.y * this.movespeed
} else if (dir.y + dir.x !== 0) {
this.currentAnimation = 'run'
targetPos.x += dir.x * this.movespeed
targetPos.y += dir.y * this.movespeed
} else {
this.currentAnimation = 'idle'
}
if (this.lastAnimation === this.currentAnimation) {
this.animationFrameCounter++
if (this.animationFrameCounter > 20) {
this.animationFrameCounter = 0
this.animationFrame++
if (this.animationFrame > this.animations[this.currentAnimation].length - 1) {
this.animationFrame = 1
}
}
console.log(this.currentAnimation + ' ' + this.animationFrame)
this.img = this.animations[this.currentAnimation][this.animationFrame]
} else {
this.animationFrame = 1
this.animationFrameCounter = 0
}
var bounds = this.bounds
this.bounds.width = window.game.scene.draw.ctx.canvas.width
this.bounds.height = window.game.scene.draw.ctx.canvas.height
if (this.pos.x < bounds.x) this.pos.x = bounds.x
if (this.pos.x > bounds.width) this.pos.x = bounds.width
if (this.pos.y < bounds.y) this.pos.y = bounds.y
if (this.pos.y > bounds.height) this.pos.y = bounds.height
this.lastAnimation = this.currentAnimation
},
Update: function (ctx) {
player.TryMove()
},
Draw: function (ctx) {
if (player.render) {
console.log(this.img.src)
ctx.drawImage(this.img, this.pos.x, this.pos.y, this.scale.width, this.scale.hieght)
}
},
Stop: function () {
this.render = false
}
}
module.exports = player
|
$(document).ready(function() {
var reader = new FileReader();
reader.addEventListener('load', function() {
$('.image-view').attr('src', reader.result);
$('.image-original').attr('src', reader.result);
}, false);
$('.image-upload').on('change', function() {
reader.readAsDataURL(this.files[0]);
});
$('.filter-setting>input').on('input', function() {
$(this).siblings('.filter-value').html($(this).val());
});
$('.filter-setting>input').on('change', function() {
var filter = $(this).attr('data-filter');
var value = $(this).val();
var clone = $('.image-original').clone();
clone.removeClass('image-original').addClass('image-view');
$('.image-view').replaceWith(clone);
Caman('.image-view', function() {
this[filter](value).render();
});
});
});
|
"use strict";
dinnerApp.controller('PaymentCtrl',
[
'$scope',
'$state',
'UserManager',
'SharedService',
'LoadingService',
'InitService',
function($scope,
$state,
$userManager,
$sharedService,
$loadingService,
$initService
) {
$scope.reservationSelected = $sharedService.get().reservations.selected;
$scope.updateUserData = function(user) {
$scope.panelShown = user.payment.has_default_card ? 'payment_confirm' : 'change_card';
$scope.paymentCard = user.payment.default_card;
};
$scope.user = $sharedService.get().user;
$scope.updateUserData($scope.user);
$scope.changeCard = function(){
$scope.panelShown = 'change_card';
$scope.cardError = false;
};
$scope.handleStripe = function(status, response){
if(response.error) {
$scope.cardError = true;
} else {
$loadingService.loading(true);
$userManager.updateCustomer(response.id).$promise.then(function(user) {
$sharedService.set({user: user});
$scope.user = user;
$scope.updateUserData(user);
$loadingService.loading(false);
$scope.panelShown = 'payment_confirm';
});
}
};
$scope.confirmPayment = function(){
$loadingService.loading(true);
$userManager.reserve($scope.reservationSelected).$promise.then(function(response) {
$sharedService.set({
requireInitUser: true
});
$loadingService.loading(false);
$state.go('user');
}, function(error){
$loadingService.loading(false);
});
};
}]);
|
import * as pokemonActions from './pokemons'
export { pokemonActions }
|
(function(angular) {
'use strict';
// Referencia para o nosso app
var app = angular.module('app');
// Cria o controlador de autenticação
app.controller('ProfileController', ['$scope', '$location', 'User', function($scope, $location, User) {
$scope.authUser = User.getAuthenticated();
// Redireciona para a página de autenticação
if (!$scope.authUser) {
window.location = '/login';
}
// Verifica o hash
var location = $location.url() || '/me';
$location.url(location);
// Usuario atual
if (location == '/me') {
$scope.user = $scope.authUser;
// Salva perfil do usuario
$scope.save = function() {
var user = User.getAuthenticated();
user.id = $scope.user.id;
user.name = $scope.user.name;
user.email = $scope.user.email;
user.bio = $scope.user.bio;
user.birthDate = $scope.user.birthDate;
user.password = $scope.user.password;
user.picture = $scope.user.picture;
user.save();
}
// Salva perfil do usuario
$scope.delete = function() {
var user = User.getAuthenticated();
user.delete();
User.setAuthenticated(null);
window.location = '/login';
}
} else {
var userId = location.slice(1, location.length);
User.findById(userId,
function success(user) {
$scope.user = new User(user);
},
function failure(user) {
window.location = '/';
}
);
}
}]);
})(window.angular);
|
import React from 'react'
import { Provider } from 'react-redux'
import Navbar from './Navbar'
import FrontPage from './FrontPage'
import { Route, Switch } from 'react-router-dom'
import PostPage from './PostPage'
const App = ({ store }) => {
return (
<Provider store={store}>
<div className="page layout">
<Navbar />
<br />
<Switch>
<Route exact path="/" component={FrontPage} />
<Route path="/post/:id" component={PostPage} />
</Switch>
</div>
</Provider>
)
}
export default App
|
'use strict';
const hakukentta = document.getElementById('hakukentta');
const nappi = document.getElementById('nappi');
const tulostusloota = document.getElementById('tuloslaatikko');
// kun nappia painetaan
nappi.addEventListener('click', function () {
// hae hakukentän teksti (value)
const hakusana = hakukentta.value;
// console.log(hakusana);
// lähetä pyynto APIin
const hakusanasi = document.getElementById('hakusanasi');
hakusanasi.innerHTML = `Tulokset haulla "${hakusana}".`;
fetch('https://api.tvmaze.com/search/shows?q=' +
hakusana) // Käynnistetään haku. Vakiometodi on GET.
.then(function (vastaus) { // Sitten kun haku on valmis,
return vastaus.json(); // muutetaan ladattu tekstimuotoinen JSON JavaScript-olioksi/taulukoksi
}).then(function (tvsarjat) { // Sitten otetaan ladattu data vastaan ja
console.log(tvsarjat); // tulosta tulos konsoliin
appendData(tvsarjat);
}).catch(function (error) { // Jos tapahtuu virhe,
console.log(error); // kirjoitetaan virhe konsoliin.
});
});
document.getElementById('nappi').addEventListener('keyup', function (event) {
event.preventDefault();
if (event.keyCode === 13) {
document.getElementById('nappi').click();
}
});
function appendData(tvsarjat) {
const paaJuttu = document.getElementById('tuloslaatikko');
//tyhjennä pääjuttu ennen seuraavaa hakua
paaJuttu.innerHTML = '';
if (tvsarjat.length == 0) {
paaJuttu.innerHTML = ` <div id="juttu" style="width:100%!important">
<h1>Ei tuloksia</h1>
<figure>
<img src="kuvat/giphy.gif" alt="404 ei tuloksia"/>
</figure>
<h4>Valitettavasti hakusanallasi "${hakukentta.value}" ei löytynyt mitään.</h4>
</div>`;
} else {
for (let i = 0; i < tvsarjat.length; i++) {
// const tulokset = document.createElement("h6");
const div = document.createElement('div');
div.setAttribute('id', 'juttu');
const o = document.createElement('h3');
const l = document.createElement('h6');
l.setAttribute('class', 'l');
o.setAttribute('class', 'o');
const p = document.createElement('p');
p.setAttribute('class', 'marginaali');
const p2 = document.createElement('p');
const p3 = document.createElement('p');
const img = document.createElement('img');
const p4 = document.createElement('p');
p4.setAttribute('class', 'linkkitv');
const p5 = document.createElement('p');
p5.setAttribute('class', 'paivaus');
p2.setAttribute('class', 'synopsis');
p3.setAttribute('class', 'rating');
const anuoli = document.createElement("a");
const a1 = document.createElement('a');
const officialsites = document.createElement("p");
div.innerHTML = '';
div.appendChild(o);
div.appendChild(l);
// div.append(tulokset);
// tulokset.innerHTML = tvsarjat.length + "tulosta";
paaJuttu.appendChild(div);
if (`${tvsarjat[i].show.image}` == 'null') {
img.src = `kuvat/404.jpg`;
img.alt = 'kuva';
img.setAttribute('class', 'klikki');
div.appendChild(img);
} else {
if (`${tvsarjat[i].show.officialSite}` == "null") {
img.src = `${tvsarjat[i].show.image.medium}`;
img.alt = 'kuva';
img.setAttribute('class', 'klikki');
div.appendChild(img);
} else {
a1.setAttribute('href', `${tvsarjat[i].show.officialSite}`);
a1.setAttribute("title", `${tvsarjat[i].show.officialSite}`)
a1.appendChild(img);
img.src = `${tvsarjat[i].show.image.medium}`;
img.alt = 'kuva';
img.setAttribute('class', 'klikki');
div.appendChild(a1);
}
}
o.innerHTML = `<b>${tvsarjat[i].show.name} </b> `;
l.innerHTML = `${tvsarjat[i].show.type}, ${tvsarjat[i].show.language}`;
p.innerHTML = `<b>Genre:</b> ${tvsarjat[i].show.genres} <br> `;
div.appendChild(p);
if (`${tvsarjat[i].show.premiered}` == 'null') {
p5.innerHTML = '';
div.appendChild(p5);
} else {
p5.innerHTML = `${tvsarjat[i].show.premiered}`;
div.appendChild(p5);
}
if (`${tvsarjat[i].show.summary}` == 'null') {
p2.innerHTML = '';
div.appendChild(p2);
} else {
p2.innerHTML += `${tvsarjat[i].show.summary}`;
div.appendChild(p2);
}
if (`${tvsarjat[i].show.rating.average}` == 'null') {
p3.innerHTML = '';
div.append(p3);
} else {
p3.innerHTML = `${tvsarjat[i].show.rating.average} ★`;
div.append(p3);
}
if (`${tvsarjat[i].show.officialSite}` == "null") {
officialsites.innerHTML = "";
div.appendChild(officialsites);
} else {
//ei varmaan ollut nopein tapa tehdä tämä mutta ainoa jonka löysin
const osoite = document.createElement("a");
const href = osoite.href = `${tvsarjat[i].show.officialSite}`;
const href2 = href.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
const href3 = href2.substring(0, href2.indexOf('.'));
const href4 = href3.charAt(0).toUpperCase() + href3.slice(1);
officialsites.innerHTML = `Virallinen sivusto: <br> <a href="${tvsarjat[i].show.officialSite}" class="tvlinkit" title="${tvsarjat[i].show.officialSite}">${href4}</a>`;
div.appendChild(officialsites);
}
if (`${tvsarjat[i].show.url}` == 'null') {
p4.innerHTML = '';
div.appendChild(p4);
} else {
p4.innerHTML = `<a class="tvlinkit" href="${tvsarjat[i].show.url}" title="Lisätietoa TVMazen sivulla">Lisätietoa</a>`;
div.appendChild(p4);
}
//tyhjentää hakukentän, helpottaa seuraavaa hakua
hakukentta.value = '';
}
}
const body2 = document.querySelector('body');
const footer = document.createElement('footer');
//halusin footerin kaikkialle paits etusivulle nii keksin nyt vaa tän tavan
if (document.contains(document.querySelector('footer'))) {
let jutska = document.querySelector('footer');
jutska.remove();
}
footer.innerHTML = ` <div class="sisus">
<h3>TV-Sarjat</h3>
<p>Timo Hyppönen</p>
<p>TXK20S1-F, Web-tekniikat ja digitaalinen media.</p>
<span style="display:inline-block;float:left;">AJAX</span><span style="display:inline-block;text-align: right;float:right;">Syyskuu 2020</span>
</div>`;
body2.appendChild(footer);
}
//enter näppäimellä haku
const input2 = document.getElementById('hakukentta');
// Execute a function when the user releases a key on the keyboard
input2.addEventListener('keyup', function (event) {
// Number 13 is the "Enter" key on the keyboard
if (event.keyCode === 13) {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById('nappi').click();
//console.log("toimii");
}
});
const mybutton = document.getElementById("myBtn");
window.onscroll = function () {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 90 || document.documentElement.scrollTop > 90) {
mybutton.style.display = "block";
} else {
mybutton.style.display = "none";
}
}
function topFunction() {
// body.style.scroll-behavior = "smooth";
document.body.scrollTop = 0; // For Safari
document.documentElement.scrollTop = 0; // For Chrome, Firefox, IE and Opera
}
|
/*
* @Author: huangyuhui
* @Date: 2020-11-06 15:43:48
* @LastEditors: huangyuhui
* @LastEditTime: 2020-11-19 11:25:49
* @Description: 全局过滤器
* @FilePath: \customs-system\src\filters\index.js
*/
/**
* boolean 转 文字 过滤器 (自带语言)
* @param { number | boolean } value 需要转换的值
* @return {string}
* @example true | formatBoolean
*/
export function formatBoolean( value = false ) {
return ( `global.${ value ? 'yes' : 'no' }` );
}
/**
* 日期时间格式化
* {{ Date() | formatDate }} -> 2020-09-28 15:54:52
* {{ '2020/11/06 12:30:45' | formatDate('yyyy-MM-dd hh:mm:ss w') }} -> 2020-11-06 12:30:45 星期四
* @param {Date} value 可以被 new Date(value) 解析的时间格式,如 Date()、2020/11/06、2020-11-06 12:00 等
* @param {String} fmt 格式化模版
*/
export const formatDate = ( () => {
const weekMap = new Map( [
[ 0, '星期日' ],
[ 1, '星期一' ],
[ 2, '星期二' ],
[ 3, '星期三' ],
[ 4, '星期四' ],
[ 5, '星期五' ],
[ 6, '星期六' ]
] );
return function formatDate( value, fmt = 'yyyy-MM-dd hh:mm:ss' ) {
const date = new Date( value );
const normalData = {
// 月份
'M+': date.getMonth() + 1,
// 日
'd+': date.getDate(),
// 小时
'h+': date.getHours(),
// 分
'm+': date.getMinutes(),
// 秒
's+': date.getSeconds(),
// 星期
'w+': date.getDay(),
// 季度
'q+': Math.floor( ( date.getMonth() + 3 ) / 3 ),
// 毫秒
S: date.getMilliseconds()
};
if ( /(y+)/.test( fmt ) ) {
fmt = fmt.replace(
RegExp.$1,
( date.getFullYear() + '' ).substr( 4 - RegExp.$1.length )
);
}
for ( const key in normalData ) {
if ( key === 'w+' ) {
fmt = fmt.replace( 'w', weekMap.get( normalData[ key ] ) );
} else if ( new RegExp( `(${ key })` ).test( fmt ) ) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length === 1
? normalData[ key ]
: ( '00' + normalData[ key ] ).substr( ( '' + normalData[ key ] ).length )
);
}
}
return fmt;
};
} )();
|
export { default } from './ImageSM'
|
let readlineSync = require('readline-sync');
let days_worked = readlineSync.question("Days worked:")
days_worked = (days_worked*30);
let ps4=200;
let Samsung_phone=900;
let TV=500;
let game_skin=9.99;
let total = (days_worked /ps4 |0 );
let total1 = (days_worked /Samsung_phone |0);
let total2 =(days_worked /TV |0);
let total3 = (days_worked /game_skin |0);
console.log(`I can by ${total} PS4 ${total1} Samsung ${total2} TV ${total3} game skin Τhanks for your purchase! have a nice day! `);
|
const express=require('express')
const morgan=require('morgan')
const cors=require('cors')
const axios=require('axios')
const app=express()
const mongoose=require('mongoose')
const Person=require('./models/Person')
const url=process.env.MONGODB_URI
morgan.token('data',(req) => {
if(req.body!==undefined)
return JSON.stringify(req.body)
})
app.use(express.static('build'))
app.use(express.json())
app.use(cors())
app.use(morgan('tiny',{
skip: (req,res) => req.method==='POST'
}))
app.use(morgan(':method :url :status :req[content-length] - :response-time ms :data',{
skip:(req,res) => req.method!=='POST'
}))
app.get('/',(req,res) => {
res.send('<h1>Phone Book</h1>')
})
app.get('/api/persons',(req,res) => {
Person.find({}).then((result) => {
res.json(result)
})
})
app.get('/api/persons/:id',(req,res,next) => {
Person.findById(req.params.id)
.then(result => {
if(result)
{
res.json(result)
}
else
{
res.status(404).end()
}
})
.catch(error => next(error))
})
app.post('/api/persons',(req,res,next) => {
const person=req.body//remember you have to enable/import json parser i.e app.use(express.json())
if(person.name===undefined || person.number===undefined)
{
if(person.name===undefined)
{
return res.status(400).json({
'error':'name is missing'
})
}
else
{
return res.status(400).json({
'error':'number is missing'
})
}
}
else
{
Person.find({ number:person.number })
.then((result) => {
if(result.length===1)
{
res.json({
error:'number must be unique'
})
}
else{
const newPerson=new Person({
name:person.name,
number:person.number,
date:Date(),
})
newPerson.save()
.then(result => {
// console.log(result)
res.json(result)
})
.catch(err => next(err))
}
})
.catch(error => next(error))
}
})
app.delete('/api/persons/:id',(req,res,next) => {
Person.findByIdAndRemove(req.params.id)
.then(result => {
res.status(204).end()
})
.catch(error => next(error))
})
app.put('/api/persons/:id',(req,res,next) => {
const body=req.body
const person={
name:body.name,
number:body.number,
}
Person.findByIdAndUpdate(req.params.id,person,{ new:true,runValidators:true })
.then(updatedPerson => {
res.json(updatedPerson.toJSON())
})
.catch(error => next(error))
})
app.get('/info',(req,res) => {
Person.countDocuments({}, function( err, count){
res.send(`<div>Phonebook has info for ${count} people</div> <br> ${new Date()}`)
})
})
const errorHandler=(error,req,res,next) => {
if(error.name==='CastError')
{
return res.status(400).send({ error:'malformatted id' })
}
else if(error.name==='ValidationError')
{
console.log(error.message)
return res.status(400).json({ error:error.message })
}
next(error)
}
app.use(errorHandler)
const PORT=process.env.PORT || 3001
app.listen(PORT,() => {
console.log(`listening on port ${PORT}`)
})
|
/*
* grunt-maven
* https://github.com/adam/grunt-maven-npm
*
* Copyright (c) 2014 Adam Dubiel
* Licensed under the Apache-2.0 license.
*/
'use strict';
module.exports = function(grunt) {
var gruntCWD = process.cwd();
grunt.initConfig({
jshint: {
all: [
'package.json',
'Gruntfile.js',
'tasks/*.js',
'<%= nodeunit.tests %>',
],
options: {
jshintrc: '.jshintrc',
},
},
clean: {
tests: ['tmp'],
},
copy: {
prepareVanilla: {
expand: true,
cwd: 'test/fixture/vanilla/',
src: ['**'],
dest: 'tmp/vanilla/'
},
prepareVanillaCwd: {
files: [
{
expand: true,
cwd: 'test/fixture/vanilla/src/static',
src: ['**'],
dest: 'tmp/vanillaCwd/src/static/extrafolder'
},
{
expand: true,
cwd: 'test/fixture/vanilla/target-grunt',
src: ['**'],
dest: 'tmp/vanillaCwd/target-grunt'
}
]
},
prepareOverrides: {
expand: true,
cwd: 'test/fixture/overrides/',
src: ['**'],
dest: 'tmp/overrides/'
}
},
execute: {
chdirToVanilla: {
call: function() {
process.chdir('tmp/vanilla/target-grunt');
}
},
chdirToVanillaCwd: {
call: function() {
process.chdir('tmp/vanillaCwd/target-grunt');
}
},
chdirToOverrides: {
call: function() {
process.chdir('tmp/overrides/target-grunt');
}
},
chdirReset: {
call: function() {
process.chdir(gruntCWD);
}
}
},
mavenPrepare: {
should_prepare_grunt_dist_and_copy_to_maven_dist: {
options: {
resources: ['**']
}
},
should_prepare_grunt_dist_and_copy_to_maven_dist_cwd: {
options: {
resources: ['**']
}
},
should_prepare_grunt_dist_and_copy_to_maven_dist_with_overriden_properties: {
options: {
resources: ['**']
}
}
},
mavenDist: {
should_prepare_grunt_dist_and_copy_to_maven_dist: {
options: {
warName: 'war',
deliverables: ['**', '!non-deliverable.js'],
gruntDistDir: 'dist'
}
},
should_prepare_grunt_dist_and_copy_to_maven_dist_cwd: {
options: {
warName: 'war',
workingDirectory: 'extrafolder',
deliverables: ['**', '!non-deliverable.js'],
gruntDistDir: 'dist'
}
},
should_prepare_grunt_dist_and_copy_to_maven_dist_with_overriden_properties: {
options: {
warName: 'war',
deliverables: ['**'],
gruntDistDir: 'dist'
}
}
},
nodeunit: {
tests: ['test/*_test.js']
}
});
grunt.loadTasks('tasks');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-nodeunit');
grunt.loadNpmTasks('grunt-execute');
grunt.registerTask('testVanilla', [
'execute:chdirToVanilla',
'mavenPrepare:should_prepare_grunt_dist_and_copy_to_maven_dist',
'mavenDist:should_prepare_grunt_dist_and_copy_to_maven_dist',
'execute:chdirReset'
]);
grunt.registerTask('testVanillaCwd', [
'execute:chdirToVanillaCwd',
'mavenPrepare:should_prepare_grunt_dist_and_copy_to_maven_dist_cwd',
'mavenDist:should_prepare_grunt_dist_and_copy_to_maven_dist_cwd',
'execute:chdirReset'
]);
grunt.registerTask('testOverrides', [
'execute:chdirToOverrides',
'mavenPrepare:should_prepare_grunt_dist_and_copy_to_maven_dist_with_overriden_properties',
'mavenDist:should_prepare_grunt_dist_and_copy_to_maven_dist_with_overriden_properties',
'execute:chdirReset'
]);
grunt.registerTask('test', ['clean', 'copy', 'testVanilla', 'testVanillaCwd', 'testOverrides', 'nodeunit']);
grunt.registerTask('default', ['jshint', 'test']);
};
|
module.exports = function () {
let popupClose = document.querySelector('.popup-close');
let popupCont = document.querySelector('.popup-home__wrap');
let popupHome = document.querySelector('.popup-home');
let popupTitle = popupHome.querySelector('.popup-home__title');
let popupSquare = popupHome.querySelector('.popup-home__square span');
let imageGallery = popupHome.querySelector('#imageGallery');
let homeCoast = popupHome.querySelector('.popup-home__coat-val');
let homeIpoteca = popupHome.querySelector('.popup-home__ipoteca');
let homeDescr = popupHome.querySelector('.popup-home__descr');
let slider;
// slider create
slider = $('#imageGallery').lightSlider({
gallery: true,
item: 1,
loop: true,
thumbItem: 3,
slideMargin: 0,
enableDrag: false,
enableTouch: false,
freeMove: true,
currentPagerPosition: 'left',
onSliderLoad: function (el) {
el.lightGallery({
selector: '#imageGallery .lslide'
});
}
});
slider.destroy();
function fillPopupHome(target) {
let dataHome = target.getAttribute('data-home');
let objHome = homes[dataHome];
popupTitle.innerHTML = objHome.title;
popupSquare.innerHTML = objHome.square + 'м';
homeIpoteca.innerHTML = 'Ипотека от ' + objHome.ipoteca + ' руб/мес.';
homeCoast.innerHTML = objHome.coast + ' млн.р.';
homeDescr.innerHTML = objHome.descr;
imageGallery.innerHTML = '';
// create gallery and fill it
for (let i = 0; i < objHome.img.length; i++) {
var li = document.createElement('LI');
var img = document.createElement('IMG');
var a = document.createElement('A');
a.setAttribute('href', objHome.img[i].big);
li.setAttribute('data-thumb', objHome.img[i].small);
li.setAttribute('data-src', objHome.img[i].big);
img.setAttribute('src', objHome.img[i].big);
a.appendChild(img);
li.appendChild(a);
imageGallery.appendChild(li);
}
}
document.body.addEventListener('click', function (e) {
if (e.target.classList.contains('project-home__btn') || e.target.classList.contains('project-home__item')) {
e.preventDefault();
fillPopupHome(e.target);
// popupCont.classList.add('active');
setTimeout(function () {
// slider create
slider = $('#imageGallery').lightSlider({
gallery: true,
item: 1,
loop: true,
thumbItem: 3,
slideMargin: 0,
enableDrag: false,
enableTouch: false,
freeMove: true,
currentPagerPosition: 'left',
onSliderLoad: function (el) {
el.lightGallery({
selector: '#imageGallery .lslide'
});
}
});
setTimeout(function() {
popupCont.classList.add('active');
}, 300);
}, 300);
}
});
// Popup close and slider destroy
popupCont.addEventListener('click', function (e) {
if (e.target.classList.contains('popup-home__wrap') || e.target.classList.contains('popup-close')) {
popupCont.classList.remove('active');
slider.destroy();
}
});
popupCont.addEventListener('keyup', function (e) {
if (e.keyCode === 27) {
popupCont.classList.remove('active');
slider.destroy();
}
});
}
|
__resources__["/naughty.js"] = {meta: {mimetype: "application/javascript"}, data: function(exports, require, module, __filename, __dirname) {
function Circle(x, y, r, color) {
this.x = x;
this.y = y;
this.r = r;
this.fateX = -10;
this.fateY = -10;
this.destX = -10;
this.destY = -10;
this.alpha = 0;
this.vx = Math.random() - .5 * 5;
this.vy = Math.random() - .5 * 5;
}
function NaughtyText(count, radius, blockSide,
backCanvas, scale,
gatherDuration, scatterDuration)
{
this.count = count;
this.radius = radius;
this.blockSide = blockSide;
this.fadeFactor = 5;
this.windX = Math.sin(Math.random() * 360) * 3;
this.windY = Math.cos(Math.random() * 360) * 3;
this.text = "";
this.scale = scale;
this.backCanvas = backCanvas;
this.canvasContext = backCanvas.getContext("2d");
var w = backCanvas.width;
var h = backCanvas.height;
// var c0 = {
// // steelblue
// r:70,
// g:130,
// b:180
// };
var c0 = {
// steelblue
r:70,
g:130,
b:180
};
var c1 = {
// orangered
r:255,
g:69,
b:0
};
var colors = [c0, c1];
c0.vr = (c1.r - c0.r) / gatherDuration;
c0.vg = (c1.g - c0.g) / gatherDuration;
c0.vb = (c1.b - c0.b) / gatherDuration;
c1.vr = (c0.r - c1.r) / scatterDuration;
c1.vg = (c0.g - c1.g) / scatterDuration;
c1.vb = (c0.b - c1.b) / scatterDuration;
this.colors = colors;
this.color = {
r: c0.r,
g: c0.g,
b: c0.b
};
var elementArray = new Array(count);
for (var i = 0; i < count; ++i)
{
elementArray[i] =
new Circle(Math.floor(Math.random() * w),
Math.floor(Math.random() * h),
radius);
}
this.elementArray = elementArray;
this.elapse = 0;
this.gatherDuration = gatherDuration;
this.scatterDuration = scatterDuration;
this.current = this._idleState;
}
NaughtyText.prototype._idleState = function ()
{
if(0 <= this.elapse)
{
this.gather();
this.current = this._gatherState;
}
};
NaughtyText.prototype._gatherState = function ()
{
if(this.gatherDuration <= this.elapse)
{
this.scatter();
this.current = this._scatterState;
}
};
NaughtyText.prototype._scatterState = function ()
{
if((this.gatherDuration + this.scatterDuration) <= this.elapse)
{
this.elapse = 0;
this.current = this._idleState;
}
};
NaughtyText.prototype.drawTextTemplate = function (text, x,y)
{
this.text = text;
var ctx = this.canvasContext;
ctx.clearRect(0, 0,
this.backCanvas.width,
this.backCanvas.height);
ctx.fillStyle = "red";
//ctx.font="36pt Verdana,san-serif";
ctx.font="36pt Verdana, Courier New";
ctx.fillText(this.text, x,y);
var imageData = ctx.getImageData(0, 0,
this.backCanvas.width,
this.backCanvas.height);
var imageWidth = Math.floor(imageData.width);
var imageHeight = Math.floor(imageData.height);
var blockSide = this.blockSide; // default 4
var area = (blockSide * blockSide);
var centerOffset = Math.floor(blockSide / 2);
var assignedCount = 0;
var threshold = 60
for (var j = 0; j < imageHeight; j = j + blockSide)
{
for (var i = 0; i < imageHeight; i = i + blockSide)
{
var sum = 0;
for (var ypos = j; ypos < j + blockSide; ++ypos)
{
for (var xpos = i; xpos < i + blockSide; ++xpos)
{
var index = (xpos * 4) * imageData.width + (ypos * 4);
var red = imageData.data[index];
sum += red;
}
}
var average = sum / area;
var ea = this.elementArray;
if (average > threshold && assignedCount < ea.length)
{
ea[assignedCount].fateX = (j + centerOffset) * this.scale;
ea[assignedCount].fateY = (i + centerOffset) * this.scale;
++assignedCount;
}
}
}
for (var i = assignedCount; i < ea.length; ++i)
{
ea[i].fateX = -10;
ea[i].fateY = -10;
}
}
NaughtyText.prototype.gather = function ()
{
var ea = this.elementArray;
for (var i = 0; i < ea.length; ++i)
{
ea[i].destX = ea[i].fateX;
ea[i].destY = ea[i].fateY;
}
}
NaughtyText.prototype.scatter = function ()
{
var windForce = 0;
this.windX = 0;//Math.sin(Math.random() * Math.PI * 2) * windForce;
this.windY = 0;//Math.cos(Math.random() * Math.PI * 2) * windForce;
var ea = this.elementArray;
for (var i = 0; i < ea.length; ++i)
{
var angle = Math.random() * Math.PI * 2;
var dir = Math.sin(angle);
var minv = 2.5;
if(dir < 0)
{
dir += -minv;
}
else
{
dir += minv;
}
ea[i].vx = dir * this.fadeFactor;
ea[i].vy = (0 + Math.cos(angle)) * this.fadeFactor;
ea[i].destX = -10;
ea[i].destY = -10;
}
}
NaughtyText.prototype._doUpdate = function (dt)
{
var ea = this.elementArray;
var colors = this.colors;
if(this.current === this._gatherState)
{
var leftTime = (0.5 * this.gatherDuration - this.elapse);
var factor = 0;
if(leftTime <= 0)
{
factor = 1;
}
else
{
factor = dt / leftTime;
}
this.color.r += (colors[1].r - this.color.r) * factor;
this.color.g += (colors[1].g - this.color.g) * factor;
this.color.b += (colors[1].b - this.color.b) * factor;
}
else if(this.current === this._scatterState)
{
var leftTime = (this.gatherDuration + this.scatterDuration - this.elapse);
var factor = 0;
if(leftTime <= 0)
{
factor = 1;
}
else
{
factor = dt / leftTime;
}
this.color.r += (colors[0].r - this.color.r) * factor;
this.color.g += (colors[0].g - this.color.g) * factor;
this.color.b += (colors[0].b - this.color.b) * factor;
}
var tf = dt / 30;
var fade = Math.pow(0.95, tf);
var damping = Math.pow(0.99, tf);
for (var i = 0; i < ea.length; ++i)
{
var e = ea[i];
if (e.destX >= 0)
{
var dx = e.destX - e.x;
var dy = e.destY - e.y;
var d = Math.sqrt(dx * dx + dy * dy);
e.x += (dx / 4 + (dx / 120 * e.vx) + this.windX) * tf;
e.y += (dy / 6 + (dy / 120 * e.vy) + this.windY) * tf;
e.alpha += ((1.0 - e.alpha) / 2) * tf ;
if (e.alpha > 1)
{
e.alpha = 1;
}
}
else
{
e.x += (e.vx + this.windX) * tf;
e.y += (e.vy + this.windY) * tf;
e.vy += 0.5 * tf; // gravity
e.alpha *= fade;
if (e.alpha < 0)
{
e.alpha = 0;
}
}
this.windX *= damping;
this.windY *= damping;
if (e.x < 0)
{
e.x = -e.x;
e.vx = -e.vx;
}
if (e.y < 0)
{
e.y = -e.y;
e.vy = -e.vy;
};
var w = this.backCanvas.width;
var h = this.backCanvas.height;
if (e.x > w)
{
e.x = w - (e.x - w);
e.vx = -e.vx;
}
if (e.y > h)
{
e.y = h - (e.y - h);
e.vy = -e.vy * 0.45;
}
}
}
NaughtyText.prototype.update = function (dt)
{
this.current();
this._doUpdate(dt);
this.elapse += dt;
}
NaughtyText.prototype.draw = function (ctx)
{
var c = 'rgb(' + Math.floor(this.color.r) + ',' +
Math.floor(this.color.g) +
',' + Math.floor(this.color.b) + ')';
ctx.fillStyle = c;
var ea = this.elementArray;
for (var i = 0; i < ea.length; ++i)
{
var e = ea[i];
ctx.globalAlpha = e.alpha;
ctx.beginPath();
//ctx.fillStyle = "#7f007f";
ctx.arc(e.x, e.y, e.r, 0, Math.PI * 2, true);
//ctx.closePath();
ctx.fill();
}
}
exports.NaughtyText = NaughtyText;
}};
|
import React, { useRef, useState, useEffect } from 'react'
import ReactDatePicker from 'react-datepicker'
import { useField } from '@unform/core'
import { registerLocale } from 'react-datepicker'
import es from 'date-fns/locale/pt-BR'
import 'react-datepicker/dist/react-datepicker.css'
import './styles.css'
registerLocale('pt-BR', es)
const DatePicker = ({ name, ...rest }) => {
const datepickerRef = useRef(null)
const { fieldName, registerField, defaultValue } = useField(name)
const [date, setDate] = useState(defaultValue || null)
useEffect(() => {
registerField({
name: fieldName,
ref: datepickerRef.current,
path: 'props.selected',
clearValue: (ref) => {
ref.clear()
},
})
}, [fieldName, registerField])
return (
<>
<span style={{ color: '#ddd', margin: '15px 0 10px' }}>
Selecione a data e o horário:
</span>
<ReactDatePicker
selected={date}
minDate={new Date()}
ref={datepickerRef}
onChange={setDate}
locale="pt-BR"
{...rest}
showTimeSelect
showDisabledMonthNavigation
timeCaption="Horário"
dateFormat="dd/MM/yy HH:mm"
className="date-picker"
required
/>
</>
)
}
export default DatePicker
|
import React from "react";
import { Input } from "antd";
import { useRouter } from "next/router";
import { useSelector, useDispatch } from "react-redux";
import styled from "styled-components";
import { fetchPosts } from "../../actions/fetchPosts";
import { UPDATE_TEXT_SEARCH, UPDATE_CURRENT_PAGE } from "../../actions/types";
const SearchWrapper = styled.section`
padding: 0.5rem;
flex: 1;
`;
const SearchBar = () => {
const { Search } = Input;
const router = useRouter();
const dispatch = useDispatch();
const searchValue = useSelector((state) => {
state.filters.textSearch;
});
const handleUpdateValue = (value) => {
dispatch({ type: UPDATE_TEXT_SEARCH, payload: value });
};
const handleSearch = () => {
router.push("/");
dispatch({ type: UPDATE_CURRENT_PAGE, payload: 1 });
dispatch(fetchPosts());
};
return (
<SearchWrapper>
<Search
enterButton='Search'
size='large'
placeholder='Find Your Next Surfboard...'
value={searchValue}
onChange={(event) => handleUpdateValue(event.target.value)}
onSearch={() => handleSearch()}
/>
</SearchWrapper>
);
};
export default SearchBar;
|
function renderSurveys(surveys) {
var surveysHTML = surveys.map(function(survey){
return `
<form class="mx-auto my-5 w-50">
<h1>${survey.title}</h1>
<hr/>
${renderFields(survey.fields)}
<button class="btn btn-primary" type="submit">${survey.submitButtonText}</button>
</form>
`
});
return `
<div class=" mt-5">
${surveysHTML.join('')}
</div>
`
}
function renderFields(fields) {
var fieldsHTML = fields.map(function(field, index){
if (field.type === "radio") {
return `
<div class="form-group">
<label>${field.label}</label>
${field.options.map(function(option) {
return `
<div class="form-check">
<input class="form-check-input" type="radio" name="radio${index}" value="${option}"/>
<label class="form-check-label">${option}</label>
</div>
`
}).join('')}
</div>
`
} else if (field.type === "text") {
return `
<div class="form-group">
<label>${field.label}</label>
<textarea ></textarea>
</div>
`
}
});
return fieldsHTML.join('');
}
function surveys() {
var surveysAbstraction = [
{
title: "Movie Goer Survey",
fields: [
{
label: "Have you gone to the movies in the last month?",
type: "radio",
options: [
"yes",
"no"
]
},
{
label: "On a scale of 1 to 5, Did you enjoy your last theater experience?",
type: "radio",
options: [
1,
2,
3,
4,
5
]
},
],
submitButtonText: "Submit Survey"
},
{
title: "DigitalCrafts Survey",
fields: [
{
label: "Are you currently enrolled in a DigitalCrafts class?",
type: "radio",
options: [
"yes",
"no"
]
},
{
label: "In 3000 words or more, explain what's so great about Adam?",
type: "text"
}
],
submitButtonText: "I'm Done"
}
]
var content = document.getElementById('content');
content.innerHTML = renderSurveys(surveysAbstraction);
}
|
import React from 'react';
import Delete from './Delete';
import Edit from './Edit';
import EditForm from './EditForm';
class Overview extends React.Component{
constructor(props){
super(props);
this.handleEditClick =this.handleEditClick.bind(this);
this.resetState = this.resetState.bind(this);
this.state = {id: ''};
}
handleEditClick(event){
this.setState({id: event.target.id});
}
resetState(event){
this.setState({id: ''});
event.preventDefault();
}
render(){
return (
<ul>
{
this.props.tasks.map((task,index) => {
const id = index.toString();
if(this.state.id === id){
return (
<li key={id} onSubmit={this.resetState}>
<EditForm task={task} id={id} onEditSubmit={this.props.handlers.onEditSubmit}/>
</li>
)
}else{
return (
<li key={id}>
{id} : {task}
<Edit id={id} onEditClick={this.handleEditClick}/>
<Delete id={id} onDeleteClick={this.props.handlers.remove}/>
</li>
)
}
})
}
</ul>
)
}
}
export default Overview;
|
'use strict'
const path = require('path')
function readPkg (root) {
return require(path.resolve(root, 'package.json'))
}
module.exports = readPkg
|
const RecipesTypes = {
SET_RECIPES: 'recipes:set',
SET_RECIPE: 'recipe:set',
}
export default RecipesTypes
|
import styled from '@emotion/styled';
const Notepad = styled.div`
height: 193px;
width: 136px;
background: linear-gradient(
to bottom,
#f17777 0,
#f17777 34px,
#fff 34px,
#fff 62px,
#cee8ef 62px,
#cee8ef 66px,
#fffefe 66px,
#fff 90px,
#cee8ef 90px,
#cee8ef 94px,
#fff 94px,
#fff 118px,
#cee8ef 118px,
#cee8ef 122px,
#fff 122px,
#fff 146px,
#cee8ef 146px,
#cee8ef 150px,
#fff 150px,
#fff 176px,
#cee8ef 176px,
#cee8ef 193px
);
box-shadow: -10px 0 0 0 rgba(172, 91, 20, 0.2);
overflow: hidden;
transform: rotate(20deg);
@media (orientation: portrait) {
transform: scale(1.2) rotate(20deg);
}
`;
export default Notepad;
|
const app = getApp()
Page({
data: {
type: null,
id:null,
companyName: null,
now: null,
shop_name: null,
begin_date: null,
end_date: null,
recruit_name: null,
content: null,
selectedWorkType: null,
selectedWorkPlace: null,
selectedJobType: null,
selectedMoneyType: null,
workType: [],
workPlace: [],
jobType: [],
},
changeName(e) {
this.setData({
shop_name: e.detail.value
})
},
changeRecruit_name(e) {
this.setData({
recruit_name: e.detail.value
})
},
changeContent(e) {
this.setData({
content: e.detail.value
})
},
switchStartTime: function (e) {
this.setData({
begin_date: e.detail.value
})
},
switchEndTime: function (e) {
this.setData({
end_date: e.detail.value
})
},
switchWorkType: function (e) {
this.setData({
selectedWorkType: this.data.workType[e.detail.value].label
})
},
switchJobType: function (e) {
this.setData({
selectedJobType: this.data.jobType[e.detail.value].label
})
},
delete() {
const _this = this
wx.showModal({
title: '提示',
content: '确定删除?',
success(res) {
if (res.confirm) {
app.fun.post('/user/deleteExperience', {
id: _this.data.id
}).then((res) => {
let pages = getCurrentPages()
let prePage = pages[pages.length - 2]
prePage.onLoad()
wx.showToast({
title: '删除成功',
})
setTimeout(function () {
wx.navigateBack({
delta: 1
})
}, 1500)
})
} else if (res.cancel) {
console.log('用户点击取消')
}
}
})
},
save: function () {
if(this.data.type === 'add') {
app.fun.post('/user/createExperience', {
resume_id: this.data.id,
shop_name: this.data.shop_name,
begin_date: this.data.begin_date,
end_date: this.data.end_date,
recruit_name: this.data.recruit_name,
content: this.data.content
}).then((res) => {
let pages = getCurrentPages()
let prePage = pages[pages.length - 2]
prePage.onLoad()
wx.showToast({
title: '保存成功',
icon: 'success'
})
setTimeout(function () {
wx.navigateBack({
delta: 1
})
}, 1500)
})
} else if (this.data.type === 'edit') {
app.fun.post('/user/updateExperience', {
id: this.data.id,
shop_name: this.data.shop_name,
begin_date: this.data.begin_date,
end_date: this.data.end_date,
recruit_name: this.data.recruit_name,
content: this.data.content
}).then((res) => {
let pages = getCurrentPages()
let prePage = pages[pages.length - 2]
prePage.onLoad()
wx.showToast({
title: res.msg,
icon: 'success',
duration: 1500
})
setTimeout(() => {
wx.navigateBack({
delta: 1
})
}, 1500)
})
}
},
onLoad(e) {
console.log(e)
this.setData({
type: e.type,
id: e.id
})
if (e.type === 'add') {
} else if (e.type === 'edit') {
app.fun.post('/user/experience', {
id: e.id
}).then((res) => {
this.setData({
shop_name: res.result.shop_name,
begin_date: res.result.begin_date,
end_date: res.result.end_date,
recruit_name: res.result.recruit_name,
content: res.result.content
})
})
}
}
})
|
App.HomeBooktabLocationController = Ember.Controller.extend({
filter: {
selectedDay: {
id: '2'
},
selectedLocation: {
id: '1'
}
},
selectedLocationChanged: function() {
// trigger filter here and get items from server
this.transitionToRoute('home.booktab.location.items', this.get('filter.selectedLocation.id'), this.get('filter.selectedDay.id'));
}.observes('filter.selectedLocation.id', 'filter.selectedDay.id')
});
|
module.exports = (item, headerStructure, index) => {
return Object.assign(
{},
headerStructure,
{number: index + 1},
item,
{
date: item.date
.toISOString()
.substr(0, 10)
.replace(/-/g, '‑'), // Replace hyphen-minus with hyphen
description: item.description.trim(),
},
Number.isFinite(item.duration)
? {duration: item.duration}
: {}
)
}
|
import React from "react";
import LoadingDots from "./components/LoadingDots";
// import './App.css';
function App() {
return (
<div className="App">
<div className="display-flex">
<LoadingDots />
</div>
</div>
);
}
export default App;
|
import React from 'react'
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Button from "@material-ui/core/Button";
import Container from "@material-ui/core/Container";
import {makeStyles} from "@material-ui/core/styles";
import Link from "@material-ui/core/Link";
const useStyles = makeStyles(theme => ({
root: {
flexGrow: 1
},
menuButton: {
marginRight: theme.spacing(1),
color: '#fff'
},
title: {
flexGrow: 1
},
appBar: {
backgroundColor: "#680A77",
boxShadow: 'none'
}
}))
export const Header = () =>{
const classes = useStyles();
return (
<AppBar position="fixed" className={classes.appBar}>
<Container fixed>
<Toolbar>
<Typography variant="h6" className={classes.title} >
Mr.Pink
</Typography>
<Button href={'/'} className="menuButton">Войти</Button>
<Button href={'/reg'} className="menuButton">Регистрация</Button>
</Toolbar>
</Container>
</AppBar>
)
}
|
const express = require('express');
const bodyParser = require('body-parser');
const sqlite = require('sqlite3');
let app = express();
app.use(bodyParser.json());
app.use(express.static('public'));
var initDatabase = (conn) => {
conn.run('CREATE TABLE IF NOT EXISTS messages(id INTEGER PRIMARY KEY, subject TEXT NOT NULL, body TEXT NOT NULL, sender TEXT NOT NULL, date TIMESTAMP DEFAULT CURRENT_TIMESTAMP, deleted BOOLEAN default false);');
db.run(`
INSERT OR IGNORE INTO messages(subject, body, sender)
VALUES
('Welcome to lilmessage', 'Welcome to our application, developer!', 'Lilmessage Team'),
('Working OK', 'Seems your app is running fine! Keep it up!', 'Lilmessage Team');
`);
};
//Conecta ao banco de dados
let db = new sqlite.Database('./app.db', sqlite.CREATE_OPEN, (err) => {
if (err) {
return console.error(err.message);
}
initDatabase(db);
console.log('Connected to database');
});
/**
* Valida o objeto mensagem
* @param {Object} messageObj
*/
let validateMessage = (messageObj) => {
if (!messageObj.subject) {
throw new Exception('Message subject is required');
}
if (!messageObj.body) {
throw new Exception('Message body is required');
}
if (!messageObj.sender) {
throw new Exception('Message sender is required');
}
return true;
};
app.get('/', (req, res) => {
res.send('Hello! For how to use our API, visit <a href="/help" title="Help page">our help page</>.');
});
app.get('/messages', (req, res) => {
db.all('SELECT * FROM messages WHERE deleted = "false"', (err, rows) => {
if (err) {
res.status(500);
return;
}
res.send(rows);
});
});
app.get('/messages/:id', (req, res) => {
let id = Number(req.params.id);
db.get('select * from messages where id = ?', [id], (err, row) => {
if (err) {
res.status(500).send();
return;
}
if (!row) {
res.status(404).send('Message not found');
return;
}
res.send(row);
});
});
app.post('/messages', (req, res) => {
let message = req.body;
try {
validateMessage(message);
db.run('INSERT INTO messages (subject, body, sender) VALUES (?, ?, ?)', [message.subject, message.body, message.sender], function (err) {
if (err) {
res.status(500).send('Something went wrong. Please, try later');
return;
}
res.status(201).send('/messages/'+this.lastID);
});
} catch (err) {
res.status(400).send(err);
}
});
app.delete('/messages/:id', (req, res) => {
let id = req.params.id;
db.run(`UPDATE messages SET deleted = 'true' WHERE id= ? AND deleted = 'false'`, [id], function (err) {
if (err) {
res.status(500).send('Something went wrong. Please, try later');
console.error(err);
return;
}
if (!this.changes) {
res.status(404).send('Not found');
return;
}
res.status(204).send();
});
});
app.get('/help', (req, res) => {
res.sendFile(__dirname + '/public/help.html');
});
app.listen(3000);
|
"use strict"
// stuff for browser interact with server
const express = require('express');
const passport = require('passport');
const cookieSession = require('cookie-session');
const GoogleStrategy = require('passport-google-oauth20');
const port = 51296
const googleLoginData = {
clientID: '345177041735-u836nsbrfj3eof6tjaskb6u01q9stak1.apps.googleusercontent.com',
clientSecret: 'Lq4vcbWYQKPooeP-pIDQU4Hj',
callbackURL: '/auth/accepted'
};
passport.use( new GoogleStrategy(googleLoginData, gotProfile) );
// server interact wiht apis
const APIrequest = require('request');
const http = require('http');
const APIkey = "AIzaSyC5jj2sM_3VyipWCB6iTnPv1EtuXsVckVw"; // ADD API KEY HERE
const url = "https://translation.googleapis.com/language/translate/v2?key="+APIkey
const sqlite3 = require("sqlite3").verbose(); // use sqlite
const fs = require("fs"); // file system
const dbFileName = "Flashcards.db";
// makes the object that represents the database in our code
let requestObject =
{
"source": "en",
"target": "es",
"q": [
"example phrase"
]
}
const db = new sqlite3.Database(dbFileName); // object, not database.
// print the database before closing it
process.on('SIGINT', function() {
db.all ( 'SELECT * FROM flashcards', dataCallback);
function dataCallback( err, data ) {
console.log("My datbase");
console.log(data);
db.close();
console.log("database closed");
process.exit(0);
}
});
// initialize table
const flashcard_table = `CREATE TABLE IF NOT EXISTS flashcards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sourceText TEXT,
translateText TEXT,
numShown INT,
numCorrect INT,
userID TEXT
)`;
const user_table = `CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
firstName TEXT,
lastName TEXT)`;
db.run(flashcard_table, tableCreationCallback);
db.run(user_table, tableCreationCallback);
// Always use the callback for database operations and print out any
// error messages you get.
// This database stuff is hard to debug, give yourself a fighting chance.
function tableCreationCallback(err) {
if (err) {
console.log("Table creation error",err);
} else {
console.log("Database loaded");
}
}
function tableInsertionCallback(err) {
if (err) {
console.log("Table insertion error",err);
} else {
console.log("entry inserted");
}
}
function saveDB(req, res, next){
let qobj2 = req.query;
if(req.query.input != undefined){//TODO: double check the condition
let english = req.query.input;
let translate = req.query.output;
const inStr = `INSERT INTO flashcards (
sourceText,
translateText,
numShown,
numCorrect,
userID
) VALUES
(@0, @1, 0, 0, @2)`;
db.run(inStr, english, translate, req.user.google_id, tableInsertionCallback);
res.json({"status":"Good"});
}
else {
next();
}
}
// server and browser
function queryHandler(req, res, next) {
let qObj = req.query;
// callback function, called when data is received from API
function APIcallback(err, APIresHead, APIresBody) {
// gets three objects as input
if ((err) || (APIresHead.statusCode != 200)) {
// API is not working
console.log("Got API error");
console.log(APIresBody);
} else {
if (APIresHead.error) {
// API worked but is not giving you data
console.log(APIresHead.error);
} else {
// print it out as a string, nicely formatted
const english = qObj.english;
const translate = APIresBody.data.translations[0].translatedText;
res.json({
"English":english,
"Spanish": translate
});
}
}
}
if(qObj.english != undefined){
requestObject.q[0] = qObj.english;
// console.log(requestObject);
APIrequest(
{ // HTTP header stuff
url: url,
method: "POST",
headers: {"content-type": "application/json"},
// will turn the given object into JSON
json: requestObject
},
APIcallback);
}
else {
next();
}
}
function fileNotFound(req, res) {
let url = req.url;
res.type('text/plain');
res.status(404);
res.send('Cannot find '+url);
}
// print the url of incoming HTTP request
function printURL (req, res, next) {
console.log(req.url);
next();
}
function checkTable(req, res){
if(req.user){
let sql = 'SELECT * FROM flashcards WHERE userID = ?';
console.log(req.user.google_id);
db.get(sql, [req.user.google_id], (err, rows) => {
if (err) {
throw err;
}
console.log("Check table", rows);
if(rows) {
res.redirect('/user/review.html'); // TODO: FIX ME
} else {
res.redirect('/user/main.html');
}
});
}
}
function updateShown(req, res, next){
if(req.query.id != undefined){
console.log("card id" + req.query.id);
let cardID = req.query.id;
let shown = 0;
const sql1 = 'SELECT * FROM flashcards WHERE id = ?';
db.get(sql1, [cardID], (err, row)=>{
if(err) {
throw err;
}
if(row) {
console.log("this is the row "+ row.numShown);
}
shown = row.numShown + 1;
console.log("shown is " + shown);
let sql = 'UPDATE flashcards SET numShown = ? WHERE id = ?';
db.run(sql, [shown,cardID], (err, rows)=>{
if(err) {
throw err;
}
res.json("success for shown");});
});
} else {
console.log("id is undefined");
}
}
function updateCorrect(req, res, next){
if(req.query.id != undefined){
console.log("card id" + req.query.id);
let cardID = req.query.id;
let correct = 0;
const sql1 = 'SELECT * FROM flashcards WHERE id = ?';
db.get(sql1, [cardID], (err, row)=>{
if(err) {
throw err;
}
if(row) {
console.log("this is the row "+ row.numCorrect);
}
correct = row.numCorrect + 1;
let sql = 'UPDATE flashcards SET numCorrect = ? WHERE id = ?';
db.run(sql, [correct,cardID], (err, rows)=>{
if(err) {
throw err;
}
res.json("success for correct");});
});
} else {
console.log("id is undefined");
}
}
function getCards(req, res){
if(req.user){
let sql = 'SELECT * FROM flashcards WHERE userID = ?';
console.log(req.user.google_id);
db.all(sql, [req.user.google_id], (err, rows) => {
if (err) {
throw err;
}
console.log(rows);
res.json(rows);
});
}
}
function getUser(req, res)
{
if(req.user){
res.json(req.user);
}
}
function isAuthenticated(req, res, next) {
if (req.user) {
// console.log("Req.session:",req.session);
// console.log("Req.user:",req.user);
next();
} else {
res.redirect('/lango.html');
}
}
function loginAuthenticated(req, res, next){
if(req.user) {
console.log("logged in already");
checkTable(req.user.google_id);
res.redirect('/user/check');
} else {
console.log("havne't logged in");
next();
}
}
function gotProfile(accessToken, refreshToken, profile, done) {
// console.log("Google profile",profile);
// console.log("ID",profile.id);
let google_id = profile.id
let firstName = profile.name.familyName;
let lastName = profile.name.givenName;
const sql = 'SELECT * FROM users WHERE id = ?'; // TODO: unable to check properly
db.get(sql, [google_id], (err, rows) => {
if (err) {
throw err;
}
console.log("PROFILE", rows);
if(!rows){
const userInsert = `INSERT INTO users (
id,
firstName,
lastName
) VALUES
(@0, @1, @2)`;
db.run(userInsert, google_id, firstName, lastName, tableInsertionCallback);
console.log("inserting new users");
let dbRowID = google_id;
done(null, dbRowID);
}else{
let dbRowID = google_id;
done(null, dbRowID);
}
});
// here is a good place to check if user is in DB,
// and to store him in DB if not already there.
// Second arg to "done" will be passed into serializeUser,
// should be key to get user out of database.
// temporary! Should be the real unique
// key for db Row for this user in DB table.
// Note: cannot be zero, has to be something that evaluates to
// True.
}
passport.serializeUser((dbRowID, done) => {
// console.log("SerializeUser. Input is",dbRowID);
done(null, dbRowID);
});
passport.deserializeUser((dbRowID, done) => {
const sql = 'SELECT * FROM users WHERE id = ?'; // TODO: unable to check properly
db.get(sql, [dbRowID], (err, row) => {
if (err) {
throw err;
}
if(row){
console.log("inside deserializer",row);
let userData = {
google_id: row.id,
firstName: row.firstName
}
console.log("inside deserializer",userData);
done(null, userData)
}
// done(null, userData);
});
// console.log("deserializeUser. Input is:", dbRowID);
// here is a good place to look up user data in database using
// dbRowID. Put whatever you want into an object. It ends up
// as the property "user" of the "req" object.
});
// put together the server pipeline
const app = express();
app.use('/', printURL);
app.use(cookieSession({
maxAge: 6 * 60 * 60 * 1000, // Six hours in milliseconds
// meaningless random string used by encryption
keys: ['hanger waldo mercy dance']
}));
// Initializes request object for further handling by passport
app.use(passport.initialize());
// If there is a valid cookie, will call deserializeUser()
app.use(passport.session());
// Public static files
app.get('/lango.html', loginAuthenticated);
app.get('/*', express.static('public'));
// handler for url that starts login with Google.
app.get('/auth/google',
passport.authenticate('google',{ scope: ['profile'] }) );
app.get('/auth/accepted',
// This will issue Server's own HTTPS request to Google
// to access the user's profile information with the
// temporary key we got in the request.
passport.authenticate('google'),
// then it will run the "gotProfile" callback function,
// set up the cookie, call serialize, whose "done"
// will come back here to send back the response
// ...with a cookie in it for the Browser!
function (req, res) {
console.log('Logged in and using cookies!');
res.redirect('/user/check');
});
app.get('/user/*', isAuthenticated, // only pass on to following function if
// user is logged in
// serving files that start with /user from here gets them from ./
express.static('.')
);
app.get('/user/check',isAuthenticated, checkTable);
app.get('/translate',isAuthenticated, queryHandler );
app.get('/save', isAuthenticated, saveDB);
app.get('/getUser', isAuthenticated, getUser);
app.get('/getCards', isAuthenticated, getCards);
app.get('/updateShown', isAuthenticated,updateShown);
app.get('/updateCorrect', isAuthenticated,updateCorrect);
app.use( fileNotFound ); // otherwise not found
app.listen(port, function (){console.log('Listening...');} )
|
/* @flow */
/* **********************************************************
* File: test/jestSetup.js
*
* Brief: Sets up the Jest environment. Runs before each test
* suite. Passed as argument to runTest.js
*
* Authors: Craig Cheney
*
* 2017.11.06 CC - Document created
*
********************************************************* */
import 'raf/polyfill';
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
configure({ adapter: new Adapter() });
/* [] - END OF FILE */
|
const lowerCaseDrivers = (drivers) => {
return drivers.map(driver => driver.toLowerCase())
};
const nameToAttributes = (drivers) => {
return drivers.map(driver => {
let first = driver.split(' ')[0]
let last = driver.split(' ')[1]
return {firstName: first, lastName: last}
})
};
const attributesToPhrase = (drivers) => {
return drivers.map(driver => {
return `${driver.name} is from ${driver.hometown}`
})
};
|
module.exports = {
'The story show page contains the story title': browser => {
browser.page.storyShowPage().navigate()
browser.expect.element('#app').to.be.visible.after(5000)
browser
.expect.element('h2')
.to.be.visible.after(2000)
.and.to.have.text.that.equals('Monochrome example story');
browser.end()
}
}
|
module.exports = (bh) => {
bh.match('map__container', (ctx) => {
ctx.attr('id', 'map');
});
};
|
const discord = require('discord.js');
module.exports.run = async(client, message, args) => {
const muteUser = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
const muteRole = message.guild.roles.cache.find(r => r.name === 'muted');
if(message.mentions.users.size < 1) return message.reply("You must provide a user to mute!");
muteUser.roles.remove(muteRole);
const b = new discord.MessageEmbed()
.setAuthor(`${muteUser.user.tag}`)
.addFields({
name: `Unmuted member`,
value: `${muteUser.user.tag}`,
inline: true
}, {
name: "Unmuted by:",
value: `${message.author.tag}`,
inline: true
},)
.setThumbnail(muteUser.user.displayAvatarURL())
.setColor("#008b8b");
message.channel.send(b);
}
exports.help = {
name: "unmute",
aliases: [],
description: "unmutes a member"
}
exports.requirements = {
clientPerms: [],
userPerms: ["MANAGE_ROLES", "MUTE_MEMBERS"],
ownerOnly: false
}
|
export default () => {
const speed = 1000
$('a[href^="#"]').on('click', function() {
const target = $(this.hash)
if (!target.length) return
const targetY = target.offset().top
$('html,body').animate({ scrollTop: targetY }, speed, 'easeOutExpo')
return false
})
}
|
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
require('dotenv').config({
path: '.env'
});
const cors = require('cors')
const helmet = require('helmet')
const router = require('./network/routes')
const app = express();
mongoose.Promise = global.Promise;
mongoose.connect(process.env.URLDB, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
.then(() => console.log('[db] Conectada con éxito'))
.catch(err => console.error('[db]', err));
router(app);
app.use(cors({
origin: true,
credentials: true
}))
app.use(helmet())
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
module.exports = app;
|
const youtubeDecoder = (function(){
const ytDomain = '.youtube.com';
const mainDescSelector = '#description.ytd-video-secondary-info-renderer';
const commentSectionSelector =
'ytd-comments#comments, ytm-comment-section-renderer';
const commentSelector = 'ytd-comment-renderer, ytm-comment-renderer';
const resultsSelector = 'ytd-search #contents.ytd-item-section-renderer';
const resultsItemSelector = 'ytd-video-renderer';
const descSelector = 'yt-formatted-string#description-text';
const mobileDescParentSelector = 'ytm-slim-video-metadata-renderer';
const emojiClassNames = emojiReplacer.classNames;
let pageManagerFound = false;
let watchedCommentsNode;
const debouncedTranslatePage = debounce(translatePage, 200);
return {
watchPageChanges,
isYoutube
}
function isYoutube() {
return document.domain.endsWith(ytDomain);
}
function runTranslation(root) {
domManipulator.start(root);
}
function clean() {
// Due to Youtube’s dynamic data binding,
// new values get added alongside modified textContent.
// Delete container nodes to prevent old text from persisting.
// remove main video description
const vidDescNode = document.querySelector(
`${mainDescSelector} > ${descSelector}`
);
if (vidDescNode) {
vidDescNode.parentNode.removeChild(vidDescNode);
}
// clear all comments on video pages
const commentsRoot = document.querySelector(commentSectionSelector);
if (commentsRoot) {
const commentsParent = commentsRoot.querySelector('#contents');
if (commentsParent) {
while (commentsParent.firstChild) {
commentsParent.removeChild(commentsParent.firstChild);
}
}
}
// clear search results
const resultNodes = document.querySelectorAll(
`${resultsSelector} > ${resultsItemSelector}`
);
for (const node of resultNodes) {
node.parentNode.removeChild(node);
}
}
function watchPageChanges() {
if (isYoutube()) {
debouncedTranslatePage();
window.addEventListener("yt-navigate-start", clean);
document.body.addEventListener(
"yt-page-data-updated", debouncedTranslatePage
);
document.body.addEventListener(
"yt-navigate-finish", debouncedTranslatePage
);
// mobile
document.documentElement.addEventListener(
"video-data-change", debouncedTranslatePage
);
}
}
function translatePage() {
if (document.querySelector(
'ytd-watch-flexy:not([hidden]), ytm-watch'
)) {
translateVideo();
} else if (document.querySelector('ytd-search:not([hidden])')) {
translateSearch();
}
}
function translateVideo() {
runTranslation(document.querySelector(mainDescSelector));
const commentsNode = document.querySelector(commentSectionSelector);
runTranslation(commentsNode);
watchComments(commentsNode);
// on mobile, descriptions dynamically loaded after opening accordion
watchDescMobile();
}
function translateSearch() {
const descriptionNodes = document.querySelectorAll(descSelector);
for (const node of descriptionNodes) {
runTranslation(node);
}
waitForSearch();
}
function watchComments(commentsNode) {
if (watchedCommentsNode !== commentsNode) {
new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.matches && node.matches(commentSelector)) {
runTranslation(node);
}
}
}
}
}).observe(
commentsNode,
{ childList: true, subtree:true }
);
watchedCommentsNode = commentsNode;
}
}
function watchSearchResults(searchNode) {
new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.matches(resultsItemSelector)) {
runTranslation(
node.querySelector(descSelector)
);
}
}
}
}
}).observe(
searchNode.querySelector(resultsSelector),
{ childList: true }
);
}
function waitForSearch() {
if (pageManagerFound) return;
const pageManagerNode = document.getElementById('page-manager');
if (pageManagerNode) {
pageManagerFound = true;
const searchNode = pageManagerNode.querySelector('ytd-search');
if (searchNode) {
watchSearchResults(searchNode);
} else {
// wait for search results to be added
new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.matches('ytd-search')) {
observer.disconnect();
watchSearchResults(node);
}
}
}
}
}).observe(
pageManagerNode,
{ childList: true }
);
}
}
}
function watchDescMobile() {
const descContainer = document.querySelector(mobileDescParentSelector);
if (descContainer) {
new MutationObserver((mutationsList, observer) => {
for (const mutation of mutationsList) {
if (mutation.addedNodes.length > 0) {
for (const node of mutation.addedNodes) {
if (node.matches('.user-text')) {
runTranslation(node);
}
}
}
}
}).observe(
descContainer,
{ childList: true }
);
}
}
// https://davidwalsh.name/javascript-debounce-function
// Returns a function, that, as long as it continues to be invoked,
// will not be triggered. The function will be called after it stops
// being called for [wait] milliseconds. If immediate is passed,
// trigger the function on the leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
}());
|
// Design Basic Game Solo Challenge
// This is a solo challenge
// Your mission description:
// Overall mission: Miner Tom has to dig out 3 pieces of good diamond
// Goals: to collect 3 pieces of good diamond
// Characters: Miner Tom
// Objects: Miner, diamond
// Functions: Explore(), a function to explore diamonds; Count(), a function to count the pieces of good diamond that the miner has.
// Pseudocode
// create an object called "diamond_mine", it has a name property and a capacity property (number of times that miner Tom can explore)
// create an object called "miner", with a name property, good_diamond property and poor_diamond property.
// create a function called "explore". Using a random number between 0 and 1, randomly generate a diamond with a quality of either "good" or "poor". And then put this diamond into the cooresponding diamond property of miner Tom. After exploring, decrease the capacity of the diamond mine by 1.
// create a function called "count". This function determines if Tom has at least 3 good diamonds or not.
//
// Initial Code
// var diamond_mine ={
// name: "diamond hill",
// capacity: 10
// };
// var miner ={
// name: "Tom",
// good_diamond:0,
// poor_diamond:0
// };
// function explore(){
// if (diamond_mine.capacity > 0) {
// var random_num = Math.random();
// if (random_num < 0.5)
// miner.poor_diamond ++;
// else
// miner.good_diamond ++;
// diamond_mine.capacity --;
// }
// else
// console.log("The mine has been fully exploited!");
// }
// function count(){
// console.log("Remaining capacity of the mine: " + diamond_mine.capacity);
// console.log("You have " + miner.good_diamond + " good diamonds and "+ miner.poor_diamond + " poor diamonds,");
// if (miner.good_diamond >=3)
// console.log("Good you already have more than 3 good diamonds, go and sell them!");
// else
// console.log("Please work harder to get at least 3 good diamond!");
// }
// explore();
// explore();
// explore();
// explore();
// explore();
// explore();
// explore();
// explore();
// explore();
// count();
// console.log(diamond_mine);
// console.log(miner);
// Refactored Code
var diamond_mine ={
name: "diamond hill",
capacity: 10
};
var miner ={
name: "Tom",
good_diamond:0,
poor_diamond:0
};
function explore(){
if (diamond_mine.capacity > 0) {
var random_num = Math.random();
if (random_num < 0.5)
miner.poor_diamond ++;
else
miner.good_diamond ++;
diamond_mine.capacity --;
}
else
console.log("The mine has been fully exploited!");
}
function count(){
console.log("Remaining capacity of the mine: " + diamond_mine.capacity);
console.log("You have " + miner.good_diamond + " good diamonds and "+ miner.poor_diamond + " poor diamonds,");
if (miner.good_diamond >=3)
console.log("Good you already have more than 3 good diamonds, go and sell them!");
else
console.log("Please work harder to get at least 3 good diamond!");
}
explore();
explore();
explore();
explore();
explore();
explore();
explore();
explore();
explore();
count();
console.log(diamond_mine);
console.log(miner);
// Reflection
/*
What was the most difficult part of this challenge?
Ans: The most difficult part is to come up with a framework of how do I want to run the game.
What did you learn about creating objects and functions that interact with one another?
Ans: Creating objects and functions that interact with one another is similar to accessing instance variables of different objects in Ruby. I feel like in JS we can create/remove/modify any properties of any objects more freely and easily. It is more intuitive.
Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?
Ans: I used the built-in method - Math.random(). It generates a random number between 0(inclusive) and 1(exclusive).
How can you access and manipulate properties of objects?
Ans: I can simply access and manipulate the properties of objects by placing the property name after a dot after the object e.g.
miner.good_diamond = 0;
*/
|
import React from 'react';
import CollocationSuccessImg from '@/icons/Collocation/collocate_success.svg';
import Link from 'next/link';
import ContentLessTopBar from '@/components/TopBar/content_less_header';
import Button from '@/components/Button';
import withAuth from '@/core/utils/protectedRoute';
const CollocationSuccess = () => {
return (
<>
<ContentLessTopBar />
<div className='flex justify-center items-center mx-6'>
<div className='flex justify-center items-center flex-col py-28'>
<CollocationSuccessImg />
<div className='flex flex-col justify-center text-center mt-10'>
<h4 className='text-[32px] font-medium mb-3 text-black-600'>Great Job!</h4>
<div>
<p className='text-grey-300 text-xl max-w-md mb-8'>
You’ve successfully scheduled your first device for collocation
</p>
<Button
path='/analytics/collocation/collocate'
className='text-blue-900 text-xl cursor-pointer'
dataTestId='collocation-view-device-status-button'
>
View device status, here {'-->'}
</Button>
</div>
</div>
</div>
</div>
</>
);
};
export default CollocationSuccess;
|
var numero = prompt(parseFloat("informe um numero menor ue 10: "))
if(isNaN(numero)){
alert("O valor digitado não é um numero")
}else{
while(numero <= 10){
console.log("while:"+numero)
numero++
}
do {
console.log("do:"+numero)
numero++
} while(numero <= 10)
for(var i = 0; i <= 10; i++){
console.log("for:"+i)
}
for (item in document) {
console.log(item);
}
}
|
import React, { Component } from "react";
import Comment from "./Comment";
import "./Comments.css";
import Comments from "./Comments";
import { getComments, postComment } from "../../services/movieService";
import { getCurrentUser } from "../../services/authService";
class index extends Component {
constructor(props) {
super(props);
this.state = {
comment: "",
comments: [],
movieId: this.props.movieId
};
}
async populateComments() {
const { data: results } = await getComments(this.state.movieId);
const comments = results.reverse();
this.setState({ comments });
}
async componentDidMount() {
await this.populateComments();
}
handleSubmit = async e => {
e.preventDefault();
try {
const { movieId, comment } = this.state;
const { user } = await getCurrentUser();
console.log(user.username);
const posted = await postComment(movieId, comment, user.username);
console.log(posted);
const refreshComment = "";
this.setState({ comment: refreshComment });
await this.populateComments();
} catch (ex) {
if (ex.response && ex.response.status === 400) {
console.log(ex.response.data);
}
}
};
handleChange = ({ currentTarget: input }) => {
let comment = this.state.comment;
comment = input.value;
console.log(comment);
this.setState({ comment });
};
render() {
const { comment, comments } = this.state;
return (
<div className='container mx-auto mt-4 comments'>
<Comment
comment={comment}
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
/>
<Comments comments={comments} />
</div>
);
}
}
export default index;
|
const topics = ["Angry", "Disgusted", "Fearful", "Happy", "Sad", "Surprised"];
for (let i = 0; i < topics.length; i++) {
$("#buttonArea").append("<button type='button' class='btn btn-light gif-button' data-search='" + topics[i] + "'>" + topics[i] + "</button>")
let queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topics[i] + "&api_key=faY502M74RA3tid3YkAoqH7IWgz6NgoM&limit=10";
}
//adds user input to a button and adds this button to the other buttons
$("#add-emotion").on("click", function (event) {
event.preventDefault();
let x = $("#user-input").val().trim();
let newBtn = $("<button>");
newBtn.addClass("gif-button btn btn-light")
newBtn.text(x);
newBtn.attr("data-search="+x);
$("#buttonArea").append(newBtn);
$("#user-input").val("");
console.log(newBtn);
});
//GIF conditions when clicked
$(".gif-button").on("click", function () {
let x = $(this).data("search");
let queryURL = "https://api.giphy.com/v1/gifs/search?q=" + x + "&api_key=faY502M74RA3tid3YkAoqH7IWgz6NgoM&limit=10";
//create a still gif
$.ajax({
url: queryURL,
method: "GET"
}).done(function (response) {
for (let i = 0; i < response.data.length; i++) {
let state = $(this).attr("data-state");
$("#GIFArea").prepend("<div class='col-sm'><img src='" + response.data[i].images.fixed_width_still.url + "' data-still='" + response.data[i].images.fixed_width_still.url + "' data-animate='" + response.data[i].images.fixed_width.url + "' data-state='still' class='gif'><p>Rating: " + response.data[i].rating + "</p>");
}
//moving from still to animated
$(".gif").on("click", function () {
let state = $(this).attr("data-state");
if (state === "still") {
$(this).attr("src", $(this).attr("data-animate"));
$(this).attr("data-state", "animate");
} else {
$(this).attr("src", $(this).attr("data-still"));
$(this).attr("data-state", "still");
}
});
});
});
//additional button attempt for user-button to pull up gif
// $("#add-emotion").on("click", function (event) {
// event.preventDefault();
// let x = $("#user-input").val().trim();
// //console.log(newBtn)
// topics.push(x);
// // console.log(topics);
// $("#buttonArea").append("<button type='button' class='btn btn-light gif-button' data-search='" + x + "'>" + x + "</button>");
// });
|
let userNumber = prompt("Type your number");
function getTheNumber(a) {
console.log(a);
}
getTheNumber(userNumber);
|
export default (name) => console.log(`Hello there, ${name}!`);
const createCard = (Title,Poster,Plot,Ratings,Rated,id,Production,Runtime,Released,Genre,Director) => {
let tempCard = "";
tempCard += `<div class="MovieCard">`;
tempCard += `<div class="titlebox"><h2 class="MovieTitle">${Title}</h2><img alt="favorite" class="star" src="./img/001-star-1.png"><img alt="trashbin" class="trash" id="${id}" src="./img/002-basket.png"></div>`;
tempCard += `<ul class="MovieInfo">`;
tempCard += `<li class="listItem"><span class="infoTitle">Plot</span>${Plot}</li>`;
tempCard += `<li class="listItem"><span class="infoTitle">IMDB Rating</span>${Ratings}</li>`;
tempCard += `<li class="listItem"><span class="infoTitle">Rated</span>${Rated}</li>`;
tempCard += `<li class="listItem"><span class="infoTitle">Producer</span>${Production}</li>`;
tempCard += `<li class="listItem"><span class="infoTitle">Runtime</span>${Runtime}</li>`;
tempCard += `<li class="listItem"><span class="infoTitle">Released</span>${Released}</li>`;
tempCard += `<li class="listItem"><span class="infoTitle">Genres</span>${Genre}</li>`;
tempCard += `<li class="listItem"><span class="infoTitle">Director</span>${Director}</li>`;
tempCard += `</ul>`;
tempCard += `<img class="titleCover" alt="${Title} Cover Image" src="${Poster}">`;
tempCard += `</div>`;
return tempCard
};
const cleardiv = () => {
return "";
};
const deletemovie = () =>{
console.log($(this).attr("id").val);
fetch('/api/movies',$(this).attr("id").val)
};
module.exports = {createCard,cleardiv,deletemovie};
|
let divide = () => {
return 2000 / 100
}
const square = (number) => {
return number * number
}
const add = (num1, num2) => {
return num1 + num2
}
|
/*When the user accepts the ToS, they should be taken to the Home Screen*/
function accept(){
window.location.href = "homeScreen.html";
}
/*When the user declines the ToS, the app should close*/
function decline(){
navigator.app.exitApp();
}
|
$(document).ready(function(){
$('.side-li').each(function(index){
$(this).click(function(){
$('.side-li').children().removeClass('li-active');
$('.side-li').eq(index).children().addClass('li-active');
});
});
$('.container-title a:first-child').click(function(){
$('.side-bar').toggle('fast');
$('.container').toggleClass('all-width');
});
$('.side-li:first').children().addClass('li-active');
});
angular.module('homeApp', ['ngFileUpload']).controller('homeCtrl', function($scope, $http){
$scope.mode = 'person.html';
$scope.chgPage = function(index){
if(index == 0){
$scope.mode = 'person.html';
}else if(index == 1){
$scope.mode = 'data-show.html';
}else if(index == 2){
$scope.mode = 'data-list.html';
}
};
$scope.toLogOut = function() {
$http.post('/logout', {
}).then(function(req){
console.log('log out');
}, function(error){
console.log('error');
});
};
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.