text stringlengths 7 3.69M |
|---|
"use strict";
//var requirejs = require('requirejs');
//
//requirejs.define('', ['./hello'], function(myModule) {
// console.log(myModule);
//});
//'use strict';
{
console.log(a);
var a = 1;
}
|
import React from "react";
import { render, screen } from "@testing-library/react";
import Planets from "./Planets";
describe("Planets components", () => {
test("Checks if planet data is requested and loads into select tags", () => {
render(<Planets />);
const listBoxElements = screen.getAllByRole("combobox");
expect(listBoxElements).not.toHaveLength(0);
});
});
|
#!/usr/bin/env node
'use strict';
const moduleName = 'server';
const root = require('shrew')();
const xServer = require('../server.js')(root, root);
const xLog = require('xcraft-core-log')(moduleName, null);
xServer.start(err => {
if (err) {
xLog.err(err);
}
});
|
import { ConfigProvider } from 'antd';
import AppLocale from 'lngProvider';
import React, { Component } from 'react';
import { IntlProvider } from 'react-intl';
import { connect, useSelector } from 'react-redux';
import { Redirect, Route, Switch } from 'react-router-dom';
import {
changeLayoutType,
changeNavStyle,
setThemeType
} from '../../redux/features/settings/themeSettingsSlice';
import {
LAYOUT_TYPE_BOXED,
LAYOUT_TYPE_FRAMED,
LAYOUT_TYPE_FULL,
NAV_STYLE_ABOVE_HEADER,
NAV_STYLE_BELOW_HEADER,
NAV_STYLE_DARK_HORIZONTAL,
NAV_STYLE_DEFAULT_HORIZONTAL,
NAV_STYLE_INSIDE_HEADER_HORIZONTAL,
THEME_TYPE_DARK
} from '../../constants/ThemeSetting';
import SignIn from '../SignIn';
// import SignUp from '../SignUp';
import MainApp from './MainApp';
const RestrictedRoute = ({ component: Component, ...rest }) => {
const token = useSelector(({ session }) => session.token);
return (
<Route
{...rest}
render={props =>
token ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: '/sign-in',
state: { from: props.location }
}}
/>
)
}
/>
);
};
class App extends Component {
setLayoutType = layoutType => {
if (layoutType === LAYOUT_TYPE_FULL) {
document.body.classList.remove('boxed-layout');
document.body.classList.remove('framed-layout');
document.body.classList.add('full-layout');
} else if (layoutType === LAYOUT_TYPE_BOXED) {
document.body.classList.remove('full-layout');
document.body.classList.remove('framed-layout');
document.body.classList.add('boxed-layout');
} else if (layoutType === LAYOUT_TYPE_FRAMED) {
document.body.classList.remove('boxed-layout');
document.body.classList.remove('full-layout');
document.body.classList.add('framed-layout');
}
};
setNavStyle = navStyle => {
if (
navStyle === NAV_STYLE_DEFAULT_HORIZONTAL ||
navStyle === NAV_STYLE_DARK_HORIZONTAL ||
navStyle === NAV_STYLE_INSIDE_HEADER_HORIZONTAL ||
navStyle === NAV_STYLE_ABOVE_HEADER ||
navStyle === NAV_STYLE_BELOW_HEADER
) {
document.body.classList.add('full-scroll');
document.body.classList.add('horizontal-layout');
} else {
document.body.classList.remove('full-scroll');
document.body.classList.remove('horizontal-layout');
}
};
// componentDidMount() {
// const { history, token, location } = this.props;
// if (location.pathname === '/') {
// if (token === null) {
// history.push('/sign-in');
// }
// }
// }
render() {
const { match, themeType, layoutType, navStyle, locale } = this.props;
if (themeType === THEME_TYPE_DARK) {
document.body.classList.add('dark-theme');
}
this.setLayoutType(layoutType);
this.setNavStyle(navStyle);
const currentAppLocale = AppLocale[locale.locale];
return (
<ConfigProvider locale={currentAppLocale.antd}>
<IntlProvider
locale={currentAppLocale.locale}
messages={currentAppLocale.messages}
>
<Switch>
<Route exact path="/sign-in" component={SignIn} />
{/*<Route exact path="/sign-up" component={SignUp} />*/}
<RestrictedRoute path={`${match.url}`} component={MainApp} />
</Switch>
</IntlProvider>
</ConfigProvider>
);
}
}
const mapStateToProps = ({ themeSettings, session }) => {
const { locale, navStyle, themeType, layoutType } = themeSettings;
const { token } = session;
return { locale, token, navStyle, themeType, layoutType };
};
const actions = {
setThemeType,
changeNavStyle,
changeLayoutType
};
export default connect(
mapStateToProps,
actions
)(App);
|
/** When your routing table is too long, you can split it into small modules */
import Layout from '@/views/layout/TheLayout.vue';
const componentsRouter = [
{
path: '/components',
component: Layout,
redirect: '/components/tinymce',
name: 'ComponentDemo',
meta: {
title: 'route.components',
icon: 'mdi-view-module'
},
children: [
{
path: 'tinymce',
component: () => import('@/demo/views/Components/tinymce'),
name: 'TinymceDemo',
meta: { title: 'route.component.tinymce' }
},
{
path: 'markdown',
component: () => import('@/demo/views/Components/markdown'),
name: 'MarkdownDemo',
meta: { title: 'route.component.markdown' }
},
{
path: 'json-editor',
component: () => import('@/demo/views/Components/jsonEditor'),
name: 'JsonEditorDemo',
meta: { title: 'route.component.jsonEditor' }
},
{
path: 'splitpane',
component: () => import('@/demo/views/Components/splitpane'),
name: 'SplitpaneDemo',
meta: { title: 'route.component.splitPane' }
},
{
path: 'dropzone',
component: () => import('@/demo/views/Components/dropzone'),
name: 'DropzoneDemo',
meta: { title: 'route.component.dropzone' }
},
{
path: 'sticky',
component: () => import('@/demo/views/Components/sticky'),
name: 'StickyDemo',
meta: { title: 'route.component.sticky' }
},
{
path: 'count-to',
component: () => import('@/demo/views/Components/countTo'),
name: 'CountToDemo',
meta: { title: 'route.component.countTo' }
},
{
path: 'back-to-top',
component: () => import('@/demo/views/Components/backToTop'),
name: 'BackToTopDemo',
meta: { title: 'route.component.backToTop' }
},
{
path: 'drag-kanban',
component: () => import('@/demo/views/Components/dragKanban'),
name: 'DragKanbanDemo',
meta: { title: 'route.component.dragKanban' }
}
]
},
{
path: '/charts',
component: Layout,
redirect: '/charts/keyboard',
name: 'Charts',
meta: {
title: 'route.charts',
icon: 'mdi-chart-bar'
},
children: [
{
path: 'keyboard',
component: () => import('@/demo/views/Components/chart.vue'),
name: 'KeyboardChart',
meta: { title: 'route.chart.keyboardChart', noCache: true },
props: { keyboard: true }
},
{
path: 'line',
component: () => import('@/demo/views/Components/chart.vue'),
name: 'LineChart',
meta: { title: 'route.chart.lineChart', noCache: true },
props: { line: true }
},
{
path: 'mix-chart',
component: () => import('@/demo/views/Components/chart.vue'),
name: 'MixChart',
meta: { title: 'route.chart.mixChart', noCache: true },
props: { mix: true }
}
]
}
/*
{
path: '/excel',
component: Layout,
redirect: '/excel/export-excel',
name: 'Excel',
meta: {
title: 'excel',
icon: 'excel'
},
children: [
{
path: 'export-excel',
component: () => import('@/demo/views/excel/export-excel'),
name: 'ExportExcel',
meta: { title: 'exportExcel' }
},
{
path: 'export-selected-excel',
component: () => import('@/demo/views/excel/select-excel'),
name: 'SelectExcel',
meta: { title: 'selectExcel' }
},
{
path: 'export-merge-header',
component: () => import('@/demo/views/excel/merge-header'),
name: 'MergeHeader',
meta: { title: 'mergeHeader' }
},
{
path: 'upload-excel',
component: () => import('@/demo/views/excel/upload-excel'),
name: 'UploadExcel',
meta: { title: 'uploadExcel' }
}
]
}, */
/*
{
path: '/zip',
component: Layout,
redirect: '/zip/download',
alwaysShow: true,
name: 'Zip',
meta: { title: 'zip', icon: 'zip' },
children: [
{
path: 'download',
component: () => import('@/demo/views/zip/index'),
name: 'ExportZip',
meta: { title: 'exportZip' }
}
]
}, */
/*
{
path: '/pdf',
component: Layout,
redirect: '/pdf/index',
children: [
{
path: 'index',
component: () => import('@/demo/views/pdf/index'),
name: 'PDF',
meta: { title: 'pdf', icon: 'pdf' }
}
]
},
{
path: '/pdf/download',
component: () => import('@/demo/views/pdf/download'),
hidden: true
}, */
/* {
path: '/clipboard',
component: Layout,
children: [
{
path: 'index',
component: () => import('@/demo/views/Components/clipboard.vue'),
name: 'ClipboardDemo',
meta: { title: 'route.clipboard', icon: 'clipboard' }
}
]
}, */
/* {
path: 'external-link',
component: Layout,
children: [
{
path: 'https://github.com/NelsonEAX/vue-vuetify-admin',
meta: { title: 'route.externalLink', icon: 'link' }
}
]
} */
];
export default componentsRouter;
|
import game from './game';
describe('bowling game', () => {
let myGame;
describe('game', () => {
beforeEach(() => {
myGame = game();
});
it('should have roll and score method', () => {
expect(typeof myGame.roll).toBe('function');
expect(typeof myGame.score).toBe('function');
expect(typeof myGame.frame).toBe('function');
});
it('starts with frame 1', () => {
expect(myGame.frame().current).toBe(1);
});
it('should step on frame 2', () => {
myGame.roll(0);
myGame.roll(0);
expect(myGame.frame().current).toBe(2);
});
it('should finish after ten frames when no strike and spare', () => {
myGame.roll(0); myGame.roll(1);
myGame.roll(2); myGame.roll(3);
myGame.roll(4); myGame.roll(5);
myGame.roll(0); myGame.roll(1);
myGame.roll(2); myGame.roll(3);
myGame.roll(4); myGame.roll(5);
myGame.roll(0); myGame.roll(1);
myGame.roll(2); myGame.roll(3);
myGame.roll(4); myGame.roll(5);
myGame.roll(0); myGame.roll(1);
expect(myGame.frame().current).toBe(11);
expect(myGame.score()).toBe(46);
});
it('should step on frame 2 when strike', () => {
myGame.roll(10);
expect(myGame.frame().current).toBe(2);
});
it('should step on frame 2 when spare', () => {
myGame.roll(4);
myGame.roll(6);
expect(myGame.frame().current).toBe(2);
});
it('should add next 2 roll to striked frame', () => {
myGame.roll(10);
myGame.roll(4); myGame.roll(5);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
expect(myGame.score()).toBe(28);
});
it('should add next roll to spared frame', () => {
myGame.roll(6); myGame.roll(4);
myGame.roll(4); myGame.roll(5);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
expect(myGame.score()).toBe(23);
});
it('should count 2 more rolls if 10th frame is striked', () => {
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(10);
myGame.roll(5); myGame.roll(4);
expect(myGame.score()).toBe(19);
});
it('should count one more roll if 10th frame is spared', () => {
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(0); myGame.roll(0);
myGame.roll(6); myGame.roll(4);
myGame.roll(5);
expect(myGame.score()).toBe(15);
});
it('should count 300 as max game', () => {
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
myGame.roll(10);
expect(myGame.score()).toBe(300);
});
it('should be ok for a sample game', () => {
myGame.roll(1);
myGame.roll(4);
myGame.roll(4);
myGame.roll(5);
myGame.roll(6);
myGame.roll(4);
myGame.roll(5);
myGame.roll(5);
myGame.roll(10);
myGame.roll(0);
myGame.roll(1);
myGame.roll(7);
myGame.roll(3);
myGame.roll(6);
myGame.roll(4);
myGame.roll(10);
myGame.roll(2);
myGame.roll(8);
myGame.roll(6);
expect(myGame.score()).toBe(133);
});
it('should test heart break', () => {
for (let i = 0; i < 11; i++) {
myGame.roll(10);
}
myGame.roll(9);
expect(myGame.score()).toBe(299);
});
it('should be ok for 10th frame spare', () => {
for (let i = 0; i < 9; i++) {
myGame.roll(10);
}
myGame.roll(9);
myGame.roll(1);
myGame.roll(1);
expect(myGame.score()).toBe(270);
});
});
}); |
import Taro, { Component } from '@tarojs/taro'
import { View, Text, ScrollView } from '@tarojs/components'
import './shop.scss'
export default class Shop extends Component {
config = {
navigationBarTitleText: '商品'
}
render () {
return (
<View className='index'>
<ScrollView scrollX scrollY className='scroll'>
<View className='row-item row-item1' />
<View className='row-item row-item2' />
<View className='row-item row-item3' />
</ScrollView>
<View>
<Text>滑动组件</Text>
</View>
</View>
)
}
}
|
var apiUrl = 'http://huobi.xia666.top/api';
function __args() {
// console.log(uni);
// console.log(uni.globalData);
var setting = {};
if (arguments.length === 1 && typeof arguments[0] !== 'string') {
setting = arguments[0];
} else {
setting.url = arguments[0];
if (typeof arguments[1] === 'object') {
setting.data = arguments[1];
setting.success = arguments[2];
setting.fail = arguments[3];
} else {
setting.success = arguments[1];
setting.fail = arguments[2];
}
}
if (setting.url.indexOf('http://') !== 0) {
setting.url = apiUrl + setting.url;
}
if (typeof(setting.data) == "undefined") {
setting.data = {};
};
//PDO 每次请求都带上token
setting.complete = function(res) {
if (res.errMsg.indexOf('timeout') != -1) {
return false;
}
if (res.errMsg.indexOf('request:fail') != -1) {
uni.showModal({
title: '提示',
content: '请求失败,请检查您的网络后重试',
showCancel: false,
});
return false;
}
let status = res.data.status;
if (status != 1) {
uni.hideLoading();
uni.showModal({
title: '提示',
content: res.data.msg,
showCancel: false,
success: function(res) {
if (status == -100 || status == -101 || status == -102 || status == -103) {
uni.clearStorage();
uni.reLaunch({
url: '/pages/login/login'
});
}
}
});
return;
}
}
return setting;
}
function __json(method, setting) {
setting.method = method;
if (method == 'GET') {
setting.header = {
'content-type': 'application/json'
};
} else {
setting.header = {
'content-type': 'application/x-www-form-urlencoded'
// 'content-type': 'multipart/form-data'
};
}
// console.log(setting);
uni.request(setting);
}
function dateFormat(ns) {
// 声明变量。
var d, s;
// 创建 Date 对象。
d = new Date(parseInt(ns) * 1000);
s = d.getFullYear() + "-";
s += ("0" + (d.getMonth() + 1)).slice(-2) + "-";
s += ("0" + d.getDate()).slice(-2) + " ";
s += ("0" + d.getHours()).slice(-2) + ":";
s += ("0" + d.getMinutes()).slice(-2) + ":";
s += ("0" + d.getSeconds()).slice(-2);
return s;
}
function dateFormat2(ns) {
// 声明变量。
var d, s;
// 创建 Date 对象。
d = new Date(parseInt(ns) * 1000);
s = d.getFullYear() + "-";
s += ("0" + (d.getMonth() + 1)).slice(-2) + "-";
s += ("0" + d.getDate()).slice(-2) + "";
return s;
}
/**
* 检查权限 返回true为通过
*/
function checkPriv(arr, key) {
console.log('checkPrive arr', arr);
if (arr === true) return true;
if (arr === false) return false;
var low = 0,
high = arr.length - 1;
while (low <= high) {
var mid = parseInt((high + low) / 2);
if (key == arr[mid]) {
return true;
} else if (key > arr[mid]) {
low = mid + 1;
} else if (key < arr[mid]) {
high = mid - 1;
} else {
return false;
}
}
return false;
};
module.exports = {
// ...mapMutations(['ceshi']),
getJSON: function() {
__json('GET', __args.apply(this, arguments));
},
postJSON: function() {
__json('POST', __args.apply(this, arguments));
},
sendTemplate: function(formId, templateData, success, fail) {
var app = getApp();
this.getJSON({
url: '/WxAppApi/sendTemplate',
data: {
rd_session: app.rd_session,
form_id: formId,
data: templateData,
},
success: success, // errorcode==0时发送成功
fail: fail
});
},
apiUrl: apiUrl,
dateFormat: dateFormat,
dateFormat2: dateFormat2,
checkPriv: checkPriv
}
|
var searchData=
[
['dessin',['dessin',['../class_forme2_d.html#a08e1387f770d371278bd2fe03695ec38',1,'Forme2D']]],
['dessiner',['Dessiner',['../class_dessiner.html',1,'']]],
['dessiner_2eh',['Dessiner.h',['../_dessiner_8h.html',1,'']]],
['dessinj',['DessinJ',['../class_dessin_j.html',1,'DessinJ'],['../class_dessin_j.html#ae6c25dd2943e9173f175688d25ccba92',1,'DessinJ::DessinJ()']]],
['dessinj_2eh',['DessinJ.h',['../_dessin_j_8h.html',1,'']]]
];
|
module.exports = (sequelize, Sequelize) => {
const FAQ = sequelize.define('faq', {
title: {
type: Sequelize.STRING,
},
category: {
type: Sequelize.STRING,
}, category: {
type: Sequelize.STRING,
},
question: {
type: Sequelize.STRING,
},
description: {
type: Sequelize.INTEGER,
defaultValue: 1
},
}, {
freezeTableName: true
});
return FAQ;
} |
const exp = module.exports = {}
const hasGroup = exp.hasGroup = function (user, group) {
const groups = user && user.groups
return (groups && groups.indexOf(group) >= 0) ? true : false
}
exp.isAdmin = function (user) {
return hasGroup(user, "admin")
} |
const { watch } = require("fs");
const { join } = require("path");
const { spawn } = require("child_process");
const { stdout } = require("process");
const DIR = "./doc";
function flush() {
for (let i = 0; i < stdout.rows; i++) {
stdout.cursorTo(0, i);
stdout.clearLine();
}
stdout.cursorTo(0, 0);
console.log("watching...");
}
(() => {
flush();
watch(DIR, (_, filename) => {
flush();
spawn("./node_modules/.bin/textlint", ["--fix", join(DIR, filename)], {
stdio: "inherit"
});
});
})();
|
import React from 'react';
const Neptune = ()=> {
return (
<div className="container-fluid">
<div className="img">
<img src="https://militaryarms.ru/wp-content/uploads/2018/03/neptun-vo-vsej-svoej-krase.jpg" width="100%" alt=""/>
<div className="text">
<h1 className="text-center">Нептун</h1>
</div>
</div>
<div className="row">
<div className="col-6 pt-5">
<table className="table table-bordered table-dark">
<tr>
<th scope="row">Масса</th>
<td>1*1026кг. (17,2 раз больше массы Земли)</td>
</tr>
<tr>
<th scope="row">Диаметр</th>
<td>49500 км. (3,9 раза больше диаметра Земли)</td>
</tr>
<tr>
<th scope="row">Тепература поверхности</th>
<td>-213oC</td>
</tr>
<tr>
<th scope="row">Длина суток</th>
<td>17,87 часа</td>
</tr>
<tr>
<th scope="row">Расстояние от Cолнца(среднее)</th>
<td>30 а.е.,то есть 4,5 млрд.км.</td>
</tr>
</table>
</div>
<div className="col-6 pt-2">
<p>Планета №8 — Нептун. Орбита этого космического объекта пересекается с орбитой Плутона в нескольких местах. Экваториальный диаметр планеты такой же, как и у Урана, но находится на 1627 миллионов километров дальше от Урана.</p>
<p> Сатурн много времени считали последней планетой солнечной системы. Затем в конце 18 века был открыт Уран, которые с большим трудом можно было заметить невооруженным глазом. К концу 40-х годов 19-го века наблюдения смогли показать, что Уран немножко уходит с пути, по которым он должен идти с учетом воздействия всех прочих известных планет. В связи с этим теория движения космических тел была подвергнута испытанию.</p>
<p>Адамс из Англии и Леверье из Франции предположили, что раз воздействие со стороны известных космических объектов не может объяснить отклонения в движении Урана, значит, существует некое не известное притяжение. Они практически одновременно смогли рассчитать, где за Ураном находиться неизвестный объект, благодаря которому происходят подобные отклонения. Они рассчитали орбиту предполагаемой планеты и её массу, а также указали место на небе, где в то время теоретически она должна была располагаться. Эту планету и обнаружили в телескоп на предполагаемом месте в 1846 году. Планета получила название Нептун.</p>
</div>
<iframe width="100%" height="700" src="https://www.youtube.com/embed/NStn7zZKXfE" frameBorder="0"
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
allowFullScreen>
</iframe>
</div>
</div>
);
}
export default Neptune; |
const db = require('./../../config');
const mongoose = require('mongoose');
mongoose.connect(db.url);
const saltSchema = new mongoose.Schema(
{
user_name : String,
salt_value : String
}
);
module.exports = mongoose.model('salt',saltSchema); |
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import { useState, useEffect } from 'react';
import styled from '@emotion/styled'
import { useRouter } from 'next/router'
import { ScrollMenu, VisibilityContext } from "react-horizontal-scrolling-menu";
import { Card } from 'react-bootstrap';
export default function Home() {
const H1 = styled.h1`color: BLue;`
// const Par = styled.p`color: Blue;`
const My = styled.li`color: turquoise;`
const [pokemon, setPokemon] = useState([]);
const [pokemonpic, setPokemonpic] = useState([]);
const [pokemon1, setPokemon1] = useState([]);
const [selectedpokemon, setPokemn] = useState([]);
const [query, setQuery] = useState([]);
const fetchPokemon=()=>{
//fetch('https://pokeapi.co/api/v2/pokemon?limit=20')
//.then(response => response.json())
//.then(data => {
//console.log(data.results)
//setPokemon(data.results.map(p => p.name))
//});
fetch('https://pokeapi.co/api/v2/pokemon?offset=1&limit=30')
.then(response=>response.json())
.then(data=>{
createPokemonObject(data.results)
console.log(data.results)}).catch((err)=>{<h1>Something went wrong</h1>})
function createPokemonObject(result){
result.forEach((pokemn) => {
fetch(`https://pokeapi.co/api/v2/pokemon/${pokemn.name}`)
.then(response=>response.json())
.then(data=>{setPokemon(currenList=>[...currenList,data])}).catch((err)=>{<h1>Something went wrong</h1>})
});
}
console.log(pokemon)
}
useEffect( ()=>
{
fetchPokemon();
},[])
const router = useRouter()
const goTo = e => {
e.preventDefault()
router.push({pathname: '/mypokemon',
})
}
const searchPokemon = (e) =>
{
e.preventDefault();
alert("Searching " + query);
fetch( `https://pokeapi.co/api/v2/pokemon/${query}`)
.then(response => response.json())
.then(data => {
console.log(data.results)
setPokemon1(data)
}).catch((err)=>
{
alert("No such pokemon exist ");
})
}
const myChangeHandler = (e) =>
{
setQuery (e.currentTarget.value)
}
return (
<div className={styles.container}>
<Head>
<title>Create Pokemon App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<header className="d-flex bg-red justify-content-center p-2">
<h1 className="md-12 text-center text-4xl md:text-5xl text-success">Lets Play with Pokemon</h1>
</header>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
</link>
<div id="search-box" className="container-fluid bg-primary ">
<div className="row">
<div className="col-2 md:col-3 text-center p-1">
<img src="\pkmn.png" className="img-fluid" style={{color: "red"}}>
</img>
</div>
<div className="col-md-6 col-7">
<form className="d-flex justify-content-center align-items-center h-auto w-100" onSubmit= {searchPokemon } >
<input id="search_name" type="text" name="searchelemet" placeholder="Enter Pokemon Name" onChange={ myChangeHandler } value = {query} ></input>
<button type="button" className="btn btn-primary" onClick={searchPokemon}>
<i className="fa fa-search"></i>
</button>
<div className="col-1 p-2">
<button type="button" className="btn btn-rounded btn-success" onClick={goTo}>
<i className="fa fa-th-list" aria-hidden="true" ></i></button>
</div>
</form>
</div>
</div>
</div>
<div className=" justify-content-center align-items-center max-w-lg sm:bg-red-300 lg:max-w-md p-2 ">
<ScrollMenu >
{pokemon.map((p)=>
<Card className="main bg1 text-center text-xl md:text-sm xs:wd-49 xs:text-3xl xs:container-fluid " key= {p} >
<img src={p.sprites.other.dream_world.front_default} alt ={p.name} height="100" width="100"/>
<small>{p.types[0].type.name}</small>
<h4>{p.name}</h4>
</Card>
)}
</ScrollMenu>
</div>
<div className="row ">
<div className="d-flex justify-content-center col-sm-3">
{pokemon1?.sprites && (
<div className="flip-box">
<div className="flip-box-inner">
<div className="flip-box-front">
<small className="text-cyan">I can Flip</small>
<img src={pokemon1.sprites.front_default} alt="Pokemon" style={{width: "200px"},{height:"200px"}}/>
</div>
<div className="flip-box-back">
<H1> Name : {pokemon1.name}</H1>
<My>
{pokemon1?.types?.length > 0 &&
pokemon1.types.map((t) => <h6 key= {t}>Type : {t.type.name}</h6>)}
</My>
</div>
</div>
</div>
)}
</div>
</div>
</div>
)
}
|
// JavaScript Document
// JavaScript Document
function convert()
{
var oprt = document.getElementById("operators").value;
var slct = document.getElementById("selectors").value;
if(slct==="g")
{ var g= parseFloat(document.getElementById("inpt").value);
if(oprt ==="g")
{
document.getElementById("result").value = g;
}
else if(oprt === "m")
{
document.getElementById("result").value = g*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = g*1001.142303;
}
}
if(slct==="m")
{ var m= parseFloat(document.getElementById("inpt").value);
if(oprt === "(m/1000)")
{
document.getElementById("result").value = m/10000;
}
else if(oprt === "m")
{
document.getElementById("result").value = m;
}
else if(oprt === "p")
{
document.getElementById("result").value = (m/1000)*1001.142303;
}
}
if(slct==="p")
{ var p= parseFloat(document.getElementById("inpt").value);
if(oprt ==="p")
{
document.getElementById("result").value = (p/1001.142303);
}
else if(oprt === "m")
{
document.getElementById("result").value = (p/1001.142303)*1000;
}
else if(oprt === "p")
{
document.getElementById("result").value = p;
}
}
} |
import p5 from 'p5';
export const chapter3 = () => {
const sketch = (p) => {
var centX;
var centY;
let step = 10;
let lastX = -999;
let lastY = -999;
let y = 200;
let yNoise = p.random(100);
p.setup = () => {
p.createCanvas(p.windowWidth, p.windowHeight);
for(let x = 20; x <= p.width - 20; x += step){
// 乱数
// y = p.random(100) + 300;
// パリーンノイズ
y = p.noise(yNoise)*100;
if(lastX > -999){
p.line(x,y,lastX,lastY);
}
lastX = x;
lastY = y;
yNoise += 0.1
}
}
p.draw = () => {
}
}
new p5(sketch);
} |
angular.module('betService', [])
.factory('Bet', function($http) {
return {
get : function() {
return $http.get('laravel/public/api/bet');
},
// save a bet
save : function(matchId, teamId) {
var data = { 'matchId': matchId, 'teamId': teamId };
return $http({
method: 'POST',
url: 'laravel/public/api/bet/' + matchId + '/' + teamId,
//url: 'laravel/public/api/bet',
headers: { 'Content-Type' : 'application/x-www-form-urlencoded' },
data: data
//data: $.param(data)
});
}
}
}); |
/* eslint-disable */
export const user = {
login: 'SaraVieira',
id: 1051509,
avatar_url: 'https://avatars0.githubusercontent.com/u/1051509?v=4',
gravatar_id: '',
url: 'https://api.github.com/users/SaraVieira',
html_url: 'https://github.com/SaraVieira',
followers_url: 'https://api.github.com/users/SaraVieira/followers',
following_url:
'https://api.github.com/users/SaraVieira/following{/other_user}',
gists_url: 'https://api.github.com/users/SaraVieira/gists{/gist_id}',
starred_url: 'https://api.github.com/users/SaraVieira/starred{/owner}{/repo}',
subscriptions_url: 'https://api.github.com/users/SaraVieira/subscriptions',
organizations_url: 'https://api.github.com/users/SaraVieira/orgs',
repos_url: 'https://api.github.com/users/SaraVieira/repos',
events_url: 'https://api.github.com/users/SaraVieira/events{/privacy}',
received_events_url:
'https://api.github.com/users/SaraVieira/received_events',
type: 'User',
site_admin: false,
name: 'Sara Vieira',
company: '@yldio ',
blog: 'http://iamsaravieira.com',
location: 'Portugal',
email: null,
hireable: null,
bio: 'I make useless stuff for the funsies.\r\nWork at @yldio ',
public_repos: 122,
public_gists: 32,
followers: 386,
following: 34,
created_at: '2011-09-14T21:43:39Z',
updated_at: '2018-03-24T17:23:53Z'
};
export const orgs = [
{
login: 'esfiddle',
id: 25109279,
url: 'https://api.github.com/orgs/esfiddle',
repos_url: 'https://api.github.com/orgs/esfiddle/repos',
events_url: 'https://api.github.com/orgs/esfiddle/events',
hooks_url: 'https://api.github.com/orgs/esfiddle/hooks',
issues_url: 'https://api.github.com/orgs/esfiddle/issues',
members_url: 'https://api.github.com/orgs/esfiddle/members{/member}',
public_members_url:
'https://api.github.com/orgs/esfiddle/public_members{/member}',
avatar_url: 'https://avatars0.githubusercontent.com/u/25109279?v=4',
description: ''
},
{
login: 'OpenSourceLove',
id: 29953818,
url: 'https://api.github.com/orgs/OpenSourceLove',
repos_url: 'https://api.github.com/orgs/OpenSourceLove/repos',
events_url: 'https://api.github.com/orgs/OpenSourceLove/events',
hooks_url: 'https://api.github.com/orgs/OpenSourceLove/hooks',
issues_url: 'https://api.github.com/orgs/OpenSourceLove/issues',
members_url: 'https://api.github.com/orgs/OpenSourceLove/members{/member}',
public_members_url:
'https://api.github.com/orgs/OpenSourceLove/public_members{/member}',
avatar_url: 'https://avatars3.githubusercontent.com/u/29953818?v=4',
description: ''
},
{
login: 'upwithxyz',
id: 33137346,
url: 'https://api.github.com/orgs/upwithxyz',
repos_url: 'https://api.github.com/orgs/upwithxyz/repos',
events_url: 'https://api.github.com/orgs/upwithxyz/events',
hooks_url: 'https://api.github.com/orgs/upwithxyz/hooks',
issues_url: 'https://api.github.com/orgs/upwithxyz/issues',
members_url: 'https://api.github.com/orgs/upwithxyz/members{/member}',
public_members_url:
'https://api.github.com/orgs/upwithxyz/public_members{/member}',
avatar_url: 'https://avatars0.githubusercontent.com/u/33137346?v=4',
description:
'Biweekly Podcast about JavaScript, Tech, and the World... I guess'
}
];
|
const lib = require("./lib-frameworkless.js")
require('http').createServer(server).listen(7777)
function server(req, res) {
ROUTE_REDIRECT = {
// req.url : target's parent directory
'/favicon.ico' : './Public/Comp/',
}
lib.Init({
'res' : res,
'req' : req,
'viewdir' : './Public',
'compdir' : './Public/Comp',
})
//lib.Init(res, req, viewdir='./Public', compdir='./Public/Comp')
lib.Route(req, res)
}
|
jQuery(document).ready(function(){
"use strict";
$(".responsive-contact a").on("click",function(){
$(this).siblings().removeClass("active");
$(this).addClass("active");
if($(this).hasClass("phone-btn")){
$(".responsive-phone").slideDown();
$(".responsive-mail").slideUp();
}else{
$(".responsive-mail").slideDown();
$(".responsive-phone").slideUp();
}
})
$(".responsive-search").on("click",function(){
$(".responsive-search > form").slideToggle();
});
$('.headercounter').downCount({
date: '06/25/2019 12:00:00',
offset: +10
});
$('.fullwidth-carousel').parent().parent().parent().addClass("expand");
$('.top-adds').parent().parent().parent().addClass("expand");
$('.audio-btn').click(function(){
$('.audioplayer').slideUp();
$(this).next('.audioplayer').slideDown();
return false;
})
$('.cross').click(function(){
$(this).parent().slideUp();
$('.sermon-media li i.audio-btn').removeClass('active');
})
$('.sermon-media li i.audio-btn').click(function() {
$('.sermon-media li i.audio-btn').removeClass('active');
$(this).addClass('active');
});
/*** ACCORDIONS ***/
$(function() {
$('#toggle .content').hide();
$('#toggle h2:first').addClass('active').next().slideDown(500).parent().addClass("activate");
$('#toggle h2').click(function() {
if($(this).next().is(':hidden')) {
$('#toggle h2').removeClass('active').next().slideUp(500).parent().removeClass("activate");
$(this).toggleClass('active').next().slideDown(500).parent().toggleClass("activate");
}
});
});
/*** SCROLLER ***/
$('.responsive-menu').enscroll();
/*** CART PAGE PRODUCT DELETE ***/
$('.cart-product .dustbin').click(function() {
$(this).parent().parent().parent().slideUp();
});
/*** BILLING ADDRESS AND SHIPPING ADDRESS ***/
$('.billing-add').click(function() {
$('.billing-address').slideDown(1000);
$('.shipping-address').slideUp(1000);
});
$('.shipping-add').click(function() {
$('.shipping-address').slideDown(1000);
$('.billing-address').slideUp(1000);
});
/*** CHECKOUT PAGE BLOCKS ***/
$('.checkout-block h5').click(function() {
$(this).toggleClass('closed');
$(this).next('.checkout-content').slideToggle();
});
/*** PASTORS CAROUSEL ***/
$('.pastors-carousel').parent().parent().parent().removeClass("container");
$('.pastors-carousel').parent().parent().parent().parent().removeClass("block");
/*** HEADER CART DROPDOWN ***/
$('.cart-dropdown > p').click(function(){
$(this).next("ul").slideToggle("slow");
});
/*** HEADER CART CLOSE BY CLICKING OUTSIDE ***/
$('.cart-dropdown').click(function(e){
e.stopPropagation();
});
$('html').click(function() {
$('.cart-dropdown > ul').slideUp('medium', function() {
// Animation complete.
});
});
/*** HEADER CART ITEM REMOVE ***/
$('.cart-dropdown > ul li span.remove').click(function(){
$(this).parent().slideUp("slow");
});
/*** STICKY HEADER ***/
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 70) {
$(".stick").addClass("sticky");
}
else{
$(".stick").removeClass("sticky");
}
});
/*** FIXED OR STATIC HEADER ON CLICK ***/
$(".sticky").click( function(){
$("header").addClass("stick");
return false;
});
$(".non-sticky").click( function(){
$("header").removeClass("stick");
$("header").removeClass("sticky");
return false;
});
$(".header1-btn").click( function(){
$("header").attr('class',"");
$(".page-top").addClass('extra-gap');
return false;
});
$(".header2-btn").click( function(){
$("header").attr('class',"");
$("header").addClass('header2');
$(".page-top").removeClass('extra-gap');
return false;
});
$(".header3-btn").click( function(){
$("header").attr('class',"");
$("header").addClass('header3');
$(".page-top").addClass('extra-gap');
return false;
});
$(".header4-btn").click( function(){
$("header").attr('class',"");
$("header").addClass('header4');
$(".page-top").removeClass('extra-gap');
return false;
});
$(".header5-btn").click( function(){
$("header").attr('class',"");
$("header").addClass('header5');
$(".page-top").addClass('extra-gap');
return false;
});
$(".header6-btn").click( function(){
$("header").attr('class',"");
$("header").addClass('header6');
$(".page-top").addClass('extra-gap');
return false;
});
$(".header7-btn").click( function(){
$("header").attr('class',"");
$("header").addClass('header7');
$(".page-top").addClass('extra-gap');
return false;
});
$(".header8-btn").click( function(){
$("header").attr('class',"");
$("header").addClass('header8');
$(".page-top").removeClass('extra-gap');
return false;
});
$(".header9-btn").click( function(){
$("header").attr('class',"");
$("header").addClass('header9');
$(".page-top").addClass('extra-gap');
return false;
});
var e = new Date( "01/31/2019 12:00:00");
e.setDate(e.getDate());
var dd = e.getDate();
var mm = e.getMonth() + 1;
var y = e.getFullYear();
var h = e.getHours();
var m = e.getMinutes();
var s = e.getSeconds();
var futureFormattedDate = mm + "/" + dd + "/" + y + " "+ h + ":" + m + ":" + s ;
console.log(futureFormattedDate);
$('.headercounter').downCount({
date: futureFormattedDate,
offset: +5
});
/*** WIDE AND BOXED LAYOUT ***/
$('.boxed').click(function() {
$('.theme-layout').addClass("boxed");
$('body').css('background-image', 'url(images/pat1.png)');
return false;
});
$('.wide').click(function() {
$('.theme-layout').removeClass("boxed");
$('body').css('background-image', 'none');
return false;
});
$('.pattern1').on('click', function() {
$('body').css('background-image', 'url(images/pat1.png)');
})
$('.pattern2').on('click', function() {
$('body').css('background-image', 'url(images/pat2.png)');
})
$('.pattern3').on('click', function() {
$('body').css('background-image', 'url(images/pat3.png)');
})
$('.pattern4').on('click', function() {
$('body').css('background-image', 'url(images/pat4.png)');
})
$('.pattern5').on('click', function() {
$('body').css('background-image', 'url(images/pat5.png)');
})
/*=================== Responsive Menu ===================*/
$(".responsive-btn").on("click",function(){
$(".responsive-menu").addClass("slidein");
return false;
});
$("html").on("click",function(){
$(".responsive-menu").removeClass("slidein");
});
$(".responsive-menu").on("click",function(e){
e.stopPropagation();
});
$(".responsive-menu li.menu-item-has-children > a").on("click",function(){
$(this).parent().siblings().children("ul").slideUp();
$(this).parent().siblings().removeClass("active");
$(this).parent().children("ul").slideToggle();
$(this).parent().toggleClass("active");
return false;
});
/*=================== LightBox ===================*/
var foo = $('.lightbox');
foo.poptrox({
usePopupCaption: true,
usePopupNav: true,
});
/*** AJAX CONTACT FORM ***/
/*$('#contactform').submit(function(){
var action = $(this).attr('action');
$("#message").slideUp(750,function() {
$('#message').hide();
$('#submit')
.after('<img src="images/ajax-loader.gif" class="loader" />')
.attr('disabled','disabled');
$.post(action, {
name: $('#name').val(),
email: $('#email').val(),
comments: $('#comments').val(),
verify: $('#verify').val(),
captcha: $(".g-recaptcha-response").val(),
},
function(data){
document.getElementById('message').innerHTML = data;
$('#message').slideDown('slow');
$('#contactform img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit').removeAttr('disabled');
if(data.match('success') != null) $('#contactform').slideUp('slow');
}
);
});
return false;
});*/
});
|
/**
* Created by hasee on 2017/12/26.
*/
Ext.define('Admin.model.hero.Hero', {
extend: 'Admin.model.Base',
idProperty: 'id',
fields: [
{name: 'id', type: 'int'},
{name: 'name', type: 'string'},
{name: 'localizedName', type: 'string'},
{name: 'headpotraitPath', type: 'string'},
{name: 'heroPath', type: 'string'}
]
});
|
"use strict";
const gulp = require('gulp');
const connect = require('gulp-connect');
const open = require('gulp-open');
const browserify = require('browserify');
const source = require('vinyl-source-stream');
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('autoprefixer');
const buffer = require('vinyl-buffer');
const log = require('gulplog');
const uglify = require('gulp-uglify');
const htmlmin = require('gulp-htmlmin');
const svgmin = require('gulp-svgmin');
const config = {
port: 5000,
devBaseUrl: 'http://localhost',
index: 'index.html',
paths: {
dist: './dist',
js: './src/**/*.js',
mainJs: './src/main.js',
sass: './src/**/*.scss',
css: './src/**/*.css',
mainSass: './src/main.scss',
html: './src/index.html',
},
};
gulp.task('connect', () => {
connect.server({
root: ['.'],
port: config.port,
base: config.devBaseUrl,
livereload: true,
});
});
gulp.task('open', ['connect'], () => {
return gulp.src(config.index)
.pipe(open({ uri: `${config.devBaseUrl}:${config.port}/` }));
});
gulp.task('html', () => {
return gulp.src(config.paths.html)
.pipe(htmlmin({
collapseWhitespace: true,
removeComments: true,
useShortDoctype: true,
removeRedundantAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkAttributes: true
}))
.pipe(gulp.dest('.'))
.pipe(connect.reload());
});
gulp.task('js', () => {
const b = browserify({
entries: config.paths.mainJs,
debug: true,
transform: [['babelify', { presets: ['env'] }]]
});
return b.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init({ loadMaps: true }))
.pipe(uglify())
.on('error', log.error)
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(`${config.paths.dist}/scripts`))
.pipe(connect.reload());
});
gulp.task('sass', () => {
return gulp.src(config.paths.mainSass)
.pipe(sass())
.on('error', sass.logError)
.pipe(gulp.dest('./src/css'))
.pipe(connect.reload());
});
gulp.task('css', () => {
return gulp.src(config.paths.css)
.pipe(sourcemaps.init())
.pipe(postcss([require('autoprefixer')]))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(`${config.paths.dist}`))
.pipe(connect.reload());
})
gulp.task('svg', () => {
return gulp.src('./src/svg/FairOaksLogo.svg')
.pipe(svgmin())
.pipe(gulp.dest('./static'));
});
gulp.task('watch', () => {
gulp.watch(config.paths.js, ['js']);
gulp.watch(config.paths.sass, ['sass']);
gulp.watch(config.paths.css, ['css']);
});
gulp.task('default', ['open', 'watch', 'sass', 'css', 'js', 'html', 'svg']);
gulp.task('build', ['sass', 'css', 'js']);
|
var grobalUrl = "http://localhost:8080";
function hidenHelpButton() {
document.getElementById("addHelp").setAttribute("style",
"float:right;visibility:hidden;");
}
function showHelpButton() {
document.getElementById("addHelp").setAttribute("style",
"float:right;visibility:visible;");
}
function delHelpItem() {
var helpboard = document.getElementById("HelpMarket");
var helpItemCheckBoxes = document.getElementsByName("HelpChecks");
var selectedCheckBoxes = new Array();
var delSeq = new Array();
for ( var i = 0; i < helpItemCheckBoxes.length; i++) {
if (helpItemCheckBoxes[i].checked == true)
selectedCheckBoxes.push(helpItemCheckBoxes[i]);
}
for(var j = 0 ;j < selectedCheckBoxes.length;j++){
var seq = selectedCheckBoxes[j].parentNode.parentNode.id;
delSeq.push(seq);
}
if(delSeq.length==0)return;
// 记录对应的id然后发送到后台,如果删除成功,则执行下面代码
jQuery.ajaxSettings.traditional = true;
$.ajax({
// async:false,
type : 'post',
url : 'http://localhost:8080/ovs/admin/help-manager!delHelpBoard.action',
dataType : 'json',
data : {
'helpBoardSeq' : delSeq,
},
success : function(msg) {
alert(msg.message);
if (msg.status == 1) {
// 提交成功
for ( var i = 0; i < selectedCheckBoxes.length; i++) {
HelpMarket.removeChild(selectedCheckBoxes[i].parentNode.parentNode);
}
var spanCounts = document.getElementsByName("spanCount");
var i = 0
for (i = 0; i < spanCounts.length; i++) {
spanCounts[i].innerText = i + 1+'-';
}
document.getElementsByName("countHelpBoard")[0].innerText=i;
}
},
error : function(msg) {
alert("连接异常");
}
});
}
function addHelpItem() {
var helpboard = document.getElementById("HelpMarket");
var firstHelpItem = (document.getElementsByName("helpItem"))[0];
var newChild = document.createElement("div");
newChild.innerHTML = "<div id='helpTitle' class='panel-heading' style='padding:10px;'>"
+ "<input type='text' class='form-control' placeholder='请输入标题'/>"
+ "</div>"
+ "<div id='helpContent' class='panel-body'>"
+ "<textarea class='form-control' style='resize:none;' rows='5' placeholder='请输入内容'></textarea>"
+ "<div style='float:right;margin-top:5px;'>"
+ "<button type='button' class='btn btn-default operateButton' style='margin-right:5px;'>保存</button>"
+ "<button type='button' class='btn btn-default operateButton'>取消</button>"
+ "</div>" + "</div>";
newChild.setAttribute("name", "enterBoard");
newChild.setAttribute("class", "panel panel-default");
helpboard.insertBefore(newChild, firstHelpItem);
document.getElementById("Whole").onmousedown = function(event) {
var nowObject = event.target;
var enterBoard = (document.getElementsByName("enterBoard"))[0];
if (enterBoard == undefined)
return;
var helpTextarea = (enterBoard.getElementsByTagName("textarea"))[0];
var input = (enterBoard.getElementsByTagName("input"))[0];
var buttons = enterBoard.getElementsByTagName("button");
var helpTitle = document.getElementById("helpTitle");
var helpContent = document.getElementById("helpContent");
if (nowObject == helpTextarea || nowObject == input
|| nowObject == helpTitle || nowObject == helpContent) {
} else if (nowObject == buttons[0]) {// 保存操作
if (input.value == "" || helpTextarea.value == "") {
if (input.value == "")
input.setAttribute("placeholder", "标题不能为空");
if (helpTextarea.value == "")
helpTextarea.setAttribute("placeholder", "标题不能为空");
} else {
$("#Whole").unbind();
submitUrl(enterBoard);
}
} else {// 取消或点击其他地方
var helpboard = document.getElementById("HelpMarket");
helpboard.removeChild(enterBoard);
$("#Whole").unbind();
}
}
}
function submitUrl(which) {
var helpTitle = (which.getElementsByTagName("input"))[0];
var helpContent = (which.getElementsByTagName("textarea"))[0];
// 先把数据发向后台,获取id
$.ajax({
// async:false,
type : 'post',
url : 'http://localhost:8080/ovs/admin/help-manager!addHelpBoard.action',
dataType : 'json',
data : {
'helpTitle' : helpTitle.value,
'helpContent' : helpContent.value
},
success : function(msg) {
alert(msg.message);
if (msg.status == 1) {
// 提交成功
saveEnterHelpItem(msg.data, helpTitle.value,
helpContent.value,which);
}
},
error : function(msg) {
alert("连接异常");
}
});
}
function saveEnterHelpItem(seq, title, content,which) {
var helpboard = document.getElementById("HelpMarket");
var newChild = document.createElement("div");
newChild.innerHTML = "<div class='checkbox' style='float:left'>"
+ "<input type='checkbox' name='HelpChecks'>" + "</div>"
+ "<div class='panel-heading' style='padding:0px 0px;'>" + "<h4>"
+ "<span name='spanCount'></span>" + title + "</h4>" + "</div>"
+ "<div class='panel-body'>" + content + "</div>";
newChild.id = seq;
newChild.setAttribute("name", "helpItem");
newChild.setAttribute("class", "panel panel-default");
helpboard.replaceChild(newChild, which);
// 排序
var spanCounts = document.getElementsByName("spanCount");
var i = 0;
for (i = 0; i < spanCounts.length; i++) {
spanCounts[i].innerText = i + 1+'-';
}
document.getElementsByName("countHelpBoard")[0].innerText=i;
}
function creatInputText(which) {
var InputText = document.createElement("div");
InputText.innerHTML = "<div class='panel-body'>"
+ "<div>"
+ "<div style='float:right;'>"
+ "<button type='button' class='btn btn-default operateButton'>"
+ "确认</button>"
+ "<button type='button' class='btn btn-default operateButton'>"
+ "取消</button>"
+ "</div>"
+ "</div>"
+ "<div>"
+ "<textarea placeholder='200字以内' class='form-control' rows='3'></textarea>"
+ "</div>" + "</div>";
InputText.setAttribute("name", "InputText");
// 绑定事件
document.getElementById("Whole").onmousedown = function(event) {
var nowObject = event.target;
var oldInputText = (document.getElementsByName("InputText"))[0];
if (oldInputText == undefined)
return;
var buttons = oldInputText.getElementsByTagName("button");
var textArea = (oldInputText.getElementsByTagName("textarea"))[0];
if (nowObject == textArea) {// 鼠标在输入框内,不做处理
} else if (nowObject == buttons[0]) {// 鼠标点击确认键
// 检查是否有输入内容
if (textArea.value == "") {
textArea.setAttribute("placeholder", "输入不能为空");
} else {
$("#Whole").unbind();
confirmMess(which,textArea);
}
} else {// 取消或者点击页面其他
$("#Whole").unbind();
cencleMess();
}
}
return InputText;
}
function confirmMess(which,textArea) {
// 向后台发送该数据,成功则显示,否则说失败
$.ajax({
// async:false,
type : 'post',
url : 'http://localhost:8080/ovs/admin/help-manager!replyHelp.action',
dataType : 'json',
data : {
'replySeq' : which.id,
'replyContent':textArea.value
},
success : function(msg) {
alert(msg.message);
if (msg.status == 1) {
// 提交成功
// 成功,则执行下面操作
var parent = which.parentNode;
var lastParent = parent.parentNode;
lastParent.removeChild(parent);
}
},
error : function(msg) {
alert("连接异常");
}
});
}
function cencleMess() {
var inputText = (document.getElementsByName("InputText"))[0];
var item = inputText.parentNode;
item.removeChild(inputText);
}
function createNewChild() {
var inputText = (document.getElementsByName("InputText"))[0];
var item = inputText.parentNode;
var inputMess2 = ((inputText.getElementsByTagName("textarea"))[0]).value;
var newChild = document.createElement("div");
// 后台把回复主的名字提出来,以及question,以及回复内容
var answer = "answer";
var question = "question";
var inputMess = inputMess2;// 先假设内容一样
newChild.innerHTML = "<div class='panel-heading' style='padding:0px 0px;background-color:#f5f5f5;'>"
+ "<span name='name'>"
+ answer
+ "</span>"
+ "<span>回复"
+ question
+ "</span>-2015-12-11 11:01:49:"
+ "<div style='float:right;font-size: 15px;font-weight: bold;line-height: 20px;color: #999999;'>"
+ "<span onclick='answerOther(this);'>回复</span> "
+ "</div>"
+ "</div>"
+ "<div class='panel-body'>"
+ inputMess
+ "</div>";
newChild.setAttribute("name", "item");
item.replaceChild(newChild, inputText);
}
function answerOther(which) {
var grandparent = which.parentNode.parentNode;
var item = grandparent.parentNode;
var messageItem = item.parentNode;
var childDIVs = messageItem.getElementsByTagName("div");
var children = new Array();
for ( var i = 0; i < childDIVs.length; i++) {
if (childDIVs[i].getAttribute("name") == "item")
children.push(childDIVs[i]);
}
var j = 0;
for (j; j < children.length; j++) {
if (children[j] == item)
break;
}
if (j < children.length) {
messageItem.insertBefore(creatInputText(item), children[j + 1]);
} else if (j == children.length) {
messageItem.appendChild(creatInputText(item));
}
;
// 定位光标
((document.getElementsByTagName("textarea"))[0]).focus();
}
function delMess(which) {
// 先向后台发送删除指令,成功后执行
var grandparent = which.parentNode.parentNode;
var item = grandparent.parentNode;
var messageItem = item.parentNode;
var tab_panel = messageItem.parentNode;
$.ajax({
// async:false,
type : 'get',
url : 'http://localhost:8080/ovs/admin/help-manager!delQuestion.action',
dataType : 'json',
data : {'questionSeq':item.id},
success : function(msg) {
alert(msg.message);
if (msg.status == 1) {
// 提交成功
tab_panel.removeChild(messageItem);
}
},
error : function(msg) {
alert("连接异常");
}
});
} |
var MINUTES_PER_HOUR = 60;
var HOURS_PER_DAY = 24;
var MINUTES_PER_DAY = HOURS_PER_DAY * MINUTES_PER_HOUR;
function afterMidnight(timeStr) {
let timeStamp = new Date('1/1/2000 ' + timeStr)
let hours = timeStamp.getHours();
let minutes = timeStamp.getMinutes();
return hours * MINUTES_PER_HOUR + minutes;
}
function beforeMidnight(timeStr) {
let timeStamp = new Date('1/1/2000 ' + timeStr)
let hours = timeStamp.getHours();
let minutes = timeStamp.getMinutes();
var deltaMinutes = MINUTES_PER_DAY - afterMidnight(timeStr);
if (deltaMinutes === MINUTES_PER_DAY) {
deltaMinutes = 0;
}
return deltaMinutes;
}
console.log(afterMidnight('00:00')); // 0
console.log(beforeMidnight('00:00')); // 0
console.log(afterMidnight('12:34')); // 754
console.log(beforeMidnight('12:34')); // 686
|
import http from 'k6/http';
export default function () {
const res = http.get('https://k6.io');
console.log(JSON.stringify(res.headers));
}
|
import axios from 'axios'
import { Message } from '../components/TMessage/TMessage.js'
import store from '@/store'
import router from '@/router'
axios.defaults.baseURL = process.env.VUE_APP_SERVER_API_PATH
axios.interceptors.request.use(configs => {
// try{
// let data = JSON.parse(localStorage.getItem('user'))
// }catch(e){
// throw e
// }
if (configs.url !== 'user/login') {
const { authorization } = store.state.user.info
if (authorization) {
configs.headers.authorization = authorization
}
}
return configs
})
axios.interceptors.response.use(
response => {
return response
},
error => {
let { message, errorDetails, statusCode } = error.response.data
if (errorDetails) {
message += ' : ' + errorDetails
}
//权限过期重新登陆
if (statusCode === 401) {
router.push({
name: 'Login',
})
}
Message.error(message)
throw error
},
)
export default axios
|
import React, { useRef, useState } from 'react'
import { Alert, Button, Card, Container, Form } from 'react-bootstrap'
import Axios from 'axios'
export default function FormTrain() {
const modelRef = useRef()
const seatsRef = useRef()
const ownerRef = useRef()
const [error, setError] = useState("")
const [success, setSuccess] = useState("")
const [loading, setLoading] = useState(false)
async function handleSubmit(e) {
e.preventDefault()
try {
setError("")
setLoading(true)
console.log(modelRef.current.value)
Axios.post("http://localhost:3001/addtrain", {
model: modelRef.current.value,
seats: seatsRef.current.value,
owner: ownerRef.current.value,
}).then((response) => {
console.log(response)
});
setSuccess("Successfully added to database")
modelRef.current.value = ""
seatsRef.current.value = ""
ownerRef.current.value = ""
setLoading(false)
} catch {
setError("Failed to add company")
}
}
return (
<>
<Container className="d-flex align-tems-center justify-content-center" style={{ minHeight: "100vh" }}>
<div className="w-100" style={{ maxWidth: "400px" }}>
<Card>
<Card.Body>
<h2 className="text-center mb-4">Train Form</h2>
{error && <Alert variant="danger">{error}</Alert>}
{success && <Alert variant="success">{success}</Alert>}
<Form onSubmit={handleSubmit}>
<Form.Group id="model">
<Form.Label>Model</Form.Label>
<Form.Control ref={modelRef} required />
</Form.Group>
<Form.Group id="seats">
<Form.Label>Seats</Form.Label>
<Form.Control ref={seatsRef} required />
</Form.Group>
<Form.Group id="owner">
<Form.Label>Owner</Form.Label>
<Form.Control ref={ownerRef} required />
</Form.Group>
<Button disabled={loading} className="w-100" type="submit">
Add
</Button>
</Form>
</Card.Body>
</Card>
</div>
</Container>
</>
)
} |
const assert = require('assert')
const flow = require('./_flow')
let schema = '//atom/email'
describe(`schema:${schema}`, () => {
it('an email', () => {
let data = 'some-one@some-where.some-country'
let e = flow.verify(schema, data)
assert.equal(e, undefined)
})
it('without divider @', () => {
let data = 'some-one some-where.some-country'
let e = flow.verify(schema, data)
assert.notEqual(e, undefined)
})
it('without domain ', () => {
let data = 'some-one@'
let e = flow.verify(schema, data)
assert.notEqual(e, undefined)
})
it('with invalid symbols ;', () => {
let data = 'some-one;@some-where.some-country'
let e = flow.verify(schema, data)
assert.notEqual(e, undefined)
})
})
|
angular.module("mobileControllers")
.controller("HomeController", function ($ionicSlideBoxDelegate, $ionicPopup, Popup, $ionicViewSwitcher, $state, $ionicScrollDelegate, $rootScope, $location, Platform, Domain, $scope, $ionicLoading, $timeout, $ionicSlideBoxDelegate, Popup, MobileService) {
$rootScope.currentPage = "current-home-page";
$scope.pullingTips = '闪电审核,现金速达';
$scope.cIndex = 0
$scope.dIndex = 0
/*
MobileService.homeVdsStatistics().then(function (data) {
if (data.code == 0) {
if (window._vds) {
window._vds.push(['setCS1', 'inviteCode', data.data.invite_code]);
return
}
var _vds = _vds || [];
window._vds = _vds;
(function () {
_vds.push(['setAccountId', '8fd2500ba4956d6d']);
_vds.push(['enableHT', true]);
_vds.push(['setCS1', 'inviteCode', data.data.invite_code]);
(function () {
var vds = document.createElement('script');
vds.type = 'text/javascript';
vds.async = true;
vds.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'dn-growing.qbox.me/vds.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(vds, s);
})();
})();
}
})
*/
if (!$rootScope.awaken && Platform.isIos) {
//$rootScope.awaken = true;
//window.location.href = Platform.isAndroid ? 'shanxiancard://com.kdlc.mcc/openapp' : 'xjbk915164674://';
}
if (Platform.isWeixin) {
/*MobileService.bindWechat().then(function (data) {
if (data.code == -1001) {
window.location.href = Domain.resolveUrl('http://credit.shanxiancard.com/wx/user-auth-template?redirectUrl=' + window.location.href)
return;
}
});*/
}
$scope.onKnow = function (data) {
$ionicLoading.show({template: '<ion-spinner></ion-spinner>'})
MobileService.confirmKnow({id: data.id}).then(function (result) {
$ionicLoading.hide()
if (result.code === 0) {
location.href = data.active_url
} else {
Popup.alert(result.message);
}
})
}
$scope.showTips = function () {
$ionicPopup.alert({
template: "综合费用=借款利息+居间服务费+信息认证费,综合费用将在借款时一次性扣除",
okText: '我知道了',
okType: 'button-credit'
})
};
//申请借款
$scope.apply = function (data) {
$ionicViewSwitcher.nextDirection('forward');
// _hmt.push(['_trackEvent', 'm版首页', '点击马上申请']);
if (data.verify_loan_pass === 0) {
$state.go('certification', {origin: 'home'});
return;
}
$ionicLoading.show({template: '<ion-spinner></ion-spinner>'})
var day = data.amount_days.days[$scope.dIndex]
var loan = {
'period': day,
'money': $scope.sliderAmount.value,
'card_type': data.card_type
}
MobileService.getConfirmLoan(loan).then(function (data) {
$ionicLoading.hide();
if (data.code !== 0) {
Popup.alert(data.message);
return;
}
if (data.code === 0) {
loan.item = data.data.item;
$state.go('loan', loan);
}
});
};
var costHandler = function () {
var interest = $scope.data.item.card[$scope.cIndex].amount_days.interests[$scope.dIndex];
var length = $scope.data.item.card[$scope.cIndex].amount_days.amounts.length
var amount = $scope.data.item.card[$scope.cIndex].amount_days.amounts[length - 1]
var ratio = interest / amount
$scope.cost = $scope.sliderAmount.value * ratio;
$scope.amount = $scope.sliderAmount.value - $scope.cost;
};
$scope.sliderAmount = {
value: 1000,
options: {
floor: 200,
step: 100,
showSelectionBar: true,
translate: function (value) {
return value + '元';
},
onChange: costHandler
}
};
var resetAmount = function (isUpdate) {
var amounts = $scope.data.item.card[$scope.cIndex].amount_days.amounts;
$scope.sliderAmount.options.floor = amounts[0] / 100;
isUpdate || ($scope.sliderAmount.value = amounts[amounts.length - 1] / 100)
costHandler()
}
$scope.slideHasChanged = function (index) {
console.log(index)
$scope.cIndex = index
resetAmount()
}
$scope.switchDay = function (index) {
$scope.dIndex = index
resetAmount(true)
}
var handler = function (data) {
if (data.code != 0) {
Popup.alert(data.message);
return;
}
$scope.data = data.data;
//console.log(data.data)
$ionicSlideBoxDelegate.update()
resetAmount()
};
$ionicLoading.show({template: '<ion-spinner></ion-spinner>'})
MobileService.getHomeData().then(function (data) {
$ionicLoading.hide();
handler(data);
});
$scope.doRefresh = function () {
MobileService.getHomeData().then(function (data) {
handler(data);
$scope.$broadcast('scroll.refreshComplete');
});
};
}) |
"use strict";
angular.module('workshop.home', [
'workshop.colorpicker',
'workshop.clock',
'workshop.my-click',
'workshop.knob'
])
.component('home', {
templateUrl: 'components/home/home.html',
controller: function($timeout, $parse, $scope) {
this.blue = 200;
this.changeColor = function() {
this.blue = 10;
};
this.outputColors = function(red, green, blue) {
console.log('R:', red, 'G:', green, 'B:', blue)
};
this.dangerClick = function(event) {
//event.preventDefault();
this.blue = 0;
console.log(event)
}
}
});
|
import {combineReducers} from 'redux'
import {routerReducer} from 'react-router-redux'
import app from './App.ducks'
import create from './_Create/Create.ducks'
import view from './_View/View.ducks'
export default combineReducers({
app,
create,
view,
router: routerReducer,
})
|
/**
* @module limitTo
*
* Creates a new array or string containing only a specified number of elements.
* The elements are taken from either the beginning or the end of the source array
* or string, as specified by the value and sign (positive or negative) of limit.
*
* Same behavior as AngularJS limitTo filter: http://docs.angularjs.org/api/ng/filter/limitTo
*
* To use this filter in a template, first register it in the Nunjucks environment:
* env.addFilter('limitTo', limitTo);
*
* @example <caption>Limit to first 5 characters of string</caption>
* {{ "hello world" | limitTo(5) }}
* // outputs: hello
*
* @example <caption>Limit to last 5 characters of string</caption>
* {{ "hello world" | limitTo(-5) }}
* // outputs: world
*
* @example <caption>Limit to first 3 items in array</caption>
* {% set items = ["alpha","beta","charlie","delta","echo"] %}
* {% for item in items | limitTo(3) %} {{ loop.index }}.{{ item }} {% endfor %}
* // outputs: 1.alpha 2.beta 3.charlie
*
* @example <caption>Limit to last 3 items in array</caption>
* {% set items = ["alpha","beta","charlie","delta","echo"] %}
* {% for item in items | limitTo(-3) %} {{ loop.index }}.{{ item }} {% endfor %}
* // outputs: 1.charlie 2.delta 3.echo
*
* @param {String|Array} input text or list of items to shorten
* @param {Number} limit either positive offset from start or negative offset from end
*/
function limitTo(input, limit){
'use strict';
if(typeof limit !== 'number'){
return input;
}
if(typeof input === 'string'){
if(limit >= 0 && limit < input.length){
return input.substring(0, limit) + '...';
} else {
return input;// input.substr(limit);
}
}
if(Array.isArray(input)){
limit = Math.min(limit, input.length);
if(limit >= 0){
return input.splice(0, limit);
} else {
return input.splice(input.length + limit, input.length);
}
}
return input;
}
module.exports = limitTo;
|
// Global variables
var gl;
var loopID;
var program, vao;
var positionAttributeLocation;
var normalAttributeLocation;
var projectionMatrixUniformLocation;
var viewMatrixUniformLocation;
var transformationMatrixUniformLocation;
var lightPositionUniformLocation;
var lightColorUniformLocation;
var entity = {
'position' : {
'x' : 0,
'y' : 0,
'z' : -4,
},
'rotation' : {
'x' : 0,
'y' : 0,
'z' : 0,
},
'scale' : {
'x' : 1,
'y' : 1,
'z' : 1,
},
}
var camera = {
'position' : {
'x' : 0,
'y' : 0,
'z' : 0,
},
'rotation' : {
'x' : 0,
'y' : 0,
'z' : 0,
},
}
var light = {
'position' : {
'x' : 0, // 20000,
'y' : 0, // 20000,
'z' : 0, // 2000,
},
'color' : {
'x' : 1,
'y' : 1,
'z' : 1,
},
}
var KEY_Q = 81;
// Entry
document.addEventListener( 'DOMContentLoaded', main, false );
function main ()
{
setup();
// programRender();
loopID = requestAnimationFrame( render );
}
// Setup
function setup ()
{
// Initialize the GL context
const canvas = document.querySelector( '#glCanvas' );
gl = canvas.getContext( 'webgl2' );
// Only continue if WebGL is available and working
if ( gl === null ) {
alert( 'Unable to initialize WebGL. Your browser or machine may not support it.' );
return;
}
programSetup();
}
// Loop
function render ( now )
{
// Get time
now *= 0.001; // convert to seconds
// Check status of asynchronous events
// ...
// Render
programRender();
// Loop
loopID = requestAnimationFrame( render );
}
// Exit
function stop ()
{
cancelAnimationFrame( loopID ); // stop loop
console.log( 'Adios!' );
}
document.addEventListener( 'keydown', function ( evt ) {
if ( evt.keyCode == KEY_Q )
{
stop();
}
} );
// ______________________________________________________________
function programSetup ()
{
// Configure GL
gl.clearColor( 0, 0, 0, 1 );
gl.enable( gl.DEPTH_TEST );
gl.depthFunc( gl.LEQUAL );
gl.clearDepth( 1.0 );
gl.enable( gl.CULL_FACE );
gl.cullFace( gl.BACK );
// Create GLSL shaders, upload the GLSL source, compile the shaders
// var vertexShader = createShader( gl.VERTEX_SHADER, vs_template );
// var fragmentShader = createShader( gl.FRAGMENT_SHADER, fs_template );
// var vertexShader = createShader( gl.VERTEX_SHADER, vs_diffuse );
// var fragmentShader = createShader( gl.FRAGMENT_SHADER, fs_diffuse );
var vertexShader = createShader( gl.VERTEX_SHADER, vs_specular );
var fragmentShader = createShader( gl.FRAGMENT_SHADER, fs_specular );
// Link the two shaders into a program
program = createProgram( vertexShader, fragmentShader );
// Get uniform locations
projectionMatrixUniformLocation = gl.getUniformLocation( program, 'projectionMatrix' );
viewMatrixUniformLocation = gl.getUniformLocation( program, 'viewMatrix' );
transformationMatrixUniformLocation = gl.getUniformLocation( program, 'transformationMatrix' );
lightPositionUniformLocation = gl.getUniformLocation( program, 'lightPosition' );
lightColorUniformLocation = gl.getUniformLocation( program, 'lightColor' );
// Load object vertex data
loadToVAO();
// Projection matrix ___________________________
var projectionMatrix;
// ___ Create matrix ___
{
const fieldOfView = toRadians( 70 );
const aspect = gl.canvas.clientWidth / gl.canvas.clientHeight;
const zNear = 0.1;
const zFar = 1000.0;
projectionMatrix = glMatrix.mat4.create();
glMatrix.mat4.perspective(
projectionMatrix,
fieldOfView,
aspect,
zNear,
zFar
);
}
// ___ Assign matrix ___
{
gl.useProgram( program );
gl.uniformMatrix4fv(
projectionMatrixUniformLocation,
false,
projectionMatrix
);
gl.useProgram( null );
}
}
function programRender ()
{
// Clear the canvas
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
// Hmmm
gl.useProgram( program );
gl.bindVertexArray( vao );
gl.enableVertexAttribArray( positionAttributeLocation );
gl.enableVertexAttribArray( normalAttributeLocation );
gl.uniform3f( lightPositionUniformLocation, light.position.x, light.position.y, light.position.z );
gl.uniform3f( lightColorUniformLocation, light.color.x, light.color.y, light.color.z );
// Update
entity.rotation.x += 0.5;
entity.rotation.y += 0.5;
// Update uniforms
loadViewMatrix();
loadTransformationMatrix();
// Draw
var primitiveType = gl.TRIANGLES;
// var primitiveType = gl.LINE_STRIP;
var count = 36;
var type = gl.UNSIGNED_SHORT;
var offset = 0;
gl.drawElements(
primitiveType,
count,
type,
offset
);
// Hmmm
gl.disableVertexAttribArray( positionAttributeLocation );
gl.disableVertexAttribArray( normalAttributeLocation );
gl.bindVertexArray( null );
gl.useProgram( null );
}
function bindAttributeLocations ( program )
{
positionAttributeLocation = 0;
normalAttributeLocation = 1;
gl.bindAttribLocation( program, positionAttributeLocation, 'position' );
gl.bindAttribLocation( program, normalAttributeLocation, 'normal' );
}
function loadToVAO ()
{
// Create a vertex array object ( attribute state )
vao = gl.createVertexArray();
// and make it the one we're currently working with
gl.bindVertexArray( vao );
{
// Create a buffer and put three 2d clip space points in it
var positionBuffer = gl.createBuffer();
// Bind it to ARRAY_BUFFER ( think of it as ARRAY_BUFFER = positionBuffer )
gl.bindBuffer( gl.ARRAY_BUFFER, positionBuffer );
var positions = [
// Front face
-1.0, -1.0, 1.0,
1.0, -1.0, 1.0,
1.0, 1.0, 1.0,
-1.0, 1.0, 1.0,
// Back face
-1.0, -1.0, -1.0,
-1.0, 1.0, -1.0,
1.0, 1.0, -1.0,
1.0, -1.0, -1.0,
// Top face
-1.0, 1.0, -1.0,
-1.0, 1.0, 1.0,
1.0, 1.0, 1.0,
1.0, 1.0, -1.0,
// Bottom face
-1.0, -1.0, -1.0,
1.0, -1.0, -1.0,
1.0, -1.0, 1.0,
-1.0, -1.0, 1.0,
// Right face
1.0, -1.0, -1.0,
1.0, 1.0, -1.0,
1.0, 1.0, 1.0,
1.0, -1.0, 1.0,
// Left face
-1.0, -1.0, -1.0,
-1.0, -1.0, 1.0,
-1.0, 1.0, 1.0,
-1.0, 1.0, -1.0,
];
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array( positions ),
gl.STATIC_DRAW
);
// look up where the vertex data needs to go.
// var positionAttributeLocation = gl.getAttribLocation( program, "position" );
// Turn on the attribute
// gl.enableVertexAttribArray( positionAttributeLocation );
// Tell the attribute how to get data out of positionBuffer ( ARRAY_BUFFER )
var size = 3; // 2 components per iteration
var type = gl.FLOAT; // the data is 32bit floats
var normalize = false; // don't normalize the data
var stride = 0; // 0 = move forward size * sizeof( type ) each iteration to get the next position
var offset = 0; // start at the beginning of the buffer
gl.vertexAttribPointer(
positionAttributeLocation,
size,
type,
normalize,
stride,
offset
);
//
gl.bindBuffer( gl.ARRAY_BUFFER, null );
}
{
// Create a buffer and put three 2d clip space points in it
var normalBuffer = gl.createBuffer();
// Bind it to ARRAY_BUFFER ( think of it as ARRAY_BUFFER = normalBuffer )
gl.bindBuffer( gl.ARRAY_BUFFER, normalBuffer );
var normals = [
// Front
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
0.0, 0.0, 1.0,
// Back
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
0.0, 0.0, -1.0,
// Top
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
0.0, 1.0, 0.0,
// Bottom
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
0.0, -1.0, 0.0,
// Right
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
1.0, 0.0, 0.0,
// Left
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0,
-1.0, 0.0, 0.0
];
gl.bufferData(
gl.ARRAY_BUFFER,
new Float32Array( normals ),
gl.STATIC_DRAW
);
// look up where the vertex data needs to go.
// var normalAttributeLocation = gl.getAttribLocation( program, "normal" );
// Turn on the attribute
// gl.enableVertexAttribArray( normalAttributeLocation );
// Tell the attribute how to get data out of normalBuffer ( ARRAY_BUFFER )
var size = 3; // 2 components per iteration
var type = gl.FLOAT; // the data is 32bit floats
var normalize = false; // don't normalize the data
var stride = 0; // 0 = move forward size * sizeof( type ) each iteration to get the next normal
var offset = 0; // start at the beginning of the buffer
gl.vertexAttribPointer(
normalAttributeLocation,
size,
type,
normalize,
stride,
offset
);
//
gl.bindBuffer( gl.ARRAY_BUFFER, null );
}
{
var indexBuffer = gl.createBuffer();
gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, indexBuffer );
var indices = [
0, 1, 2, 0, 2, 3, // front
4, 5, 6, 4, 6, 7, // back
8, 9, 10, 8, 10, 11, // top
12, 13, 14, 12, 14, 15, // bottom
16, 17, 18, 16, 18, 19, // right
20, 21, 22, 20, 22, 23, // left
];
gl.bufferData(
gl.ELEMENT_ARRAY_BUFFER,
new Uint16Array( indices ),
gl.STATIC_DRAW
)
}
//
gl.bindVertexArray( null );
}
var loadViewMatrix = function ()
{
var viewMatrix;
// ___ Create matrix ___
{
viewMatrix = glMatrix.mat4.create();
glMatrix.mat4.identity( viewMatrix );
// Rotate
glMatrix.mat4.rotate(
viewMatrix, // destination matrix
viewMatrix, // matrix to rotate
toRadians( camera.rotation.x ), // amount to rotate in radians
[ 1, 0, 0 ], // axis to rotate around
);
glMatrix.mat4.rotate(
viewMatrix, // destination matrix
viewMatrix, // matrix to rotate
toRadians( camera.rotation.y ), // amount to rotate in radians
[ 0, 1, 0 ], // axis to rotate around
);
glMatrix.mat4.rotate(
viewMatrix, // destination matrix
viewMatrix, // matrix to rotate
toRadians( camera.rotation.z ), // amount to rotate in radians
[ 0, 0, 1 ], // axis to rotate around
);
// Translate
// something about camera opposite direction...
glMatrix.mat4.translate(
viewMatrix, // destination matrix
viewMatrix, // matrix to translate
[ // amount to translate
- camera.position.x,
- camera.position.y,
- camera.position.z,
]
);
}
// ___ Assign matrix ___
{
gl.uniformMatrix4fv(
viewMatrixUniformLocation,
false,
viewMatrix
);
}
}
function loadTransformationMatrix ()
{
var transformationMatrix;
// ___ Create matrix ___
{
transformationMatrix = glMatrix.mat4.create();
// Translate
glMatrix.mat4.translate(
transformationMatrix, // destination matrix
transformationMatrix, // matrix to translate
[ // amount to translate
entity.position.x,
entity.position.y,
entity.position.z,
]
);
// Rotate
glMatrix.mat4.rotate(
transformationMatrix, // destination matrix
transformationMatrix, // matrix to rotate
toRadians( entity.rotation.x ), // amount to rotate in radians
[ 1, 0, 0 ], // axis to rotate around
);
glMatrix.mat4.rotate(
transformationMatrix, // destination matrix
transformationMatrix, // matrix to rotate
toRadians( entity.rotation.y ), // amount to rotate in radians
[ 0, 1, 0 ], // axis to rotate around
);
glMatrix.mat4.rotate(
transformationMatrix, // destination matrix
transformationMatrix, // matrix to rotate
toRadians( entity.rotation.z ), // amount to rotate in radians
[ 0, 0, 1 ], // axis to rotate around
);
// Scale
glMatrix.mat4.scale(
transformationMatrix, // destination matrix
transformationMatrix, // matrix to scale
[ // amount to scale
entity.scale.x,
entity.scale.y,
entity.scale.z
]
);
}
// ___ Assign matrix ___
{
gl.uniformMatrix4fv(
transformationMatrixUniformLocation,
false,
transformationMatrix
);
}
}
function createShader ( type, source )
{
var shader = gl.createShader( type );
gl.shaderSource( shader, source );
gl.compileShader( shader );
var success = gl.getShaderParameter( shader, gl.COMPILE_STATUS );
if ( success )
{
return shader;
}
console.log( gl.getShaderInfoLog( shader ) ); // eslint-disable-line
gl.deleteShader( shader );
return undefined;
}
function createProgram ( vertexShader, fragmentShader )
{
var program = gl.createProgram();
gl.attachShader( program, vertexShader );
gl.attachShader( program, fragmentShader );
bindAttributeLocations( program );
gl.linkProgram( program );
var success = gl.getProgramParameter( program, gl.LINK_STATUS );
if ( success )
{
return program;
}
console.log( gl.getProgramInfoLog( program ) ); // eslint-disable-line
gl.deleteProgram( program );
return undefined;
}
function toRadians ( deg )
{
return deg * Math.PI / 180;
}
|
import React, {Fragment, PureComponent} from 'react';
import {StyleSheet, View, Text, TouchableOpacity, Image} from 'react-native';
import {SvgXml} from 'react-native-svg';
const TALK = [
{
img: '../images/1.jpeg',
title: '사랑의 불시착',
content: `사랑의 불시착 와 내일 한다 드디어!!! 내일 주말이니까 하루종일
침대에 누워서 넷플릭스 봐야지 ㅇㅎㅎ`,
type: '자유게시판',
},
];
export default class CardList extends PureComponent {
constructor(props) {
super(props);
this.state = {};
}
_intoDetail = () => {
this.props.navigation.navigate('Detail');
};
_getList = (datas) => {
return datas.map((data, index) => {
return (
<TouchableOpacity
style={[talks.gridBox,{marginVertical:this.props.itemMarginVertical || 0}]}
key={index}
onPress={this.props.nav}>
{/* {data.img == null ? null : <View style={talks.image}></View>} */}
{index % 2 != 1 ? (
<Image
source={require('../images/3.jpeg')}
style={{width: 60, height: 60}}
resizeMode="contain"
/>
) : null}
<View style={{flex: 8}}>
<View style={{flexDirection: 'row', width: '100%'}}>
<View style={{flex: 1}}>
<Text style={{fontSize: 15, fontWeight: 'bold'}}>
{data.title}
</Text>
</View>
<View
style={{
alignItems: 'flex-end',
}}>
<Text style={{fontSize: 10, color: 'lightgray'}}>
{data.type}
</Text>
</View>
</View>
<View style={{marginTop: 12}}>
<Text numberOfLines={2} style={{fontSize: 12, color: 'gray'}}>
{data.content}
</Text>
</View>
</View>
</TouchableOpacity>
);
});
};
render() {
return (
<Fragment>
<View style={[talks.talks,this.props.style || {}]}>
{/* 헤더 */}
<View style={talks.header}>
{this.props.title ? (
<View style={{flex: 9, justifyContent: 'center'}}>
<Text style={talks.headerTitle}>{this.props.title}</Text>
</View>
) : null}
<TouchableOpacity
onPress={this.props.more}
style={{flex: 1, justifyContent: 'center'}}>
<Text style={{fontSize: 10, color: '#6B6B6B'}}>더보기</Text>
</TouchableOpacity>
</View>
<View>{this._getList(this.props.datas)}</View>
</View>
</Fragment>
);
}
}
const talks = StyleSheet.create({
talks: {},
header: {
flexDirection: 'row',
marginBottom:8,
marginHorizontal:16
},
headerTitle: {
fontSize: 16,
fontWeight: 'bold',
color: '#1d1d1d',
},
gridBox: {
backgroundColor: 'white',
borderRadius: 10,
padding: 15,
flexDirection: 'row',
//
shadowColor: '#000',
shadowOffset: {
width: 0,
height: 5,
},
shadowOpacity: 0.1,
shadowRadius: 3.84,
elevation: 5,
},
image: {
width: 60,
height: 60,
backgroundColor: 'white',
borderRadius: 5,
marginRight: 10,
flex: 1.8,
},
});
|
// Dependencies
const exp = require('constants');
const express = require('express');
const path = require('path');
const fs = require("fs");
const { v4: uuidv4 } = require('uuid');
// Sets up the Express App
const app = express();
const PORT = process.env.PORT || 3000;
// Sets up the Express app to handle data parsing
app.use(express.urlencoded({ extended: true}));
app.use(express.json());
app.use(express.static('public'));
// API Routes
// GET Request
app.get("/api/notes", (req, res) => {
let data = JSON.parse(fs.readFileSync("db/db.json", "utf8",));
res.json(data);
});
// POST Request
app.post("/api/notes", (req, res) => {
const newNote = req.body;
newNote.id = uuidv4();
let data = JSON.parse(fs.readFileSync("db/db.json", "utf8",));
data.push(newNote);
fs.writeFileSync('./db/db.json', JSON.stringify(data));
res.json(data);
})
// HTML Routes
app.get('/notes', function(req, res) {
res.sendFile(path.join(__dirname, "./public/notes.html"));
});
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, "./public/index.html"));
});
// Sets up server to begin listening
app.listen(PORT, () =>
console.log('App listening on PORT: ' + PORT)
);
|
import { Platform } from 'react-native';
import { Navigation } from 'react-native-navigation';
// screen related book keeping
import { registerScreens } from './screens';
registerScreens();
const createTabs = () => {
const tabs = [
{
label: 'ProfileScreen',
screen: 'ProfileScreen',
icon: require('../img/profile.png'),
selectedIcon: require('../img/profile_selected.png'),
title: 'Profile',
navigatorStyle: {
navBarBackgroundColor: '#415DAE',
navBarTextColor: '#fff'
}
},
{
label: 'ToDoScreen',
screen: 'ToDoScreen',
icon: require('../img/todo.png'),
selectedIcon: require('../img/todo_selected.png'),
title: 'To Do List',
navigatorStyle: {
navBarBackgroundColor: '#415DAE',
navBarTextColor: '#fff'
}
},
{
label: 'PageViewScreen',
screen: 'PageViewScreen',
icon: require('../img/scene.png'),
selectedIcon: require('../img/scene_selected.png'),
title: 'Page View Controller',
navigatorStyle: {
navBarBackgroundColor: '#415DAE',
navBarTextColor: '#fff'
}
},
{
label: 'MapScreen',
screen: 'MapScreen',
icon: require('../img/map.png'),
selectedIcon: require('../img/map_selected.png'),
title: 'Maps',
navigatorStyle: {
navBarBackgroundColor: '#415DAE',
navBarTextColor: '#fff'
}
}
];
/*
if (Platform.OS === 'android') {
tabs.push({
label: 'Collapsing',
screen: 'example.CollapsingTopBarScreen',
icon: require('../img/one.png'),
title: 'Collapsing',
});
}
*/
return tabs;
};
// this will start our app
Navigation.startTabBasedApp({
tabs: createTabs()
});
/*
import React, { Component } from 'react';
import { LoginButton, AccessToken, GraphRequest, GraphRequestManager } from 'react-native-fbsdk';
import { View, Text } from 'react-native';
import { Header, styles } from './components/common'; // Actually importing from ./components/common/index.js, but index is automattic
const user = [];
class Login extends Component {
test() {
console.log('Name: ', user.name);
console.log('Id: ', user.id);
}
render() {
return (
<View>
<LoginButton
publishPermissions={['publish_actions']}
onLoginFinished={
(error, result) => {
if (error) {
alert('Login failed with error: ', result.error)
} else if (result.isCancelled) {
alert('Login was cancelled')
} else {
AccessToken.getCurrentAccessToken().then(
(data) => {
var api = 'https://graph.facebook.com/v2.5/me?fields=email,name,friends&access_token=' + data.accessToken;
fetch(api)
.then((response) => response.json())
.then((json) => {
user.name = json.name;
user.id = json.id;
this.test();
// user.user_friends = json.friends;
// user.email = json.email;
// user.username = json.name;
// user.loading = false;
// user.loggedIn = true;
// console.log('User ID:', data.user);
// // user.avatar = setAvatar(json.id);
})
.catch(() => {
reject('ERROR GETTING DATA FROM FACEBOOK')
});
}
);
}
}
}
onLogoutFinished={() => alert('User logged out')}
/>
</View>
);
}
}
class App extends Component {
render() {
return (
<View style={{ backgroundColor: '#4099FF', flex: 1 }}>
<Header headerText="Facebook Login" />
<View style={styles.containerCenter}>
<Login />
<Text>
{user.name}
</Text>
</View>
</View>
);
}
}
export default App;
*/
|
const puppeteer = require("puppeteer");
const { get } = require("request");
const express = require("express");
const app = express();
app.get("/", function (req, res) {
res.send("E O TREM BALAAAA");
});
app.get("/alt", function (res, res) {
res.send("Pagina dos ALT");
});
app.listen(8081, function () {
console.log("Servidor rodando na url http://localhost8081");
});
|
require("../../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/packageA/sec_hand_m/new_house_trend/main" ], {
1697: function(e, n, t) {
var o = t("e336");
t.n(o).a;
},
"8c82": function(e, n, t) {
t.r(n);
var o = t("95b48"), r = t("96cb");
for (var c in r) [ "default" ].indexOf(c) < 0 && function(e) {
t.d(n, e, function() {
return r[e];
});
}(c);
t("1697");
var a = t("f0c5"), u = Object(a.a)(r.default, o.b, o.c, !1, null, "5796b67d", null, !1, o.a, void 0);
n.default = u.exports;
},
"95b48": function(e, n, t) {
t.d(n, "b", function() {
return o;
}), t.d(n, "c", function() {
return r;
}), t.d(n, "a", function() {});
var o = function() {
var e = this;
e.$createElement;
e._self._c;
}, r = [];
},
"96cb": function(e, n, t) {
t.r(n);
var o = t("d1e5"), r = t.n(o);
for (var c in o) [ "default" ].indexOf(c) < 0 && function(e) {
t.d(n, e, function() {
return o[e];
});
}(c);
n.default = r.a;
},
d1e5: function(e, n, t) {
function o(e, n) {
var t = Object.keys(e);
if (Object.getOwnPropertySymbols) {
var o = Object.getOwnPropertySymbols(e);
n && (o = o.filter(function(n) {
return Object.getOwnPropertyDescriptor(e, n).enumerable;
})), t.push.apply(t, o);
}
return t;
}
function r(e) {
for (var n = 1; n < arguments.length; n++) {
var t = null != arguments[n] ? arguments[n] : {};
n % 2 ? o(Object(t), !0).forEach(function(n) {
c(e, n, t[n]);
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : o(Object(t)).forEach(function(n) {
Object.defineProperty(e, n, Object.getOwnPropertyDescriptor(t, n));
});
}
return e;
}
function c(e, n, t) {
return n in e ? Object.defineProperty(e, n, {
value: t,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[n] = t, e;
}
Object.defineProperty(n, "__esModule", {
value: !0
}), n.default = void 0;
var a = function(e) {
return e && e.__esModule ? e : {
default: e
};
}(t("1e6c")), u = function(e) {
return {
towards: Number(e) > 0,
value: (100 * Math.abs(Number(e))).toFixed(2) || 0
};
}, i = {
data: function() {
return {
item: {},
zones: {
current_month: "",
items: []
}
};
},
onReady: function() {
this.getLastMonth(), this.getZones();
},
components: {
DetailNav: function() {
t.e("pages/packageA/sec_hand_m/new_house_trend/components/_nav").then(function() {
return resolve(t("afca"));
}.bind(null, t)).catch(t.oe);
},
Trend: function() {
Promise.all([ t.e("pages/packageA/common/vendor"), t.e("pages/packageA/sec_hand_m/new_house_trend/components/_trend") ]).then(function() {
return resolve(t("7a55"));
}.bind(null, t)).catch(t.oe);
},
Percent: function() {
t.e("pages/packageA/sec_hand_m/new_house_trend/components/_percent").then(function() {
return resolve(t("5dc1"));
}.bind(null, t)).catch(t.oe);
}
},
methods: {
getLastMonth: function() {
var e = this;
a.default.getLastMonth().then(function(n) {
e.item = r({
avg_price: Number(n.avg_price).toFixed(1),
current_month: n.current_month
}, u(n.mom));
});
},
getZones: function() {
var e = this;
a.default.getZones().then(function(n) {
e.zones.current_month = n.current_month, e.zones.items = n.items.map(function(e) {
var n = e.mom, t = e.avg_price, o = e.zone;
return r({
avg_price: Number(t).toFixed(1),
zone: o
}, u(n));
});
});
},
goDetail: function(e, n) {
wx.navigateTo({
url: "/pages/packageA/sec_hand_m/new_house_trend/detail?current_month=".concat(n, "&zone=").concat(e.zone, "&avg_price=").concat(e.avg_price, "&towards=").concat(e.towards, "&value=").concat(e.value)
});
}
}
};
n.default = i;
},
e336: function(e, n, t) {}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/packageA/sec_hand_m/new_house_trend/main-create-component", {
"pages/packageA/sec_hand_m/new_house_trend/main-create-component": function(e, n, t) {
t("543d").createComponent(t("8c82"));
}
}, [ [ "pages/packageA/sec_hand_m/new_house_trend/main-create-component" ] ] ]); |
const inquirer = require("inquirer");
const mysql = require("mysql");
//set up a connection to mysql
var connection = mysql.createConnection({
host:"localhost",
user:"root",
password: "7%#ll3R#R@nF#90^T&!e",
database: "employee_tracker_DB"
})
connection.connect(function(err){
if(err) throw err
})
//----------------------------------------
//use inquirer to prompt user for information
function firstQuestion(){
inquirer.prompt(
{
name:"firstQuestion",
message:"What would you like to do?",
type:"list",
choices:["View all employees","View all employees by manager","View all employees by department","Add employee","Remove employee","Update employee role","View departments","Add departments","Delete departments","View roles","Add roles","Delete roles"]
}
).then((answer)=>{
switch(answer.firstQuestion){
case "View all employees":
viewAllEmployees();
break;
case "View all employees by manager":
employeeByManager()
break;
case "View all employees by department":
employeeByDepartment()
break;
case "Add employee":
addEmployee();
break;
case "Remove employee":
deleteEmployee()
break;
case "Update employee role":
updateEmployeeRole()
break;
case "View departments":
viewDepartment()
break;
case "Add departments":
addDepartment()
break;
case "Delete departments":
deleteDepartment()
break;
case "View roles":
viewRole()
break;
case "Add roles":
addRole()
break;
case "Delete roles":
deleteRole()
break;
}
})
};
//-------------------------------------------------------------------
function addDepartment(){
inquirer.prompt([
{
name:"name",
message:"What is the name of the department you want to add?",
type:"input"
}
]).then((answer)=>{
connection.query(`INSERT INTO department (name) VALUES ('${answer.name}')`,function(err,data){
if(err) throw err
choiceToContinue()
})
})
}
//----------------------------------------------------
function viewDepartment(){
connection.query("SELECT * FROM department",function(err,data){
if(err) throw err
console.table(data)
choiceToContinue()
})
};
//---------------------------------------------------------
//function used to invoke the prompts when adding roles
function addRole_InquirerPrompt(departmentArray){
//Creating an array of department names based on what's currently in the sql database
var departmentChoicesArray = [];
for(let i in departmentArray){
departmentChoicesArray.push(departmentArray[i].name)
}
//-----
inquirer.prompt([
{
name:"title",
message:"What is the name of the role?",
type:"input"
},
{
name:"salary",
message:"What is this role's salary (must be in decimal format: $--.00)",
type:"input"
},
{
name:"department",
message:"What is the name of the department this role falls under?",
type:"list",
choices: departmentChoicesArray
}
]).then((answer)=>{
connection.query(`SELECT id FROM department WHERE name='${answer.department}'`,function(err,data){
if(err) throw err
connection.query(`INSERT INTO role (title,salary,department_id) VALUES('${answer.title}',${answer.salary},${data[0].id})`,function(err,data){
if(err) throw err
choiceToContinue()
})
})
})
}
//function used to add roles to the role database
function addRole(){
connection.query("SELECT * FROM department",function(err,data){
if(err) throw err
addRole_InquirerPrompt(data)
})
};
//--------------------------------------------------------
function viewRole(){
connection.query("SELECT * FROM role",function(err,data){
if(err) throw err
console.table(data)
choiceToContinue()
})
};
//--------------------------------------------------------
function inquirerForAE(arg1,arg2,arg3){
inquirer.prompt([
{
name:"firstName",
message:"What's the employees first name?",
type:"input"
},
{
name:"lastName",
message:"What's the employees last name?",
type:"input"
},
{
name:"employeeRole",
message:"What is the employees role/title?",
type:"list",
choices: arg1
},
{
name:"employeeManager",
message:"What manager will this employee fall under (If this is employee is the manager select his title)?",
type:"list",
choices: arg2
}
]).then((answer)=>{
for(let k in arg3){
if(arg3[k].title===answer.employeeRole && !answer.employeeManager.includes("N/A") && !answer.employeeRole.includes("N/A")){
connection.query(`SELECT id FROM role WHERE title='${answer.employeeManager}'`,function(err,managerData){
if(err) throw err
connection.query(`INSERT INTO employee (first_name,last_name,role_id,manager_id) VALUES('${answer.firstName}','${answer.lastName}',${arg3[k].id},${managerData[0].id})`,function(err,insertData){
if(err) throw err
choiceToContinue()
})
})
}else{
}
}
if(answer.employeeRole==="N/A (If role not available go back and select 'Add a new role')" || answer.employeeManager==="N/A (if manager not available go back and select 'Add a new role'. Make sure to include the work 'Manager' in the role title)"){
addRole()
}
})
}
//--------------------------------------------------------
function addEmployee(){
connection.query("SELECT title, id FROM role",function(err,roleData){
if(err) throw err
var roleDataTitleArray = ["N/A (If role not available go back and select 'Add a new role')"];
for(let i in roleData){
roleDataTitleArray.push(roleData[i].title)
};
var managerDataIdArray = ["N/A (if manager not available go back and select 'Add a new role'. Make sure to include the work 'Manager' in the role title)"];
for(let j in roleData){
if(roleData[j].title.includes("Manager")){
managerDataIdArray.push(roleData[j].title)
}
};
switch(managerDataIdArray.length>0){
case false:
inquirer.prompt([
{
name:"noManager",
message:"It looks like you dont't have any managers in your roles table. You need at least one manager to to begin updating your employees table. Would you like to go back and add a manager? (If you do, make sure to include the word 'Manager' in the roles name)",
type:"list",
choices:["Yes","No"]
}
]).then((answer1)=>{
if(answer1.noManager==="Yes"){
addRole()
}else{
choiceToContinue()
}
})
break;
case true:
inquirerForAE(roleDataTitleArray,managerDataIdArray,roleData)
}
})
};
//-------------------------------------------------------------
function viewAllEmployees(){
//this will be a query to the database
connection.query("SELECT * FROM employee", function(err,data){
console.table(data)
choiceToContinue()
})
}
//-------------------------------------------------------------
function choiceToContinue(){
inquirer.prompt({
name:"continue",
message:"Would you like to continue editing data?",
type:"list",
choices:["Yes","No"]
}).then((answer)=>{
if(answer.continue==="Yes"){
firstQuestion()
}else{
console.log("press 'Ctrl+c' to exit Node...")
return
}
})
}
//---------------------------------------
function deleteDepartment(){
connection.query("SELECT name FROM department",function(err,departmentData){
//Creating an array of department names based on what's currently in the sql database
var departmentChoicesArray = [];
for(let i in departmentData){
departmentChoicesArray.push(departmentData[i].name)
}
//-------
inquirer.prompt([{
name:"delete",
message:"Which department would you like to remove from the database?",
type:"list",
choices:departmentChoicesArray
}]).then(answer=>{
connection.query(`DELETE FROM department WHERE name='${answer.delete}'`,function(err,deletionData){
if(err) throw err
choiceToContinue()
})
})
})
}
//----------------------------------------------
function deleteRole(){
connection.query("SELECT title FROM role",function(err,roleData){
//Creating an array of department names based on what's currently in the sql database
var roleChoicesArray = [];
for(let i in roleData){
roleChoicesArray.push(roleData[i].title)
}
//-------
inquirer.prompt([{
name:"delete",
message:"Which role would you like to remove from the database?",
type:"list",
choices:roleChoicesArray
}]).then(answer=>{
connection.query(`DELETE FROM role WHERE title='${answer.delete}'`,function(err,deletionData){
if(err) throw err
choiceToContinue()
})
})
})
}
//---------------------------------------------
function deleteEmployee(){
connection.query("SELECT * FROM employee",function(err,employeeData){
//Creating an array of department names based on what's currently in the sql database
var employeeChoicesArray = [];
for(let i in employeeData){
employeeChoicesArray.push(employeeData[i].first_name+" "+employeeData[i].last_name)
}
//-------
inquirer.prompt([{
name:"delete",
message:"Which employee would you like to remove from the database?",
type:"list",
choices:employeeChoicesArray
}]).then(answer=>{
var answerArray = answer.delete.split(" ")
connection.query(`DELETE FROM employee WHERE first_name ='${answerArray[0]}' AND last_name='${answerArray[1]}'`,function(err,employeeData){
if(err) throw err
choiceToContinue()
})
})
})
}
//---------------------------------------------
function employeeByManager(){
connection.query("SELECT * FROM employee",function(err,data){
EBMInquirer(data)})
}
//--------------------------------------------
function EBMInquirer(data1){
var managerNames = ["Not enough managers to choose from. I'd like to add more employees"]
for(let i in data1){
managerNames.push(data1[i].first_name+" "+data1[i].last_name)
}
inquirer.prompt([
{
name:"manager",
message:"Which employee do you want to see direct reports for?",
type:"list",
choices:managerNames
}
]).then((answer)=>{
var managerNameArray = answer.manager.split(" ");
if(answer.manager==="Not enough managers to choose from. I'd like to add more employees"){
addEmployee()
}
for(let j in data1){
if(data1[j].first_name===managerNameArray[0]&&data1[j].last_name===managerNameArray[1]){
var managerId = data1[j].role_id;
connection.query(`SELECT * FROM employee WHERE manager_id='${managerId}'`,function(err,data2){
if(err) throw err
console.table(data2)
choiceToContinue()
})
}}
/*
for(let j in data1){
if(data1[j].first_name===managerNameArray[0]&&data1[j].last_name===managerNameArray[1]){
var managerId = data1[j].role_id;
connection.query(`SELECT * FROM employee WHERE manager_id='${managerId}'`,function(err,data2){
if(err) throw err
console.table(data2)
//choiceToContinue()
})
}else if(answer.manager==="Not enough managers to choose from"){
//addEmployee()
choiceToContinue()
}
}*/
})
}
//---------------------------------------------
function employeeByDepartment(){
connection.query("SELECT * FROM department",function(err,data){
var departmentArray = ["Not enough departments to choose from"]
for(let i in data ){
departmentArray.push(data[i].name)
}
inquirer.prompt([
{
name:"departmentName",
message:"Which department would you like to see employees for?",
type:"list",
choices:departmentArray
}
]).then((answer)=>{
for(let k in data){
if(answer.departmentName==="Not enough departments to choose from"){
addDepartment()
}
if(answer.departmentName===data[k].name){
var departmentId = data[k].id
connection.query(`SELECT id FROM role WHERE department_id='${departmentId}'`,function(err,roleId){
connection.query(`SELECT * FROM employee INNER JOIN role ON employee.role_id=role.id WHERE role.department_id=${departmentId}`,function(err,innerJoinTable){
if(err) throw err
console.table(innerJoinTable);
choiceToContinue();
})
})
}
}
})
})
}
//----------------------------------------------------
function updateEmployeeRole(){
connection.query("SELECT * FROM employee",function(err,data){
var nameArray = ["Not enough employees to choose from"]
for(let i in data){
nameArray.push(data[i].first_name+" "+data[i].last_name)
}
inquirer.prompt([
{
name:"employee",
message:"Which employee's role do you want to update?",
type:"list",
choices:nameArray
}
]).then(answer=>{
if(answer.employee==="Not enough employees to choose from"){
addEmployee()
}
connection.query(`SELECT * FROM role`,function(err,roleData){
var roleTitleArray = ["Not enough roles to choose from"]
for(let j in roleData){
roleTitleArray.push(roleData[j].title)
}
inquirer.prompt([
{
name:"role",
message:"Which role do you want to assign the selected employee?",
type:"list",
choices:roleTitleArray
}
]).then(answer2=>{
if(answer2.role==="Not enough roles to choose from"){
addRole()
}
for(let k in roleData ){
if(answer2.role===roleData[k].title){
var roleId= roleData[k].id
}
}
connection.query(`UPDATE employee SET role_id=${roleId} WHERE first_name='${answer.employee.split(" ")[0]}' AND last_name='${answer.employee.split(" ")[1]}'`,function(err,data){
if(err) throw err
choiceToContinue();
})
})
})
})
})
}
//call first question function
firstQuestion() |
import React from 'react';
import Coin from './Coin'
import Styles from './CoinList.module.scss';
const CoinList = (props) => {
return (
<div className={Styles.coinsContainer}>
<div className={Styles.coinList}>
{
props.coins && props.coins.map((value, index) => <Coin key={index} coin={value}/>)
}
</div>
</div>
)
}
export default CoinList; |
const { postTransfers, putTransfers } = require('./client')
const { ApiErrorCodes } = require('../models/errors')
const post = 'postTransfers'
const put = 'putTransfers'
const createParty = async (ctx) => {
if (!Object.prototype.hasOwnProperty.call(ctx.request.body, 'idValue')) {
ctx.response.body = ApiErrorCodes.MISSING_ID_VALUE
ctx.response.status = 500
return
}
try {
await ctx.state.model.party.create(ctx.request.body)
ctx.response.status = 204
return
} catch (err) {
ctx.response.body = ApiErrorCodes.ID_NOT_UNIQUE
ctx.response.status = 500
}
}
/**
* Handles all operation scenarios
*
* @param {Array} ops operation scenarios to test
* @returns {Promise.<Array|void|Boolean>} results
* @throws
*/
const handleOps = async (ops) => {
if (!Array.isArray(ops)) {
throw new Error(ApiErrorCodes.OPS_ERROR.message)
}
ops.forEach(async (op) => {
try {
const results = []
const { name, operation } = op
if (!(operation && (operation === post || operation === put))) {
return false
}
if (operation === post) {
const response = await postTransfers(op.body)
results.push({ name, operation, response })
}
if (operation === put) {
const response = await putTransfers(op.params.transferId)
results.push({ name, operation, response })
}
return results
} catch (error) {
throw error
}
})
}
const handleScenarios = async (ctx) => {
try {
const res = await handleOps(ctx.request.body)
if (res) {
ctx.response.body = res
ctx.response.status = 200
return
}
ctx.response.body = ApiErrorCodes.OP_NOT_SET
ctx.response.status = 400
return
} catch (err) {
ctx.response.body = ApiErrorCodes.OPS_ERROR
ctx.response.status = 500
}
}
const map = {
'/scenarios': {
post: handleScenarios
},
'/repository/parties': {
post: createParty
}
}
module.exports = {
map
}
|
(function(){
'use strict';
angular
.module('app')
.controller('mainController', mainController)
.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
mainController.$inject = ['$scope', '$http','$window'];
function mainController($scope, $http, $window)
{
$scope.product_line = 'women tops';
$scope.image_info = {};
$scope.image_url = '';
$scope.update_response = {};
$scope.loading_status = false;
$scope.image_links = [
"https://assets.myntassets.com/h_640,q_90,w_480/v1/assets/images/1329664/2016/4/28/11461839194506-Bhama-Couture-Women-Tops-2961461839193770-1.jpg",
"https://assets.myntassets.com/h_640,q_90,w_480/v1/assets/images/2172006/2017/10/12/11507791895870-plusS-Women-Grey-Solid-Top-2251507791895611-1.jpg",
"https://assets.myntassets.com/h_640,q_90,w_480/v1/assets/images/2286263/2017/11/28/11511860757348-na-1321511860757093-1.jpg",
"https://assets.myntassets.com/h_640,q_90,w_480/v1/assets/images/2029796/2017/8/8/11502193376933-ESPRIT-Women-Tops-2041502193376733-1.jpg",
"https://assets.myntassets.com/h_640,q_90,w_480/v1/assets/images/1543826/2016/9/21/11474447918879-Miss-Chase-Women-Tops-4691474447917923-1.jpg"
];
$scope.product_lines = ["women tops"];
$scope.submit = function (status) {
console.log("Inside submit function");
var image_url = $scope.image_url;
var product_line = $scope.product_line.split(" ").join("_");
if(image_url=='')
{
if(!status)
{
$scope.update_response = {"status" :false, message:"Please enter image link"}
return;
}
else
{
image_url = $scope.image_links[0];
}
}
$scope.loading_status = true;
$scope.image_info = {};
var baseUrl = "https://imagetag.in/image-tagging/get-attributes";
var parameter = {product_line:product_line, image_links:[image_url]};
var config={
'content-type': 'application/json'
};
$http.post(baseUrl, parameter, config).then(function (response) {
// This function handles success
$scope.loading_status = false;
var response_data = response.data;
console.log(response_data);
$scope.image_info = response_data;
$scope.image_url = '';
}, function (response) {
// this function handles error
$scope.update_response = {"status":false, "message":"Error while getting response from server, try again"}
$scope.loading_status = false;
$scope.image_url = '';
});
};
$scope.submit(true);
$scope.changeProductLine = function(pl)
{
$scope.product_line = pl;
}
$scope.getSelectedImage = function(img_url)
{
$scope.image_url = img_url;
$scope.submit();
}
$scope.uploadFile = function(files) {
console.log("Upload file");
$scope.loading_status = true;
$scope.image_info = {};
//Take the first selected file
var fd = new FormData();
fd.append("file", files[0]);
console.log(fd);
var uploadUrl = "https://imagetag.in/image-tagging/upload-files";
var config = {'content-type': undefined};
$http({
url: uploadUrl,
method: 'POST',
data: fd,
//assign content-type as undefined, the browser
//will assign the correct boundary for us
headers: config,
//prevents serializing payload. don't do it.
transformRequest: angular.identity
}).then(function (response) {
// This function handles success
$scope.loading_status = false;
var response_data = response.data;
console.log(response_data);
$scope.update_response = response_data;
if(response_data["type"]=="jpg")
{
$scope.image_url = response_data["message"];
$scope.submit();
}
}, function (response) {
// this function handles error
console.log("Error")
$scope.image_url = '';
$scope.loading_status = false;
$scope.update_response = {status : false, message : "Error while uploading the file"};
});
}
$scope.showAlert = function(message)
{
window.alert(message);
$scope.update_response.status = true;
}
$scope.contact_name ='';$scope.contact_email ='',$scope.contact_message = '';
$scope.contactMessage = function()
{
var username = $scope.contact_name;
var email = $scope.contact_email;
var message = $scope.contact_message;
var baseUrl = "https://imagetag.in/image-tagging/contact-us";
var parameter = {username:username, email:email, message: message};
var config={ 'content-type': 'application/json' };
$http.post(baseUrl, parameter, config).then(function (response) {
// This function handles success
var response_data = response.data;
$scope.showAlert("your query successfully submitted");
}, function (response) {
// this function handles error
});
}
}
})(); |
import React from 'react';
import { connect } from 'react-redux';
import store from '../../config/store';
class MovieForm extends React.Component {
componentWillMount() {
if(this.props.type === "new_movie") {
store.dispatch({
type: 'formData',
payload: {
fields: {id: store.getState().movies.Search.length+1,
Title: "",
Year: "",
new_movie: true
}
}
});
} else {
store.dispatch({
type: 'formData',
payload: {
fields: {id: this.props.id,
title: this.props.title,
year: this.props.year,
errors: this.props.errors
}
}
});
}
}
handleChange = (e) => {
store.dispatch({
type: 'formData',
payload: {
fields: {...store.getState().formData.fields , [e.target.name]: e.target.value}
}
});
}
render () {
const { fields, errors } = store.getState().formData;
return (
<React.Fragment>
<form>
{console.log("errorspage")}
{console.log(errors)}
{console.log(fields)}
{!!errors && <div><p>Please check the data you entered</p></div>}
<div className="form_inputs">
<label htmlFor="title">Title</label>
<input
name="title"
value={fields.title || ""}
onChange={this.handleChange}
id="title"
placeholder="Movie Title"
/>
{/* {console.log("formform")}
{console.log(errors)} */}
<span>{!!errors && !!errors.title && <div>{errors.title}</div>}</span>
</div>
<div className="form_inputs">
<label htmlFor="title">Year</label>
<input
name="year"
value={fields.year || ""}
onChange={this.handleChange}
id="year"
placeholder="Movie Year"
/>
<span>{!!errors && !!errors.year && <div>{errors.year}</div>}</span>
</div>
</form>
</React.Fragment>
)
}
}
function mapStateToProps(state){
return state;
}
export default connect(mapStateToProps)(MovieForm); |
import React, { useState } from "react";
import '../App.css';
function Home(){
const [submitted , setSubmitted] = useState(false);
const[valid, setValid] = useState(false);
const [values , setValues] = useState({
firstName:"",
lastName:"",
email:""
});
// const [firstName, setFirstName] = useState(null);
// const [lastName, setlastName] = useState(null);
// const [email, setEmail] = useState(null);
// const handleFirstNameChange = (event) => {
// setValues({...values, firstName:event.target.value})
// }
// const handleLastNameChange = (event) => {
// setValues({...values, lastName:event.target.value})
// }
// const handleEmailChange = (event) => {
// setValues({...values, email:event.target.value})
// }
const handleChange = prop => event => {
setValues({...values, prop: event.target.value})
}
const handleSubmit = (event) => {
event.preventDefault();
if ( values.firstName && values.lastName && values.email){
setValid(true)
}
setSubmitted(true);
}
console.log(values.firstName);
return(
<>
<h1>{values.firstName}</h1>
<div className = "form">
<form onSubmit = {handleSubmit}>
{submitted ? <div className="success-emerge">success</div>: null}
<input
value = {values.firstName}
onChange={() => handleChange('firstName')}
className="form-field"
placeholder="First Name"
name="firstName"></input>
<br/>
{submitted && !values.firstName ? <span>Please enter a first name</span> : null}
<br/>
<input
onChange={() => handleChange('lastName')}
value = {values.lastName}
className="form-field"
placeholder="Last Name"
name="lastName"></input>
<br/>
{submitted && !values.lastName ?<span>Please enter a last name</span> : null}
<br/>
<input
onChange={() => handleChange('email')}
value = {values.email}
className="form-field"
placeholder="Email"
name="email"></input>
<br/>
{submitted && !values.email ?<span>Please enter an email</span> : null}
<br/>
<button type="submit" className="submit">SUBMIT</button>
</form>
</div>
</>
);
}
export default Home; |
//import { dupa } from "./add"; // babel; instalacja paczki, pozniej rozdziel plioki na klasy++
DOMStrings = {
fields: document.querySelectorAll(".field"),
newGameBtn: document.querySelector(".btn"),
circle: '<i class="ion-android-radio-button-off"></i>',
cross: '<i class="ion-close-round"></i>',
symbolMenu: document.querySelector(".symbolMenu"),
symbolList: document.querySelectorAll(".symbolList li"),
info: document.querySelector(".turn"),
sendBtn: document.querySelector(".SubmitButton"),
mailDialog: document.querySelector(".MailDialog"),
openMailer: document.querySelector(".ContactIcon"),
closeMailer: document.querySelector(".CancelIcon"),
backdrop: document.querySelector(".Backdrop"),
mailFormDiv: document.querySelector(".mailFormDiv"),
mailStatus: document.querySelector(".StatusMail"),
mailStatusP: document.querySelector(".StatusMail p"),
loadingSpinner: document.querySelector(".Loader"),
emailAddressInput: document.getElementById("emailInput"),
messageInput: document.getElementById("msgInput"),
nameInput: document.getElementById("nameInput")
};
var gamePlaying, activePlayer, blockBoard;
board = [
"",
"",
"", // 0, 1, 2
"",
"",
"", // 3, 4, 5
"",
"",
"" // 6, 7, 8
];
winCombinations = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8], // rows
[0, 3, 6],
[1, 4, 7],
[2, 5, 8], // columns
[0, 4, 8],
[2, 4, 6] // diagonals
];
// Player class //
class Player {
moves = [];
constructor() {
this.name = "Gracz";
}
move = () => {};
}
// Computer class //
class Computer {
moves = [];
s;
indexes;
minimaxC = 0;
constructor() {
this.name = "Komputer";
}
move = () => {
blockBoard = true;
DOMStrings.info.classList.toggle("loading");
let time;
const length = this.getPossibleMoves(board).length;
// time for make move
length > 5 ? (time = 1000) : (time = 500);
setTimeout(() => {
if (length == 9) {
// First random item on the board full empty board
const indexes = board
.map((field, index) => (field === "" ? index : ""))
.filter(String);
this.fieldID = indexes[Math.floor(Math.random() * indexes.length)]; // Random item
this.s = `#_${this.fieldID}`;
} else {
const field = this.minimax(board, comp);
this.fieldID = field.index;
this.s = `#_${this.fieldID}`;
}
if (length > 0) {
board[this.fieldID] = this.name;
this.moves.push(this.fieldID);
document.querySelector(this.s).innerHTML = this.symbol;
Controller.whoWin(this.moves);
}
this.minimaxC = 0;
DOMStrings.info.classList.toggle("loading");
blockBoard = false;
Controller.switchPlayer();
}, time);
};
nextMovePossible = array => {
return array.filter(field => field === "").length > 0;
};
getPossibleMoves = array => {
return array.map((cur, index) => (cur === "" ? index : "")).filter(String);
};
getBoardForMove = (e, currentPlayer, array) => {
const copiedBoard = [...array];
copiedBoard[e] = currentPlayer.name;
return copiedBoard;
};
getFieldIndexes = (array, currentPlayer) => {
return array
.map((field, index) => (field === currentPlayer.name ? index : ""))
.filter(String);
};
checkIfWin = (array, player) => {
let board;
board = this.getFieldIndexes(array, player);
for (let i = 0; i < winCombinations.length; i++) {
var combination = winCombinations[i];
if (combination.every(index => board.indexOf(index) > -1)) {
return true;
} else {
continue;
}
}
};
// the main minimax function
minimax = (newBoard, actPlayer) => {
this.minimaxC++;
const possibleMoves = this.getPossibleMoves(newBoard);
if (this.checkIfWin(newBoard, player)) {
return { score: -10 };
} else if (this.checkIfWin(newBoard, comp)) {
return { score: 10 };
} else if (possibleMoves.length === 0) {
return { score: 0 };
}
// for collecting all moves
var minimoves = [];
for (let el of possibleMoves) {
// create a move object to store move (index, score)
var move = {};
move.index = el;
//set index of newboard to actPlayer
newBoard[el] = actPlayer.name;
if (actPlayer == comp) {
var result = this.minimax(newBoard, player);
move.score = result.score;
} else {
var result = this.minimax(newBoard, comp);
move.score = result.score;
}
//reset the spot to empty
newBoard[el] = "";
minimoves.push(move);
}
var bestMove;
// Get a high score move
if (actPlayer === comp) {
var bestScore = -100; // For checking if score is higher than this
for (var i = 0; i < minimoves.length; i++) {
if (minimoves[i].score > bestScore) {
bestScore = minimoves[i].score;
bestMove = i;
}
}
} else {
var bestScore = 100;
for (var i = 0; i < minimoves.length; i++) {
if (minimoves[i].score < bestScore) {
bestScore = minimoves[i].score;
bestMove = i;
}
}
}
return minimoves[bestMove];
};
}
// Create objects (players)
comp = new Computer();
player = new Player();
class Controller {
pickedSym;
IDSplit;
fieldID;
static switchPlayer = () => {
if (gamePlaying) {
activePlayer === player ? (activePlayer = comp) : (activePlayer = player);
DOMStrings.info.innerHTML = `Tura ${activePlayer.name}a`;
}
return activePlayer;
};
makeMove = () => {
DOMStrings.fields.forEach(el =>
el.addEventListener("click", function() {
if (gamePlaying && !blockBoard) {
if (el.innerHTML === "") {
el.innerHTML = activePlayer.symbol;
this.IDSplit = el.getAttribute("id");
this.fieldID = parseInt(this.IDSplit[1]);
activePlayer.moves.push(this.fieldID);
board[this.fieldID] = activePlayer.name;
Controller.whoWin(activePlayer.moves);
Controller.switchPlayer();
comp.move();
}
}
})
);
};
clearMailInputs = () => {
DOMStrings.emailAddressInput.value = "";
DOMStrings.nameInput.value = "";
DOMStrings.messageInput.value = "";
};
// Setup events
setup = () => {
DOMStrings.newGameBtn.addEventListener("click", function() {
DOMStrings.symbolMenu.classList.toggle("hidden");
});
DOMStrings.symbolList.forEach(el =>
el.addEventListener("click", function() {
this.pickedSym = el.innerHTML;
console.log(`Gracz wybral ${this.pickedSym}`);
if (this.pickedSym === DOMStrings.cross) {
activePlayer = player;
player.symbol = this.pickedSym;
comp.symbol = DOMStrings.circle;
console.log(`Rozpoczyna ${activePlayer.name}`);
} else {
activePlayer = comp;
comp.symbol = DOMStrings.cross;
player.symbol = DOMStrings.circle;
console.log(`Rozpoczyna ${activePlayer.name}`);
}
// Clear fields
Controller.newGame();
if (activePlayer === comp) {
comp.move();
}
})
);
// DOMStrings.openMailer.addEventListener("click", () => {
// if (DOMStrings.mailDialog.className.includes("Close")) {
// DOMStrings.mailDialog.classList.remove("Close");
// DOMStrings.mailDialog.classList.add("Open");
// DOMStrings.backdrop.classList.toggle("hidden");
// } else {
// DOMStrings.mailDialog.classList.remove("Open");
// DOMStrings.mailDialog.classList.add("Close");
// }
// });
// DOMStrings.closeMailer.addEventListener("click", () => {
// DOMStrings.mailDialog.classList.remove("Open");
// DOMStrings.mailDialog.classList.add("Close");
// DOMStrings.backdrop.classList.toggle("hidden");
// });
// // DOMStrings.sendBtn.addEventListener('click', this.sendHandler())
// DOMStrings.sendBtn.addEventListener("click", () => {
// this.sendHandler();
// });
// DOMStrings.backdrop.addEventListener("click", () => {
// DOMStrings.mailDialog.classList.remove("Open");
// DOMStrings.mailDialog.classList.add("Close");
// DOMStrings.backdrop.classList.toggle("hidden");
// });
};
// sendHandler = () => {
// //paste to senFeedback (template , ...)
// const templateId = "template_uMFom1rL";
// const emailAddress = DOMStrings.emailAddressInput.value;
// const message = DOMStrings.messageInput.value;
// const name = DOMStrings.nameInput.value;
// if (emailAddress !== "" && message !== "" && name !== "") {
// this.sendFeedback(templateId, {
// message_html: message,
// from_name: name,
// from_email: emailAddress
// });
// }
// };
// sendFeedback(templateId, variables) {
// DOMStrings.mailFormDiv.classList.toggle("hidden");
// DOMStrings.loadingSpinner.classList.toggle("hidden");
// window.emailjs
// .send("gmail", templateId, variables)
// .then(res => {
// DOMStrings.loadingSpinner.classList.toggle("hidden");
// if (res.text === "OK") {
// DOMStrings.mailStatusP.innerHTML = "Email send successfully!";
// DOMStrings.mailStatus.classList.add("Green");
// this.clearMailInputs();
// }
// })
// .catch(error => {
// console.log(error);
// DOMStrings.mailStatusP.innerHTML =
// "Something went wrong with sending email. Please try again... ;(";
// DOMStrings.mailStatus.classList.add("Red");
// });
// DOMStrings.mailStatus.classList.toggle("hidden");
// setTimeout(() => {
// DOMStrings.mailFormDiv.classList.toggle("hidden");
// DOMStrings.mailStatus.classList.toggle("hidden");
// }, 3000);
// }
static newGame = () => {
DOMStrings.fields.forEach(el => (el.innerHTML = ""));
DOMStrings.symbolMenu.classList.toggle("hidden");
player.moves = [];
comp.moves = [];
board = ["", "", "", "", "", "", "", "", ""];
gamePlaying = true;
blockBoard = false;
DOMStrings.info.innerHTML = `Rozpoczyna ${activePlayer.name}`;
};
static whoWin = array => {
let winner;
winCombinations.forEach(combination => {
if (combination.every(index => array.indexOf(index) > -1)) {
winner = activePlayer.name;
if (winner === "Komputer") {
Swal.fire({
title: "Przegrałeś!",
text: "Spróbuj jeszcze raz!",
imageUrl: "images/sadEmoji.png",
imageHeight: "50",
confirmButtonText: "OK!"
});
} else {
Swal.fire({
title: "Wygrałeś!",
text: "Gratulacje! Chcesz zagrać ponownie?",
imageUrl: "images/happyEmoji.png",
imageHeight: "50",
confirmButtonText: "OK!"
});
}
DOMStrings.info.innerHTML = `Wygrał ${winner}`;
gamePlaying = false;
} else if (!board.includes("") && winner === undefined) {
Swal.fire({
title: "Remis!",
text: "Spróbuj jeszcze raz!",
confirmButtonText: "OK!"
});
gamePlaying = false;
DOMStrings.info.innerHTML = `Remis`;
}
});
return winner;
};
}
cntr = new Controller();
cntr.setup();
cntr.makeMove();
|
//MAICO
//START VARIABLES
//var -- it can be updated and also can be re-declared || var keyword two types of scope global and function not block level scope
//let -- it can be updated and also cannot be re-declared || let keyword support function and block level scope
//const -- it cannot be updated and also cannot be re-declared || const keyword support function and block level scope
// const course = "zero to hero"
// //course="qwe" -- cannot update value
// console.log(course)
// function abv()
// {
// const x = 20
// console.log(x)
// }
// abv()
// const x = 30
// console.log(x)
// //block scope
// if(1==1){
// let y = "block scope"
// console.log(y)
// }
// console.log(x)
//END VARIABLES
/*****************************************************************************************************************************************/
//START DATA TYPES
// //number
// var x = 10.66 //number limit +-(253-1)
// console.log(typeof x)
// //big int
// var y = 999999999999999990n //n means big int
// console.log(typeof y)
// //string
// var name = "jhonejay"
// console.log(typeof name)
// //boolean
// var isMonday = true
// console.log(typeof isMonday)
// //undefined
// var w
// console.log(typeof w)
// //objects
// var obj={}
// console.log(typeof obj)
// var arr={}
// console.log(typeof arr)
// //symbol
// var sym = Symbol("id")
// console.log(typeof sym)
// //null
// var x = 10
// x = null
// console.log(typeof x)
// //String() Boolean()
// console.log(typeof new String("qwe"))
//END DATA TYPE
/*****************************************************************************************************************************************/
//START NULL VS UNDEFINED
//equality comparision
//normal comparision
//strict comparision
//1. Normal comparision || only compare value
// console.log(3==3)
// console.log("parba" == "parba")
// //2. strict comparision(===)
// //compare value + data type
// console.log(3===3)
// //NULL vs UNDEFINED
// var x
// console.log(x)
// var y = null
// console.log(y)
// console.log(x==y)
//END NULL VS UNDEFINED
/*****************************************************************************************************************************************/
//START SPREAD OPERATOR
// //1 Array
// var arr = ["a","b","c"]
// console.log(arr)
// //array index start from zero
// console.log(arr[0])
// console.log(arr[1])
// arr.push("3")
// console.log(arr)
// //object
// var obj = {
// "name": "salesforce",
// "age": 23,
// "fullname": "JHONE JAY PARBA"
// }
// console.log(obj.age)
// console.log(obj["fullname"])
// obj.hobbies = "test"
// console.log(obj)
// //1. Expanding of string
// let greeting = "Hello Everyone"
// let charList = [...greeting]
// console.log(charList)
// //2. Combing array
// let arr1 = ["amazon", "google"]
// let arr2 = ["facebook", "instagram"]
// let arr3 = [...arr1,...arr2]
// console.log(arr3)
// //3. adding values to an array
// let arr4 = ["a","b","c"]
// let arr5 = [...arr4,"test"]
// console.log(arr5)
// //4. combining objects
// let obj1 = {
// name: "salesforce",
// age:23,
// date: "12-12-2021"
// }
// let obj2 = {
// name : "facebook",
// age:35,
// test : "01-01-2022"
// }
// let obj3 = {...obj1, ...obj2}
// console.log(obj3)
// //5. Shallow Copy
// var arr10 = ["x","y","z"]
// var arr11 = [...arr10]
// arr11.push("test")
// console.log(arr10)
// console.log(arr11)
// //6. Nested copy
// var arrObj = [
// {
// name : "nikhil"
// },
// {
// name: "salesforce"
// }
// ]
// // var arrObj1 = [...arrObj]
// // console.log( arrObj1)
// // arrObj1[0].name = "superman"
// // console.log(arrObj1)
// // console.log(arrObj)
// //Hack for nested copy
// var arrObj1 = JSON.parse(JSON.stringify(arrObj))
// arrObj1[0].name = "superman"
// console.log(arrObj1)
// console.log(arrObj)
//END SPREAD OPERATOR
/*****************************************************************************************************************************************/
//START destructuring
// //array destructuring
// let arr = ["amazon", "google"]
// // let company1 = arr[0]
// // let company2 = arr[1]
// let [company1, company2] = arr
// console.log(company1)
// console.log(company2)
// //object destructing
// let options ={
// title: "zero to hero",
// age: 23,
// type : "CRM"
// }
// // var title = options.title
// // var age = options.age
// let {title,age, type} = options
// console.log(title)
// console.log(age)
// console.log(type)
//END destructuring
/*****************************************************************************************************************************************/
// //START STRING INTERPOLATIOn
// var name ="jhone jay parba"
// var age = "24"
// //console.log(name+age)
// var str = "my name is " + name + " and my age is " + age
// console.log(str)
// console.log(`my name is ${name} and my age is ${age}`)
// var a = 1
// var b = 2
// var str1 = "the sum of " + a + " and " + b + " is " + a+b
// console.log(str1)
// console.log(`the sum of ${a} and ${b} is ${a+b}`)
// //END STRING INTERPOLATIOn
/*****************************************************************************************************************************************/
// //START String methods
// let str = "Hello guys I hope your are doing good"
// //1. Includes()
// let check = str.includes("hope")
// console.log(check)
// //2. indexof
// let index = str.indexOf("doing")
// console.log(index)
// //3. Startwith
// console.log(str.startsWith("Hello"))
// //4.slice
// console.log(str.slice(0,5))
// //5. toLowerCase
// console.log(str.toLowerCase())
// //6. toUpperCase
// console.log(str.toUpperCase())
// //7.trim
// console.log(" trim this string ".trim().toUpperCase())
//END String methods
/*****************************************************************************************************************************************/
//START Object/JSON Operations
// let obj={
// name : "Salesforce",
// age: 23,
// dob:"23/10/1990"
// }
// //object.keys()
// console.log(Object.keys(obj))
// //object.values()
// console.log(Object.values(obj))
// //json.stringify
// console.log(JSON.stringify(obj))
// //json.parse
// console.log(JSON.parse(JSON.stringify(obj)))
//END Object/JSON Operations
/*****************************************************************************************************************************************/
//START ARRAY METHODS
// let arr = [2,3,5,7,9,10]
// //map()
// //syntax
// // arr.methodName(function(currentItem,index,actualarray)
// // {
// // })
// let newArray = arr.map(function(currentItem, index, array)
// {
// //console(index)
// console.log(`currentItem is ${currentItem} index ${index} array ${array}`)
// return currentItem*2
// })
// console.log(newArray)
// //filter()
// let filteredValues = arr.filter(function(currentItem, index,array){
// return currentItem > 5
// })
// console.log(filteredValues)
// //every()
// let age = [32,33,18,40]
// let isAllAdult = age.every(function(currentItem){
// return currentItem >= 18
// })
// console.log(isAllAdult)
// //some()
// let ageList = [32,33,18,40]
// let isAdult = ageList.some(function(currentItem){
// return currentItem > 32
// })
// console.log(isAdult)
// //sort()
// var names = ["test","qwe", "asd"]
// console.log(names.sort())
// //sorting of numbers
// var points = [10,11,54,23,64,1]
// let sortedvalue = points.sort(function(a,b){
// return a-b
// })
// console.log(sortedvalue)
// //reduce methods
// // array.reduce(fucntion(total, currentValue, index, array){
// // }, initialValue)
// let num = [12, 78, 30]
// let sum = num.reduce(function(total, currentItem){
// return total+currentItem
// },0)
// console.log(sum)
// //forEach
// num.forEach(function(currentItem){
// console.log(currentItem)
// })
//END ARRAY METHODS
/*****************************************************************************************************************************************/
//START PROMISE
//is an object that may produce a single value sometime in the future
//are used to handle asynchronous operations is JS
//pending()
// function checkIsSuccess(data)
// {
// return new Promise(function(resolve,reject){
// if(data== "success")
// {
// return resolve("successfully executed")
// }
// return reject("unsuccessfully executed")
// })
// }
// checkIsSuccess('success').then(function(result){
// console.log(result)
// }).catch(function(error){
// console.error(error)
// })
// //console.log(checkIsSuccess('success'))
// fetch('https://api.github.com/users/karkranikhil').then(function(result){
// console.log(result)
// })
//END PROMISE
/*****************************************************************************************************************************************/
//MODULE IMPORTS AND EXPORTS
//export
//import minus, {PI2, add2} from './utils.js' - import by functions
// import * as UTILS from './utils.js' // - import all function inside JS
// console.log(UTILS.PI2)
// console.log(UTILS.add(5,3))
// console.log(UTILS.minus(5,3))
/*****************************************************************************************************************************************/
//QUERY SELECTOR
// let element = document.querySelector('div')
// console.log(element)
// element.style.color="red"
// let elementAll = document.querySelectorAll('div')
// console.log(elementAll)
// Array.from(elementAll).forEach(function(item){
// item.style.color="green"
// })
/*****************************************************************************************************************************************/
//EVENTS
// function firstFunction()
// {
// console.log("click success")
// }
// let btn = document.querySelector("button")
// btn.addEventListener("click",firstFunction)
// document.addEventListener("mousemove",handler)
// function handler()
// {
// document.querySelector(".demo").innerHTML = Math.random()
// }
// function removeHandler()
// {
// document.removeEventListener("mousemove",handler)
// }
// document.addEventListener("Hello", function(data){
// console.log("hello was called and send", data.detail)
// })
// function callCustomMethod()
// {
// let event = new CustomEvent("Hello",{
// detail:
// {
// name: "jhonejay"
// }
// })
// document.dispatchEvent(event)
// }
/*****************************************************************************************************************************************/
//ARROW FUNCTIONS
// function abc()
// {
// console.log("hello")
// }
// abc()
// const abc = () => console.log("hello")
// abc()
// function sum (data)
// {
// let sum = data + 10
// return sum
// }
// console.log(sum(4))
// const sum = (data) =>
// {
// let sum = data + 10
// return sum
// }
// console.log(sum(5))
// const qwe = (data1,data2) => data1+data2+10
// console.log(qwe(5,5))
// var arr = [1,2,3,4]
// let newArr = arr.map((item) => item*2)
// console.log(newArr)
//problem solved by arrow function
// let obj =
// {
// name1: "jhonejay",
// getName: function()
// {
// console.log(this.name1)
// const fullname = () =>
// {
// console.log("my full name is "+ this.name1 + " parba")
// }
// fullname()
// }
// }
// obj.getName()
/*****************************************************************************************************************************************/
//SetTimeout
// let timerID = window.setTimeout(function()
// {
// console.log("hello")
// },2000)
// console.log(timerID)
// clearTimeout(timerID)
// //SetInterval
// let intervalID = window.setInterval(function(){
// console.log("hello")
// },1000)
// clearInterval(intervalID)
/*****************************************************************************************************************************************/ |
({
doInit : function(component, event, helper) {
var action = component.get("c.getUnits");
action.setCallback(this, function(results){
var State = results.getState();
console.log('State: '+State);
if(State == 'SUCCESS'){
component.set("v.unit",results.getReturnValue());
console.log(results.getReturnValue());
}
});
$A.enqueueAction(action);
},
handleApplicationEvent : function(component, event, helper) {
var unit = event.getParam("unit");
component.set("v.unit", unit);
}
// controller na mag geget ng value sa event
}) |
require('newrelic')
const mongoose = require('mongoose');
const db = require('../database/index.js');
module.exports = {
getAll: function(callback) {
console.log('getAll Model');
db.imageInfo.find({}).exec(callback);
},
getByPlace: function(params, callback) {
console.log('get image by placeid');
db.imageInfo.find({listingId: Math.ceil(Math.random()*10000000)}).exec(callback);
}
};
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import {Helmet} from "react-helmet";
import VcitaPic from "../assests/vCita-new-clients.gif"
import AddClientsPic from "../assests/add-clients.png"
import NewClientsPic from "../assests/new-client.png"
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
}
}));
export default function FullWidthGrid() {
const classes = useStyles();
return (
<div className={classes.root}>
<Helmet>
<meta charSet="utf-8" />
<title>vCita</title>
<meta name="description" content="vCita accounts to manage patients information and online appointments"></meta>
</Helmet>
<Grid container spacing={0} className="pt-md-5 py-xs-5 mt-xs-3 mt-md-5 vCita-Page-container">
<Grid item xs={12} sm={12} md={7} className="vCita-new-clients-h1-col text-right pr-md-5 pb-md-5">
<h1 className="vCita-new-clients-h1 text-right pr-xs-2">
خطوات انشاء حساب للمراجعين
</h1>
</Grid>
<Grid item xs={11} sm={11} md={7} className="vCita-new-clients-steps-img-col pr-md-5 py-xs-1">
<img className="vCita-new-clients-steps-img w-100 px-xs-2" src={VcitaPic}></img>
</Grid>
<Grid item xs={11} sm={11} md={7} className="vCita-new-clients-steps-list-col pr-md-5">
<ul className="vCita-new-clients-steps-list text-right">
<li className="item">
New Client ثم أضغط Clients الخطوة الاولى: أضغط على زر
</li>
<li className="item">
<img className="add-client-pic w-100" src={AddClientsPic} alt="add clients to vCita"/>
</li>
<li className="item">
أملأ معلومات المراجع
</li>
<li className="item">
لحفظ معلومات المراجعين Save أضغط
</li>
<li className="item">
تم حفظ الحساب الجديد
</li>
<li className="item">
<img className="add-client-pic w-100" src={NewClientsPic} alt="New clients"/>
</li>
</ul>
</Grid>
</Grid>
</div>
);
}
|
var sliders = function () {
$(".range_01").ionRangeSlider({
min: 1,
max: 12,
});
};
var autoScroll = function () {
$(".home-menu-item").on("click", function (e) {
e.preventDefault();
var link = "#" + $(this).find("div").text().toLowerCase();
$("html,body").animate(
{
scrollTop: $(link).offset().top - 30,
},
"slow"
);
});
$(".contact-link").on("click", function (e) {
e.preventDefault();
var link = $(this).attr("href");
$("html,body").animate(
{
scrollTop: $(link).offset().top - 55,
},
"slow"
);
});
};
function selectionPicker() {
basecost = parseInt($("span.price").text());
var updatePrice = function () {
optioncount = $(".page-selector li.selected").length * 10;
pagesnum = parseInt($(".irs-single").text());
optionsarray = [];
$(".page-selector li.selected").each(function () {
optionsarray.push($(this).attr("data-item"));
});
if (pagesnum <= 10) {
switch (true) {
case pagesnum <= 1:
$(".pricing-meta").html(
"Uw Pagina Voor Ongeveer <i class='icon-question-sign'></i>"
);
total = optioncount + basecost;
break;
case pagesnum <= 3:
$(".pricing-meta").html(
"Uw Pagina's Voor Ongeveer <i class='icon-question-sign'></i>"
);
// 15% extra per pagina
total = (1 + pagesnum * 0.15) * (optioncount + basecost);
break;
case pagesnum <= 5:
// 25% extra per pagina
total = (1 + pagesnum * 0.25) * (optioncount + basecost);
break;
case pagesnum <= 7:
// 32% extra per pagina
total = (1 + pagesnum * 0.35) * (optioncount + basecost);
break;
case pagesnum <= 10:
$(".pricing-meta").html(
"Uw Pagina's Voor Ongeveer <i class='icon-question-sign'></i>"
);
$(".price-tenure").text("Vaste Prijs!");
// 40% extra per pagina
total = (1 + pagesnum * 0.45) * (optioncount + basecost);
break;
default:
break;
}
$(".price").text(parseInt(total));
$("#template-contactform-options").val(
pagesnum +
" pagina's | " +
optioncount / 10 +
" opties (" +
optionsarray +
") | +-" +
parseInt(total) +
" euro"
);
} else {
$(".pricing-meta").text("Contacteer mij");
$(".price-tenure").text("Voor een offerte!");
$(".price-special").text("???");
$("#template-contactform-options").val("Special Quote");
}
};
$(".page-selector li").on("click", function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
updatePrice();
});
$(".range_01").on("change", updatePrice);
}
function add(a, b) {
return a + b;
}
function selectionPickerEn() {
basecost = parseInt($("span.price").text());
var updatePrice = function () {
optioncount = $(".page-selector li.selected").length * 10;
pagesnum = parseInt($(".irs-single").text());
optionsarray = [];
$(".page-selector li.selected").each(function () {
optionsarray.push($(this).attr("data-item"));
});
if (pagesnum <= 10) {
switch (true) {
case pagesnum <= 1:
$(".pricing-meta").html(
"Your Page For About <i class='icon-question-sign'></i>"
);
total = optioncount + basecost;
break;
case pagesnum <= 3:
$(".pricing-meta").html(
"Your Pages For About <i class='icon-question-sign'></i>"
);
// 15% extra per pagina
total = (1 + pagesnum * 0.2) * (optioncount + basecost);
break;
case pagesnum <= 5:
// 25% extra per pagina
total = (1 + pagesnum * 0.3) * (optioncount + basecost);
break;
case pagesnum <= 7:
// 32% extra per pagina
total = (1 + pagesnum * 0.4) * (optioncount + basecost);
break;
case pagesnum <= 10:
$(".pricing-meta").html(
"Your Pages For About <i class='icon-question-sign'></i>"
);
$(".price-tenure").text("Fixed Pricing!");
// 40% extra per pagina
total = (1 + pagesnum * 0.5) * (optioncount + basecost);
break;
default:
break;
}
$(".price").text(parseInt(total));
$("#template-contactform-options").val(
pagesnum +
" pages | " +
optioncount / 10 +
" options (" +
optionsarray +
") | +-" +
parseInt(total) +
" dollar"
);
} else {
$(".pricing-meta").text("Contact Me");
$(".price-tenure").text("For A Custom Quote!");
$(".price-special").text("???");
$("#template-contactform-options").val("Special Quote");
}
};
$(".page-selector li").on("click", function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
updatePrice();
});
$(".range_01").on("change", updatePrice);
}
function add(a, b) {
return a + b;
}
function selectionPicker2() {
service = $("#wrapper > div > div.heading-block.center > h2").text();
basecost = parseInt($("span.price").text());
var updatePrice = function () {
optioncount = $(".page-selector li.selected").length;
optionsarray = [];
pricings = [];
$(".page-selector li.selected").each(function () {
optionsarray.push($(this).attr("data-item"));
var price = parseInt($(this).attr("data-price"));
pricings.push(price);
});
optiontotal = $(pricings.reduce(add, 0));
if (optiontotal.length > 0) {
total = parseInt(optiontotal[0]) + basecost;
} else {
total = basecost;
}
$(".price").text(total);
$("#template-contactform-options").val(
service +
" | " +
pricings.length +
" options (" +
optionsarray +
") | +-" +
parseInt(total) +
" euro"
);
};
$(".page-selector li").on("click", function () {
if ($(this).hasClass("selected")) {
$(this).removeClass("selected");
} else {
$(this).addClass("selected");
}
updatePrice();
});
}
var fancyFade = function () {
$(".contact-special").on("click", function () {
$(".col-hidden").fadeIn(500);
$("html,body").animate(
{
scrollTop: $("#contact").offset().top - 60,
},
"slow"
);
$(".which-articles-wrapper").fadeOut();
});
};
function createForm() {
$(".table-fade").slideUp();
$(".create-form").fadeIn();
$("html,body").animate(
{
scrollTop: $("#createForm").offset().top - 60,
},
"slow"
);
}
function closeForm() {
$(".create-form").slideUp();
$(".table-fade").slideDown();
$("html,body").animate(
{
scrollTop: 0,
},
"slow"
);
}
function getText() {
$(".locale-nl")
.find(".trumbowyg-editor")
.on("input DOMSubtreeModified click", function () {
value = $(".locale-nl").find(".trumbowyg-editor").html();
$(".form-nl #article_body").val(value);
});
$(".trumbowyg-editor").height(500);
}
function getText2() {
$(".locale-en")
.find(".trumbowyg-editor")
.on("input DOMSubtreeModified click", function () {
value = $(".locale-en").find(".trumbowyg-editor").html();
$(".form-en #article_en_body").val(value);
});
$(".trumbowyg-editor").height(500);
}
function getText3() {
$(".locale-nl")
.find(".trumbowyg-editor")
.on("input DOMSubtreeModified click", function () {
value = $(".locale-nl").find(".trumbowyg-editor").html();
$(".form-nl #page_body").val(value);
});
$(".trumbowyg-editor").height(500);
}
var showOptions = function () {
$(".subscribe #mce-EMAIL, .subscribe #mce-FNAME").on("change", function () {
if ($(this).val() != "") {
$(this).closest("form").find("div.which-articles-wrapper").fadeIn();
}
if ($(this).val() == "") {
$(this).closest("form").find("div.which-articles-wrapper").fadeOut();
}
});
};
// If it's a phone, don't show tooltips
if ($(window).width() < 768) {
$("[data-original-title]").each(function () {
$(this).removeAttr("data-toggle", "data-placement");
});
}
function changeLocale() {
$(".change-locale").on("click", function (e) {
$(".locale-menu").toggleClass("nl").toggleClass("en");
$(".locale-field").toggleClass("col-hidden");
});
}
function loadArticle() {
var text_nl = $(".form-nl #article_body").val();
$(".locale-nl").find(".trumbowyg-editor").html(text_nl);
var text_en = $(".form-en #article_en_body").val();
$(".locale-en").find(".trumbowyg-editor").html(text_en);
}
function loadPage() {
var text_nl = $(".form-nl #page_body").val();
$(".locale-nl").find(".trumbowyg-editor").html(text_nl);
}
function unleash_unicorn() {
$(".unleash-fluffy-rainbow-unicorn").on("click", function (e) {
e.preventDefault();
$("img.unicorn").addClass("active");
setTimeout(function () {
$("img.unicorn").removeClass("active");
}, 19000);
});
}
;
|
var brightRow = [];
var setBrightRow = [];
var darkRow = [];
var setDarkRow = [];
var bgDefault = [];
var txtDefault = [];
var profiles = [];
//name element for saving
var profName;
var profilesCombo;
function Profile(brightColors, normalColors, bg, text ){
this.NormalColors = normalColors;
this.BrightColors = brightColors;
this.BackGround = bg;
this.TextColor = text;
}
//color
var DefaultNormalColors = ['#000000', '#800000', '#008000', '#808000', '#000080', '#800080', '#008080', '#C0C0C0'];
var DefaultBrightColors = ['#808080', '#FF0000', '#00FF00', '#FFFF00', '#0000FF', '#FF00FF', '#00FFFF', '#FFFFFF' ];
function createColorWidget(){
profiles = JSON.parse(localStorage.getItem("colorProfiles"));
profName = document.getElementById('profileName');
profilesCombo = document.getElementById('profiles');
var br = document.getElementById('bright');
var currEl;
var colors = term.getColors();
//label the bright colors cell
br.appendChild(createCell("Bright Colors", undefined, "label"));
//create color elements
for( idx in colors.bright ){
currEl = createCell( undefined, colors.bright[idx]);
//save reference to the element for later use
brightRow.push(currEl);
br.appendChild(currEl);
}
br = br.nextElementSibling;
//add spacer
br.appendChild(createCell( undefined, undefined, "spacer"));
for( idx in colors.bright ){
currEl = createCell();
var txt = createInputField(colors.bright[idx]);
currEl.appendChild(txt);
setBrightRow.push(txt);
br.appendChild(currEl);
}
br = br.nextElementSibling;
// dark colors
br.appendChild(createCell("Normal Colors", undefined, "label"));
for( idx in colors.dark ){
currEl = createCell( undefined, colors.dark[idx]);
darkRow.push(currEl);
br.appendChild(currEl);
}
br = br.nextElementSibling;
br.appendChild(createCell(undefined, undefined, "spacer"));
for( idx in colors.dark ){
currEl = createCell();
var txt = createInputField(colors.dark[idx]);
currEl.appendChild(txt);
setDarkRow.push(txt);
br.appendChild(currEl);
}
//background
br = br.nextElementSibling;
br.appendChild(createCell("background", undefined, 'label'));
//create the color cell
currEl = createCell(undefined, term.background, undefined);
bgDefault.push(currEl);
br.appendChild(currEl);
//text color
br.appendChild(createCell('Text Color', undefined, 'label'));
currEl = createCell(undefined, term.getTextDefault(), undefined);
txtDefault.push(currEl);
br.appendChild(currEl);
//color selector
br = br.nextElementSibling;
br.appendChild(createCell(undefined, undefined, 'spacer'));
currEl = createCell();
var txt = createInputField(term.background);
currEl.appendChild(txt);
bgDefault.push(txt);
br.appendChild(currEl);
//text color selector
br.appendChild(createCell(undefined, undefined, 'spacer'));
currEl = createCell();
var txt = createInputField(term.getTextDefault());
currEl.appendChild(txt);
txtDefault.push(txt);
br.appendChild(currEl);
if( profiles == null ){
profiles = {};
SaveProfile("default");
}else{
for( name in profiles ){
profilesCombo.appendChild(createOption(name));
}
}
loadProfile();
setColors();
}
function createOption( name ){
var el = document.createElement('option');
el.value = name;
el.innerHTML = name;
return el;
}
function createCell( text, bg, className ){
var el = document.createElement('td');
if( text == undefined ){
text = "";
}
el.innerHTML = text;
el.style.background = bg;
el.className = className;
return el;
}
function createInputField(text ){
var el = document.createElement('input');
el.type = 'text';
el.value = text;
return el;
}
function showColorSelector(){
document.getElementById('colors').style.display = 'block';
}
function hideColorSelector(){
document.getElementById('colors').style.display = 'none';
}
function createProfile( ){
var bColors = [];
var dColors = [];
for( idx in setBrightRow ){
bColors.push(setBrightRow[idx].value);
dColors.push(setDarkRow[idx].value);
}
var txtDef = txtDefault[1].value;
var bgDef = bgDefault[1].value;
return new Profile( bColors, dColors, bgDef, txtDef);
}
function setColors(){
var bColors = [];
var dColors = [];
for( idx in setBrightRow ){
bColors.push(setBrightRow[idx].value);
dColors.push(setDarkRow[idx].value);
}
term.setColors(bColors, dColors);
var txtDef = txtDefault[1].value;
var bgDef = bgDefault[1].value;
term.setTerminalDefaults(bgDef, txtDef);
}
function getKeyboard(){
document.getElementById('copybuff').focus();
}
function SaveProfile(){
if( profName.value == ""){
//do nothing for now
return;
}
profiles[profName.value] = createProfile( ) ;
localStorage.setItem('colorProfiles', JSON.stringify(profiles));
profilesCombo.appendChild(createOption(profName.value));
}
function loadProfile(){
var prof = profiles[profilesCombo.value];
for( i in brightRow ){
brightRow[i].style.background = prof.BrightColors[i];
setBrightRow[i].value = prof.BrightColors[i];
darkRow[i].style.background = prof.NormalColors[i];
setDarkRow[i].value = prof.NormalColors[i];
}
bgDefault[0].style.background = prof.BackGround;
bgDefault[1].value = prof.BackGround;
txtDefault[0].style.background = prof.TextColor;
txtDefault[1].value = prof.TextColor;
};
function clearProfiles(){
localStorage.removeItem('colorProfiles');
}
|
const gulp = require('gulp');
gulp.task('css', function() {
gulp.src('build/static/css/*.css')
.pipe(gulp.dest('./css'));
});
gulp.task('js', function() {
gulp.src('build/static/js/*.js')
.pipe(gulp.dest('./js'));
});
gulp.task('ico', function() {
gulp.src('build/favicon.ico')
.pipe(gulp.dest('./'))
});
gulp.task('default', ['css', 'js', 'ico']);
|
class HelloWorld {
constructor(message) {
this.message = message;
}
getMessage() {
return this.message;
}
}
let helloWorld = new HelloWorld('ES6 can compile');
document.querySelector('.es6').innerHTML = helloWorld.getMessage();
|
import React, { useContext } from "react";
import {
Text,
View,
StyleSheet,
Image,
TouchableOpacity
} from "react-native";
// Contexts
import { UserContext } from 'contexts/UserContext';
export default function Setting({
icon,
text,
textColor,
onPress,
windowWidth,
windowHeight,
}) {
const settingMarginSides = windowWidth * 0.05;
const settingMarginTopBottom = windowWidth * 0.03;
const descMargin = windowWidth * 0.03;
const fontColor = textColor == undefined ? "black" : textColor;
const { userData } = useContext(UserContext);
const { isLightTheme } = userData;
const styles = StyleSheet.create({
icon: {
resizeMode: "contain",
width: 50,
height: 50,
},
iconDescGroup: {
flexDirection: "row",
alignItems: "center",
},
setting: {
alignItems: "center",
justifyContent: "center",
flexDirection: "row",
justifyContent: "space-between",
marginLeft: settingMarginSides,
marginRight: settingMarginSides,
marginTop: settingMarginTopBottom,
padding: 5,
backgroundColor: '#EEE',
},
desc: {
marginLeft: descMargin,
color: fontColor,
},
});
return (
<TouchableOpacity style={styles.setting} onPress={onPress}>
<View style={styles.iconDescGroup}>
<Image source={icon} style={styles.icon} />
<Text style={styles.desc}>{text}</Text>
</View>
<Text>{">"}</Text>
</TouchableOpacity>
);
}
|
import React from "react"
import styled from "styled-components"
import { useStaticQuery, graphql, navigate } from "gatsby"
import Headline3 from "../Headlines/Headline3"
import TransformationResultCard from "../Cards/TransformationResultCard"
import BaseButton from "../Shared/Buttons/BaseButton"
import { above } from "../../styles/Theme"
const TransformationSection = () => {
const query = graphql`
query {
transformations: allFile(
filter: {
sourceInstanceName: { eq: "HomeCopy" }
name: { regex: "/Transformation/" }
}
) {
nodes {
childMarkdownRemark {
html
frontmatter {
photoId
name
image {
childImageSharp {
fluid(maxWidth: 200, maxHeight: 200, quality: 90) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
}
`
const data = useStaticQuery(query)
const cards = data.transformations.nodes.map(card => {
const id = card.childMarkdownRemark.frontmatter.photoId
const name = card.childMarkdownRemark.frontmatter.name
const result = card.childMarkdownRemark.html
const image =
card.childMarkdownRemark.frontmatter.image.childImageSharp.fluid
return (
<TransformationResultCard
key={id}
id={id}
name={name}
result={result}
image={image}
/>
)
})
const handleButtonClick = () => navigate("/14for14Trial")
return (
<SectionContainer>
<Headline3>When We Burn Fat... We Burn Fat!</Headline3>
<CardsContainer>{cards}</CardsContainer>
<Headline3>If These Women Can Do It... You Can Too!</Headline3>
<ButtonContainer>
<BaseButton handleClick={handleButtonClick}>
Get My 14 Day Trial!
</BaseButton>
</ButtonContainer>
</SectionContainer>
)
}
export default TransformationSection
const SectionContainer = styled.div`
margin: 80px 0 0 0;
padding: 0 12px;
display: flex;
flex-direction: column;
width: 100%;
max-width: 800px;
${above.mobile`
margin: 120px 0 0 0;
`}
`
const CardsContainer = styled.div`
margin: 40px 0;
display: grid;
grid-template-columns: 1fr;
row-gap: 8px;
width: 100%;
max-width: 800px;
${above.mobile`
grid-template-columns: 1fr 1fr;
max-width: 800px;
`}
`
const ButtonContainer = styled.div`
margin: 40px 0 0 0;
display: flex;
justify-content: center;
width: 100%;
`
|
const ApiRoutes = {
'all': 'http://localhost:8000/api/notes/all/',
'regular': 'http://localhost:8000/api/notes/regular/',
'image': 'http://localhost:8000/api/notes/image/',
'url': 'http://localhost:8000/api/notes/url/',
'link': 'http://localhost:8000/api/notes/url/',
'trash': 'http://localhost:8000/api/notes/trash/'
};
export { ApiRoutes } |
import gql from "graphql-tag";
export default gql`
query GetUserPosts ($nextToken: String) {
getUserPosts(limit:10, nextToken:$nextToken) {
items {
id
username
profilePic {
bucket
region
key
}
caption
createdAt
likes
liked
file {
bucket
region
key
}
tags
}
nextToken
}
}` |
const express = require('express')
const app = express()
app.use(express.json())
const projects = []
app.use((req, res, next) => {
console.count("Quantidade Requisições")
next()
})
//Middleware que checa se o projeto existe
function checkProjectExists(req, res, next){
const { id } = req.params
const project = projects.find(p => p.id == id)
if (!project){
return res.status(404).json({ message: "Project not found" })
}
next()
}
//Middleware que checa se foi passado id no corpo da requisição
function checkProjectID(req, res, next){
if (!req.body.id){
return res.status(400).json({ message: "Id project not found" })
}
next()
}
//Middleware que checa se foi passado title no corpo da requisição
function checkProjectTitle(req, res, next){
if (!req.body.title){
return res.status(400).json({ message: "Title project not found" })
}
next()
}
//Retorna todos os projetos cadastrados
app.get('/projects', (req, res) => {
return res.json(projects)
})
//Cria um novo projeto
app.post('/projects', checkProjectID, checkProjectTitle, (req, res) => {
const { id, title } = req.body
const project = {
id,
title,
tasks:[]
}
projects.push(project)
return res.json(project)
})
//Altera o título de um projeto
app.put('/projects/:id', checkProjectExists, checkProjectTitle, (req, res) => {
const { id } = req.params
const { title } = req.body
const project = projects.find(p => p.id == id)
project.title = title
return res.json(project)
})
//Deleta um projeto
app.delete('/projects/:id', checkProjectExists, (req, res) => {
const { id } = req.params
const projectIndex = projects.findIndex(p => p.id == id)
projects.splice(projectIndex, 1)
return res.send()
})
//Adiciona tarefas a um projeto
app.post('/projects/:id/tasks', checkProjectExists, checkProjectTitle, (req, res) => {
const { id } = req.params
const { title } = req.body
const project = projects.find(p => p.id == id)
project.tasks = title
return res.json(project)
})
app.listen(3000) |
'use strict';
const availability = stampit().init(function() {
var $open = false; // private
this.open = function open() {
$open = true;
return this;
};
this.close = function close() {
$open = false;
return this;
};
this.isOpen = function isOpen() {
return $open;
};
});
const membership = stampit()
.methods({
addMember(member) {
this.members[member.name] = member;
return this;
},
getMember(name) {
return this.members[name];
}
})
.refs({
members: {}
});
const defaults = stampit().refs({
name: 'The Saloon',
specials: 'Whisky, Gin, Tequila'
});
const bar = stampit()
.static({
print() {
console.log('This is a static function');
}
})
.compose(defaults, availability, membership);
// Build an object
const moe = bar({name: 'Moe\'s', specials: 'Beer'});
//------------------------------------------------------------------------------
// Open Moe's and let Homer in ;-)
moe.open().addMember({name: 'Homer'});
console.log('Bar open?', moe.isOpen());
console.log('Is Homer inda House?', angular.isObject(moe.getMember('Homer')));
// Close Moe's
moe.close();
console.log('Still open?', moe.isOpen());
console.log('Name:', moe.name);
console.log('Specials:', moe.specials);
// Calling a static function
bar.print();
|
import React from "react";
export class UserItem extends React.Component {
render() {
return (
<React.Fragment>
<div className="userPanel">
<div className="userPanelDetails">
<div className="leftContentSection">
{this.props.object.image ? (
<img
alt="user"
src={this.props.object.image}
width="130"
height="130"
className="userImage"
></img>
) : (
<img
alt="user"
src="images/anonymousMan.png"
width="130"
height="130"
className="userImage"
></img>
)}
</div>
<div className="rightContentSection">
<h1>
{this.props.object.first_name} {this.props.object.last_name}
</h1>
<div className="smallContentSection">
{" "}
{this.props.object.bio}
</div>
<div className="smallContentSection">
<span>
<span className="fa fa-university" />
{this.props.object.affiliation}{" "}
</span>
<span>
<span className="fa fa-map-marker-alt" aria-hidden="true" />
{this.props.object.country}{" "}
</span>
<span>
<span className="fa fa-clock" aria-hidden="true" />
{this.props.object.date}{" "}
</span>
</div>
</div>
</div>
<div className="userPanelStats">
<div className="smallContentSection">Uploads</div>
<div className="smallContentSection">
<span>
<span className="fa fa-database" />
{this.props.object.datasets_uploaded}
</span>
<span>
<span className="fa fa-cogs flow" />
{this.props.object.flows_uploaded}
</span>
<span>
<span className="fa fa-trophy" />
{this.props.object.tasks_uploaded}
</span>
<span>
<span className="fa fa-star" />
{this.props.object.runs_uploaded}
</span>
</div>
</div>
</div>
<div>
<table className="userTable">
<tbody>
<tr>
<td className="itemName">
<span>
<span className="fa fa-database" /> Datasets
</span>
</td>
<td className="itemDetail-small">
<span>
<span className="fa fa-cloud-upload-alt" />
{this.props.object.datasets_uploaded}
</span>
</td>
<td className="itemDetail-small">
<span>
<span className="fa fa-cloud-download-alt" />
{this.props.object.downloads_received_data}
</span>
</td>
<td className="itemDetail-small">
<span>
<span className="fa fa-heart" />
{this.props.object.likes_received_data}
</span>
</td>
<td className="itemDetail-small">
<span>
<span className="fa fa-spinner" />
{this.props.object.runs_on_datasets}
</span>
</td>
</tr>
<tr>
<td className="itemName">
<span>
<span className="fa fa-cogs flow" /> Flows
</span>
</td>
<td>
<span>
<span className="fa fa-cloud-upload-alt" />
{this.props.object.flows_uploaded}
</span>
</td>
<td>
<span>
<span className="fa fa-cloud-download-alt" />
{this.props.object.downloads_received_flow}
</span>
</td>
<td>
<span>
<span className="fa fa-heart" />
{this.props.object.likes_received_flow}
</span>
</td>
<td>
<span>
<span className="fa fa-spinner" />
{this.props.object.runs_on_flows}
</span>
</td>
</tr>
<tr>
<td className="itemName">
<span>
<span className="fa fa-trophy" /> Tasks
</span>
</td>
<td>
<span>
<span className="fa fa-cloud-upload-alt" />
{this.props.object.tasks_uploaded}
</span>
</td>
<td>
<span>
<span className="fa fa-cloud-download-alt" />
{this.props.object.downloads_received_task}
</span>
</td>
<td>
<span>
<span className="fa fa-heart" />
{this.props.object.likes_received_task}
</span>
</td>
</tr>
<tr>
<td className="itemName">
<span>
<span className="fa fa-star" /> Runs
</span>
</td>
<td>
<span>
<span className="fa fa-cloud-upload-alt" />
{this.props.object.runs_uploaded}
</span>
</td>
<td>
<span>
<span className="fa fa-cloud-download-alt" />
{this.props.object.downloads_received_run}
</span>
</td>
<td>
<span>
<span className="fa fa-heart" />
{this.props.object.likes_received_run}
</span>
</td>
</tr>
</tbody>
</table>
</div>
</React.Fragment>
);
}
}
|
import React from "react"
import "@shopify/polaris/styles.css"
import { Page, Card, TextStyle, TextContainer } from "@shopify/polaris"
export default ({ data }) => {
return (
<Page
title="Markdown blog with Gatsby and Shopify Polaris"
singleColumn={true}
>
<TextContainer spacing="tight">
<p>{data.allMarkdownRemark.totalCount} Posts</p>
<p> </p>
</TextContainer>
{data.allMarkdownRemark.edges.map(({ node }) => (
<Card
title={node.frontmatter.title}
sectioned
key={node.id}
secondaryFooterAction={{
content: "Read Blog",
url: node.fields.slug,
}}
>
<TextContainer spacing="tight">
<TextStyle variation="subdued">{node.frontmatter.date}</TextStyle>
<p>{node.htmlAst.children[0].children[0].value}</p>
</TextContainer>
</Card>
))}
</Page>
)
}
export const query = graphql`
query IndexQuery {
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
totalCount
edges {
node {
id
frontmatter {
title
date(formatString: "DD MMMM, YYYY")
}
fields {
slug
}
htmlAst
}
}
}
}
`
|
import React from 'react';
import { ImageBackground, TouchableWithoutFeedback, Keyboard, View, TextInput } from 'react-native';
import Logo from './Logo';
import Form from './Form';
import bgSrc from './images/wallpaper.png';
// eslint-disable-next-line
class Login extends React.Component {
render() {
return (
<ImageBackground source={bgSrc} style={{ flex: 1 }} >
{/* <TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<View style={{ flex: 1 }}> */}
<Logo flex={0.30} toValFlex={0.3} />
<TextInput />
{/* </View>
</TouchableWithoutFeedback> */}
</ImageBackground>
);
}
}
export default Login;
|
import * as actionTypes from '../constants';
import {valueReducer} from './common';
import PowersList from '../lib/powers';
const initialState = {};
for (const c of ['mage', 'rogue', 'warrior']) {
for (const p of PowersList[c]) {
initialState[`${c} ${p.level}`] = false;
}
}
export const classPowers = valueReducer(actionTypes.CHANGE_CLASS_POWERS, initialState);
|
const faqList = [
{
id: 1,
title: '如何加入',
url: 'https://txcdn.emodor.com/h5/20180711/index.html',
// url: 'https://mp.weixin.qq.com/s?__biz=MzUyODgzMTkyMA==&mid=100001063&idx=4&sn=08ac5981800be9949c6af5040a3d8197&scene=19#wechat_redirect',
},
{
id: 2,
title: '权限说明',
url: 'https://mp.weixin.qq.com/s?__biz=MzUyODgzMTkyMA==&mid=100001063&idx=3&sn=2fc8b7b55b046996483d36ad2db82c78&scene=19#wechat_redirect',
},
{
id: 3,
title: '如何添加班组长',
url: 'https://mp.weixin.qq.com/s?__biz=MzUyODgzMTkyMA==&mid=100001063&idx=2&sn=d8560e74c44d69cc9229b5f1b8623de6&scene=19#wechat_redirect',
},
{
id: 4,
title: '如何添加管理员',
url: 'https://mp.weixin.qq.com/s?__biz=MzUyODgzMTkyMA==&mid=100001063&idx=1&sn=3070c97f36cb0cc7c8c324e64d7bfdaf&scene=19#wechat_redirect',
},
{
id: 5,
title: '产品功能介绍',
url: 'https://txcdn.emodor.com/h5/20180711/index.html',
},
{
id: 6,
title: '新功能介绍',
url: 'https://mp.weixin.qq.com/s/9pBKarwoE4roPf818vSPzQ',
},
{
id: 7,
title: '项目管理员说明',
url: 'https://mp.weixin.qq.com/s/UXwP_DoajMKl0hOm5JDrUg',
},
{
id: 8,
title: '项目经理说明',
url: 'https://mp.weixin.qq.com/s/-rJEISpFFf6uUbYIZGRa9g',
},
{
id: 9,
title: '考勤设备',
url: 'https://mp.weixin.qq.com/s/s-J4pqiR-0rQJhYs0Py1Fw',
},
{
id: 10,
title: '实名认证协议',
url: 'https://h5.emodor.com/service-landing/#/real_name',
},
{
id: 11,
title: '组织架构添加/加入说明',
url: 'https://mp.weixin.qq.com/s/kgA56o2aNo5r_23HSwQOAg',
},
{
id: 12,
title: '如何录入黑名单',
url: 'https://mp.weixin.qq.com/s/2tVNz7I_xS-_DEsNHczSXw',
},
{
id: 13,
title: '关于黑名单',
url: 'https://mp.weixin.qq.com/s/movwnq5V6Z3oB16SN2SJcg',
},
{
id: 14,
title: '权限说明',
url: 'https://mp.weixin.qq.com/s/-4gDGTR_1VYeraIj1Vb2Fg',
},
{
id: 15,
title: '测试跳转到百度',
url: 'https://www.qq.com',
},
];
const faqTable = {};
faqList.map((f) => {
const { id, title, url } = f;
faqTable[id] = {
title,
url,
path: `/pages/webview/help/index?id=${id}`,
route: {
name: 'webview.help',
query: {
id,
},
},
};
return f;
});
module.exports = faqTable;
|
//
// Code adapted from https://github.com/HeroicEric/ember-group-by (MIT licensed)
//
import { A } from '@ember/array';
import { module, test } from 'qunit';
import groupBy from 'kredits-web/utils/group-by';
module('Unit | Utils | group-by', function () {
let car1 = { name: 'Carrera', color: 'red' };
let car2 = { name: 'Veyron', color: 'red' };
let car3 = { name: 'Corvette', color: 'blue' };
let car4 = { name: 'Viper', color: 'blue' };
let car5 = { name: 'Cobra', color: 'green' };
let cars = A([car1, car2, car3, car4, car5]);
test('it groups cars by color', function (assert) {
assert.expect(1);
let redGroup = { property: 'color', value: 'red', items: [car1, car2] };
let blueGroup = { property: 'color', value: 'blue', items: [car3, car4] };
let greenGroup = { property: 'color', value: 'green', items: [car5] };
let result = groupBy(cars, 'color');
let expected = [redGroup, blueGroup, greenGroup];
assert.deepEqual(result, expected);
});
test('it does not fail with empty array', function (assert) {
let cars = [];
let result = groupBy(cars, 'color');
assert.deepEqual(result, []);
});
test('it does not failkwith null', function (assert) {
let cars = null;
let result = groupBy(cars, 'color');
assert.deepEqual(result, []);
});
});
|
import styled from 'styled-components';
export const CatsListStyles = styled.ul`
padding: 0;
margin: 0;
list-style: none;
display: grid;
grid-gap: 2rem;
${props => props.theme.media.md} {
grid-template-columns: 1fr 1fr;
}
${props => props.theme.media.lg} {
grid-template-columns: 1fr 1fr 1fr;
}
li.cat {
position: relative;
display: flex;
flex-flow: column;
background: ${props => props.theme.light};
box-shadow: 0 15px 35px 0 rgba(42, 51, 83, 0.12),
0 5px 15px rgba(0, 0, 0, 0.06);
border-radius: 0.5rem;
padding: 1.5rem 2rem;
max-width: 100%;
border-top: 0.25rem solid transparent;
${props => props.theme.media.md} {
min-height: 14rem;
}
.btn-wrap {
margin: auto -2rem -1.5rem;
padding: 1rem 2rem;
background: rgb(239 246 249 / 50%);
border-radius: 0 0 0.5rem 0.5rem;
display: flex;
justify-content: space-between;
align-items: center;
}
}
.card-header {
display: flex;
justify-content: space-between;
margin: 0 0 1em;
}
.cat-name {
text-align: center;
margin: 0;
}
.status {
font-size: 0.875rem;
border-radius: 2em;
padding: 0.4em 1.6em;
font-weight: 700;
background: 1px solid transparent;
&.happy {
background-color: #d4edda;
color: #155724;
border-color: #c3e6cb;
}
&.hungry {
background-color: #d1ecf1;
color: #0c5460;
border-color: #bee5eb;
}
&.very-hungry {
background-color: #fff3cd;
color: #856404;
border-color: #ffeeba;
}
&.starving {
background-color: #f8d7da;
color: #721c24;
border-color: #f5c6cb;
}
}
.fed {
text-align: center;
margin: 1em 0 2.35em;
p {
margin: 0;
}
}
`;
|
import React from 'react';
import {connect} from 'react-redux';
import {withRouter} from 'react-router-dom';
import Modal from 'react-modal';
import { Result, Button } from 'antd';
import {closeModal} from '../actions/modal';
const customStyles = {
content : {
height : '400px',
width : '600px',
top : '50%',
left : '50%',
right : 'auto',
bottom : 'auto',
marginRight : '-50%',
transform : 'translate(-50%, -50%)',
boxShadow : '0 8px 12px 0 rgba(0,0,0,0.2)'
},
overlay: {
zIndex: 2
}
};
const ResultModal = (props) => {
return(
<Modal
id="modal"
isOpen={props.modal.isOpen}
onRequestClose={() => props.dispatch(closeModal())}
style={customStyles}
ariaHideApp={false}
contentLabel="Transaction Result"
>
<div id="result_modal_container">
<Result
status="success"
title="Transaction Successful"
subTitle="The transaction has been successfully submitted."
extra={[
<Button type="primary" key="console" onClick={() => {
props.history.push({
pathname: `/dashboard${props.modal.path}`,
state: {
refetch: true
}
});
props.dispatch(closeModal());
}}>
Go to dashboard
</Button>,
<Button key="buy" onClick={() => props.dispatch(closeModal())}>Continue</Button>,
]}
/>
</div>
</Modal>
);
}
const mapStateToProps = (state) => {
return{
modal: state.modal
};
};
export default withRouter(connect(mapStateToProps)(ResultModal)); |
import React, { useState } from "react";
import { Grid, Chip } from "@material-ui/core";
import { connect } from "react-redux";
const DATA = [
{
step: 1,
description: 'Answer three questions so we can better help you with finding the right grants for your entity',
question: '1. What industry below best describes your entity?',
chips: [
'Research & Science',
'Police Brutality',
'Healthcare',
'Affordable Housing',
'Economic Development',
'Agriculture and Environment',
'Technology',
'Woman Owned',
'Other'
],
img: 'question-1.png'
},
{
step: 2,
description: 'Answer three questions so we can better help you with finding the right grants for your entity',
question: '2. Are you a registered 501 (c) 3 non profit organization?',
chips: [
'Yes',
'No',
],
img: 'question-2.png'
},
{
step: 3,
description: 'Answer three questions so we can better help you with finding the right grants for your entity',
question: '3. What can Venture Plans do to better serve your needs?',
chips: [
'Grant Proposal & Budget',
'Full Grant(s) Application Management',
],
img: 'question-3.png'
},
{
step: 4,
description: 'Fill out our contact form so one of our accredited advisors can get in touch with you for your free consultation',
question: '1. What is your full name, email, and phone number?',
chips: [
'Full Name',
'Email',
'Phone Number',
'Submit'
],
img: 'question-4.png'
},
]
function Questions(props) {
const [step, setStep] = useState(1);
const onChip = () => {
if (step === 4)
return
setStep(step + 1);
}
return (
<div className="grants-questions">
<Grid container spacing={6}>
{DATA.map((item, index) => (
item.step === step &&
<React.Fragment key={index}>
<Grid item lg={7} md={7} xs={12} className="question-grid">
<div className="question-container">
<div className="question-title">Your trusted partner in navigating through uncertain times. Let’s accelerate your growth.</div>
<div className="question-description">{item.description}</div>
<div className="question-wrapper">
<div className="question-step">
<span className="question">{item.question} </span>
<span className="step">{item.step !== 4 ? `Question ${item.step} / 3` : 'Contact Information'}</span>
</div>
<div className="question-content">
{item.chips.map((chip, index) => (
<Chip
key={index}
label={chip}
color="primary"
variant="outlined"
className="chip"
onClick={onChip}
/>
))}
</div>
</div>
</div>
</Grid>
<Grid item lg={5} md={5} xs={12}>
<img src={`/assets/images/grants/${item.img}`} className="question-img" alt="question" />
</Grid>
</React.Fragment>
))}
</Grid>
</div>
);
}
const mapStateToProps = state => ({
});
export default connect(
mapStateToProps,
{ }
)(Questions); |
$(document).ready(function(){
/* $(".delete").click(function(){
var tr = $(this).closest('tr'),
del_id = $(this).attr('id');//del_id
$.ajax({
url: "deleteUser.php",
method:"post",
dataType:"text",
success:function(result){
if($result == true ){
tr.css("background-color" , "tomato");
tr.fadeOut(500, function(){
$(this).remove();
});
}else{
//do nothing
}
}
});
}); */
init();
});
function init() {
$(document).on('click','.menu-list a',function(e){
var url = $(this).attr( "href" )
e.preventDefault();
$("#loading").fadeIn();
$( "#main_container" ).load( url + " #main_container" );
setTimeout(function() {
$("#loading").fadeOut();
}, 2500);
window.history.pushState("object or string", "Title", url);
});
}
function messageFailed(message){
$('#message').html("<div class='alert alert-danger'>"+message+"</div>");
}
function messageSuccess(message){
$('#message').html("<div class='alert alert-success'>"+message+"</div>");
}
function deleteUser(user_id){
$.get("phpAjax.php",
{
action:"deleteUser",
id:user_id
},
function(data){
if(data.result == true){
$('#user_'+user_id).css("background-color" , "#d08888").delay(500).fadeOut(500, function(){
this.remove()
messageFailed(".کاربر مورد نظر با موفقیت حذف شد");
});
}else{
alert('متاسفیم!شما امکان حذف ادمین اصلی را ندارید.');
alert.addClass("alert");
}
},"json");
}
function deleteMessage(message_id){
$.get("phpAjax.php",
{
action:"deleteMessage",
id:message_id
},
function(data){
if(data.result == true){
$('#message_'+message_id).css("background-color" , "#d08888").delay(500).fadeOut(500, function(){
this.remove();
messageFailed(".پیام مورد نظر با موفقیت حذف شد");
});
}else{
alert('خطا ! ');
}
},"json");
}
function deleteOrder(order_id){
$.get("phpAjax.php",
{
action:"deleteOrder",
id:order_id
},
function(data){
if(data.result == true){
$('#order_'+order_id).css("background-color" , "#d08888").delay(500).fadeOut(500, function(){
this.remove();
messageFailed(".سفارش مورد نظر با موفقیت حذف شد");
});
}else{
alert('خطا ! ');
}
},"json");
}
function deleteWash(wash_id){
$.get("phpAjax.php",
{
action:"deleteWash",
id:wash_id
},
function(data){
if(data.result == true){
$('#wash_'+wash_id).css("background-color" , "#d08888").delay(500).fadeOut(500, function(){
this.remove();
messageFailed(".نوع شستشوی مورد نظر با موفقیت حذف شد");
});
}else{
alert('خطا ! ');
}
},"json");
}
function deleteCarpet(carpet_id){
$.get("phpAjax.php",
{
action:"deleteCarpet",
id:carpet_id
},
function(data){
if(data.result == true){
$('#carpet_'+carpet_id).css("background-color" , "#d08888").delay(500).fadeOut(500, function(){
this.remove();
messageFailed(".نوع فرش مورد نظر با موفقیت حذف شد");
});
}else{
//alert('خطا ! ');
}
},"json");
}
function deleteService(service_id){
$.get("phpAjax.php",
{
action:"deleteService",
id:service_id
},
function(data){
if(data.result == true){
$('#service_'+service_id).css("background-color" , "#d08888").delay(500).fadeOut(500, function(){
this.remove();
messageFailed(".نوع خدمت مورد نظر با موفقیت حذف شد");
});
}else{
//alert('خطا ! ');
}
},"json");
}
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'phpAjax.php',
dataType: 'json',
data: $('form').serialize(),
success: function (data) {
if(data.result == true){
messageSuccess(".اطلاعات مورد نظر با موفقیت ثبت شد");
}else{
//alert('خطا ! ');
}
}
});
});
});
/* function addWash(){
$.get("phpAjax.php",
{
action:"addWash"
},
function(data){
if(data.result == true){
data: $('form').serialize();
success: function () {
alert('form was submitted');
}
}else{
alert('خطا ! ');
}
},"json");
} */
|
/*
* @Author: your name
* @Date: 2020-11-04 13:23:54
* @LastEditTime: 2020-11-12 12:33:05
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \vue-admain\src\http\userList.js
*/
import request from "./index";
/**
* get 获取用户数据
*/
export function getUserList() {
return request({
url: "/getUserList"
});
}
/**
* put 发送数据修改
* @param {object}} data 提交修改用户数据
*/
export function putUser(data) {
return request({
url: "/putUser",
method: "put",
data
});
}
/**
* delete 发送删除数据
* @param {number} id 删除的 id
*/
export function deleteUser(id) {
return request({
url: "/deleteUser",
method: "delete",
data: {
id
}
});
}
/**
* post 添加用户数据
* @param {object} user 添加的用户数据对象
*/
export function postUser(user) {
return request({
url: "/postUser",
method: "post",
data: {
user
}
});
}
|
var timer;
var sound;
var otpExpireSound;
chrome.storage.local.get(null, beginScript);
function beginScript(datas) {
sound = new Audio("https://dm0qx8t0i9gc9.cloudfront.net/previews/audio/BsTwCwBHBjzwub4i4/alarm-clock-buzzer-beeps_MyERv24__NWM.mp3");
otpExpireSound=new Audio('https://mp3.fastupload.co/dl.php?file=YUhSMGNITTZMeTl0Y0RNdVptRnpkSFZ3Ykc5aFpDNWpieTlrWVhSaEx6RTJNakV5TmpZM09USXZiM1J3Ulhod0xtMXdNdz09');
let slots = document.querySelectorAll(".vaccine-box a").length;
timer = setInterval(checkfree, 2000);
let target = document.querySelector(".pin-search-btn");
function checkfree() {
if(document.querySelectorAll('ion-button.login-btn').length>0){
otpExpireSound.play();
clearInterval(timer);
}
target.click();
console.log("<----------->");
setTimeout(() => {
A: for (let i = 0; i < slots; i++) {
let freeSlot = document.querySelectorAll(".vaccine-box a")[i];
if (condition(i)) {
console.log(freeSlot.innerText);
sound.play();
clearInterval(timer);
if(datas.fwd){
freeSlot.click();
setTimeout(() => document.querySelectorAll('ion-button')[datas.sst].click(), 100);
}
break A;
}
}
}, 1000)
}
function condition(i){
let content=document.querySelectorAll('.slots-box')[i].innerText.split('\n');
if(content.length==3 && !content[0].includes("Booked") && checkfor18(datas.etplus, content[2]) && checkVaccine(content[1]) )
return true;
else
return false;
}
function checkfor18(state, check) {
if(state==false)
return true;
else if(check=="Age 18+")
return true;
else
return false;
}
function checkVaccine(V){
if(datas.vacc[0]==true && V.toLowerCase().includes("covaxin"))
return true;
else if(datas.vacc[1]==true && V.toLowerCase().includes("covishield"))
return true;
else if(datas.vacc[2]==true && V.toLowerCase().includes("sputnik"))
return true;
else
return false;
}
} |
const url = "https://makra-stenkloev.no/thebean/wp-json/wp/v2/posts?_embed";
const carouselContainer = document.querySelector("#posts-carousel");
const rightArrow = document.querySelector("#right-carousel-button");
const leftArrow = document.querySelector("#left-carousel-button");
const indicator1 = document.querySelector(".dot-indicator-one");
const indicator2 = document.querySelector(".dot-indicator-two");
async function fetchPosts(){
try{
const response = await fetch(url);
const json = await response.json();
const posts = json;
// only displays right arrow after left arrow have been pressed (See righArrowFunction below)
leftArrow.style.display = "none";
rightArrow.style.display = "block";
//background-color on dot-indicators
indicator1.style.background = "rgb(15, 15, 15)";
indicator2.style.background = "rgb(50, 50, 50)";
// empty the container when json gets fetched
carouselContainer.innerHTML = "";
for(let i = 0; i < posts.length; i++){
let featuredImage = posts[i]._embedded["wp:featuredmedia"][0].source_url;
let altImageText = posts[i]._embedded["wp:featuredmedia"][0].alt_text;
let postTitle = posts[i].title.rendered;
// error handling if elements are missing
if(checkForUndefined(postTitle)){
postTitle = "Title Missing";
}
if(checkForUndefined(featuredImage)){
featuredImage = "https://via.placeholder.com/300x250?text=Image+missing";
}
if(checkForUndefined(altImageText)){
altImageText = "We are sorry, but the alt image text is missing";
}
if(i<=3){
carouselContainer.innerHTML +=
`<a href="specific-post.html?id=${posts[i].id}">
<div class="post-container">
<div class="featured-image" style="background-image:url(${featuredImage})" alt="${altImageText}"></div>
<h4>${postTitle}</h4>
<p class="read-link">read<i class="fas fa-angle-double-right"></i></p>
</div>
</a>`;
}
}
}
catch(error){
console.log(error);
// gets rid of grid to center the error message
carouselContainer.style.grid = "none";
//creates the error message
carouselContainer.innerHTML = errorMessage("error", `The website messed up. Please try to <a href="posts.html" class="reload-link">reload</a> the page.`);
}
}
fetchPosts();
// function for rightArrow-button
async function rightArrowFunction(){
try{
const response = await fetch(url);
const json = await response.json();
const posts = json;
carouselContainer.innerHTML = "";
for(let i = 0; i < posts.length; i++){
const featuredImage = posts[i]._embedded["wp:featuredmedia"][0].media_details.sizes.full.source_url;
const altImageText = posts[i]._embedded["wp:featuredmedia"][0].alt_text;
if((i>=4) && (i<=7)){
// only displays left arrow after right arrow have been pressed (See righArrowFunction below)
leftArrow.style.display = "block";
rightArrow.style.display = "none";
//background-color on dot-indicators
indicator1.style.background = "rgb(50, 50, 50)";
indicator2.style.background = "rgb(15, 15, 15)";
carouselContainer.innerHTML +=
`<a href="specific-post.html?id=${posts[i].id}">
<div class="post-container">
<div class="featured-image" style="background-image:url(${featuredImage})" alt="${altImageText}"></div>
<h4>${posts[i].title.rendered}</h4>
<p class="read-link">read<i class="fas fa-angle-double-right"></i></p>
</div>
</a>`;
}
}
}
catch(error){
console.log(error);
// gets rid of grid to center the error message
carouselContainer.style.grid = "none";
//creates the error message
carouselContainer.innerHTML = errorMessage("error", `The website messed up. Please try to <a href="posts.html" class="reload-link">reload</a> the page.`);
}
};
// eventlisteners for posts-carousel right arrow button, with function for fetching/creating html
rightArrow.addEventListener("click", rightArrowFunction);
rightArrow.onkeyup = rightArrowFunction;
// eventlisteners for posts-carousel right arrow button, with function for fetching/creating html
leftArrow.addEventListener("click", fetchPosts);
leftArrow.onkeyup = fetchPosts;
|
import {FILL_FORM, GET_FORM, SEND_FORM_ERROR, SEND_FORM_GOOD, SEND_FORM_IN, FORM_NOT_VALID} from "../constants";
const initialState = {
isLoaded: false,
isSent: null,
notValid: null,
name: {
name: "name",
value: "",
isError: null,
validation: "NAME",
},
surname: {
name: "surname",
value: "",
isError: null,
validation: "NAME",
},
email: {
name: "email",
value: "",
isError: null,
validation: "EMAIL",
},
phone: {
name: "phone",
value: "",
isError: null,
validation: "PHONE",
},
message: {
name: "message",
value: "",
isError: null,
validation: "MESSAGE",
},
sizes: {
name: "sizes",
value: "",
isError: null,
validation: "TEXT",
},
file: {
name: "file",
value: "",
isError: null,
validation: "FILE",
},
};
export default (state = initialState, action) => {
switch (action.type) {
case SEND_FORM_IN:
return {...state, ...action.payload};
case SEND_FORM_GOOD:
return {...initialState, isLoaded: true, isSent: true, sentData: action.payload.sentData};
case SEND_FORM_ERROR:
return {...state, isSent: false, notValid: false, ...action.payload};
case FORM_NOT_VALID:
return {...state, isSent: null, notValid: true, ...action.payload};
case GET_FORM:
return {...state, isLoaded: true, ...action.payload};
case FILL_FORM:
const {old, name, value, isError} = action.payload;
old[name].value = value;
old[name].isError = isError;
return {...state, ...old};
default:
return state;
}
};
|
import React from "react";
import _JSXStyle from "styled-jsx/style";
const Instruction = ({ title, subtitle }) => {
return (
<div className="instruction">
<h2>{title}</h2>
{!!subtitle && <h3>{subtitle}</h3>}
<_JSXStyle id="Instruction">{`
.instruction {
display: grid;
background-color: #c4c4c4;
align-items: center;
height: 6.5em;
margin-top: 1.5em;
grid-area: instruction;
}
h2,
h3 {
margin: 0;
font-style: normal;
font-weight: normal;
font-size: 2em;
/* line-height: 56px; */
text-align: center;
color: #000000;
}
@media (max-width: 920px) {
h2,
h3 {
font-size: 1.4em;
}
.instruction {
border-radius: 5px;
height: auto;
padding: 5px;
}
}
@media (max-width: 768px) {
h2,
h3 {
font-size: 1em;
}
.instruction {
border-radius: 5px;
height: auto;
padding: 5px;
}
}
`}</_JSXStyle>
</div>
);
};
export default Instruction;
|
const resume = JSON.parse(localStorage.getItem('resume_playback')) || {};
class SavedPosition {
constructor(stream) {
this.ids = stream.hash.split(',');
if (stream.offsets) {
this.offsets = stream.offsets.split(',').map((t) => +t);
} else if (stream.offset) {
this.offsets = [stream.offset];
} else {
this.offsets = [0];
}
}
set(t) {
let match = null;
this.ids.map((id, i) => {
let offset = this.offsets[i];
if (t >= offset) {
match = [id, offset];
}
delete resume[id];
});
if (match !== null) {
resume[match[0]] = t - match[1];
localStorage.setItem('resume_playback', JSON.stringify(resume));
}
}
get() {
let positions = this.ids.map((id, i) => {
return +resume[id] + this.offsets[i];
}).filter((x) => !isNaN(x));
return positions[positions.length - 1];
}
exists() {
for (let i = 0; i < this.ids.length; i++) {
if (resume[this.ids[i]]) {
return true;
}
}
return false;
}
}
export { SavedPosition }; |
var mongoose = require('mongoose');
var WeatherSchema = new mongoose.Schema({
location: String,
temperature: String,
wind: String,
humidity: String,
rainfall: String,
updated_date: { type: Date, default: Date.now },
});
module.exports = mongoose.model('Weather', WeatherSchema);
|
function isInvalidNumber(n) {
let num = Number(n);
if (!(num >= 100 && num <= 200) && num != 0) {
console.log('invalid')
}
}
isInvalidNumber(220) |
import React from "react";
import { withRouter, Link } from "react-router-dom";
import { LazyLoadImage } from "react-lazy-load-image-component";
import "react-lazy-load-image-component/src/effects/blur.css";
class PersonCard extends React.Component {
constructor(props) {
super(props);
this.state = {
imgLoaded: false,
};
this.imgLoaded = this.imgLoaded.bind(this);
}
imgLoaded() {
this.setState({
imgLoaded: true,
});
}
render() {
let knownFor = null;
let person = this.props.person;
if (!person || person.gender === 0) {
return null;
}
if (person.known_for && person.known_for.length) {
person.known_for.map((item) => {
return (
<Link key={`${item.id}__kf`} to={`/movie/${item.id}`}>
{item.title}
</Link>
);
});
}
return (
<div
key={person.id}
className={`card person-card ${
this.state.imgLoaded ? "img-loaded" : "img-not-loaded"
}`}
>
<div className="card--inner">
<Link to={`/person/${person.id}`} className="full-link"></Link>
<div className="image-wrap">
<LazyLoadImage
alt={person.name}
src={
person.profile_path
? `https://image.tmdb.org/t/p/w200${person.profile_path}`
: `${window.location.pathname.replace(
/\/$/,
""
)}/images/no-poster-person.jpg`
}
onLoad={this.imgLoaded}
/>
</div>
<div className="text-wrap">
<p className="title">{person.name}</p>
{knownFor ? <p className="known-for">{knownFor}</p> : null}
{this.props.character ? (
<p className="character">{this.props.character}</p>
) : null}
</div>
</div>
</div>
);
}
}
export default withRouter(PersonCard);
|
import React, { lazy } from 'react';
import ReactDom from 'react-dom';
import Switch, { Screen } from '../../dist/index';
import Button from './Button';
const Home = lazy(() => import(/* webpackChunkName: "Home" */ './Home/index'));
export default ReactDom.render(
<Switch
notFoundView={_ => <div>404 no found</div>}
loadingView={<div>Loading...</div>}
>
<Screen viewComponent={Home} name="home" initialProps={{ name: 'Home' }} />
<Screen
viewComponent={({ to, name }) => (
<div
style={{ display: 'flex', flexDirection: 'column', width: '400px' }}
>
<input
style={{
border: '1px solid',
borderRadius: '5px',
margin: '10px 0'
}}
onChange={({ target }) => to('page1', { name: target.value })}
placeholder="input name passed to context's viewProps for re-rendering"
/>
<Button
onClick={e => to('home', { name: name })}
label={`Back to Home (with input: ${name})`}
/>
</div>
)}
name="page1"
/>
</Switch>,
document.getElementById('app')
);
|
/**
* This class contains functions {sequenceOfExecution} and {onClickSequenceOfExecution}.
* @function {sequenceOfExecution} executes when user clicks submit in th UI.
* @function {onClickSequenceOfExecution} executes when user enters mass shift
* on any amino acid and click "OK" button.
*/
let backGroundColorList_g = []
class SeqOfExecution
{
constructor(){
this.onClickMassShift = {};
this.massShiftList = [];
}
/**
* Function executes all the functionalities one by one and displays all the
* needed contant on to HTML.
* @param {string} errorType - This gives which type of error needed to be
* considered when matched peaks are to be considered.
* @param {float} errorVal - This gives the user entered threshhold value to
* be considered when calculating matched peaks.
* @param {char} removeAcid - This gives the acid up on which the fixed ptm
* mass has to be removed when "X" is clicked at fixed ptms.
*/
sequenceOfExecution(errorType,errorVal,removeAcid){
/**
* unbind all the actions previously binded else each action will be
* binded multiple times.
*/
let fixedMassShiftList = [];//contains fixedPTM
let protVarPtmsList = [];//contains protein variable PTM
let variablePtmsList = [];//contains non-protein variable PTM
let completeShiftList = [];//contains all 3 kinds of mass shifts
let unknownMassShiftList = [];//contains unknown mass shifts
let modifiablePeakData = [];//will change value if shared peak
let massErrorthVal = null;
let matchedPeakList = [];
let matchedPairList = [];
let ppmErrorthVal = null;
let spectrumGraphObj;
let monoMassGraphObj;
/* show submit button for precursor mass and add event handler*/
jqueryElements.precursorMassSubmit.show();
setPrecursorMassEventHandler();
/* Hide everything when page launched before data is computed*/
$("#"+Constants.SEQSVGID).hide();
$("#"+Constants.SVGDOWNLOADID).hide();
$("#"+Constants.GRAPHDOWNLOAD).hide();
$("#"+Constants.SPECTRUMGRAPHID).hide();
$("#"+Constants.SPECTRUMDOWNLOADID).hide();
$("#"+Constants.DIVTABLECONTAINER).hide();
$("#"+Constants.PEAKCOUNTID).hide();
$("#"+Constants.SPECTRUMGRAPHID).hide();
$("#"+Constants.MONOMASSGRAPHID).hide();
/* create a nav bar and a tab for ms2 graph and mono mass graph */
clearMs2NavElement(Constants.GRAPHTABNAV);
createMs2NavElement(0, Constants.GRAPHTABDIV, Constants.GRAPHTABNAV, "");
addEventNavBar();
/**
* Get the parsed sequence after removing mass shift list from
* the entered sequence.
* Returns mass list embedded in [] in sequence of user entered sequence.
*/
let sequence = "";
sequence = getSequenceFromUI();
[sequence,unknownMassShiftList, protVarPtmsList, variablePtmsList] = parseSequenceMassShift(sequence);
fixedMassShiftList = parseCheckedFixedPtm(sequence);
/* If user removed fixed ptm mass, remove the mass from the list*/
if(removeAcid !== "") {
removeAcid = removeAcid.toUpperCase()
for(let i=0;i<fixedMassShiftList.length;i++) {
let position = fixedMassShiftList[i].getLeftPos();
if(this.sequence_[position] === removeAcid) {
fixedMassShiftList.splice(i,1);
}
}
}
/*create proteoform object containing mass shift information and sequence */
let proteoformObj = new Proteoform("", "", sequence, 0, sequence.length -1, "", unknownMassShiftList, fixedMassShiftList, protVarPtmsList, variablePtmsList);
/**
* Check if mass shift is entered by clicking on the acid. If entered
* consider that mass shift and and append to the current mass shift list
*/
/*if(!$.isEmptyObject(this.onClickMassShift)) {
let tempPosition = this.onClickMassShift.position;
let tempMass = this.onClickMassShift.mass;
massShiftObj.appendtoMassShiftList(tempPosition,tempMass);
}*/
/**
* Form sequence with mass shift embedded in []
*/
// let seqToUI = massShiftObj.formSequence();
/**
* Write back to UI
*/
// writeSeqToTextBox(seqToUI);
/* Get all the Mass List data entered by the user.*/
let monoMassList = getMassListFromUI();
/* Get all the peak list data entered by the user */
modifiablePeakData = getPeakListFromUI();
let monoMassListLen = monoMassList.length;
let seq = proteoformObj.getSeq();
let matchedUnMatchedPeaks = [];
let envelopeList;
/* Setting masserror threshold value and ppm error threshhold value*/
if(errorType === Constants.MASSERROR) massErrorthVal = errorVal ;
else ppmErrorthVal = errorVal ;
/*Get all the n, c terminus ions selected.*/
let n_TerminusList = getNterminusCheckedList();
let c_TerminusList = getCterminusCheckedList();
/* create spectrum object*/
let spectrum = new Spectrum("", "", "", getPeakListFromUI(), n_TerminusList, c_TerminusList, getPrecursorMass());
/* Get all the matched peaks for all the n terminus fragmented ions selected.*/
let calcMatchedPeaks = new CalcMatchedPeaks();
spectrum.getNTerminalIon().forEach(function(ion){
let prefixMassList = proteoformObj.getNMasses(ion.getName());
/* Get matched peak list*/
let matchedPeaks = calcMatchedPeaks.getMatchedPeakList(prefixMassList,monoMassList,
seq,massErrorthVal,ppmErrorthVal,ion, matchedPairList);
/* copy the matched peaks to a new list for each ion selected*/
let temp_matchedPeaks = matchedPeaks.map(x => ({...x}));
matchedPeakList = matchedPeakList.concat(temp_matchedPeaks);
})
/* Get all the matched peaks for all the c terminus fragmented ions selected.*/
spectrum.getCTerminalIon().forEach(function(ion) {
/* Get claculated suffix mass list*/
let suffixMassList = proteoformObj.getCMasses(ion.getName());
/* Get matched peak list*/
let matchedPeaks = calcMatchedPeaks.getMatchedPeakList(suffixMassList,monoMassList,seq,
massErrorthVal,ppmErrorthVal,ion,matchedPairList);
/*copy the matched peaks to a new list for each ion selected*/
let temp_matchedPeaks = matchedPeaks.map(x => ({...x}));
matchedPeakList = matchedPeakList.concat(temp_matchedPeaks);
})
/* Get combined list of both matched and unmatched peaks to write to table*/
matchedUnMatchedPeaks = calcMatchedPeaks.getMatchedAndUnMatchedList(monoMassList,matchedPeakList);
// console.log("matchedUnmatchedpeaks:", matchedUnMatchedPeaks);
/*Do the below function when Sequence entered is not empty*/
if(seq.length !== 0) {
/*Draw SVG of Sequence*/
let breakPoints = formBreakPoints(matchedPeakList);
let prsmObj = new Prsm("", proteoformObj, "", spectrum, breakPoints, matchedPeakList.length);
let prsmGraphObj = new PrsmGraph(Constants.SEQSVGID,prsmObj);
prsmGraphObj.para.rowLength = 40;
prsmGraphObj.para.letterWidth = 25;
prsmGraphObj.redraw();
$("#"+Constants.SEQSVGID).show();
$("#"+Constants.SVGDOWNLOADID).show();
$("#"+Constants.GRAPHDOWNLOAD).show();
/*Get total mass and wite to HTML*/
let totalMass = proteoformObj.getMass();
setTotalSeqMass(totalMass);
//Set Mass Difference, precursorMass is a global variable form spectrum.html
let precursorMass = getPrecursorMass();
setMassDifference(precursorMass,totalMass);
/*draw for the prsm download modal */
let savePrsmObj = new SavePrsm(prsmGraphObj);
savePrsmObj.main();
}
/**
* calculate envelope distribution and draw spectrum graph
*/
if(spectrum.getPeaks().length !== 0)
{
let calcMatchedPeaks = new CalcMatchedPeaks();
//distributionList = matchedPeaksObj.getDistribution(peakDataList,sequence,matchedUnMatchedPeaks);
envelopeList = calcMatchedPeaks.getDistribution(modifiablePeakData,sequence,matchedUnMatchedPeaks,completeShiftList);
//console.log("envelopeList:", envelopeList);
spectrum.setEnvs(envelopeList);
/**
* Display the graph formed
*/
$("#"+Constants.SPECTRUMGRAPHID).show();
//$("#"+Constants.MONOMASSGRAPHID).show();
/**
* Call generateCorrespondingGraph which calls addSpectrum function in invokeSpectrum file to draw graph
*/
let spectrumDataPeaks = new SpectrumFunction();
let spectrumDataEnvs = new SpectrumFunction();
spectrumDataPeaks.assignLevelPeaks(spectrum.getPeaks());
spectrumDataEnvs.assignLevelEnvs(spectrum.getEnvs());
let ionList = getIonsSpectrumGraph(matchedPeakList, spectrum.getEnvs());
spectrumGraphObj = new SpectrumGraph(Constants.SPECTRUMGRAPHID, spectrum.getPeaks());
spectrumGraphObj.addRawSpectrumAnno(spectrum.getEnvs(),ionList);
// console.log("envPeakList:", spectrumGraphObj.envPeakList);
spectrumGraphObj.redraw();
}/**
* Do the below function when mono mass list entered is not empty
*/
if(monoMassListLen !== 0)
{
jqueryElements.monoMassTableContainer.show();
/**
* Display All-peaks/matched/non-matched buttons on click of submit
*/
// jqueryElements.peakCount.show();
/**
* Create tabe to display the input mass list data and calculated data
*/
createMonoMassTable();
/**
* Add data to the table
*/
addMassDataToTable(matchedUnMatchedPeaks, spectrumGraphObj);
/**
* function to show the count of matched peaks, un matched peaks and All peaks
*/
jqueryElements.peakCount.show();
/**
* Bootstrap syntax to keep the table box to 400px height
* and setting properties to the table.
*/
this.setBootStarpTableProperties();
showPeakCounts(monoMassList, matchedPeakList);
}
/**
* Local function to set the actions on click of download button in HTML
*/
this.download();
let completeListofMasswithMatchedInd = [];
let nIonType = "B";
let cIonType = "Y";
/**
* Code to form the second table with all the prefix masses with matched
* masses for each ion fragment selected.
*/
spectrum.getNTerminalIon().forEach(function(ion){
let calcMatchedPeaks = new CalcMatchedPeaks();
let prefixMassList = new Array();
let matchedAndUnMatchedList = new Array();
let matchedAndUnMatchedListObj = {};
//let massShift = parseFloat(ion.mass);
if (ion.getName().indexOf("A") > -1 || ion.getName().indexOf("B") > -1 || ion.getName().indexOf("C") > -1) {
nIonType = ion.getName();
}
/**
* Get calculated prefix mass
*/
prefixMassList = proteoformObj.getNMasses(nIonType);
prefixMassList.shift();
prefixMassList.pop();
/**
* Get Matched peaks
*/
matchedAndUnMatchedList = calcMatchedPeaks.getMatchedAndUnmatchedPrefixAndSuffixMassList(prefixMassList,
monoMassList,massErrorthVal,ppmErrorthVal,"prefix");
matchedAndUnMatchedListObj = {ionFragment:ion.getName(),massList:matchedAndUnMatchedList};
/**
* Complete list of all the peaks for each ion fragment
*/
completeListofMasswithMatchedInd.push(matchedAndUnMatchedListObj);
})
spectrum.getCTerminalIon().forEach(function(ion){
let calcMatchedPeaks = new CalcMatchedPeaks();
let suffixMassList = new Array();
let matchedAndUnMatchedList = new Array();
let matchedAndUnMatchedListObj = {};
//let massShift = parseFloat(ion.mass);
if (ion.getName().indexOf("X") > -1 || ion.getName().indexOf("Y") > -1 || ion.getName().indexOf("Z") > -1 || ion.getName().indexOf("Z_DOT") > -1) {
cIonType = ion.getName();
}
/**
* Get calculated prefix mass
*/
suffixMassList = proteoformObj.getCMasses(cIonType);
suffixMassList.shift();
suffixMassList.pop();
// console.log("monoMassList:",monoMassList);
/**
* Get Matched peaks
*/
matchedAndUnMatchedList = calcMatchedPeaks.getMatchedAndUnmatchedPrefixAndSuffixMassList(suffixMassList,
monoMassList,massErrorthVal,ppmErrorthVal,"suffix");
matchedAndUnMatchedListObj = {ionFragment:ion.getName(),massList:matchedAndUnMatchedList};
/**
* Complete list of all the peaks for each ion fragment
*/
completeListofMasswithMatchedInd.push(matchedAndUnMatchedListObj);
})
// console.log("completeListofMasswithMatchedInd:", completeListofMasswithMatchedInd);
// console.log("monomasslist:", monoMassList);
if(completeListofMasswithMatchedInd.length !== 0)
{
$("#"+Constants.H_FRAGMENTEDTABLE).show();
}
$("#monoMasstitle").show();
let ions = getIonsMassGraph(matchedPeakList);
let monoMassPeakList = [];
for (let i = 0; i < monoMassList.length; i++){
let peak = new Peak(monoMassList[i].peakId, monoMassList[i].mass, monoMassList[i].intensity)
monoMassPeakList.push(peak);
}
let spectrumDataMonoPeaks = new SpectrumFunction();
spectrumDataMonoPeaks.assignLevelPeaks(monoMassPeakList);
monoMassGraphObj = new SpectrumGraph("monoMassGraph",monoMassPeakList);
// monoMassGraphObj.para.errorThreshold = 0.06;
monoMassGraphObj.addMonoMassSpectrumAnno(ions,proteoformObj, nIonType, cIonType);
monoMassGraphObj.para.setMonoMassGraph(true);
monoMassGraphObj.redraw();
/**
* add download for mono mass and spectrum graph
*/
let saveSpectrumObj = new SaveSpectrum([spectrumGraphObj], [monoMassGraphObj]);
saveSpectrumObj.main();
/**
* Disply the table of masses for all the fragmented ions
*/
createTableForSelectedFragmentIons(sequence,completeListofMasswithMatchedInd,monoMassGraphObj);
this.setBootStarpropertiesforFragmentIons();
}
/**
* Function executes all the functionalities one by one and displays all the
* needed contant on to HTML on change of mass shift on any acid.
* @param {string} errorType - This gives which type of error needed to be
* considered when matched peaks are to be considered.
* @param {float} errorVal - This gives the user entered threshhold value to
* be considered when calculating matched peaks.
*/
onClickSequenceOfExecution(errorType,errorVal){
//console.log("This.completeShiftList : ", this.massShiftList);
/**
* unbind all the actions previously binded else each action will be
* binded multiple times.
*/
$( "#"+Constants.SPECDOWNLOADPNG ).unbind();
$( "#"+Constants.SPECDOWNLOADSVG ).unbind();
$( "#"+Constants.SEQDOWNLOADPNG ).unbind();
$( "#"+Constants.SEQDOWNLOADSVG ).unbind();
$( ".rectBGColor").remove();
let massShiftList = [];
let sequence = "";
let massErrorthVal = null;
let ppmErrorthVal = null;
let matchedPeakList = [];
let monoMassList = [];
let peakDataList = [];
let massShift_ClassId = "."+Constants.MASSSHIFT_CLASSID;
/**
* Remove all the mass shift notation on the sequence if exists
*/
$(massShift_ClassId).remove();
/**
* Get all the Mass List data entered by the user.
*/
let UIHelperObj = new UIHelper();
monoMassList = UIHelperObj.getMassListFromUI();
/**
* Get the parsed sequence after removing mass shift list from
* the entered sequence.
* Returns mass list embedded in [] in sequence of user entered sequence.
*/
let massShiftObj = new MassShifts();
[sequence,massShiftList] = massShiftObj.getSequenceFromUI();
let rectBGColorObj = new rectBGColor(backGroundColorList_g);
let bgColorList ;
/**
* Check if mass shift is entered by clicking on the acid. If entered
* consider that mass shift and and append to the current mass shift list
*/
if(!$.isEmptyObject(this.onClickMassShift))
{
let tempPosition = this.onClickMassShift.position;
let tempMass = this.onClickMassShift.mass;
let color = this.onClickMassShift.color;
bgColorList = rectBGColorObj.getMassListToColorBG(tempPosition,color);
massShiftList = massShiftObj.appendtoMassShiftList(tempPosition,tempMass,massShiftList,color);
}
//Add Background color to the massshifted elements
rectBGColorObj.setBackGroundColorOnMassShift(bgColorList);
let seqToUI = massShiftObj.formSequence(sequence,massShiftList);
massShiftObj.writeSeqToTextBox(seqToUI);
peakDataList = UIHelperObj.getPeakListFromUI();
modifiablePeakData = UIHelperObj.getPeakListFromUI();//added for modified version of getNormalizedIntensity to adjust envelopes
let peakListLen = peakDataList.length;
let monoMassListLen = monoMassList.length;
let seqln = sequence.length;
let matchedUnMatchedPeaks = [];
if(peakListLen != 0 && monoMassListLen != 0 && seqln != 0)
{
/**
* Setting masserror threshold value and ppm error threshhold value
*/
if(errorType == Constants.MASSERROR) massErrorthVal = errorVal ;
else ppmErrorthVal = errorVal ;
let calculatePrefixAndSuffixMassObj = new calculatePrefixAndSuffixMass();
let iontabledataObj = new iontabledata();
let n_TerminusList = iontabledataObj.getNterminusCheckedList();
/**
* Get all the matched peaks for all the n terminus fragmented ions selected.
*/
n_TerminusList.forEach(function(ion){
// Calculate Matched Peaks and Distribution
let matchedPeaksObj = new MatchedPeaks();
let prefixMassList = [];
let matchedPeaks = [];
let massShift = parseFloat(ion.mass);
let ionType = ion.ionType;
/**
* Get claculated prefix mass list
*/
prefixMassList = calculatePrefixAndSuffixMassObj
.getPrefixMassList(sequence,massShiftList,massShift);
/**
* Get matched peak list
*/
matchedPeaks = matchedPeaksObj.getMatchedPeakList(prefixMassList,monoMassList,
sequence,massErrorthVal,ppmErrorthVal,ionType,"prefix");
/**
* copy the matched peaks to a new list for each ion selected
*/
let temp_matchedPeaks = matchedPeaks.map(x => ({...x}));
matchedPeakList = matchedPeakList.concat(temp_matchedPeaks);//concat(matchedPeaks);
})
/**
* Get all the c terminus ions selected
*/
let c_TerminusList = iontabledataObj.getCterminusCheckedList();
/**
* Get all the matched peaks for all the c terminus fragmented ions selected.
*/
c_TerminusList.forEach(function(ion){
let matchedPeaksObj = new MatchedPeaks();
let suffixMassList = [];
let matchedPeaks = [];
let massShift = parseFloat(ion.mass);
let ionType = ion.ionType;
/**
* Get claculated suffix mass list
*/
suffixMassList = calculatePrefixAndSuffixMassObj
.getSuffixMassList(sequence,
massShiftList,massShift);
/**
* Get matched peak list
*/
matchedPeaks = matchedPeaksObj.getMatchedPeakList(suffixMassList,monoMassList,
sequence,massErrorthVal,ppmErrorthVal,ionType,"suffix");
let temp_matchedPeaks = matchedPeaks.map(x => ({...x}));
/**
* copy the matched peaks to a new list for each ion selected
*/
matchedPeakList = matchedPeakList.concat(temp_matchedPeaks);
})
let matchedPeaksObj = new MatchedPeaks();
/**
* Get combined list of both matched and unmatched peaks to write to table
*/
matchedUnMatchedPeaks = matchedPeaksObj.getMatchedAndUnMatchedList(monoMassList,matchedPeakList);
/**
* Get calculated distribution
*/
let distributionList = matchedPeaksObj.getDistribution(modifiablePeakData,sequence,matchedUnMatchedPeaks);
//let distributionList = matchedPeaksObj.getDistribution(peakDataList,sequence,matchedUnMatchedPeaks);
/**
* Draw SVG of Sequence
*/
let para = new parameters();
para = buildSvg(para,sequence,Constants.SEQSVGID,massShiftList,monoMassList);
getNumValues(para,sequence,Constants.SEQSVGID);
annotations(para,matchedPeakList,Constants.SEQSVGID);
$("#"+Constants.SEQSVGID).show();
$("#"+Constants.SVGDOWNLOADID).show();
$("#"+Constants.GRAPHDOWNLOAD).show();
$("#"+Constants.MONOGRAPHDOWNLOAD).show();
/**
* Get total mass and wite to HTML
*/
let totalMass = calculatePrefixAndSuffixMassObj.getTotalSeqMass(sequence,massShiftList);
UIHelperObj.setTotalSeqMass(totalMass);
//Set Mass Difference, precursorMass is a global variable
UIHelperObj.setMassDifference(precursorMass,totalMass);
$("#"+Constants.SPECTRUMGRAPHID).show();
/**
* Call generateCorrespondingGraph which calls addSpectrum function in invokeSpectrum file to draw graph
*/
document.getElementById("monoMasstitle").style.display = "block";
generateCorrespondingGraph(peakDataList,distributionList,null);
$("#"+Constants.SPECTRUMDOWNLOADID).show();
/**
* Display All-peaks/matched/non-matched buttons on click of submit
*/
$("#peakCount").show();
/**
* Create tabe to display the input mass list data and calculated data
*/
UIHelperObj.createMonoMassTable();
/**
* Add data to the table
*/
UIHelperObj.addMassDataToTable(matchedUnMatchedPeaks);
/**
* function to show the count of matched peaks, un matched peaks and All peaks
*/
$("#"+Constants.PEAKCOUNTID).show();
/**
* Bootstrap syntax to keep the table box to 400px height and setting properties to the table
*/
this.setBootStarpTableProperties();
UIHelperObj.showPeakCounts();
/**
* Local function to set the actions on click of download button in HTML
*/
this.download();
}
}
/**
* Sets the properties of bootstrap table
*/
setBootStarpTableProperties()
{
$("#tableContainer").DataTable({
"scrollY": Constants.TABLEHEIGHT,
"scrollCollapse": true,
"paging": false,
"bSortClasses": false,
"searching": false,
"bInfo" : false,
"columns":[
{ "type": "num" },
{ "type": "num" },
null,
{ "type": "num" },
{ "type": "num" },
{ "type": "num" },
null,
{ "type": "num" },
{ "type": "num" },
{ "type": "num" }
]
});
}
/**
* Sets the properties of bootstrap table
*/
setBootStarpropertiesforFragmentIons()
{
//to be correctly sorted, column type should be num for each ion column
//this code will work regardless of number of ions selected
let columnCnt = 0;
let columnTypes = [];
$("#selectedIonTableContainer .th-sm").each(function () {
columnCnt++;
});
for (let i = 0; i < columnCnt; i++){
let type = null;
if (i != 1){
type = { "type": "num" };
}
columnTypes.push(type);
}
$("#selectedIonTableContainer").DataTable({
"scrollY": Constants.TABLEHEIGHT,
"scrollCollapse": true,
"paging": false,
"bSortClasses": false,
"searching": false,
"bInfo" : false,
"columns":columnTypes
});
}
/**
* Download function to download the SVG's
*/
download()
{
/**
* On click action to download sequence SVG in .svg format
*/
d3.select("#"+Constants.SEQDOWNLOADSVG).on("click",function(){
x = d3.event.pageX;
y = d3.event.pageY - 40;
//function in prsmtohtml
popupnamewindow("svg","seq",Constants.SEQSVGID,x,y)
})
/**
* On click action to download sequence svg in .svg format
*/
d3.select("#"+Constants.SEQDOWNLOADPNG).on("click",function(){
x = d3.event.pageX;
y = d3.event.pageY ;
//function in prsmtohtml
popupnamewindow("png","seq", Constants.SEQSVGID,x,y)
})
d3.select("#"+Constants.GRAPHDOWNLOADSVG).on("click",function(){
x = d3.event.pageX;
y = d3.event.pageY + 40;
//function in prsmtohtml
popupnamewindow("svg","graph", Constants.SPECTRUMGRAPHID,x,y)
})
d3.select("#"+Constants.GRAPHDOWNLOADPNG).on("click",function(){
x = d3.event.pageX;
y = d3.event.pageY + 80;
//function in prsmtohtml
popupnamewindow("png","graph", Constants.SPECTRUMGRAPHID,x,y)
})
d3.select("#"+Constants.MONOGRAPHDOWNLOADSVG).on("click",function(){
x = d3.event.pageX;
y = d3.event.pageY + 40;
//function in prsmtohtml
popupnamewindow("svg","graph", Constants.MONOMASSGRAPHID,x,y)
})
d3.select("#"+Constants.MONOGRAPHDOWNLOADPNG).on("click",function(){
x = d3.event.pageX;
y = d3.event.pageY + 80;
//function in prsmtohtml
popupnamewindow("png","graph", Constants.MONOMASSGRAPHID,x,y)
})
}
}
|
var myCenter = new google.maps.LatLng(44.831395, 19.212974);
function initialize() {
var mapProp = {
center: myCenter,
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: myCenter,
map: map,
animation: google.maps.Animation.DROP,
title: "Batković",
icon: "images/markerGoogleMap.png"
});
google.maps.event.addListener(map, 'center_changed', function () {
// 3 seconds after the center of the map has changed, pan back to the
// marker.
window.setTimeout(function () {
map.panTo(marker.getPosition());
}, 3000);
});
var styles = [
{
featureType: "all",
elementType: "",
stylers: [
{
saturation: "-100"
}
]
},
{
featureType: "",
elementType: "labels.text",
stylers: [
{
color: "gray"
},
{
weight: "0.1"
}
]
}
];
google.maps.event.addListener(map, 'center_changed', function () {
// 3 seconds after the center of the map has changed, pan back to the
// marker.
window.setTimeout(function () {
map.panTo(marker.getPosition());
}, 3000);
});
map.setOptions({
styles: styles
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
|
var o=require("os");console.log(o.platform());
|
document.addEventListener("DOMContentLoaded", () => {
// your code here
//let button = document.getElementById('ourbutton')
let button = document.getElementsByTagName('input')[1]
let form = document.getElementById('create-task-form')
let selectbox = document.getElementById('priority-select')
form.addEventListener("submit", function(e){
e.preventDefault()
let theList = document.getElementById('tasks')
let doneList = document.getElementById('done')
let button = e.target
const userInput = document.getElementById("new-task-description").value
let newLi = document.createElement("LI")
newLi.innerHTML = userInput
let checkBox = document.createElement("INPUT")
checkBox.type = "checkbox"
checkBox.classList = "check"
if (selectbox.value == "low") {
newLi.style.backgroundColor = "green"
} else if (selectbox.value == "medium") {
newLi.style.backgroundColor = "yellow"
} else {
newLi.style.backgroundColor = "red"
}
newLi.append(checkBox)
theList.append(newLi)
checkBox.addEventListener("change", function(e){
//console.log("worked...")
//let targ = e.target
doneList.append(e.target.parentNode)
//e.target.parentNode.remove()
})
ourCheckBox = document.getElementsByClassName('check')
checks = Array.from(ourCheckBox)
console.log(checks)
})
checks.forEach( console.log(checks))
});
//check => check.addEventListener("change", function (e) { |
angular.module('boosted')
.controller('storeCtrl', function($scope, service, $state, $http, $location, $anchorScroll) {
service.getItems(2).then(function(response){
$scope.Items2 = response.data;
console.log($scope.Items2);
})
service.getItems(1).then(function(results){
$scope.Items1 = results.data;
console.log($scope.Items1);
})
$scope.gotoAnchor = function(param){
$location.hash(param);
$anchorScroll();
}
});
|
/**
* Helper function to check if there is more space to explore in a graph when performing double BFS
* It compares the current sizes of maps vs previous sizes of the same maps.
* In case one of the maps has the same size as previous, then this method returns false.
* True otherwise
*
* @param {*} previousStartPointMapSize
* @param {*} startPointMapSize
* @param {*} previousEndPointMapSize
* @param {*} endPointMapSize
*/
const isMoreSpaceToExplore = (previousStartPointMapSize,
startPointMapSize,
previousEndPointMapSize,
endPointMapSize) => {
if ((previousStartPointMapSize != startPointMapSize) &&
(previousEndPointMapSize != endPointMapSize)) {
return true
}
return false
}
module.exports = {
isMoreSpaceToExplore: isMoreSpaceToExplore
} |
import { useState } from "react";
const useKeyboard = () => {
const [selectedNotes, setSelectedNotes] = useState([]);
return {
setSelectedNotes,
selectedNotes
};
};
export default useKeyboard;
|
const initDb = require('./initDb')
const queries = require('./queries')
var db
beforeEach((done) => {
initDb((dbInstance) => {
db = dbInstance
done()
})
})
afterEach((done) => {
db.end(() => done())
})
describe('matchUserCreds', () => {
test('it should return a user id', (done) => {
const params = { email: 'doctor@doctor.com', password: 'doctor', userType: 'doctor-user' }
queries.matchUserCreds(db, params, (err, userId) => {
expect(err).toBeNull()
expect(userId).toBe('101')
done()
})
})
})
describe('matchUserSession', () => {
test('it retrieve a user from a session key, for the doctor', (done) => {
queries.createSession(db, { userId: 101 }, (err, sessionKey) => {
expect(err).toBeNull()
queries.matchUserSession(db, { sessionKey }, (err, user) => {
expect(err).toBeNull()
expect(user.id).toBe('101')
expect(user.own_doctor_id).toBe('201')
expect(user.own_patient_id).toBeNull()
done()
})
})
})
test('it retrieve a user from a session key, for the patient', (done) => {
queries.createSession(db, { userId: 102 }, (err, sessionKey) => {
expect(err).toBeNull()
queries.matchUserSession(db, { sessionKey }, (err, user) => {
expect(err).toBeNull()
expect(user.id).toBe('102')
expect(user.own_doctor_id).toBeNull()
expect(user.own_patient_id).toBe('301')
done()
})
})
})
})
describe('createSession', () => {
test('it should create a session', (done) => {
const params = { userId: 101 }
queries.createSession(db, params, (err, sessionKey) => {
expect(err).toBeNull()
expect(sessionKey).toMatch(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/)
db.query('select * from sessions where key=$1::uuid', [sessionKey], (err, result) => {
expect(err).toBeNull()
expect(result.rows[0].user_id).toBe('101')
done()
})
})
})
})
describe('getPatientDataForSession', () => {
test('it should retrieve a patient record by session key', (done) => {
queries.createSession(db, { userId: 102 }, (err, sessionKey) => {
expect(err).toBeNull()
queries.getPatientDataForSession(db, { sessionKey }, (err, patient) => {
expect(err).toBeNull()
expect(patient.first_name).toBe('Patsy')
done()
})
})
})
})
|
(function() {
'use strict';
angular.module('cyber', [
//angular modules
'ngAnimate',
'ngResource',
'ngMessages',
//3rd party modules
'ui.router',
'smoothScroll',
'ui.bootstrap',
//custom modules
'cyber.config',
'cyber.controllers',
'cyber.services'
])
.run(runBlock)
.config(configBlock)
runBlock.$inject = ['$rootScope', '$state', '$stateParams'];
function runBlock($rootScope, $state, $stateParams) {
$rootScope.$state = $state;
$rootScope.$stateParams = $stateParams;
}
configBlock.$inject = ['$stateProvider', '$urlRouterProvider', '$httpProvider'];
function configBlock($stateProvider, $urlRouterProvider, $httpProvider) {
//$httpProvider.interceptor.push('httpInterceptor');
$urlRouterProvider
//if invalid URL, navigate to '/'
.otherwise('/');
$stateProvider
.state('home', {
url: '/',
templateUrl: '../views/home.html',
controller: 'HomeController',
controllerAs: 'vm',
resolve: {
// alertResource: 'AlertService',
// alerts: function(alertResource) {
// return alertResource.query().$promise;
// }
}
})
.state('settings', {
url: '/settings',
templateUrl: '../views/settings.html',
controller: 'SettingsController',
controllerAs: 'vm'
})
.state('signup', {
url: '/signup',
templateUrl: '../views/signup.html',
controller: 'SignupController',
controllerAs: 'vm'
})
}
})();
|
// @flow
import { curry2, curry3 } from "./curry";
function pureSet<A>(a: A) : Set<A> {
return new Set().add(a);
}
function apSet<A, B>(fnSet: Set<A => B>, aSet: Set<A>) : Set<B> {
const result = new Set();
for (const fn of fnSet) {
for (const a of aSet) {
result.add(fn(a));
}
}
return result;
}
function mapSet<A, B>(fn: A => B, a: Set<A>) : Set<B> {
return apSet(pureSet(fn), a);
}
function subtract(x: number, y: number) : number {
return x - y;
}
const curriedSubtract = curry2(subtract);
const nums = new Set([5, 6, 7]);
const fns = mapSet(curriedSubtract, nums);
console.log(apSet(fns, new Set([1, 2, 3])));
console.log(
apSet(mapSet(curriedSubtract, new Set([5, 6, 7])),
new Set([1, 2, 3])));
function isBetween(x: number, y: number, z: number) : boolean {
return x < y && y < z;
}
console.log(
apSet(
apSet(
mapSet(curry3(isBetween), new Set([1, 2])),
new Set([3, 4, 99])),
new Set([5, 6])));
function liftA2Set<A, B, C>(
fn: A => B => C,
s1: Set<A>,
s2: Set<B>) : Set<C> {
return apSet(mapSet(fn, s1), s2);
}
function liftA3Set<A, B, C, D>(
fn: A => B => C => D,
s1: Set<A>,
s2: Set<B>,
s3: Set<C>) : Set<D> {
return apSet(liftA2Set(fn, s1, s2), s3);
}
function liftA4Set<A, B, C, D, E>(
fn: A => B => C => D => E,
s1: Set<A>,
s2: Set<B>,
s3: Set<C>,
s4: Set<D>) : Set<E> {
return apSet(liftA3Set(fn, s1, s2, s3), s4);
}
console.log(liftA2Set(curry2(subtract), new Set([5, 6, 7]), new Set([1, 2, 3])));
console.log(liftA3Set(curry3(isBetween),
new Set([1, 2]),
new Set([3, 4]),
new Set([5, 6])));
|
const handleRepository = (oGen) => {
const { payload } = oGen;
if (!payload.repositoryName) {
payload.repositoryName = payload.mainName;
}
const url = `https://github.com/${
payload.repositoryOrgName ? payload.repositoryOrgName + "/" : ""
}${payload.repositoryName}`;
payload.repository = {
type: "git",
url,
};
payload.repositoryUrl = url;
if (payload.babelRootMode) {
let pkgPath = `packages/${payload.mainName}`;
if (payload.repositoryName) {
const destFolder = oGen.destinationRoot();
const findRepositoryName = destFolder.lastIndexOf(payload.repositoryName);
if (-1 !== findRepositoryName) {
pkgPath = destFolder.substring(
findRepositoryName + payload.repositoryName.length + 1
);
}
}
payload.repository.directory = pkgPath;
payload.repositoryHomepage = `${url}/tree/main/${pkgPath}`;
} else {
payload.repositoryHomepage = url;
}
};
const handleAnswers =
(oGen) =>
(answers, cb = () => {}) => {
const { mainName, isUseWebpack } = answers;
oGen.mainName = mainName;
oGen.payload = {
...answers,
description: answers.description || "TODO: description",
keyword: answers.keyword || mainName,
npmDependencies: {},
babelRootMode: "",
webpackEnabled: "",
};
if (answers.babelRootMode) {
oGen.payload.babelRootMode = " --root-mode upward";
}
if (isUseWebpack) {
oGen.payload.webpackEnabled = "on";
oGen.payload.npmDependencies["reshow-app"] = "*";
}
handleRepository(oGen);
cb(oGen.payload);
};
module.exports = handleAnswers;
|
/**
* Created by giufus on 23/06/16.
*/
var logger= require('morgan')
var a = process.argv[2];
var aPromise_A = new Promise((resolve, reject) => {
if (a <= 0) {
console.error('aPromise_A reject', a)
a++;
reject(a)
}
else {
console.log('aPromise_A resolve', a)
resolve(a)
}
});
var aPromise_B = new Promise((resolve, reject) => {
if (a <= 0) {
console.error('aPromise_B reject', a)
a++;
reject(a)
}
else {
console.log('aPromise_B resolve', a)
resolve(a)
}
});
function promises() {
aPromise_A
.then(aPromise_B)
/*.then(
(res) => {
console.log('RESOLVED')
return 42;
}, (res) => {
console.error('REJECTED')
return res;
}
)*/.catch((val) => {
console.error('THE FINAL rejection', val);
});
}
function promiseAll() {
Promise.all([aPromise_A, aPromise_B])
.then(
function () {
console.log(':) YOOOO-OOOHHHH!!!');
}, function () {
console.error(':( DOHHHH!!!')
});
}
setTimeout(promises, 3000);
//setTimeout(promiseAll, 3000);
|
var myApp = angular.module("MyApp",[]);
myApp.controller('phoneListControl', ['$scope', '$http',
function ($scope, $http) {
$http.get('phones/phones.json').success(function(data) {
$scope.phones = data;
}).error(function() {
console.log("error");
});
$scope.orderProperty = 'age';
}]);
|
import {EbayLoading} from "./EbayLoading";
export const LoadingComponent = {
template: `
<div class="LoadingComponent">
<ebay-loading-component></ebay-loading-component>
</div>
`,
components: {
'ebay-loading-component': EbayLoading,
}
}; |
const convict = require('convict');
const config = convict({
http: {
port: {
doc: 'The port to listen on',
default: 3000,
env: 'PORT'
}
},
authentication: {
google: {
"clientId": {
"doc": "The Client ID from Google to use for authentication",
"default": "",
"env": "GOOGLE_CLIENTID"
},
"clientSecret": {
"doc": "The Client Secret from Google to use for authentication",
"default": "",
"env": "GOOGLE_CLIENTSECRET"
}
},
facebook: {
"clientId": {
"doc": "1349052711830842",
"default": "",
"env": "FACEBOOK_CLIENTID"
},
"clientSecret": {
"doc": "47af6edaa2c4a2881a53a3d8ffb7ab09",
"default": "",
"env": "FACEBOOK_CLIENTSECRET"
}
},
token: {
secret: {
doc: 'The signing key for the JWT',
default: 'mySuperSecretKey',
env: 'JWT_SIGNING_KEY'
},
issuer: {
doc: 'The issuer for the JWT',
default: 'social-logins-spa'
},
audience: {
doc: 'The audience for the JWT',
default: 'social-logins-spa'
}
}
}
});
config.validate();
module.exports = config;
|
/*global ODSA */
// Written by Jun Yang and Cliff Shaffer
// Astack pop method
$(document).ready(function() {
"use strict";
var av_name = "astackPopCON";
// Load the config object with interpreter and code created by odsaUtils.js
var config = ODSA.UTILS.loadConfig({av_name: av_name}),
interpret = config.interpreter, // get the interpreter
code = config.code; // get the code object
var av = new JSAV(av_name);
var pseudo = av.code(code[0]);
// Relative offsets
var leftMargin = 20;
var topMargin = 0;
var arr = av.ds.array([12, 45, 5, 81, "", "", "", ""],
{indexed: true, left: leftMargin, top: topMargin});
arr.addClass([4, 5, 6, 7], "unused");
var topArr = av.ds.array([4], {left: leftMargin + 100, top: topMargin + 55});
av.label("top", {left: leftMargin + 73, top: topMargin + 58});
var arrReturn = av.ds.array([""], {left: leftMargin + 100,
top : topMargin + 90});
arrReturn.hide();
var labelReturn = av.label("return", {left: leftMargin + 55,
top : topMargin + 93});
labelReturn.hide();
// Slide 1
av.umsg(interpret("sc1"));
arr.highlight(4);
pseudo.setCurrentLine("sig");
av.displayInit();
// Slide 2
av.umsg(interpret("sc2"));
pseudo.setCurrentLine("empty");
av.step();
// Slide 3
av.umsg(interpret("sc3"));
arr.unhighlight(4);
arr.highlight(3);
topArr.value(0, 3);
topArr.highlight(0);
pseudo.setCurrentLine("return");
av.step();
// Slide 4
av.umsg(interpret("sc4"));
arrReturn.show();
labelReturn.show();
av.effects.copyValue(arr, 3, arrReturn, 0);
arrReturn.highlight();
topArr.unhighlight(0);
arr.value(3, "");
av.recorded();
});
|
//promises example by Joost Faber https://codepen.io/joostf/pen/OQxpxx
const loadInsults = new Promise(function(resolve, reject) {
const request = new XMLHttpRequest()
const link = 'https://api.whatdoestrumpthink.com/api/v1/quotes'
request.open('GET', link, true)
request.onload = () => {
if (request.status >= 200 && request.status < 400) {
// Success!
const data = JSON.parse(request.responseText)
resolve(data.messages.personalized)
} else {
// We reached our target server, but it returned an err
reject(error)
}
}
request.onerror = () => {
// There was a connection error of some sort
}
request.send()
})
const loadNames = new Promise(function(resolve, reject) {
const request = new XMLHttpRequest()
const linkNames = 'https://randomuser.me/api/?results=573'
request.open('GET', linkNames, true)
request.onload = () => {
if (request.status >= 200 && request.status < 400) {
// Success!
const data = JSON.parse(request.responseText)
// const randomNames = []
// data.results.forEach(element => {
// randomNames.push(element.name.first)
// })
const users = data.results.map(user => ({
name: user.name.first,
lastName: user.name.last,
title: user.name.title,
email: user.email,
cellphone: user.cell,
gender: user.gender,
picture: user.picture,
location: user.location
}))
resolve(users)
} else {
// We reached our target server, but it returned an error
reject(error)
}
}
request.onerror = () => {
// There was a connection error of some sort
}
request.send()
})
Promise.all([loadNames, loadInsults]).then(function(values) {
createTable(values)
})
function createTable(values) {
const names = values[0]
const insults = values[1]
console.log(names)
console.log(values)
document.getElementById('insult').innerHTML =
'Insulting ' + insults.length + ' people Donald Trump style'
// get the reference for the body
const body = document.getElementsByTagName('body')[0]
// creates a <table> element and a <tbody> element
const tbl = document.createElement('table')
const tblBody = document.createElement('tbody')
// creating all cells
for (let i = 0; i < insults.length; i++) {
// creates a table row
const row = document.createElement('tr')
// Create a <td> element and a text node, make the text
// node the contents of the <td>, and put the <td> at
// the end of the table row
const cell = document.createElement('td')
const cellText = document.createTextNode(
names[i].name.charAt(0).toUpperCase() +
names[i].name.slice(1) +
' ' +
insults[i]
)
cell.appendChild(cellText)
row.appendChild(cell)
// add the row to the end of the table body
tblBody.appendChild(row)
}
// put the <tbody> in the <table>
tbl.appendChild(tblBody)
// appends <table> into <body>
body.appendChild(tbl)
// sets the border attribute of tbl to 2;
tbl.setAttribute('border', '2')
}
|
import React, { Component } from "react";
import axios from "./axios";
class UploaderCover extends Component {
constructor(props) {
super(props);
this.imageSelected = this.imageSelected.bind(this);
this.upload = this.upload.bind(this);
}
imageSelected(e) {
this.setState({
imageFile: e.target.files[0]
});
}
upload() {
var formData = new FormData();
if (this.state.imageFile == "") {
this.setState({
error: "Please, select a file to upload."
});
} else {
formData.append("file", this.state.imageFile);
axios.post("/uploadcover", formData).then(res => {
if (res.data.success) {
this.props.setCover(res.data.coverUrl);
}
});
}
}
render() {
const { closeCoverUploader } = this.props;
return (
<div id="uploader">
<div className="uploader-modal">
<div className="uploader-inlet">
<div className="wrapper-inlet">
<h3 className="text-upload">Update Cover Photo</h3>
<i
className="fas fa-times icon-modal"
onClick={closeCoverUploader}
/>
</div>
<div className="linha2" />
<div className="wrapper-inlet-2">
<label id="file-label" htmlFor="file-field">
Select a Image
</label>
<input
id="file-field"
type="file"
onChange={this.imageSelected}
name=""
value=""
/>
<button
id="upload-button"
onClick={this.upload}
name="button"
>
Save
</button>
</div>
</div>
</div>
</div>
);
}
}
export default UploaderCover;
|
export const width = 40;
export const height = 30;
export const mines = 100;
|
import { weekDayJson, MONTH_NAME } from "./variable"
import isObject, { deepClone } from './isObject'
export const add0 = function (m) {
return m < 10 ? '0' + m : m
}
//**时间转换
export const reDate = function (date){
var date = date ? new Date(date) : new Date(),
year = date.getFullYear(),
mon = date.getMonth() + 1,
day = date.getDate();
return year + '-' + add0(mon) + '-' + add0(day);
}
export const plWeekDate = (gd, pday, initAct) => {
var wJson = initAct || deepClone(weekDayJson),
m = 0;
if(!isObject(wJson)) return {};
if(typeof gd !== 'number' || typeof pday !== 'number') return wJson;
if(pday === 0){
for( var i in wJson ) {
m++;
m <= gd ? wJson[i] = [0, false] : wJson[i] = [m - gd, true];
}
} else {
for( var i in wJson ) {
m++;
m < gd ? wJson[i] = [(pday - gd) + m + 1, true] : wJson[i] = [0, false];
}
}
return wJson;
}
export const monthTrans = (month) => {
let mon = parseInt(month),
len = MONTH_NAME.length;
if(typeof mon !== 'number') return MONTH_NAME[0];
if(mon <= 0) return MONTH_NAME[0];
if(mon > 12) return MONTH_NAME[len - 1];
for(let i = 0; i < len; i++) {
if(mon === i + 1) return MONTH_NAME[i]
}
}
export const moyEstimate = (moy) => {
let eg = /^20\d{2}(-|\/)\d{1,2}$/,
ym = {
year: '2018',
month: '01'
}
if(!moy.match(eg)) return ym;
let year = moy.slice(0, 4),
month = moy.substring(5);
return {
year,
month
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.