text
stringlengths 7
3.69M
|
|---|
const PromptsArray = [
"Describe an experience where you were unsuccessful in achieving your goal. What lessons did you learn from this experience?",
"Describe an experience that forever changed your life and your outlook on life.",
"What movie, poem, musical composition, or novel has most influenced your life and the way that you view the world? Why?",
"What do you plan on doing after you graduate from college?",
"If you were given the ability to change one moment in your life, would you do so? Why or why not? If so, what moment would you change and why?",
"Presuming there was only one open admission spot remaining, why should this college choose to accept your application and not that of another student?",
"Describe some tasks that you have accomplished over the past two years that have no connection to academic studies.",
"What would you describe to be your most unique or special skill that differentiates you from everyone else?",
"What do you consider to be the best advice you ever received? Who gave you that advice and did you follow that advice or not?",
"What do you consider to be the most important political or social movement of the 20th century? Why?",
"Choose one quotation that defines who you are and explain why that quotation describes you so well.",
"How has the neighborhood you've grown up in molded you into the person you are today?",
"Describe the most embarrassing moment of your life and explain what you learned from that experience and how it has made you a better or stronger person today.",
"Tell a story that directly or indirectly illustrates the type of person you are.",
"Think back to a situation in your life where you had to decide between taking a risk and playing it safe. Which choice did you make?",
"Choose the invention that you think has had the most negative impact on our world and explain why you chose that invention.",
"Devise a question that is not on this college admission form and provide a complete, thoughtful answer to it.",
"What have been some of the major challenges you’ve encountered in your life? And was there a silver lining?",
"Did a parent’s fragile health situation challenge you to take on more responsibilities than the average teenager?",
"Did a series of setbacks on your road to becoming a child actor introduce you to screenwriting, your professional goal and biggest passion?",
"Are you the kind of person who can rebound and turn every experience, good or bad, into one from which you can learn something? What experiences might illustrate this quality?"
];
var randomPrompt;
function display(){
randomPrompt = PromptsArray[Math.floor(Math.random() * PromptsArray.length)];
document.getElementById('theprompt').innerHTML = randomPrompt;
}
|
export * from './superheroes.service';
export * from './todos.service';
|
import regeneratorRuntime from '../../../lib/regenerator-runtime'
import { connect } from '../../../lib/wechat-weapp-redux'
import { fetching, fetchend, clearError } from '../../../store/actions/loader'
import { clearWxRequestPayment } from '../../../store/actions/group'
import promisify from '../../../lib/promisify'
const mapStateToData = (state, options) => {
return {
isFetching: state.loader.isFetching,
displayError: state.loader.displayError,
buying: state.buying
}
}
const mapDispatchToPage = dispatch => ({
fetching: _ => dispatch(fetching()),
fetchend: _ => dispatch(fetchend()),
clearError: _ => dispatch(clearError()),
clearWxRequestPayment: _ => dispatch(clearWxRequestPayment())
})
const pageConfig = {
data:{
remainingTime:900
},
async onLoad () {
const { remainingTime } = this.options
if(remainingTime) {
this.setData({ remainingTime })
}
const { wxRequestPayment, _paying } = this.data.buying
if (!wxRequestPayment) return wx.redirectTo({ url: '/pages/mine/orderList/orderList?type=waitPay'})
this.setData({ _paying })
// don't need wechat pay
if (!wxRequestPayment.toWeixin) {
this.fetching()
return setTimeout(() => {
this.fetchend()
wx.redirectTo({ url: `/pages/group/paySuccess/paySuccess?id=${wxRequestPayment.orderId}`})
}, 500)
}
try {
const success = await promisify(wx.requestPayment)(wxRequestPayment)
this.clearWxRequestPayment()
if (success) return wx.redirectTo({ url: `/pages/group/paySuccess/paySuccess?id=${wxRequestPayment.orderId}`})
return wx.redirectTo({ url: '/pages/mine/orderList/orderList?type=waitPay'})
} catch (error) {
return wx.redirectTo({ url: '/pages/mine/orderList/orderList?type=waitPay'})
}
},
countdownOver () {
return wx.redirectTo({ url: '/pages/mine/orderList/orderList?type=waitPay'})
},
reload () {
this.clearError()
this.onLoad()
},
onUnload () {
this.clearError()
}
}
Page(
connect(
mapStateToData,
mapDispatchToPage
)(pageConfig)
)
|
export { SliderButton } from './SliderButton';
|
$(document).ready(function () {
const url = 'http://localhost:50401/api/game';
let ob = {
next: (value) => {
console.log(value.response)
print(value.response)
},
error: (err) => console.log(err),
complete: () => console.log("completed")
}
$('#btnOb').on('click', function(){
Rx.Observable.ajax(url).subscribe(ob)
})
});
function print(data) {
for (var i = 0; i < data.length; i++) {
var item = data[i];
for (var field in item) {
$('#txtResult').append(" " + field +
" : " + item[field] + ", ")
}
$('#txtResult').append("<br>")
}
}
|
/*
findCommunity 内在灵魂,沉稳坚毅
生成时间:Mon Aug 15 2016 破门狂人R2-D2为您服务!
【使用方法】:
1。 引入该文件
2. 在html中添加组件标签:
<tsy:find config="$opt">
</tsy:find>
3. 在 $opt中传入配置参数,需要传入callback,以及依赖对象函数,例如:
$opt:{
callback: function (res) {
alert(res)
},
target:'Community'
},
其中,会在点击之后,将所选中的项目作为res传入到callback中,
*/
define('findCommunity', [
'avalon',
'text!../../lib/find/find.html',
'css!../../lib/find/find.css'
], function (avalon, html, css) {
//批量绑定快捷键
function bindK(obj) {
require(['../../plugins/shortcut/shortcut.js'], function () {
/*快捷键设置*/
var x;
for (x in obj) {
if (x.charAt(0) != "$") {
if (obj.$opt != undefined) {
shortcut.add(x, obj[x], obj.$opt)
} else {
shortcut.add(x, obj[x])
}
//console.log(x + "快捷键绑定成功")
}
}
})
}
//批量删除快捷键
function removeK(obj) {
require(['../../plugins/shortcut/shortcut.js'], function () {
/*快捷键设置*/
var x;
for (x in obj) {
if (x.charAt(0) != "$") {
shortcut.remove(x)
//console.log(x + "已解除绑定")
}
}
})
}
avalon.component('tsy:find', {
$template: html,
target: "",
id: "",
/*
* ***************参数队列区**************************/
showAdd:false,
//回调函数
callback: function () {
},
//但输入过程中
onInput: function () {
},
//搜索关键字
Keywords: '',
//要填入的字段的名称
keyName:"",
placeholder:"",
//上次的关键字
$lastKey: "",
//即将插入的输入框
listTmp: '',
//这个输入框
input: "",
//数据列表
list: [],
P: 1,
N: 6,
T: 1,
//当前选中项
active: 0,
//当前列表状态 0:未开启 1:查询中 2:查询结束
state: 0,
$out: {
1: true,
2: true
},
//错误提示
err: '',
//请求延迟
timeout: "",
//快捷键列表
$hotKey: {},
/*
* ***************函数空位**************************/
//搜索函数
search: function () {
},
//立正
attention: function () {
},
//稍息
ease: function () {
},
//阻止稍息
dontEase: function () {
},
//选择过程
hover: function () {
},
//选中回调
select: function () {
},
//重置
reset: function () {
},
//添加
add: function () {
},
/*
* ***************自启动项目**************************/
$init: function (vm, elem) {
//主动读取配置
var elem = avalon(elem);
//将参数放入对于的地方
try {
if (elem.data('id') != undefined) {
vm.id = elem.data('id');
//todo 改写上方的'lv'为你想要获取到的值
}
} catch (err) {
}
require(['text!../../lib/find/' + vm.target + '.html'], function (html) {
vm.listTmp = html
})
//加载函数
avalon.mix(vm, {
$hotKey: {
$opt: {
type: "keydown"
},
"up": function () {
vm.hover('up')
},
"down": function () {
vm.hover('down')
},
'left': function () {
if (vm.P > 1) {
vm.search(-1)
}
},
"right": function () {
if (vm.P < (Math.ceil(vm.T / vm.N)))
vm.search(1)
},
'enter': function () {
vm.select(vm.active)
}
},
//选择过程
hover: function (i) {
if (i == 'up') {
if (vm.active > 0) {
vm.active--
}
return
}
if (i == 'down') {
if (vm.active < vm.list.length - 1) {
vm.active++
}
return
}
vm.active = i
},
//立正
attention: function (input) {
vm.$hotKey.$opt.target = input
bindK(vm.$hotKey, input)
vm.state = 2
vm.$out[1] = false
vm.search(0)
},
//搜索函数
search: function (p) {
vm.state = 1
var data = {
Keyword: vm.Keywords,
P: Number(vm.P) + Number(p),
N: vm.N
}
//if (data.Keyword == "") {
// return vm.state = 2
//}
if (data.P < 1) {
data.P = 1
}
if (data.P > Math.ceil(vm.T / data.N)) {
data.P = Math.ceil(vm.T / data.N)
}
if (data.P > Math.ceil(vm.T / vm.N)) {
data.P = Math.ceil(vm.T / vm.N)
}
if (vm.$lastKey != vm.Keywords) {
data.P = 1;
try{
vm.onInput(vm)
}
catch (err){}
}
clearTimeout(vm.timeout);
vm.$lastKey = data.Keyword;
require(['../../obj/Management/' + vm.target + '.js'], function (comm) {
vm.timeout = setTimeout(function () {
comm.search(data, {
success: function (res) {
avalon.mix(vm, {
P: res.P,
T: res.T,
list: res.L
})
vm.state = 2
vm.err = ''
},
error: function (err) {
vm.state = 2
vm.err = err
}
})
})
})
},
//选中回调
select: function (i) {
if (i === undefined) {
i = vm.active
}
var res = vm.list[i]
try{
vm.$lastKey=vm.Keywords=res[vm.keyName]
}catch (err){}
vm.callback(res,vm.id,vm)
vm.ease()
},
//稍息
ease: function (i) {
if (i === undefined) {
out()
return
}
vm.$out[i] = true
if (vm.$out[1] && vm.$out[2]) {
out()
}
console.log(vm.target + ":" + vm.$out[1] + "," + vm.$out[2])
function out() {
removeK(vm.$hotKey)
vm.state = 0
vm.$out = {
1: true,
2: true,
}
}
}
,
//阻止稍息
dontEase: function () {
vm.$out[2] = false
}
,
//重置
reset: function () {
avalon.mix(vm, {
//搜索关键字
Keywords: '',
//上次的关键字
$lastKey: "",
//数据列表
list: [],
P: 1,
N: 8,
T: 0,
//当前选中项
active: 0,
//当前列表状态 0:未开启 1:查询中 2:查询结束
state: 0,
$out: {
1: true,
2: true,
},
//错误提示
err: '',
})
}
,
//添加
add: function () {
vm.state = 1
if (vm.Keywords == '') {
vm.err = '没有输入区域名称'
vm.state = 2
return
}
require(['../../obj/' + vm.target + '.js'], function (comm) {
if (!confirm('是否添加【' + vm.Keywords + '】到列表中?')) {
vm.err = ''
return
}
comm.add({
Title: vm.Keywords
}, {
success: function (res) {
vm.state = 2
vm.search(0)
vm.err = ''
},
error: function (err) {
vm.state = 2
vm.err = err
}
})
})
}
,
})
if (vm.id != "") {
window[vm.id] = vm
}
},
$ready: function (vm, elem) {
//vm.build()
},
})
})
|
import React, { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import style from './character.module.css'
const API = 'https://rickandmortyapi.com/api/character/'
const productItem = () => {
//initialState
const [character, setCharacter] = useState({episode: []})
//get id
const { query: { id }, } = useRouter([]);
//getData
useEffect(() => {
if(id) {
window.fetch(`${API}${id}`)
.then((response) => response.json())
.then((data) => setCharacter(data))
}
}, [id])
return (
<main className={style.section}>
<div className={style.container}>
<div className={style.picture}>
<img src={character.image}/>
<h1>{character.name}</h1>
</div>
<div className={style.list}>
<h3>Nombre: {character.name}</h3>
<h3>Estado: {character.status}</h3>
<h3>Especie: {character.species}</h3>
<h3>Genero: {character.gender}</h3>
<h3>Episodios: {character.episode.length}</h3>
</div>
</div>
</main>
)
}
export default productItem
|
export default {
VEHICLES: '/vehicle',
};
|
import React from 'react';
import Footer from './Footer/Footer';
const links = {
firstCol: [
{ href: 'https://video.ibm.com/contact-us', linkText: 'Contact' },
{ href: 'https://www.ibm.com/privacy/us/en/', linkText: 'Privacy' },
{ href: 'https://www.ibm.com/legal/us/en/', linkText: 'Terms of use' },
{
href: 'https://www-03.ibm.com/software/sla/sladb.nsf/sla/sd-7525-06',
linkText: 'Terms and conditions for IBM Video Streaming',
},
],
secondCol: [
{ href: 'https://www.ibm.com/accessibility/us/en/', linkText: 'Accessibility' },
{ href: 'https://video.ibm.com/copyright-policy', linkText: 'Copyright Policy' },
{ href: 'https://video.ibm.com/acceptableusepolicy', linkText: 'Acceptable use policy' },
{
href: 'https://video.ibm.com/',
linkText: 'Cookie preferences',
onClick: (e) => {
e.preventDefault();
const teconsentLink = document.querySelector('#teconsent > a');
const event = new MouseEvent('click');
if (teconsentLink) {
teconsentLink.dispatchEvent(event);
}
},
},
],
};
const CustomFooter = () => <Footer links={links} Content={() => ''} />;
export default CustomFooter;
|
const fetch = require('node-fetch');
const { URLSearchParams } = require('url');
class CucumberStudio {
constructor ({
token,
clientId,
uid,
projectId,
projectToken
}) {
this.token = token;
this.clientId = clientId;
this.uid = uid;
this.projectId = projectId || null;
this.projectToken = projectToken || null;
this.baseUrl = 'https://studio.cucumber.io/api';
this.exportUrl = 'https://export.cucumber.io/download';
this.defaultHeaders = {
'Accept': 'application/vnd.api+json; version=1',
'Access-Token': this.token,
'Client': this.clientId,
'Uid': this.uid
};
}
request(url, options = {}) {
url = (options.noBaseUrl ? '' : this.baseUrl) + url;
if (options.params) {
const params = new URLSearchParams(options.params);
url += (url.includes('?') ? '&' : '?') + params.toString();
}
return fetch(url, {
...options,
headers: Object.assign({}, this.defaultHeaders, options.headers || {})
})
.then(res => res.json())
.then(res => res.data || res);
}
// https://studio-api.cucumber.io/#get-projects
getProjects() {
return this.request('/projects');
}
// https://studio-api.cucumber.io/#get-a-particular-project
getProjectById(projectId = this.projectId) {
return this.request(`/projects/${projectId}`);
}
// https://studio-api.cucumber.io/#create-a-project-backup
createProjectBackup(projectId = this.projectId) {
return this.request(`/projects/${projectId}/backups`, { method: 'POST' });
}
// https://studio-api.cucumber.io/#get-last-backup-state
getLastProjectBackup(projectId = this.projectId) {
return this.request(`/projects/${projectId}/backups/last`);
}
// https://studio-api.cucumber.io/#action-words
getActionWords(projectId = this.projectId) {
return this.request(`/projects/${projectId}/actionwords`);
}
// https://studio-api.cucumber.io/#get-a-single-action-word
getActionWordById(actionWordId, { projectId = this.projectId } = {}) {
return this.request(`/projects/${projectId}/actionwords/${actionWordId}`);
}
// https://studio-api.cucumber.io/#create-an-action-word
createActionWord(actionWord, { projectId = this.projectId } = {}) {
return this.request(`/projects/${projectId}/actionwords`, {
method: 'POST',
body: JSON.stringify(actionWord),
headers: { 'Content-Type': 'application/json' }
});
}
// https://studio-api.cucumber.io/#get-scenarios-of-a-given-project
async getScenarios({ projectId = this.projectId, include = [] } = {}) {
const scenarios = await this.request(`/projects/${projectId}/scenarios`, {
params: { include }
});
if (include.includes('tags')) {
const tagsMap = await this._getScenariosTagsMap(scenarios.map(s => s.id), projectId);
return scenarios.map(scenario => this._hydrateWithTags(scenario, tagsMap));
}
return scenarios;
}
_hydrateWithTags(item, tagsMap) {
return {
...item,
relationships: {
...item.relationships,
tags: {
...item.relationships.tags,
data: item.relationships.tags.data
.map(tag => Object.assign({}, tag, tagsMap[tag.id]))
}
}
};
}
// https://studio-api.cucumber.io/#get-tags-of-a-given-scenario
getScenarioTags(scenarioId, { projectId = this.projectId } = {}) {
return this.request(`/projects/${projectId}/scenarios/${scenarioId}/tags`);
}
// Cucumber Studio does not include tag labels with lists (only tag IDs),
// we need to fetch each item one by one.
_getScenariosTagsMap(scenarioIds, { projectId = this.projectId } = {}) {
if (scenarioIds.length) {
return this.getScenarioTags(scenarioIds[0], { projectId })
.then(tags => {
return this._getScenariosTagsMap(scenarioIds.slice(1), { projectId })
.then(res => Object.assign({}, this._arrayToMap(tags), res));
});
} else {
return Promise.resolve({});
}
}
_arrayToMap(arr) {
return arr.reduce((res, item) => ({ ...res, [item.id]: item }), {});
}
// https://studio-api.cucumber.io/#get-test-runs-of-a-project
async getTestRuns({ projectId = this.projectId, include = [], status = null } = {}) {
const runs = await this.request(`/projects/${projectId}/test_runs`, {
params: {
'filter[status]': status,
include
}
});
if (include.includes('tags')) {
const tagsMap = await this._getTestRunsTagsMap(runs.map(s => s.id), { projectId });
return runs.map(run => this._hydrateWithTags(run, tagsMap));
}
return runs;
}
// https://studio-api.cucumber.io/#create-tag-in-a-test-run
getTestRunTags(runId, { projectId = this.projectId } = {}) {
return this.request(`/projects/${projectId}/test_runs/${runId}/tags`);
}
// Cucumber Studio does not include tag labels with lists (only tag IDs),
// we need to fetch each item one by one.
async _getTestRunsTagsMap(runIds, { projectId = this.projectId } = {}) {
if (runIds.length) {
const tags = await this.getTestRunTags(runIds[0], { projectId });
const res = await this._getTestRunsTagsMap(runIds.slice(1), { projectId });
return Object.assign({}, this._arrayToMap(tags), res);
} else {
return Promise.resolve({});
}
}
// https://studio-api.cucumber.io/#create-a-test-run
createTestRun({ name = 'Untitled', description = '', scenarioIds = null, projectId = this.projectId }) {
return this.request(`/projects/${projectId}/test_runs`, {
method: 'POST',
body: JSON.stringify({
data: {
attributes: {
name,
description,
scenario_ids: scenarioIds
}
}
}),
headers: { 'Content-Type': 'application/json' }
});
}
// https://export.cucumber.io/
exportTestRun(testRunId) {
const params = new URLSearchParams({
token: this.projectToken,
lang: 'cucumber-javascript',
test_run: testRunId,
filter_on: '',
filter_on_value: '',
filter_on_status: '',
'only[]': 'features',
with_folders: 'on',
keep_filenames: 'on',
keep_foldernames: 'on',
with_dataset_names: 'on'
});
return fetch(`${this.exportUrl}?${params}`)
.then(res => res.buffer());
}
}
module.exports = CucumberStudio;
|
const initialState = { email: '', password: '', isAdmin: '', isAuth: false };
function reducer(state = initialState, action) {
switch (action.type) {
case 'SET_EMAIL_PASSWORD':
return {
...state,
email: action.payload.email,
password: action.payload.password,
};
case 'SET_ADMIN':
return {
...state,
isAdmin: action.payload.isAdmin,
};
case 'SET_IS_AUTH':
return {
...state,
isAuth: action.payload,
};
default:
return state;
}
}
export default reducer;
|
import React from "react";
import "./location.css";
import "./bulma.css";
function Location() {
return (
<div className="container location-container">
<div className="title-section">
<img src="/images/logo.svg" alt="" />
</div>
<div className="main-section">
<div className="main-wrapper">
<div className="waiting-img">
<img src="/images/pluto-coming-soon.png" alt="" />
</div>
<div className="waiting-title">
미세먼지 정보를 가져오고 있습니다!
</div>
</div>
</div>
</div>
);
}
export default Location;
|
const router = require('./routes');
const errorHandler = require('./errorHandler');
module.exports = {
router,
errorHandler,
};
|
const AJV = require('ajv').default;
const addFormats = require('ajv-formats');
const ajv = new AJV({ useDefaults: true });
addFormats(ajv);
module.exports = ajv;
|
import { Emitter, ErrorEmitter } from '../../../helpers/emitter';
import { GetValues } from '../service/values';
class ValueController {
/**
* @description Pega uma ligação do banco.
* @param {Object} req
* @param {Object} res
*/
static async GetValues(req, res) {
const { _idCall, _idPlan } = req.params;
const { query } = req;
Object.keys(query).forEach(x => (req.query[x] ? null : delete req.query[x]));
if (!('time' in query)) {
return ErrorEmitter(res, 400);
}
try {
const data = await GetValues({ _idCall, _idPlan }, query);
return Emitter(res, { status: 200, data });
} catch (err) {
return ErrorEmitter(res, 500, err);
}
}
}
export default ValueController;
|
import React from 'react';
import Enzyme, { shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Header from './index';
import { findByDataId } from '../../utils';
Enzyme.configure({
adapter: new Adapter()
});
const setup = (props={}) => {
return shallow(<Header {...props} />);
}
describe("Header Component", () => {
let component;
beforeAll(() => {
component = setup();
})
it ("Header is being rendered", () => {
const ele = component.find(`[data-test-id='header']`);
expect(ele.length).toEqual(1);
});
it ("Logo in Header shoudl render", () => {
const ele = component.find(`[data-test-id='img']`);
expect(ele.length).toEqual(1);
});
});
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
// import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
// import { faUserPlus } from '@fortawesome/free-solid-svg-icons';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import ReCAPTCHA from 'react-google-recaptcha';
import {
FormGroup,
FormControl,
Col,
Row,
Checkbox,
Button,
} from 'react-bootstrap';
import axios from 'axios';
import { toastr } from 'react-redux-toastr';
import {
validateFirstName,
validateLastName,
validateEmail,
validatePassword,
validatePasswordConfirm,
} from '../../../validation';
import { errors, titles } from '../../../constants/messages';
import FieldError from '../../../components/FieldError/FieldError';
import logoDark from '../../../../public/logo/dark.png';
import logoLight from '../../../../public/logo/light.png';
import s from './Register.css';
import routes from '../../../constants/routes';
import themify from '../../../themify';
import config from '../../../config';
import Panel from '../../../components/Panel';
import TermNConditionsModal from './TermNConditionsModal';
import PrivacyPolicyModal from './PrivacyPolicyModal';
/* eslint-disable css-modules/no-undef-class */
class Register extends React.Component {
constructor() {
super();
this.state = {
showWarnings: false,
Name: '',
LastName: '',
email: '',
password: '',
confirmPassword: '',
isAgreeWithTermAndConditions: false,
showTermsAndConditions: false,
showPrivacyPolicy: false,
submitting: false,
};
this.handleSubmit = this.handleSubmit.bind(this);
this.reCaptchaRef = React.createRef();
}
// componentDidMount() {
// if (this.props.isLoggedIn) window.location.href = routes.DASHBOARD;
// }
getLogo() {
if (this.props.theme === 'light') return logoLight;
return logoDark;
}
handleSubmit(captchaValue) {
// if (captchaValue) {
this.setState({ showWarnings: true });
const formHasError = !(
validateFirstName(this.state.Name).length === 0 &&
validateLastName(this.state.LastName).length === 0 &&
validateEmail(this.state.email).length === 0 &&
validatePasswordConfirm(this.state.password, this.state.confirmPassword)
.length === 0 &&
validatePassword(this.state.password, false).length === 0
);
if (formHasError) {
return;
}
localStorage.setItem('email', this.state.email);
// reset recaptcha value
this.reCaptchaRef.current.reset();
this.setState({ submitting: true });
axios
.post(
`${config.api.serverUrl}/v1/auth/register`,
{
firstName: this.state.Name,
lastName: this.state.LastName,
email: this.state.email,
password: this.state.password,
referralToken: this.props.referralToken,
captchaValue,
},
{
headers: {
Authorization: this.props.authToken,
[config.apiKeyHeader]: config.apiKey,
},
},
)
.then(() => {
window.location.href = `${routes.VERIFY_EMAIL}?email=${
this.state.email
}`;
// history.push(`${routes.VERIFY_EMAIL}?email=${email}`);
})
.catch(err => {
this.setState({ submitting: false });
if (err.message === 'Network Error') {
toastr.error(titles.CONNECTION_ERROR, errors.SERVER_CONNECTION_LOST);
} else if (err.response && err.response.data.error) {
toastr.error(
err.response.data.error.title,
err.response.data.error.description,
);
}
});
// }
}
render() {
return (
<div>
<div className={themify(s, s.registerMain, this.props.theme)}>
<div className={s.registerHeader}>
<img src={this.getLogo()} alt="innovation exchange platform" />
</div>
<div className={s.registerContainer}>
<Panel theme={this.props.theme} style={{ textAlign: 'center' }}>
<div className={s.registerTitle}>Create your account</div>
<form className={s.regForm}>
<Row>
<Col md={6} xs={12}>
<FormGroup
controlId="name"
className={s.customInput}
validationState={this.state.nameValidation || null}
>
<FormControl
value={this.state.Name}
onChange={e => this.setState({ Name: e.target.value })}
type="text"
name="Name"
placeholder="First name"
/>
<FieldError
error={validateFirstName(this.state.Name)}
show={this.state.showWarnings}
/>
</FormGroup>
</Col>
<Col md={6} xs={12}>
<FormGroup
controlId="lastname"
className={s.customInput}
validationState={this.state.lastnameValidation || null}
>
<FormControl
value={this.state.LastName}
onChange={e =>
this.setState({ LastName: e.target.value })
}
type="text"
name="LastName"
placeholder="Last name"
/>
<FieldError
error={validateLastName(this.state.LastName)}
show={this.state.showWarnings}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col xs={12}>
<FormGroup
controlId="email"
className={s.customInput}
validationState={this.state.emailValidation || null}
>
<FormControl
value={this.state.email}
onChange={e => this.setState({ email: e.target.value })}
type="email"
name="email"
placeholder="Email"
/>
<FieldError
error={validateEmail(this.state.email)}
show={this.state.showWarnings}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col xs={12}>
<FormGroup
controlId="password"
className={s.customInput}
validationState={this.state.passwordValidation || null}
>
<FormControl
value={this.state.password}
onChange={e =>
this.setState({ password: e.target.value })
}
type="password"
name="password"
placeholder="Password"
/>
<FieldError
error="password should contain at least 10 characters with one lowercase, one uppercase and one special character."
show={!this.state.showWarnings}
color="white"
fontWeight="100"
/>
<FieldError
error={validatePassword(this.state.password, false)}
show={this.state.showWarnings}
/>
{/* <HelpBlock style={{ textAlign: 'left', fontSize: '11px' }}>password should contain 8 characters with at least 1 digit and 1 alpha character.</HelpBlock> */}
</FormGroup>
</Col>
</Row>
<Row>
<Col xs={12}>
<FormGroup
controlId="confirmPassword"
className={s.customInput}
validationState={
this.state.confirmPasswordValidation || null
}
>
<FormControl
value={this.state.confirmPassword}
onChange={e =>
this.setState({ confirmPassword: e.target.value })
}
type="password"
name="confirmPassword"
placeholder="Confirm Password"
/>
<FieldError
error={validatePasswordConfirm(
this.state.password,
this.state.confirmPassword,
)}
show={this.state.showWarnings}
/>
</FormGroup>
</Col>
</Row>
<Row>
<Col xs={12}>
<ReCAPTCHA
size="invisible"
ref={this.reCaptchaRef}
sitekey={config.recaptcha.siteKey}
onChange={captchaValue => this.handleSubmit(captchaValue)}
/>
</Col>
</Row>
<Row>
<Col xs={12}>
<Checkbox
checked={this.state.isAgreeWithTermAndConditions}
onChange={e =>
this.setState({
isAgreeWithTermAndConditions: e.target.checked,
})
}
name="isAgreeWithTermAndConditions"
className={s.rememberMe}
>
{'I agree to '}
<span
style={{ color: 'blueviolet' }}
role="presentation"
onClick={() => {
this.setState({ showPrivacyPolicy: true });
}}
>
Privacy Policy
</span>
<span> and </span>
<span
style={{ color: 'blueviolet' }}
role="presentation"
onClick={() => {
this.setState({ showTermsAndConditions: true });
}}
>
Terms & Conditions
</span>
<span> of {config.platformName}</span>
</Checkbox>
<Button
bsStyle="primary"
disabled={
this.state.isAgreeWithTermAndConditions === false ||
this.state.submitting
}
block
className={s.registerBtn}
onClick={() => this.reCaptchaRef.current.execute()}
>
{this.state.submitting
? 'Submitting ...'
: 'Create account'}
</Button>
</Col>
</Row>
</form>
</Panel>
<div className={s.registerFooter}>
<span>Already have an account?</span>
<span
role="presentation"
className={s.login}
onClick={() => {
window.location.href = routes.LOGIN;
}}
>
Login
</span>
</div>
</div>
</div>
<TermNConditionsModal
show={this.state.showTermsAndConditions}
onHide={() => this.setState({ showTermsAndConditions: false })}
/>
<PrivacyPolicyModal
show={this.state.showPrivacyPolicy}
onHide={() => this.setState({ showPrivacyPolicy: false })}
/>
</div>
);
}
}
Register.propTypes = {
theme: PropTypes.string,
authToken: PropTypes.string.isRequired,
referralToken: PropTypes.string,
// isLoggedIn: PropTypes.bool.isRequired,
};
Register.defaultProps = {
theme: 'dark',
referralToken: '',
};
const mapState = state => ({
theme: state.theme,
authToken: state.userInfo.authToken,
isLoggedIn: state.isLoggedIn,
});
export default connect(mapState)(withStyles(s)(Register));
|
$(document).ready(function(){
// setup ul.tabs to work as tabs for each div directly under div.panes
$("ul.tabs").tabs(".content");
$("#overviewTable").flexigrid({
url: './../../app/controller/getOverview.php',
dataType: 'json',
colModel : [
{display: 'ID', name : 'id', width : 40, sortable : true, align: 'center'},
{display: 'Rang', name : 'rank', width : 60, sortable : true, align: 'left'},
{display: 'User', name : 'user', width : 60, sortable : true, align: 'left'},
{display: 'Punkte', name : 'points', width : 60, sortable : true, align: 'left'}
],
searchitems : [
{display: 'Punkte', name : 'points'},
{display: 'User', name : 'user', isdefault: true}
],
sortname: "points",
sortorder: "asc",
usepager: true,
title: 'Übersicht aller Mitspieler',
width: 860,
height: 400,
singleSelect: true
});
$("#login_form").submit(function(){
var id = $("input[name=ID]").val();
var pw = $("input[name=PW]").val();
if (id == "" || pw == ""){
$('#login_error').remove();
$("#login_form").after("<p id='login_error'>Bitte füllen Sie alle Felder aus.</p>");
return false;
}
});
$("#registry_form").submit(function(){
var prename = $("input[name=prename]").val();
var name = $("input[name=name]").val();
var username = $("input[name=username]").val();
var password = $("input[name=password]").val();
var email = $("input[name=email]").val();
// $.post('./../../app/controller/checkRegistry.php', {
// 'username' : username,
// 'email' : email
// },function(data) {
// alert(data);
// if(data == 'no'){
// alert('hi');
// $('#registry_error').remove();
// $("#registry_form").after("<p id='registry_error'>Username oder Email schon vorhanden.</p>");
// return false;
// }
// });
// return false;
if (prename == "" || name == "" || username == "" || password == "" || email == ""){
$('#registry_error').remove();
$("#registry_form").after("<p id='registry_error'>Bitte füllen Sie alle Felder aus.</p>");
return false;
}
else{
var error = false;
$.post('./../../app/controller/checkRegistry.php', {
'username' : username,
'email' : email
},function(data) {
alert(data);
if(data == 'no'){
error = true;
}
});
if (error == true){
$('#registry_error').remove();
$("#registry_form").after("<p id='registry_error'>Username oder Email schon vorhanden.</p>");
return false;
}
}
});
});
|
jQuery(document).ready(function(){
jQuery('#facebook').on('click',function(){
console.log("facebook selected");
jQuery('#facebook-field').show();
})
jQuery('#twitter').on('click',function(){
console.log("twitter selected");
jQuery('#twitter-field').show();
})
jQuery('#other').on('click',function(){
console.log("twitter selected");
jQuery('.hiddenOther').show();
})
jQuery('#google').on('click',function(){
console.log("google+ selected");
jQuery('#google-field').show();
})
jQuery('#github').on('click',function(){
console.log("github selected");
jQuery('#github-field').show();
})
jQuery('#other').on('click',function(){
console.log("other selected");
jQuery('.hiddenOther').show();
})
jQuery('#fb-remove').on('click',function(){
jQuery('#facebook-field').hide();
jQuery('#contact_fb').val('');
})
jQuery('#twitter-remove').on('click',function(){
jQuery('#twitter-field').hide();
jQuery('#contact_twitter').val(''); // take value of text
// field using .val()
})
jQuery('#google-remove').on('click',function(){
jQuery('#google-field').hide();
jQuery('#contact_google_plus').val(''); // take value of text
// field using .val()
})
jQuery('#github-remove').on('click',function(){
jQuery('#github-field').hide();
jQuery('#contact_github').val(''); // take value of text
// field using .val()
})
var value= jQuery("#contact_google_plus").val();
if(value != ""){
jQuery('#google-field').show();
}
var value= jQuery("#contact_fb").val();
console.log(value);
if(value != "" ||value == undefined){
jQuery('#facebook-field').show();
}
var value= jQuery("#contact_twitter").val();
console.log(value);
if(value != "" || value == undefined){
jQuery('#twitter-field').show();
}
var value= jQuery("#contact_github").val();
console.log(value);
if(value != ""){
jQuery('#github-field').show();
}
function fbremove(){
jQuery('#facebook-field').hide();
jQuery('#contact_fb').val('');
}
});
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
var uname, id, password, fullname;
// -- ajax to add user ------
function addUser(id) {
if (checkValues(id)) {
$("#error").hide();
$("#error").empty();
$.ajax({
type: "POST",
url: "HandleUser?action=add",
data: $(".add-users-form").serialize(),
success: function(html) {
$("#add-user-message").remove();
$("#add-users-div").prepend(html);
$("#uname").val("");
$("#name").val("");
$("#password").val("");
}
});
} else
$("#error").show();
return false;
}
function deleteUserFromList() {
var old, oid, n;
var passData = {"id": id};
$.ajax({
type: "POST",
url: "HandleUser?action=deleteFrmList",
data: passData,
success: function(html) {
$("td[id=user-count]").each(function(e) {
old = $(this).siblings("#user-actions").find(".delete-user");
oid = old.attr("id");
n = oid.substr(oid.indexOf("-") + 1, oid.length - 1);
if (n > count) {
oid = oid.replace("-" + n, "-" + (n - 1));
old.attr("id", oid);
$(this).html(n - 1);
}
});
$("tr[id=i" + id + "]").remove();
}
});
}
function editUser(id) {
if (checkValues(id)) {
$("#error").hide();
$("#error").empty();
$.ajax({
type: "POST",
url: "HandleUser?action=edit&id=" + id,
data: $(".add-users-form").serialize(),
success: function(html) {
$("#add-user-message").remove();
$("#add-users-div").prepend(html);
}
});
} else
$("#error").show();
return false;
}
function checkValues(id) {
var valid = false;
var username = $("#uname").val();
var name = $("#name").val();
var utype = $("#utype").val();
var password = $("#password").val();
var error = $("#error");
error.empty();
if (username.search(/[<>&\=;"'.?//]/ig) !== -1) {
valid = false;
error.append("<p>Please enter a proper username.</p><br/>");
} else
valid = true;
if (name.search(/([<>&\=;"'.?//])|(\d)/ig) !== -1) {
valid = false;
error.append("<p>Please enter a proper full name.</p><br/>");
} else if (valid)
valid = true;
if (utype < 0 || utype > 3 || utype.search(/[<>&\=;"'.?//a-zA-Z]/ig) !== -1) {
valid = false;
error.append("<p>\nThere are only three user types." +
"Please select a proper user type.</p><br/>");
} else if (valid)
valid = true;
if (password.search(/[<>&\=;"'.?//]/ig) !== -1 && id === -1) {
error.append("<p>Please enter a proper password.</p>");
valid = false;
} else if (valid)
valid = true;
// if(!valid){
// error.show();
//// event.preventDefault();
// }
//
// if(valid) {
// error.hide();
// error.empty();
//// document.login.submit();
// }
return valid;
}
$(document).ready(function() {
$("#error").hide();
$(document).on("click", "#yes-delete-user", function(e) {
name = $(this).attr('name');
id = name.substr(1, name.indexOf("d") + 1);
location.href = "HandleUser?action=deleteFrmView&id=" + id;
});
$(document).on("click", "#yes-delete", function(e) {
name = $(this).attr('name');
id = name.substr(1, name.indexOf("-") - 1);
count = name.substr(name.indexOf("-") + 1, name.length - 1);
deleteUserFromList(id, count);
});
});
|
function pairElement(str) {
let result = [];
str
.split("")
.map(function(item){
if (item == "A"){
result.push([item,"T"])
} else if( item == "C"){
result.push([item, "G"])
} else if( item == "T"){
result.push([item, "A"])
} else if(item == "G"){
result.push([item, "C"])
}
})
return result
}
console.log(pairElement("GCG"));
// // Alternative Solution
//
// function pairElement(str) {
// //create object for pair lookup
// var pairs = {
// A: "T",
// T: "A",
// C: "G",
// G: "C"
// };
// //split string into array of characters
// var arr = str.split("");
// //map character to array of character and matching pair
// return arr.map(x => [x, pairs[x]]);
// }
//
// //test here
// pairElement("GCG");
|
/**
* Created by pablo on 2/25/2016.
*/
/* global $J, isDefinedAndTrue, isDefined, Spinner, es, console */
/** Properties **/
/*
TODO: we may be able to align smState.smVals and saveDimensionSelections() values
SM Dimension values need to be updated in the following locations:
1. MASTER - > smState.smVals{}
2. SLAVE - > DD_ON_LOAD{}
3. SLAVE - > saveDimensionSelections()
*/
var smState = {
smVals: { // current SM values
Scenario: '', // not needed in DD_ON_LOAD
Period: '',
Division: '',
BusinessLine: '',
Region: '',
WorkforceCategory: '',
WorkerType: '',
FLSA: '', // a.k.a. JobGrade
UDC1: '', // a.k.a. FunctionalGroup
JobFunction: ''
},
eventRequests: {},
ScenarioNames: [],
DimensionsData: {},
singleDimensionDataSuccesses: 0,
DimensionsSelections: [],
loadFailures: {} // counts data load attempt failures, keys by function name
},
MAX_FAILS = 3, // user prompted when max is reached
DEFAULT_SCENARIO_NAME = 'Actual', // value for default option of Scenario dropdown
SAVED_SCENARIO_KEY = 'sasc', // key for URL param designating which Scenario is active
DEF_CHILD_OPT_NAME = "More specifically...", // value for default option of Dimension child dropdowns
protectedScenarios = ['Benchmark', DEFAULT_SCENARIO_NAME], // prevent delete option for these
modalMsgs = [], // modal message queue container
spinnerOpts = { // Spinner options
lines: 11, // The number of lines to draw
length: 10, // The length of each line
width: 8, // The line thickness
radius: 20, // The radius of the inner circle
scale: 0.5, // Scales overall size of the spinner
corners: 1, // Corner roundness (0..1)
color: '#000', // #rgb or #rrggbb or array of colors
opacity: 0.25, // Opacity of the lines
rotate: 0, // The rotation offset
direction: 1, // 1: clockwise, -1: counterclockwise
speed: 1, // Rounds per second
trail: 60, // Afterglow percentage
fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
zIndex: 2e9, // The z-index (defaults to 2000000000)
className: 'spinner', // The CSS class to assign to the spinner
top: '50%', // Top position relative to parent
left: '50%', // Left position relative to parent
shadow: false, // Whether to render a shadow
hwaccel: false, // Whether to use hardware acceleration
position: 'relative' // Element positioning
},
allowConsoleLog = __DEV__, // flag for custom console log printing
onSelect2 = false, // prevents premature #smFilters.mouseleave events. select2 is positioned absolute-ly, so when we mouseover select2 dropdown Dimension label onMouseEnter event affects disappear
periodYearOnly = false, // certain dashboards can only filter by year Dimension and not any more specific
tm1CurrentYear = null, // holds the current year from TM1
dependSelects = {}, // holds list of dependent select lists: dependSelects{ selectID-optValue:subSelectID }
wasSelectedVal = {}, // holds previously selected value - used to clear sub-selects in case they are active: wasSelectedVal{ selectID:subSelectID }
dimensionsResults = {}, // holds Dimensions dropdown selections web method Results JSON string
assumptionsResults = {}, // holds Assumptions web method Results JSON string
ddRange = [], // range of numbers for Assumptions ("% Change") dropdown options
DISPLAY_SECTION_NAMES = { // formatting of Actuals & Assumptions Section names
'Workforce': { displayName: 'Workforce Assumptions' },
'Business&Financial': { displayName: 'Business & Financial' },
'Learning': { displayName: 'Learning Dashboard' },
'Performance&Engagement': { displayName: 'Performance & Engagement' }
},
/**
config for top level dropdowns:
resultsMembersID = Id of web method result object member: {Results:Members:ID:Children}
selectID = Id of select tag, doesn't include css id hash character
selectLabel = label for select element
defOptName = default select option name/text
methodName = TM1 web method name
webMParamKey1 = web method 1st parameter key, TM1 dimension name
webMParamVal1 = web method 1st parameter value
webMParamKey2 = web method 2nd parameter key
webMParamVal2 = web method 2nd parameter value
**/
DD_ON_LOAD = {
Period: {
// TM1DimensionMembers?DimName=Period
resultsMembersID: 'All Years',
selectID: 'year',
selectLabel: 'Period',
defOptName: 'Current Year',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'Period',
webMParamKey2: 'AttrName1',
webMParamVal2: 'DashboardName'
},
Division: {
// TM1DimensionMembers?DimName=Division
resultsMembersID: 'All Divisions',
selectID: 'division',
selectLabel: 'Division',
defOptName: 'All Divisions',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'Division',
webMParamKey2: '',
webMParamVal2: ''
},
BusinessLine: {
// TM1DimensionMembers?DimName=Business%20Line
resultsMembersID: 'All Business Lines',
selectID: 'businessLine',
selectLabel: 'Business Unit',
defOptName: 'All Business Units',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'Business Line',
webMParamKey2: '',
webMParamVal2: ''
},
Region: {
// TM1DimensionMembers?DimName=Region
resultsMembersID: 'All Countries',
selectID: 'region',
selectLabel: 'Geographic Location',
defOptName: 'All Regions',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'Region',
webMParamKey2: '',
webMParamVal2: ''
},
WorkforceCategory: {
// TM1DimensionMembers?DimName=Workforce%20Category
resultsMembersID: 'All Workforce Categories',
selectID: 'workforceCategory',
selectLabel: 'Workforce Category',
defOptName: 'All Workforce Categories',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'Workforce Category',
webMParamKey2: '',
webMParamVal2: ''
},
WorkerType: {
// TM1DimensionMembers?DimName=Worker%20Type
resultsMembersID: 'All Workers',
selectID: 'workerType',
selectLabel: 'Worker Type',
defOptName: 'All Worker Types',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'Worker Type',
webMParamKey2: '',
webMParamVal2: ''
},
FLSA: {
// TM1DimensionMembers?DimName=FLSA
resultsMembersID: 'All FLSA Statuses',
selectID: 'jobGrade',
selectLabel: 'Job Grade / Level',
defOptName: 'All Job Grades / Levels',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'FLSA',
webMParamKey2: '',
webMParamVal2: ''
},
UDC1: {
// TM1DimensionMembers?DimName=UDC1
resultsMembersID: 'All UDC1',
selectID: 'functionalGroup',
selectLabel: 'Functional Group',
defOptName: 'All Functional Groups',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'UDC1',
webMParamKey2: '',
webMParamVal2: ''
},
JobFunction: {
// TM1DimensionMembers?DimName=Job%20Function
resultsMembersID: 'All Job Functions',
selectID: 'jobFunction',
selectLabel: 'Job Function',
defOptName: 'All Job Functions',
methodName: 'TM1DimensionMembers',
webMParamKey1: 'DimName',
webMParamVal1: 'Job Function',
webMParamKey2: '',
webMParamVal2: ''
}
},
applyModalMsg;
/** Helpers **/
applyModalMsg = function(msgType, msgItem){
// msgType(s): 'status', 'success', 'error'
var fontColor,
overlayDiv = $J('#overlay'),
spinnerDiv = $J('#overlayLoading'),
spinner;
fontColor = msgType === 'error' ? 'red' : 'green';
overlayDiv.find('.titleD').html('<span style="color:' + fontColor + '">' + msgItem.title + '</span>');
if (msgItem.message) {
overlayDiv.find('.overlayMsg').html('<span style="color:' + fontColor + '">' + msgItem.message + '</span>');
}
if (msgItem.spinner) {
if (spinnerDiv.children().length === 0) {
spinner = new Spinner(spinnerOpts).spin(document.getElementById('overlayLoading'));
}
spinnerDiv.show();
}
if (!$J.isEmptyObject(msgItem.confirm)) {
$J('#overlayConfirmBtn').show().html(msgItem.confirm.msg).click(function () {
$J(this).unbind('click');
deleteMsg();
if (msgItem.confirm.funcs.length > 0) {
msgItem.confirm.funcs.forEach(function (item) {
item();
});
}
});
}
if (!$J.isEmptyObject(msgItem.deny)) {
$J('#overlayDenyBtn').show().html(msgItem.deny.msg).click(function () {
$J(this).unbind('click');
deleteMsg();
if (msgItem.deny.funcs.length > 0) {
msgItem.deny.funcs.forEach(function (item) {
item();
});
}
});
}
overlayDiv.show();
};
function processingMsg(){
pushMsg('status', {
title: 'SOLVE™ is Processing...',
message: '',
spinner: true,
confirm: {},
deny: {}
});
}
function failedToUpdateMsg(errorItemStr, cbFuncArr){
var cbArray = cbFuncArr && cbFuncArr.length ? cbFuncArr : [];
pushMsg('error', {
title: 'Sorry!',
message: errorItemStr + ' failed to update. Please try again.',
spinner: false,
confirm: {
msg: 'Try Again',
funcs: cbArray
},
deny: {}
});
}
function hideCurrentMsg(){
var overlayDiv = $J('#overlay'),
spinnerDiv = $J('#overlayLoading');
overlayDiv.find('p').each(function() {
$J(this).empty();
});
overlayDiv.find('button').each(function() {
$J(this).hide();
});
spinnerDiv.hide();
}
function pushMsg(mType, mItem){
var newLen,
arrIdx;
if (modalMsgs.length > 0){
hideCurrentMsg();
}
newLen = modalMsgs.push({mType: mType, mItem: mItem});
arrIdx = newLen - 1;
applyModalMsg(modalMsgs[arrIdx].mType, modalMsgs[arrIdx].mItem);
}
function deleteMsg(){
var arrIdx;
hideCurrentMsg();
modalMsgs.pop();
if (modalMsgs.length > 0){
arrIdx = modalMsgs.length - 1;
applyModalMsg(modalMsgs[arrIdx].mType, modalMsgs[arrIdx].mItem);
}
}
function clearAllMsgs(){
var overlayDiv = $J('#overlay'),
spinnerDiv = $J('#overlayLoading');
overlayDiv.find('p').each(function() {
$J(this).empty();
});
overlayDiv.find('button').each(function() {
$J(this).hide();
});
spinnerDiv.hide();
overlayDiv.hide();
modalMsgs.length = 0;
}
function setPageToScenario(){
var urlParams;
if (window.location.search === '') {
setScenarioStateAndUrl(DEFAULT_SCENARIO_NAME);
} else {
urlParams = getQueryParams(window.location.search);
if (SAVED_SCENARIO_KEY in urlParams) {
setScenarioStateAndUrl(urlParams[SAVED_SCENARIO_KEY]);
} else {
setScenarioStateAndUrl(DEFAULT_SCENARIO_NAME);
}
}
}
function resetPageScenarioToDefault(scName, cb){
pushMsg('error', {
title: 'Scenario Does Not Exist',
message: 'An attempt was made to pull up a Scenario saved under the name "' + scName + '." Unfortunately, this Scenario no longer exists. We have reverted to the default Scenario, "' + DEFAULT_SCENARIO_NAME + '."',
spinner: false,
confirm: {
msg: 'Ok',
funcs: [cb]
},
deny: {}
});
setScenarioStateAndUrl(DEFAULT_SCENARIO_NAME);
}
function testPageScenario(cb, cb2, requestID, subEvent){
var pageScenarioExists = false,
scenarioName = smState.smVals.Scenario,
continueRequest;
smState.ScenarioNames.forEach(function (value){
if (scenarioName === value){
pageScenarioExists = true;
}
});
if (pageScenarioExists){
cb(cb2, requestID, subEvent);
} else {
continueRequest = function(){
cb(cb2, requestID, subEvent);
};
resetPageScenarioToDefault(scenarioName, continueRequest);
}
}
function filterSMVals(paramsToAvoid){
var newVals = $J.extend(true, {}, smState.smVals),
arrLen = paramsToAvoid.length,
i;
for (i = 0; i < arrLen; i++){
delete newVals[paramsToAvoid[i]];
}
return newVals;
}
function detectIE() {
var ua = window.navigator.userAgent,
msie,
trident,
edge;
// http://codepen.io/gapcode/pen/vEJNZN
// test values
// IE 10
// ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
// IE 11
// ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
// IE 12 / Spartan
// ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
// return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
return true;
}
trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
// var rv = ua.indexOf('rv:');
// return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
return true;
}
edge = ua.indexOf('Edge/');
if (edge > 0) {
// IE 12 => return version number
// return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
return true;
}
// other browser
return false;
}
function expandedSM(doIt) {
var adj = 0,
adjForIE = detectIE() ? 30 : 0,
width,
expandMe = doIt || false;
if (expandMe) {
$J('#dimRowDropdowns').removeClass('hidden');
adj = 100;
}
else {
$J('#dimRowDropdowns').addClass('hidden');
}
width = [
515 + adj + (adjForIE * 1.7), // 0
325 + adj + (adjForIE * 1.5), // 1
340 + adj + (adjForIE * 1.5), // 2
450 + adj + (adjForIE * 1.5), // 3
270 + adjForIE // 4
];
$J('#sm').css('width', width[0] + 'px');
$J('#sm .titleD').css('width', width[3] + 'px');
$J('#smScenario').css('width', width[3] + 'px');
$J('#smFilters').css('width', width[3] + 'px');
$J('#smEntities').css('width', width[3] + 'px');
$J('#cur-scenario-tab select').css('width', width[1] + 'px');
$J('#cur-scenario-tab .select2-container').css('width', width[1] + 'px');
$J('#create-scenario-name').css('width', width[2] + 'px');
$J('#dimRowLabels').css('width', width[4] + 'px');
}
function getQueryParams(qs) {
var qstr = qs.split('+').join(' '),
params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qstr)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
function addParamsToUrl(paramsToAdd) {
var pathName = window.location.pathname,
qString = window.location.search,
newQString = '',
separator = '?',
urlParams,
key;
if (qString === '') {
for (key in paramsToAdd){
if (paramsToAdd.hasOwnProperty(key)){
newQString += separator + encodeURIComponent(key) + '=' + encodeURIComponent(paramsToAdd[key]);
separator = '&';
}
}
} else {
urlParams = getQueryParams(qString);
urlParams[SAVED_SCENARIO_KEY] = paramsToAdd[SAVED_SCENARIO_KEY];
for (key in urlParams) {
if (urlParams.hasOwnProperty(key)) {
newQString += separator + encodeURIComponent(key) + '=' + encodeURIComponent(urlParams[key]);
separator = '&';
}
}
}
window.history.pushState('', 'Modified URL', pathName + newQString);
}
function rewriteLinks() {
var linksToRewrite = [
'.powerToolsLI',
'#navigation-menu'
];
linksToRewrite.forEach(function(elem) {
$J(elem).find('a').each(function() {
var oldHref = $J(this).attr("href"),
newHref = '',
urlAndParams,
urlParams,
qString,
separator,
key;
if (oldHref.indexOf('?') > -1) {
urlAndParams = oldHref.split('?'); // split loc & params
urlParams = getQueryParams(urlAndParams[1]); // check for existing 'scenario' value
urlParams[SAVED_SCENARIO_KEY] = smState.smVals.Scenario;
qString = '';
separator = '?';
for (key in urlParams) {
if (urlParams.hasOwnProperty(key)) {
qString += separator + encodeURIComponent(key) + '=' + encodeURIComponent(urlParams[key]);
separator = '&';
}
}
newHref = urlAndParams[0] + qString;
} else {
newHref = oldHref + '?' + SAVED_SCENARIO_KEY + '=' + smState.smVals.Scenario;
}
$J(this).attr("href", newHref);
});
});
}
function toggleRecalcBtn(scName){
if (scName === DEFAULT_SCENARIO_NAME){
$J('#update-scenario-btn').hide();
} else {
$J('#update-scenario-btn').show();
}
}
function setScenarioStateAndUrl(scName){
var urlParamsObj = {};
/* TODO: create setter and getter methods for smState */
smState.smVals.Scenario = scName;
urlParamsObj[SAVED_SCENARIO_KEY] = smState.smVals.Scenario;
addParamsToUrl(urlParamsObj);
rewriteLinks();
adjustTabForScenario();
toggleRecalcBtn(scName);
}
function formatStringSpace(thisStr) {
// removes whitespace
return thisStr.replace(/\s+/g, '');
}
function formatStringChars(thisStr) {
// removes non-alphanumeric
return thisStr.replace(/\W/g, '');
}
function clearChildSelect(idToClear) {
var key,
obj,
thisSel;
// clears select with idToClear and children selects
for (key in dependSelects) {
if (dependSelects.hasOwnProperty(key)) {
obj = dependSelects[key];
if (obj.substring(0, idToClear.length) === idToClear) {
thisSel = $J('#' + obj);
thisSel.find('option:selected').removeAttr('selected');
thisSel.find('option:first').attr('selected', 'selected');
thisSel.val($J('#' + obj + 'option:first').val());
$J('#' + obj + '-container').addClass('hidden');
}
}
}
}
function updateRunningTab(selDimid, txt) {
$J('#rt' + selDimid).html(txt);
}
function updateSMDimensionVals() { // updates Dimension values (excluding Scenario) in smState.smVals
$J('#smFilters select').each(function() { // iterate thru drop downs, pull name/value pairs
var thisSel = $J(this),
rtText,
thisSeldimid = thisSel.attr('dimid'),
thisText = thisSel.find(':selected').text(),
thisElem;
if (thisText !== DEF_CHILD_OPT_NAME) {
rtText = thisText;
}
thisElem = $J(this).val(); // non-blank values will be params for TM1 web methods
if (thisElem || rtText){
smState.smVals[thisSeldimid] = thisElem;
updateRunningTab(thisSeldimid, rtText);
}
});
}
function consoleLog(funcName, msgArr, obj, type) {
var consoleType;
if (allowConsoleLog) {
consoleType = type || 'log';
switch (consoleType) {
case 'warn':
console.warn('*** ' + funcName + ' ***');
break;
case 'error':
console.error('*** ' + funcName + ' ***');
break;
case 'info':
console.info('*** ' + funcName + ' ***');
break;
default:
console.log('*** ' + funcName + ' ***');
}
if (isDefined(msgArr)) {
msgArr.forEach(function(value) {
console.log(value);
});
}
if (isDefined(obj)) {
console.log(obj);
}
console.log('*** ' + funcName + ' ***');
}
}
function cleanNumber(value, decimalPlaces) {
if (value === 0) {
return 0;
}
else {
// hundreds
if (value <= 999) {
return value;
}
// thousands
else if (value >= 1000 && value <= 999999) {
return (value / 1000).toFixed(decimalPlaces) + 'K';
}
// millions
else if (value >= 1000000 && value <= 999999999) {
return (value / 1000000).toFixed(decimalPlaces) + 'M';
}
// billions
else if (value >= 1000000000 && value <= 999999999999) {
return (value / 1000000000).toFixed(decimalPlaces) + 'B';
}
else {
return value;
}
}
}
function formatActualVal(actTitle, actVal) {
var displayRowFormat = { // formatting of Row name, and formatting of Actuals
'Average Employee Salary': {
displayName: '',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Average Contingent Worker Cost': {
displayName: '',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Annual High Performer Salary': {
displayName: '',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Salary vs Market': {
displayName: '',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Bonus / Incentives Average': {
displayName: 'Bonus & Incentive Pay (Average)',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Benefits Percent': {
displayName: 'Benefits as a % of Salary',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Inflation Rate': {
displayName: 'Annual Inflation Rate',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Revenue': {
displayName: 'Revenue Growth',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Operating Expenses': {
displayName: '',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Operating Profit': {
displayName: '',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Total Cost of Workforce': {
displayName: 'Total Cost of Workforce Change Rate',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'HR Costs': {
displayName: 'Total HR Costs',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Recruiting Cost': {
displayName: 'Total Recruiting Cost',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Internal Cost per Hire': {
displayName: '',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Internal vs External Cost per Hire': {
displayName: '',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'High Performers Terminations': {
displayName: 'High Performer Terminations',
dollarize: 0,
percentify: 0,
decimalize: 0
},
'Training Cost': {
displayName: 'Total Training Investment',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Training Performance Differential': {
displayName: '',
dollarize: 1,
percentify: 0,
decimalize: 0
},
'Percent of Workforce Trained': {
displayName: '',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Employees with Training Prod Gains': {
displayName: 'Employees with Training Prod. Gains',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Satisfaction with Training': {
displayName: '',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Training Hours per Employee': {
displayName: '',
dollarize: 0,
percentify: 0,
decimalize: 1
},
'High Performers Headcount': {
displayName: 'High Performer Headcount',
dollarize: 0,
percentify: 0,
decimalize: 0
},
'High Performer Prod Diff': {
displayName: 'High Performer Productivity Diff.',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Employee Engagement': {
displayName: 'Employee Engagement Rate',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'High Engagement Revenue': {
displayName: 'High Engagement Revenue Impact',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Promotion Rate': {
displayName: '',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Transfer Rate': {
displayName: '',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Percent Job Requirements Met': {
displayName: 'Job Requirements Met',
dollarize: 0,
percentify: 1,
decimalize: 0
},
'Time to Fill (Days)': {
displayName: '',
dollarize: 0,
percentify: 0,
decimalize: 1
}
},
formattedResults = [], // [title, value]
formatVal = null,
name,
dollar,
percent,
decimal;
if (actTitle in displayRowFormat) {
name = displayRowFormat[actTitle].displayName;
dollar = displayRowFormat[actTitle].dollarize;
percent = displayRowFormat[actTitle].percentify;
decimal = displayRowFormat[actTitle].decimalize;
if (name !== '') {
actTitle = displayRowFormat[actTitle].displayName;
}
if (dollar) {
formatVal = '$' + cleanNumber(parseInt(actVal), 2);
} else if (decimal) {
formatVal = parseFloat(actVal).toFixed(2);
} else if (percent) {
if (name === 'Employee Engagement Rate') {
formatVal = parseFloat(actVal);
formatVal = parseInt(formatVal) + '%';
}
else if (name === 'High Engagement Revenue Impact') {
formatVal = (parseFloat(actVal) * 100).toFixed(1) + '%';
}
else {
formatVal = parseFloat(actVal) * 100;
formatVal = parseInt(formatVal) + '%';
}
}
else {
formatVal = cleanNumber(actVal, 2);
}
}
else {
formatVal = cleanNumber(actVal, 2);
}
formattedResults.push(actTitle);
formattedResults.push(formatVal);
return formattedResults;
}
function applySelect2(applyToDDs) {
switch (applyToDDs) {
case 'scenario':
$J('.scenarioDD').select2({
placeholder: 'Load a scenario..'
});
break;
case 'dimensions':
$J('.dimensionDD').select2();
break;
case 'assumptions':
function matchStart(term, text) {
return text.toUpperCase().indexOf(term.toUpperCase()) === 0;
}
$J.fn.select2.amd.require(['select2/compat/matcher'], function(oldMatcher) {
$J('.varPercent').select2({
matcher: oldMatcher(matchStart)
});
});
break;
default:
// do nothing
}
}
function destroySelect2(applyToDDs){
switch(applyToDDs){
case 'scenario':
if ($J('#scenarioContainer').find('.select2').length){
$J('.scenarioDD').select2('destroy');
}
break;
case 'dimensions':
if ($J('#dimRowDropdowns').find('.select2').length){
$J('.dimensionDD').each(function(){
$J(this).select2('destroy');
});
}
break;
case 'assumptions':
if ($J('.assumptionVal').find('.select2').length){
$J('.varPercent').each(function(){
$J(this).select2('destroy');
});
}
break;
default:
// do nothing
}
}
function getTM1CurrentYear() {
var params = { // web method: TM1SubsetMembers?DimName=Period&SubsetName=Current
"DimName": "Period",
"SubsetName": "Current"
},
onSuccess,
onFailure,
self = this;
onSuccess = function(resultObj) {
self.tm1CurrentYear = resultObj.Results.Members[0].ID;
};
onFailure = function() {
getTM1CurrentYear();
};
es.get("TM1SubsetMembers", params, onSuccess, onFailure, false);
}
function createNewScenario(cb, requestID, subEvent) {
var params = { "p_element": smState.eventRequests[requestID].extras.ScenarioName }, // web method: ScenarioElementInsert?p_element=newScenarioNameStr
onSuccess,
onFailure,
newParamsObj = {};
smState.loadFailures.createNewScenario = smState.loadFailures.createNewScenario || 0;
pushMsg('success', {
title: 'Creating New Scenario',
message: 'A new Scenario is being created. This may take a moment.',
spinner: true,
confirm: {},
deny: {}
});
onSuccess = function() {
var continueRequest = function(){
cb(requestID, subEvent);
};
smState.loadFailures.createNewScenario = 0;
newParamsObj[SAVED_SCENARIO_KEY] = smState.eventRequests[requestID].extras.ScenarioName;
addParamsToUrl(newParamsObj);
deleteMsg();
pushMsg('success', {
title: 'Success',
message: 'Scenario "' + smState.eventRequests[requestID].extras.ScenarioName + '" was created and can now be loaded.',
spinner: false,
confirm: {
msg: 'Continue',
funcs: [continueRequest]
},
deny: {}
});
};
onFailure = function(){
var recursiveCall = function(){
createNewScenario(cb, requestID, subEvent);
};
if (smState.loadFailures.createNewScenario < MAX_FAILS){
(smState.loadFailures.createNewScenario)++;
createNewScenario(cb, requestID, subEvent);
} else {
pushMsg('error', {
title: 'Sorry!',
message: 'We experienced a temporary challenge creating a new Scenario. Please try again.',
spinner: false,
confirm: {
msg: 'Try Again',
funcs: [recursiveCall]
},
deny: {}
});
smState.loadFailures.createNewScenario = 0;
}
};
es.get("ScenarioElementInsert", params, onSuccess, onFailure, false, "json", 120000, "There is still no response from the server. Do you want to abort the request?", 120000);
}
function isScenarioNameUnique(cb, cb2, requestID, subEvent){
var params = { "DimName": "Scenario" }, // web method: TM1DimensionMembers?DimName=Scenario
testPassed = true,
onSuccess,
onFailure;
smState.loadFailures.isScenarioNameUnique = smState.loadFailures.isScenarioNameUnique || 0;
onSuccess = function(resultObj) {
smState.loadFailures.isScenarioNameUnique = 0;
resultObj.Results.Members.forEach(function(value) {
if (value.Name === smState.eventRequests[requestID].extras.ScenarioName) {
pushMsg('error', {
title: 'Sorry!',
message: 'The proposed Scenario name already exists. Please choose another name.',
spinner: false,
confirm: {
msg: 'Continue',
funcs: []
},
deny: {}
});
testPassed = false;
}
});
if (testPassed){
cb(cb2, requestID, subEvent);
}
};
onFailure = function(){
var recursiveCall = function(){
isScenarioNameUnique(cb, cb2, requestID, subEvent);
};
if (smState.loadFailures.isScenarioNameUnique < MAX_FAILS){
(smState.loadFailures.isScenarioNameUnique)++;
isScenarioNameUnique(cb, cb2, requestID, subEvent);
} else {
pushMsg('error', {
title: 'Sorry!',
message: 'We experienced a temporary challenge creating a new Scenario. Please try again.',
spinner: false,
confirm: {
msg: 'Try Again',
funcs: [recursiveCall]
},
deny: {}
});
smState.loadFailures.isScenarioNameUnique = 0;
}
};
es.get("TM1DimensionMembers", params, onSuccess, onFailure, false);
}
function scenarioDeleteConfirmed(cb, requestID, subEvent){
var params = { "DimName": "Scenario", "MemberID": smState.smVals.Scenario }, // web method: TM1DimensionDeleteMember?DimName=Scenario&MemberID=Test
onSuccess,
onFailure,
newParamsObj = {};
pushMsg('status', {
title: 'Deleting Scenario',
message: 'Scenario ' + smState.smVals.Scenario + ' is being deleted. This may take a moment.',
spinner: true,
confirm: {},
deny: {}
});
smState.loadFailures.scenarioDeleteConfirmed = smState.loadFailures.scenarioDeleteConfirmed || 0;
onSuccess = function() {
var continueRequest = function(){
cb(requestID, subEvent);
};
smState.loadFailures.scenarioDeleteConfirmed = 0;
newParamsObj[SAVED_SCENARIO_KEY] = DEFAULT_SCENARIO_NAME;
addParamsToUrl(newParamsObj);
deleteMsg();
pushMsg('success', {
title: 'Success',
message: 'Scenario ' + smState.smVals.Scenario + ' was successfully deleted.',
spinner: false,
confirm: {
msg: 'Ok',
funcs: [continueRequest]
},
deny: {}
});
};
onFailure = function() {
var tryAgain = function(){
scenarioDeleteConfirmed(cb, requestID, subEvent);
};
if (smState.loadFailures.scenarioDeleteConfirmed < MAX_FAILS){
(smState.loadFailures.scenarioDeleteConfirmed)++;
scenarioDeleteConfirmed(cb, requestID, subEvent);
} else {
pushMsg('error', {
title: 'Delete Failed',
message: 'Scenario ' + smState.smVals.Scenario + ' failed to delete.',
spinner: false,
confirm: {
msg: 'Try Again',
funcs: [tryAgain]
},
deny: {}
});
smState.loadFailures.scenarioDeleteConfirmed = 0;
}
};
es.get("TM1DimensionDeleteMember", params, onSuccess, onFailure, true);
}
function deleteScenario(cb, requestID, subEvent){
var confirmed = function(){
scenarioDeleteConfirmed(cb, requestID, subEvent);
},
cancel = function(){
cancelRequest(requestID);
};
pushMsg('status', {
title: 'Confirm Delete',
message: 'Are you sure you want to delete Scenario ' + smState.smVals.Scenario + '?',
spinner: false,
confirm: {
msg: 'Yes',
funcs: [confirmed]
},
deny: {
msg: 'No',
funcs: [cancel]
}
});
}
function selectScenario(requestID){
var newParamsObj = {};
newParamsObj[SAVED_SCENARIO_KEY] = smState.eventRequests[requestID].extras.thisSelectVal;
addParamsToUrl(newParamsObj);
}
function selectDimension(requestID, directDeliveryObj){
var ddO,
parentDivID,
setTo,
formattedVal,
hasChildSel;
ddO = directDeliveryObj ? directDeliveryObj : smState.eventRequests[requestID].extras;
// if current select has an option previously selected, clear children of previous option
if (ddO.thisSelectID in wasSelectedVal) {
clearChildSelect(wasSelectedVal[ddO.thisSelectID]);
}
// set dimRowOptSelected text to most current selection
parentDivID = ddO.thisSelect.closest('.varSelect').attr('id');
setTo = ddO.thisSelectVal === '' ? ddO.thisDefaultOpt : ddO.thisSelectVal;
if (setTo !== DEF_CHILD_OPT_NAME) {
$J('.dimRowLabel[dimid="' + parentDivID + '"]').text(setTo);
}
// check to see if this select has any dependencies, display child
formattedVal = isDefinedAndTrue(ddO.thisSelectVal) ? formatStringChars(ddO.thisSelectVal) : ddO.thisSelectVal;
hasChildSel = ddO.thisSelectID + formattedVal + '-container';
if ($J('#' + hasChildSel).length) {
$J('#' + hasChildSel).removeClass('hidden');
}
repositionVarSelect(parentDivID);
// reset wasSelectedVal
for (var key in wasSelectedVal) {
if (wasSelectedVal.hasOwnProperty(key)) {
delete wasSelectedVal[key];
}
}
}
function saveDimensionSelections(cb, requestID, subEvent) {
var localDimResults = $J.extend(true, {}, dimensionsResults),
dimRows = localDimResults.RowSet.Rows[0],
key,
onSuccess,
onFailure;
updateSMDimensionVals();
for (key in dimRows) {
if (dimRows.hasOwnProperty(key)) {
switch (key) {
case 'Scenario':
dimRows.Scenario = smState.smVals.Scenario;
break;
case 'SelectedYear':
dimRows.SelectedYear = smState.smVals.Period ? smState.smVals.Period : DD_ON_LOAD.Period.resultsMembersID;
break;
case 'SelectedLegalEntity':
dimRows.SelectedLegalEntity = smState.smVals.Division ? smState.smVals.Division : DD_ON_LOAD.Division.resultsMembersID;
break;
case 'SelectedBusinessUnit':
dimRows.SelectedBusinessUnit = smState.smVals.BusinessLine ? smState.smVals.BusinessLine : DD_ON_LOAD.BusinessLine.resultsMembersID;
break;
case 'SelectedRegion':
dimRows.SelectedRegion = smState.smVals.Region ? smState.smVals.Region : DD_ON_LOAD.Region.resultsMembersID;
break;
case 'SelectedWorkforceCategory':
dimRows.SelectedWorkforceCategory = smState.smVals.WorkforceCategory ? smState.smVals.WorkforceCategory : DD_ON_LOAD.WorkforceCategory.resultsMembersID;
break;
case 'SelectedWorkerType':
dimRows.SelectedWorkerType = smState.smVals.WorkerType ? smState.smVals.WorkerType : DD_ON_LOAD.WorkerType.resultsMembersID;
break;
case 'SelectedJobGrade':
dimRows.SelectedJobGrade = smState.smVals.FLSA ? smState.smVals.FLSA : DD_ON_LOAD.FLSA.resultsMembersID;
break;
case 'SelectedFunctionalGroup':
dimRows.SelectedFunctionalGroup = smState.smVals.UDC1 ? smState.smVals.UDC1 : DD_ON_LOAD.UDC1.resultsMembersID;
break;
case 'SelectedJobFunction':
dimRows.SelectedJobFunction = smState.smVals.JobFunction ? smState.smVals.JobFunction : DD_ON_LOAD.JobFunction.resultsMembersID;
break;
default:
consoleLog('saveDimensionSelections', ['Error on switch! Case not met for - ' + key], null, 'error');
}
}
}
smState.loadFailures.saveDimensionSelections = smState.loadFailures.saveDimensionSelections || 0;
onSuccess = function() {
smState.loadFailures.saveDimensionSelections = 0;
cb(requestID, subEvent);
};
onFailure = function() {
if (smState.loadFailures.saveDimensionSelections < MAX_FAILS){
(smState.loadFailures.saveDimensionSelections)++;
saveDimensionSelections();
} else {
failedToUpdateMsg('Scenario "' + smState.smVals.Scenario + '"', [saveDimensionSelections]);
smState.loadFailures.saveDimensionSelections = 0;
}
};
$J.ajax({
type: "POST",
data: JSON.stringify(localDimResults),
cache: false,
url: es3 + "json/TM1ViewWrite",
error: onFailure,
success: onSuccess
});
}
function saveAssumptions(cb, requestID, subEvent) {
var saveToCompany = 'unassigned',
view,
resultsRows,
assumptionsDDVals = [],
count = 0,
key,
onSuccess,
onFailure;
if (smState.smVals.Scenario !== DEFAULT_SCENARIO_NAME) {
// set to var set in getAssumptions()
view = assumptionsResults;
view.TitleDimensions.Scenario.ID = smState.smVals.Scenario;
view.TitleDimensions.Scenario.Name = smState.smVals.Scenario;
view.TitleDimensions.Company.ID = saveToCompany;
view.TitleDimensions.Company.Name = saveToCompany;
resultsRows = view.RowSet.Rows;
// get Assumptions vals from SM
$J('.varPercent').each(function() {
assumptionsDDVals.push($J(this).val());
});
// set Assumptions vals in object before post
for (key in resultsRows) {
if (resultsRows.hasOwnProperty(key)) {
resultsRows[key].AnalysisYear = assumptionsDDVals[count] / 100;
count++;
}
}
view.RowSet.Rows = resultsRows;
smState.loadFailures.saveAssumptions = smState.loadFailures.saveAssumptions || 0;
onSuccess = function() {
smState.loadFailures.saveAssumptions = 0;
cb(requestID, subEvent);
};
onFailure = function() {
if (smState.loadFailures.saveAssumptions < MAX_FAILS){
(smState.loadFailures.saveAssumptions)++;
saveAssumptions();
} else {
failedToUpdateMsg('The assumptions/projection change just made ', [saveAssumptions]);
smState.loadFailures.saveAssumptions = 0;
}
};
$J.ajax({
type: "POST",
data: JSON.stringify(view),
cache: false,
url: es3 + "json/TM1ViewWrite",
error: onFailure,
success: onSuccess
});
}
}
function setPeriodToYearOnly(tOrF){
periodYearOnly = tOrF;
}
function getLFFormattedName(dataToGet){
var formattedName;
switch (dataToGet) {
case 'Actuals':
formattedName = 'Actuals_' + smState.smVals.Scenario;
break;
case 'Assumptions':
formattedName = 'Assumptions_' + smState.smVals.Scenario;
break;
default:
return null;
}
return formattedName;
}
function clearLocalForage(){
localforage.removeItem(getLFFormattedName('Actuals'));
localforage.removeItem(getLFFormattedName('Assumptions'));
}
/** Request Handling **/
function requestBuilder(event, extrasObject){
var tStamp = Date.now(),
requestObj = {
extras: extrasObject,
event: event,
stage: 0
};
switch(event){
case 'dimensionsPreLoad':
requestObj.subEvents = [
{
BeginProcessing: false
},
{
DimensionsPreLoad: false
},
{
FinishProcessing: false
}
];
break;
case 'pageLoad':
requestObj.subEvents = [
{ // stage 0
BeginProcessing: false
},
{ // stage 1
AdjustSM: false,
SetPageScenario: false
},
{ // stage 2
Scenarios: false,
Dimensions: false,
Assumptions: false
},
{ // stage 3
DimensionSelections: false,
SetEventListeners: false
},
{ // stage 4
Charts: false,
Actuals: false
},
{ // stage 5
CollapseActAndAss: false,
FinishProcessing: false
}
];
break;
case 'createScenario':
requestObj.subEvents = [
{
BeginProcessing: false
},
{
CreateScenario: false
},
{
SetPageScenario: false
},
{
Scenarios: false,
HideActsAndAss: false,
Assumptions: false
},
{
DimensionSelections: false
},
{
Charts: false,
Actuals: false
},
{
CollapseActAndAss: false,
ResetSMDisplay: false,
FinishProcessing: false
}
];
break;
case 'saveScenario':
requestObj.subEvents = [
{
BeginProcessing: false
},
{
ClearLF: false
},
{
SaveDimensions: false,
SaveAssumptions: false
},
{
Charts: false,
Actuals: false
},
{
FinishProcessing: false
}
];
break;
case 'deleteScenario':
requestObj.subEvents = [
{
BeginProcessing: false
},
{
DeleteScenario: false
},
{
SetPageScenario: false
},
{
Scenarios: false,
HideActsAndAss: false,
Assumptions: false
},
{
DimensionSelections: false
},
{
Charts: false,
Actuals: false
},
{
CollapseActAndAss: false,
FinishProcessing: false
}
];
break;
case 'selectScenario':
requestObj.subEvents = [
{
BeginProcessing: false
},
{
SelectScenario: false
},
{
SetPageScenario: false
},
{
DimensionSelections: false,
HideActsAndAss: false,
Assumptions: false
},
{
Charts: false,
Actuals: false
},
{
CollapseActAndAss: false,
FinishProcessing: false
}
];
break;
case 'selectDimension':
requestObj.subEvents = [
{
SelectDimension: false
}
];
break;
default:
consoleLog('requestBuilder', ['The ' + event + ' event does not exist.'], null, 'error');
}
smState.eventRequests[tStamp] = requestObj;
return tStamp;
}
function requestRouter(rID, subEv){
/**
When a function uses async processes, then we need to use a
callback function to call postRequestProcessor.
Otherwise, postRequestProcessor can be called inline below
within each case.
**/
switch(subEv){
case 'Actuals':
loadActuals(buildActuals, postRequestProcessor, rID, subEv);
break;
case 'AdjustSM':
expandedSM(false); // set SM width
postRequestProcessor(rID, subEv);
break;
case 'Assumptions':
loadAssumptions(buildAssumptions, postRequestProcessor, rID, subEv);
break;
case 'BeginProcessing':
processingMsg();
postRequestProcessor(rID, subEv);
break;
case 'Charts':
assembleCharts();
postRequestProcessor(rID, subEv);
break;
case 'ClearLF':
clearLocalForage();
postRequestProcessor(rID, subEv);
break;
case 'CollapseActAndAss':
collapseActualsAndAssumptions();
postRequestProcessor(rID, subEv);
break;
case 'CreateScenario':
isScenarioNameUnique(createNewScenario, postRequestProcessor, rID, subEv);
break;
case 'DeleteScenario':
deleteScenario(postRequestProcessor, rID, subEv);
break;
case 'Dimensions':
loadDimensionsData(buildDimensionsDD, postRequestProcessor, rID, subEv);
break;
case 'DimensionsPreLoad':
loadDimensionsData(null, postRequestProcessor, rID, subEv);
break;
case 'DimensionSelections':
loadDimensionSelections(showDimensionSelections, postRequestProcessor, rID, subEv);
break;
case 'FinishProcessing':
clearAllMsgs();
postRequestProcessor(rID, subEv);
break;
case 'HideActsAndAss':
hideActsAndAss();
postRequestProcessor(rID, subEv);
break;
case 'ResetSMDisplay':
resetSMDisplay();
postRequestProcessor(rID, subEv);
break;
case 'Scenarios':
loadCurrScenarioData(buildCurrScenarioDD, postRequestProcessor, rID, subEv);
break;
case 'SaveDimensions':
saveDimensionSelections(postRequestProcessor, rID, subEv);
break;
case 'SaveAssumptions':
saveAssumptions(postRequestProcessor, rID, subEv);
break;
case 'SelectDimension':
selectDimension(rID);
postRequestProcessor(rID, subEv);
break;
case 'SelectScenario':
selectScenario(rID);
postRequestProcessor(rID, subEv);
break;
case 'SetEventListeners':
sectionScenariosEvents();
generalSMEventsHandler();
adjustSMPanel(); // adjust height of SM panel
postRequestProcessor(rID, subEv);
break;
case 'SetPageScenario':
setPageToScenario();
postRequestProcessor(rID, subEv);
break;
default:
consoleLog('requestRouter', ['The ' + subEv + 'event does not exist.'], null, 'error');
}
}
function postRequestProcessor(rID, subEv){
var eventObj = smState.eventRequests[rID],
eventsCompleted = 0;
smState.eventRequests[rID].subEvents[smState.eventRequests[rID].stage][subEv] = true;
for (var anEvent in eventObj.subEvents[eventObj.stage]){
if (eventObj.subEvents[eventObj.stage].hasOwnProperty(anEvent)){
if (eventObj.subEvents[eventObj.stage][anEvent] === true){
eventsCompleted++;
}
}
}
if (eventsCompleted === Object.keys(eventObj.subEvents[eventObj.stage]).length){
(eventObj.stage)++;
consoleLog('postReqProc', ['sub-Ev: ' + subEv], eventObj, 'warn');
if (eventObj.stage >= eventObj.subEvents.length){
delete smState.eventRequests[rID];
} else {
requestHandler(rID);
}
}
}
function requestHandler(rID){
var eventObj = smState.eventRequests[rID];
for (var anEvent in eventObj.subEvents[eventObj.stage]){
if (eventObj.subEvents[eventObj.stage].hasOwnProperty(anEvent)){
requestRouter(rID, anEvent);
}
}
}
function cancelRequest(rID){
delete smState.eventRequests[rID];
}
/** Data Loads **/
function loadCurrScenarioData(cb, cb2, requestID, subEvent) {
var params = { "DimName": "Scenario"}, // web method: TM1DimensionMembers?DimName=Scenario
webMethod = 'TM1DimensionMembers',
savedScenarioNames = [],
onSuccess,
onFailure;
smState.loadFailures.loadCurrScenarioData = smState.loadFailures.loadCurrScenarioData || 0;
onSuccess = function(resultObj) {
smState.loadFailures.loadCurrScenarioData = 0;
resultObj.Results.Members.forEach(function(value) {
savedScenarioNames.push(value.Name);
});
savedScenarioNames.sort();
smState.ScenarioNames = savedScenarioNames;
testPageScenario(cb, cb2, requestID, subEvent);
};
onFailure = function() {
var recursiveCall = function(){
loadCurrScenarioData(cb, cb2, requestID, subEvent);
};
if (smState.loadFailures.loadCurrScenarioData < MAX_FAILS){
(smState.loadFailures.loadCurrScenarioData)++;
loadCurrScenarioData(cb, cb2, requestID, subEvent);
} else {
failedToUpdateMsg('The "Current Scenario" drop down', [recursiveCall]);
smState.loadFailures.loadCurrScenarioData = 0;
}
};
es.get(webMethod, params, onSuccess, onFailure, true);
}
function loadSingleDimensionData(cb, method, parameters, cb2, requestID, subEvent){
var formattedName = formatStringSpace(parameters.DimName),
failureName = 'dimension' + formattedName,
onSuccess,
onFailure;
smState.loadFailures[failureName] = smState.loadFailures[failureName] || 0;
onSuccess = function(resultObj, localTest) {
if (localTest !== 'fromLocalStorage'){
localforage.setItem(formattedName, resultObj);
}
smState.loadFailures[failureName] = 0;
smState.DimensionsData[formattedName] = resultObj;
(smState.singleDimensionDataSuccesses)++;
if (smState.singleDimensionDataSuccesses === Object.keys(DD_ON_LOAD).length){
smState.singleDimensionDataSuccesses = 0;
if (cb){
cb(cb2, requestID, subEvent);
} else {
cb2(requestID, subEvent);
}
}
};
onFailure = function() {
var recursiveCall = function(){
loadSingleDimensionData(cb, method, parameters, cb2, requestID, subEvent);
};
if (smState.loadFailures[failureName] < MAX_FAILS){
(smState.loadFailures[failureName])++;
loadSingleDimensionData(cb, method, parameters, cb2, requestID, subEvent);
} else {
failedToUpdateMsg('The ' + parameters.DimName + ' drop down', [recursiveCall]);
smState.loadFailures[failureName] = 0;
}
};
localforage.getItem(formattedName, function(err, val){
if (val !== null){
onSuccess(val, 'fromLocalStorage');
} else {
es.get(method, parameters, onSuccess, onFailure, true);
}
});
}
function loadDimensionsData(cb, cb2, requestID, subEvent) {
var key,
params = {},
pCopy;
for (key in DD_ON_LOAD){ // create this first so that "counter" is accurate in loadSingleDimensionData
if (DD_ON_LOAD.hasOwnProperty(key)) {
smState.DimensionsData[key] = {};
}
}
for (key in DD_ON_LOAD) {
if (DD_ON_LOAD.hasOwnProperty(key)) {
params[DD_ON_LOAD[key].webMParamKey1] = DD_ON_LOAD[key].webMParamVal1;
if (DD_ON_LOAD[key].webMParamKey2) {
params[DD_ON_LOAD[key].webMParamKey2] = DD_ON_LOAD[key].webMParamVal2;
}
pCopy = $J.extend(true, {}, params);
loadSingleDimensionData(cb, DD_ON_LOAD[key].methodName, pCopy, cb2, requestID, subEvent);
}
}
}
function loadDimensionSelections(cb, cb2, requestID, subEvent) {
var params = {},
webMethod = "ScenarioManager", // web method: ScenarioManager?Scenario=Actual
onSuccess,
onFailure;
smState.loadFailures.loadDimensionSelections = smState.loadFailures.loadDimensionSelections || 0;
onSuccess = function(resultObj) {
smState.loadFailures.loadDimensionSelections = 0;
var dimensionsRows = resultObj.Results.RowSet.Rows,
rowKey = 0,
key,
dimensionArr = [ // get saved Dimension selections
dimensionsRows[rowKey].SelectedYear,
dimensionsRows[rowKey].SelectedLegalEntity,
dimensionsRows[rowKey].SelectedBusinessUnit,
dimensionsRows[rowKey].SelectedRegion,
dimensionsRows[rowKey].SelectedWorkforceCategory,
dimensionsRows[rowKey].SelectedWorkerType,
dimensionsRows[rowKey].SelectedJobGrade,
dimensionsRows[rowKey].SelectedFunctionalGroup,
dimensionsRows[rowKey].SelectedJobFunction
];
dimensionsResults = resultObj.Results; // save copy of Results JSON for post via saveDimensionSelections()
dimensionArr.forEach(function(value, index) {
for (key in DD_ON_LOAD) {
if (DD_ON_LOAD.hasOwnProperty(key)) {
if (value === DD_ON_LOAD[key].resultsMembersID && DD_ON_LOAD[key].resultsMembersID !== DD_ON_LOAD[key].defOptName) {
dimensionArr[index] = DD_ON_LOAD[key].defOptName; // intention is to display default value, but we must display custom default value, i.e. not 'All Years' but 'Current Year'
}
}
}
});
smState.DimensionsSelections = dimensionArr;
cb(cb2, requestID, subEvent);
};
onFailure = function() {
var recursiveCall = function(){
loadDimensionSelections(cb, cb2, requestID, subEvent);
};
if (smState.loadFailures.loadDimensionSelections < MAX_FAILS){
(smState.loadFailures.loadDimensionSelections)++;
loadDimensionSelections(cb, cb2, requestID, subEvent);
} else {
failedToUpdateMsg('Some of the data', [recursiveCall]);
smState.loadFailures.loadDimensionSelections = 0;
}
};
params.Scenario = smState.smVals.Scenario;
es.get(webMethod, params, onSuccess, onFailure, false);
}
function loadActuals(cb, cb2, requestID, subEvent) {
var webMethod = "ScenarioManagerActuals", // web method: ScenarioManagerActuals
formattedName,
tempArr = [],
onSuccess,
onFailure;
smState.loadFailures.loadActuals = smState.loadFailures.loadActuals || 0;
formattedName = getLFFormattedName('Actuals');
onSuccess = function(resultObj, localTest) {
var actuals = resultObj.Results.RowSet.Rows,
key,
actSect,
actTitle,
actVal;
if (localTest !== 'fromLocalStorage'){
localforage.setItem(formattedName, resultObj);
}
smState.loadFailures.loadActuals = 0;
for (key in actuals) {
if (actuals.hasOwnProperty(key)) {
actSect = actuals[key].ScenarioManagerActualsSection;
actTitle = actuals[key].ScenarioManagerActuals;
actTitle = actTitle.replace(' Actual', '');
actVal = actuals[key].AllUDC2;
tempArr.push([actTitle, actSect, actVal]);
}
}
cb(tempArr, cb2, requestID, subEvent);
};
onFailure = function() {
var tryAgain = function(){
loadActuals(cb, cb2, requestID, subEvent);
};
if (smState.loadFailures.loadActuals < MAX_FAILS){
(smState.loadFailures.loadActuals)++;
loadActuals(cb, cb2, requestID, subEvent);
} else {
failedToUpdateMsg('The actual/current data', [tryAgain]);
smState.loadFailures.loadActuals = 0;
}
};
localforage.getItem(formattedName, function(err, val){
if (val !== null){
onSuccess(val, 'fromLocalStorage');
} else {
es.get(webMethod, filterSMVals(['Scenario']), onSuccess, onFailure, true);
}
});
}
function loadAssumptions(cb, cb2, requestID, subEvent) {
var webMethod = "ScenarioAssumptionsChange", // web method: ScenarioAssumptionsChange
formattedName,
params = {},
tempArr = [],
onSuccess,
onFailure;
smState.loadFailures.loadAssumptions = smState.loadFailures.loadAssumptions || 0;
formattedName = getLFFormattedName('Assumptions');
onSuccess = function(resultObj, localTest) {
var assumptions = resultObj.Results.RowSet.Rows,
assSect,
assTitle,
assVal;
if (localTest !== 'fromLocalStorage'){
localforage.setItem(formattedName, resultObj);
}
smState.loadFailures.loadAssumptions = 0;
assumptionsResults = resultObj.Results;
assumptions.forEach(function(item, index){
assSect = assumptions[index].ScenarioAssumptionSection;
assTitle = assumptions[index].ScenarioAssumption;
assTitle = assTitle.replace(' Change Percent', '');
assVal = assumptions[index].AnalysisYear;
tempArr.push([assTitle, assSect, assVal]);
});
cb(tempArr, cb2, requestID, subEvent, smState);
};
onFailure = function() {
var tryAgain = function(){
loadAssumptions(cb, cb2, requestID, subEvent);
};
if (smState.loadFailures.loadAssumptions < MAX_FAILS){
(smState.loadFailures.loadAssumptions)++;
loadAssumptions(cb, cb2, requestID, subEvent);
} else {
failedToUpdateMsg('The projection/assumption data', [tryAgain]);
smState.loadFailures.loadAssumptions = 0;
}
};
localforage.getItem(formattedName, function(err, val){
if (val !== null){
onSuccess(val, 'fromLocalStorage');
} else {
params.Scenario = smState.smVals.Scenario;
es.get(webMethod, params, onSuccess, onFailure, true);
}
});
}
/** Build Components **/
function buildCurrScenarioDD(cb, requestID, subEvent) {
var selectCurrScenario = $J('#curScenarioSel'),
optionStr = '',
selectedValue;
destroySelect2('scenario');
selectCurrScenario.empty();
smState.ScenarioNames.forEach(function(value) {
optionStr = '<option value="' + value + '"';
if (value === smState.smVals.Scenario) {
optionStr += 'selected="selected"';
selectedValue = value;
}
optionStr += '>' + value + '</option>';
selectCurrScenario.append(optionStr);
});
/* TODO: delete if not needed after all testing is complete
if (selectedValue){
// trigger change so that it registers with select2
selectCurrScenario.val(selectedValue).trigger('change', selectedValue);
selectCurrScenario.next().find('.select2-selection__rendered').text(selectedValue);
}*/
scenarioDDLEventsHandler();
applySelect2('scenario');
cb(requestID, subEvent);
}
function iterateDimChildren(childObj, obj, aParID, isPeriodChildAttr) {
var sortOptions = [],
parID = isDefinedAndTrue(aParID) ? aParID : '',
dimNameAsKey = formatStringSpace(obj.webMParamVal1),
selectCurrScenario,
setOptText,
optionText,
dimDDText = { // format Dimension dropdown labels/text
// i.e. 'Management & Senior Leadership': 'Mgmt and Senior Leadership'
};
$J('#' + dimNameAsKey).append('<div class="clear-fix hidden" id="' + obj.selectID + '-container"><select name="' + obj.selectID + '" size="1" class="dimensionDD" id="' + obj.selectID + '" dimid="' + dimNameAsKey + '" parid="' + parID + '"></select></div>');
selectCurrScenario = $J('#' + obj.selectID);
setOptText = isDefinedAndTrue(obj.defOptName) ? obj.defOptName : DEF_CHILD_OPT_NAME;
selectCurrScenario.empty().append('<option value="" selected="selected">' + setOptText + '</option>');
childObj.forEach(function(value) {
var valueToAdd = isPeriodChildAttr ? value.Attributes[0].Value : value.Name,
hasChildren = value.Children,
yearOnly = periodYearOnly && obj.resultsMembersID === DD_ON_LOAD.Period.resultsMembersID,
childObj,
selIdOptVal;
sortOptions.push(valueToAdd);
if (isDefinedAndTrue(hasChildren) && hasChildren.length > 0 && !yearOnly) {
childObj = {};
childObj.webMParamVal1 = dimNameAsKey;
childObj.selectID = obj.selectID + formatStringChars(valueToAdd);
childObj.resultsMembersID = null;
parID = obj.selectID;
// add dependency of selects to dependSelects object
selIdOptVal = obj.selectID + '-' + formatStringChars(valueToAdd);
dependSelects[selIdOptVal] = childObj.selectID;
iterateDimChildren(hasChildren, childObj, parID, isPeriodChildAttr);
}
});
for (var i = 0, arrLen = sortOptions.length; i < arrLen; i++) {
optionText = sortOptions[i];
// uncomment to format Dimension dropdown option TEXT
// if (optionText in dimDDText) {
// optionText = dimDDText[optionText];
// }
selectCurrScenario.append('<option value="' + sortOptions[i] + '">' + optionText + '</option>');
}
}
function buildDimensionsDD(cb, requestID, subEvent) {
var dLabels = $J('#dimRowLabels'),
dDDowns = $J('#dimRowDropdowns'),
key;
dLabels.empty();
dDDowns.empty();
for (key in DD_ON_LOAD){
if (DD_ON_LOAD.hasOwnProperty(key)) {
dLabels.append('<div class="dimRowLabel" dimid="' + formatStringSpace(DD_ON_LOAD[key].webMParamVal1) + '" ddid="' + DD_ON_LOAD[key].selectID + '">' + DD_ON_LOAD[key].defOptName + '</div>');
dDDowns.append('<div class="clear-fix varSelect" id="' + formatStringSpace(DD_ON_LOAD[key].webMParamVal1) + '"></div>');
smState.DimensionsData[key].Results.Members.forEach(function(value) {
if (value.ID === DD_ON_LOAD.Period.resultsMembersID) { // if this == period, then parse differently
iterateDimChildren(value.Children, DD_ON_LOAD[key], null, true);
} else if (value.ID === DD_ON_LOAD[key].resultsMembersID) {
iterateDimChildren(value.Children, DD_ON_LOAD[key], null, false);
}
});
}
}
cb(requestID, subEvent);
}
function buildAssumptionDD(actTitle, assVal) {
var rangeStart = -200,
rangeEnd = 200,
percentified = (parseFloat(assVal) * 100).toFixed(0),
returnStr = '<select name="' + actTitle + '" class="varPercent">';
if (ddRange.length === 0){
do {
ddRange.push(rangeStart);
rangeStart++;
} while (rangeStart <= rangeEnd);
}
ddRange.forEach(function(value) {
returnStr += '<option value="' + value + '"';
if (value.toString() === percentified) {
returnStr += ' selected="selected"';
}
returnStr += '>' + value + '%</option>';
});
returnStr += '</select>';
return returnStr;
}
function buildAssumptions(assumptionsArr, cb, requestID, subEvent) {
var actualsExist,
i = 0,
newSectionTitle,
arrSectionTitle,
savedActVal,
arrAssTitle,
arrAssVal;
actualsExist = $J('#smEntities .actualVal').first().text() !== '' ? $J('#smEntities .actualVal') : null;
destroySelect2('assumptions');
$J('#smEntities').empty();
newSectionTitle = '';
while (i < assumptionsArr.length) {
arrSectionTitle = assumptionsArr[i][1];
if (arrSectionTitle !== newSectionTitle) { // if new Section title found, print
newSectionTitle = arrSectionTitle;
if (arrSectionTitle in DISPLAY_SECTION_NAMES) {
arrSectionTitle = DISPLAY_SECTION_NAMES[arrSectionTitle].displayName;
}
$J('#smEntities').append('<div class="sectContainer"><p class="sectTitle">+ ' + arrSectionTitle + '</p><table border="0"><thead><tr><th class="varGroupTH">- ' + arrSectionTitle + '</th><th class="varGroupVal">Actual</th><th class="varGroupVal">% Change</th></tr></thead><tbody></tbody></table></div>');
}
// add rows to Section
savedActVal = actualsExist ? actualsExist.eq(i).text() : '';
arrAssTitle = assumptionsArr[i][0];
arrAssVal = assumptionsArr[i][2];
$J('#smEntities div:last-child table tbody').append('<tr><td class="varLabelTD">' + arrAssTitle + '</td><td class="actualVal">' + savedActVal + '</td><td class="assumptionVal">' + buildAssumptionDD(arrAssTitle, arrAssVal) + '</td></tr>');
i++;
}
applySelect2('assumptions');
assumptionDDLClickHandler();
cb(requestID, subEvent);
}
function buildActuals(actualsArr, cb, requestID, subEvent) {
var smEntities,
i = 0,
arrActTitle,
arrActVal,
formattedResult;
smEntities = $J('#smEntities .actualVal');
while (i < actualsArr.length) {
arrActTitle = actualsArr[i][0];
arrActVal = actualsArr[i][2];
formattedResult = formatActualVal(arrActTitle, arrActVal);
smEntities.eq(i).empty().text(formattedResult[1]);
i++;
}
cb(requestID, subEvent);
}
/** Set & Display Components **/
function showIndDimSelection(selectedOption) {
var thisClosestSelect = selectedOption.closest('select'),
thisParID = thisClosestSelect.attr('parid'),
curSelectOpt,
containerDivID,
extrasObj = {};
if (thisParID !== '') {
for (var key in dependSelects) {
if (dependSelects.hasOwnProperty(key)) {
if (dependSelects[key] === thisClosestSelect.attr('id')) {
var parentSelectVal = key.split('-')[1];
$J('#' + thisParID).find('option').each(function() {
var thisParOption = $J(this),
thisParOptionText = formatStringChars(thisParOption.text());
if (thisParOptionText === parentSelectVal) {
showIndDimSelection(thisParOption);
}
});
}
}
}
}
curSelectOpt = thisClosestSelect.find('option:selected');
if (curSelectOpt.text() !== selectedOption.text()) {
curSelectOpt.removeAttr('selected');
selectedOption.attr('selected', 'selected');
thisClosestSelect.val(selectedOption.val());
extrasObj.thisSelect = thisClosestSelect;
extrasObj.thisSelectVal = thisClosestSelect.val();
extrasObj.thisSelectID = thisClosestSelect.attr('id');
extrasObj.thisDefaultOpt = thisClosestSelect.find('option:first').text();
selectDimension(null, extrasObj);
}
containerDivID = thisClosestSelect.attr('id');
$J('#' + containerDivID + '-container').removeClass('hidden'); // show container div
}
function showDimensionSelections(cb, requestID, subEvent) {
var key,
savedSelectVal,
index = 0,
thisOption;
destroySelect2('dimensions');
dimensionDDLEventsHandler('unbind');
for (key in DD_ON_LOAD){
if (DD_ON_LOAD.hasOwnProperty(key)){
clearChildSelect(DD_ON_LOAD[key].selectID); // reset dropdowns first
savedSelectVal = smState.DimensionsSelections[index]; // get saved Option value
$J('#' + formatStringSpace(DD_ON_LOAD[key].webMParamVal1)).find('option').each(function() {
thisOption = $J(this);
if (thisOption.text() === savedSelectVal) {
showIndDimSelection(thisOption);
}
});
index++;
}
}
applySelect2('dimensions');
dimensionDDLEventsHandler();
updateSMDimensionVals();
cb(requestID, subEvent);
}
function hideActsAndAss(){
$J('#smEntities').hide();
}
function collapseActualsAndAssumptions() {
$J('#smEntities table').toggle();
$J('#smEntities p').click(function() {
$J(this).next().toggle();
$J(this).toggle();
});
$J('#smEntities th.varGroupTH').click(function() {
$J(this).closest('table').toggle();
$J(this).closest('.sectContainer').find('p.sectTitle').toggle();
});
$J('#smEntities').show();
}
function resetSMDisplay() {
$J('#select-toggle-btn').trigger('click');
}
function repositionVarSelect(divID) {
var divJ = $J('#dimRowDropdowns').children('#' + divID),
curTop,
drl,
baseTop,
newTop;
divJ.css({ 'position': 'relative', 'top': '0px', 'left': '0px' });
if ($J('.dimRowLabelFocus').length > 0){
curTop = $J('.dimRowLabelFocus').position().top;
drl = $J('#dimRowLabels');
baseTop = drl.position().top;
newTop = (curTop - baseTop) + divJ.height() > drl.height() ?
drl.height() - divJ.height() - 1 :
curTop - baseTop;
divJ.css({ 'position': 'relative', 'top': newTop + 'px', 'left': '0px' });
}
}
/** Events & UX **/
function adjustTabForScenario(){
$J('#new-scenario-tab').hide();
$J('#cur-scenario-tab').show();
if (protectedScenarios.indexOf(smState.smVals.Scenario) !== -1){
$J('#cur-scenario-tab-btns').hide();
} else {
$J('#cur-scenario-tab-btns').css('display', 'inline-block');
}
}
function adjustSMPanel(){
$J(window).scroll(function() {
var bodyHeight = $J('#body').height();
if (bodyHeight > $J('.smOpenD').height()) {
$J('.smOpenD').height(bodyHeight);
$J('.smCloseD').height(bodyHeight);
$J('#sm').height(bodyHeight - 34);
}
});
$J('#sm').scroll(function() {
if (($J('#sm')[0].scrollHeight - $J('.smCloseD').height()) > 19) {
$J('.smCloseD').height($J('#sm')[0].scrollHeight);
}
});
}
function sectionScenariosEvents(){
var nameInput,
defVal = '',
errorVal = 'Please enter a name',
extrasObj = {};
// *** Current Scenario ***
// ************************
$J('#select-toggle-btn').click(function() {
$J('#new-scenario-tab').hide();
$J('#cur-scenario-tab').show();
$J('#smFilters').show();
$J('#smEntities').show();
$J('#update-scenario-btn').show();
});
// *** Create Scenario ***
// ***********************
nameInput = $J('#create-scenario-name');
$J('#create-toggle-btn').click(function() {
$J('#smFilters').hide();
$J('#smEntities').hide();
$J('#cur-scenario-tab').hide();
$J('#update-scenario-btn').hide();
$J('#new-scenario-tab').show();
nameInput.val('');
nameInput.focus();
});
nameInput.click(function() {
nameInput.val(defVal).css('color', '#000');
if (nameInput.val() === defVal || nameInput.val() === errorVal) {
$J(this).val('');
}
});
$J('#create-scenario-btn').click(function() {
if (nameInput.val() === '' || nameInput.val() === defVal) {
nameInput.val(errorVal).css('color', 'red');
}
else {
extrasObj.ScenarioName = nameInput.val();
init('createScenario', extrasObj);
}
});
// *** Delete Scenario ***
// ***********************
$J('#delete-scenario-btn').click(function() {
init('deleteScenario');
});
// *** Update Scenario ***
// ***********************
$J('#update-scenario-btn').click(function() {
init('saveScenario');
});
}
function scenarioDDLEventsHandler(){
var thisDDL = $J('#curScenarioSel');
thisDDL.unbind('change');
thisDDL.change(function(){
var extrasObj = {};
extrasObj.thisSelectVal = $J(this).val();
init('selectScenario', extrasObj);
});
}
function dimensionDDLEventsHandler(cmd){
var thisDDL = $J('.dimensionDD'),
thisRowLabels = $J('.dimRowLabel');
if (cmd === 'unbind') {
thisDDL.unbind('click').unbind('change');
thisRowLabels.unbind('click');
} else {
thisRowLabels.click(function() {
var thisRowLabel = $J(this),
divToShow,
containerToShow;
if (smState.smVals.Scenario === DEFAULT_SCENARIO_NAME) {
pushMsg('error', {
title: 'Choose Another Scenario',
message: 'Dimension selections are allowed in Scenarios other than ' + DEFAULT_SCENARIO_NAME + '. Please choose another Scenario.',
spinner: false,
confirm: {
msg: 'Ok',
funcs: [clearAllMsgs]
},
deny: {}
});
return;
}
$J('.dimRowLabel').removeClass('dimRowLabelFocus'); // clear hover styling from all row labels
thisRowLabel.addClass('dimRowLabelFocus'); // add hover styling to THIS row label
expandedSM(true);
$J('#smFilters').addClass('dimRowDropdownsFocus'); // add gray background, appears to apply to dropdowns column only
$J('.varSelect').addClass('hidden'); // hide all dropdowns
divToShow = thisRowLabel.attr('dimid'); // show dropdown for label being hovered over
containerToShow = thisRowLabel.attr('ddid');
divToShow = formatStringSpace(divToShow);
$J('#' + divToShow).removeClass('hidden');
$J('#' + containerToShow + '-container').removeClass('hidden');
repositionVarSelect(divToShow);
});
$J('#smFilters').on('click', '.select2-selection__rendered', function() {
var thisSelID = $J(this).closest('div').find('select').attr('id'),
hasDepends = thisSelID + '-' + formatStringChars($J(this).text()),
subSelectID;
if (hasDepends in dependSelects) {
subSelectID = dependSelects[hasDepends];
if (!$J('#' + subSelectID + '-container').hasClass('hidden')) {
wasSelectedVal[thisSelID] = subSelectID;
}
}
});
thisDDL.change(function(initEvent){
var thisSelect = $J(this),
extrasObj = {};
if (initEvent !== false){
extrasObj.thisSelect = thisSelect;
extrasObj.thisSelectVal = thisSelect.val();
extrasObj.thisSelectID = thisSelect.attr('id');
extrasObj.thisDefaultOpt = thisSelect.find('option:first').text();
init('selectDimension', extrasObj);
}
});
}
}
function assumptionDDLClickHandler(){
var thisSection = $J('#smEntities');
thisSection.unbind('click');
thisSection.on('click', '.select2-selection', function() {
if (smState.smVals.Scenario === DEFAULT_SCENARIO_NAME) {
pushMsg('error', {
title: 'Choose Another Scenario',
message: 'Projections are allowed in Scenarios other than ' + DEFAULT_SCENARIO_NAME + '. Please choose another Scenario to make projections.',
spinner: false,
confirm: {
msg: 'Ok',
funcs: [clearAllMsgs]
},
deny: {}
});
}
});
}
function generalSMEventsHandler(){
function dimOriginalState(){
setTimeout(function() {
if (!onSelect2) {
$J('.dimRowLabel').removeClass('dimRowLabelFocus'); // remove hover styling to row labels
$J('#smFilters').removeClass('dimRowDropdownsFocus'); // remove gray background that appears behind dropdowns column
$J('.varSelect').addClass('hidden'); // hide all dropdowns
expandedSM(false);
}
}, 200);
}
// onMouseLeave, clear Dimension and related elements
$J('#smFilters').mouseleave(function() {
dimOriginalState();
});
// prevent #smFilters.mouseleave from executing
$J('body').on('mouseenter', '.select2-dropdown', function() {
onSelect2 = true;
});
// undo onMouseEnter above
$J('body').on('mouseleave : focusout', '.select2-dropdown', function() {
onSelect2 = false;
});
// closes select2 dropdown without the need for a click outside of the element
$J('body').on('mouseenter', '#sm', function() {
$J('.dimensionDD').each(function() {
$J(this).select2("close");
});
});
}
/** Ante Up **/
function init(event, extrasObject){
var requestID = requestBuilder(event, extrasObject);
requestHandler(requestID);
}
/*
To be called from within each esApp script
scManager.smInit('pageLoad');
*/
module.exports = {
smInit: init,
getSMVals: smState.smVals,
getTM1CurrentYear: getTM1CurrentYear,
tm1CurrentYear: tm1CurrentYear,
processingMsg: processingMsg,
setPeriodToYearOnly: setPeriodToYearOnly
};
|
import React, { useState } from "react";
import { Container, Typography, Grid } from "@material-ui/core";
import SearchBar from "../../components/search-bar";
import SearchList from "../../components/search-list";
import ToggleButton from "@material-ui/lab/ToggleButton";
import Brightness2Icon from "@material-ui/icons/Brightness2";
import Brightness5Icon from "@material-ui/icons/Brightness5";
import axios from "axios";
function Results(props) {
const { results, click } = props;
return (
<div>
{results.map((result) => (
<SearchList key={result.imdbID} result={result} click={click} />
))}
</div>
);
}
function Component(props) {
const apiUrl = "http://www.omdbapi.com/?apikey=2c11df7f";
const { classes } = props;
const [dark, setDark] = useState(false);
const [type, setType] = useState({
s: "",
results: [],
selected: {},
});
const search = (e) => {
if (e.key === "Enter") {
axios(apiUrl + "&s=" + type.s).then(({ data }) => {
let results = data.Search;
setType(({ prevType }) => {
return { ...prevType, results: results };
});
});
}
};
const handleInput = (e) => {
let s = e.target.value;
setType((prevType) => {
return { ...prevType, s: s };
});
console.log(type.s);
};
const select = (id) => {
axios(apiUrl + "&i=" + id).then(({ data }) => {
let result = data;
console.log(result);
localStorage.setItem("selectedFilm", JSON.stringify(result));
props.history.push(`/detail/${result.Title}`);
setType((prevType) => {
return { ...prevType, selected: result };
});
});
};
return (
<React.Fragment>
<Container
maxWidth="xs"
className={classes.Container}
style={{
background: dark ? "#f6f6f6" : "#0C0F13",
border: dark ? "solid 1px #000" : "solid 1px #0c0f13",
}}
>
<SearchBar handleInput={handleInput} search={search} />
<Grid container spacing={0} style={{ marginTop: "3%" }}>
<Grid item xs="12">
<Typography
variant="subtitle1"
style={{ color: dark ? "#0C0F13" : "#f6f6f6" }}
className={classes.poptext}
>
<b>Recomended FIlms</b>
</Typography>
</Grid>
<Grid item xs="12">
<Results results={type.results} click={select} />
</Grid>
</Grid>
<div
style={{
position: "fixed",
bottom: 0,
top: 0,
display: "flex",
justifyContent: "flex-end",
transformOrigin: "center center",
}}
>
<ToggleButton
selected={dark}
onChange={() => {
setDark(!dark);
}}
>
{dark ? (
<Brightness2Icon style={{ color: "0C0F13" }} />
) : (
<Brightness5Icon style={{ color: "#f6f6f6" }} />
)}
</ToggleButton>
</div>
</Container>
</React.Fragment>
);
}
export default Component;
|
/**
* Created by falvojr on 13/10/15.
*/
(function (io) {
'use strict';
angular.module('app')
.service('CoreService', CoreService);
CoreService.$inject = ['$http'];
/* @ngInject */
function CoreService($http) {
this.getDropboxImages = getDropboxImages;
this.onUpdateImages = onUpdateImages;
////////////////
function getDropboxImages() {
return $http.get('/api/image');
}
function onUpdateImages(event) {
io.connect("http://localhost:3001").on('update-images', event);
}
}
})(io);
|
module.exports = function parseRequestBody(request) {
return new Promise(resolve => {
const body = []
request.on('data', chunk => body.push(chunk))
request.on('end', () => {
const result = body.join('')
if (request.headers['content-type'] === 'application/json') {
resolve(JSON.parse(result))
} else {
resolve(result)
}
})
})
}
|
var colorWell
var defaultColor = "#0000ff";
window.addEventListener("load", choosecolor, false);
function choosecolor() {
colorWell = document.querySelector("#colorWell");
colorWell.value = defaultColor;
colorWell.addEventListener("input", changecolor, false);
colorWell.select();
}
function changecolor(e) {
var p = document.querySelector("p");
if (p) {
p.style.color = e.target.value;
}
}
function fontsize() {
var p =document.querySelector("p");
var Num=document.getElementById("Num");
p.style.fontsize=Num.value;
}
function fontfamily(selectTag) {
var listValue = selectTag.options[selectTag.selectedIndex].text;
document.querySelector("p").style.fontFamily = listValue;
}
|
import axios from 'axios';
import qs from 'qs';
var Banks = {
getAll: function(){
return axios.get(window.apiDomainUrl+'/banks/get-all', qs.stringify({}))
},
getAllByCountryId: function(countryId){
return axios.get(window.apiDomainUrl+'/banks/get-all-by-country-id?countryId='+countryId, qs.stringify({}))
},
get: function(id){
return axios.get(window.apiDomainUrl+'/banks/get-by-id?id='+id, qs.stringify({}))
},
create: function(createData){
return axios.post(window.apiDomainUrl+'/banks/create', qs.stringify(createData))
},
update: function(updateData){
return axios.post(window.apiDomainUrl+'/banks/update', qs.stringify(updateData))
},
deleteRow: function(companyId){
return axios.post(window.apiDomainUrl+'/banks/delete', qs.stringify({id:companyId}))
},
};
export function BanksManager() {
return Banks;
}
|
/**
* @license
*
* Copyright IBM Corp. 2020, 2021
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { render } from 'react-dom';
import ArrowRight20 from '@carbon/icons-react/es/arrow--right/20.js';
import DDSCard from '@carbon/ibmdotcom-web-components/es/components-react/card/card';
import DDSCardFooter from '@carbon/ibmdotcom-web-components/es/components-react/card/card-footer';
import DDSCardHeading from '@carbon/ibmdotcom-web-components/es/components-react/card/card-heading';
import DDSCarousel from '@carbon/ibmdotcom-web-components/es/components-react/carousel/carousel';
import './index.css';
const headingDefault = 'Lorem ipsum dolor sit amet';
const copyDefault = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean et ultricies est.';
const copyOdd = `
${copyDefault}
Mauris iaculis eget dolor nec hendrerit. Phasellus at elit sollicitudin, sodales nulla quis, consequat libero.
`;
// eslint-disable-next-line react/prop-types
const Card = ({ copy = copyDefault, heading = headingDefault } = {}) => (
<DDSCard href="https://www.ibm.com/standards/carbon">
<DDSCardHeading>{heading}</DDSCardHeading>
{copy}
<DDSCardFooter>
<ArrowRight20 slot="icon" />
</DDSCardFooter>
</DDSCard>
);
const App = () => (
<DDSCarousel>
<Card />
<Card copy={copyOdd} />
<Card />
<Card copy={copyOdd} />
<Card />
</DDSCarousel>
);
render(<App />, document.getElementById('root'));
|
const Schema = require('mongoose').Schema;
const db = require('../config/db');
const Employee = db.model('Employee', {
name:String,
dateOfBirth:Date,
profession:String,
succesRate:Number,
loyalty:Number,
picture:String,
_employer: {
type: Schema.Types.ObjectId,
ref: 'Boss'
}
});
module.exports = Employee;
|
import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '@/views/Main.vue'
import Category from '@/views/CategoryNews'
import PieceOfNews from '@/views/PieceOfNews'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'home',
component: Main
},
{
path: '/category',
name: 'category',
component: Category
},
{
path: '/example',
name: 'pieceOfNews',
component: PieceOfNews
},
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
|
import React from "react";
import { Menu } from "semantic-ui-react";
import { Link } from "react-router-dom";
const FilterComponent = ({ address, index }) => {
return (
<Menu.Item key={index} as={Link} to={`/AddressBookForm/${address.id}`}>
{address.fName + " " + address.lName}
</Menu.Item>
);
};
export default FilterComponent;
|
/**
* ReportsDailyLayout is the landing page for the daily reports page.
*
* It displays a chart of daily reps, sets or volume for a given month.
* @class
* @augments P.views.ReportsAbstract
*/
P.views.ReportsDailyLayout = P.views.ReportsAbstract.extend({
templateId: 'reports.layout',
period: 'daily',
range: 'month',
/**
* end is the final date of the charted period.
*/
end: function() {
return this.date.clone().add(1, 'month').startOf('month').format();
},
/**
* isCurrentPeriod checks if the rendered date range includes today.
*/
isCurrentPeriod: function() {
return this.date.isSame(new Date(), 'month');
},
/**
* start is the beginning date of the charted period.
*/
start: function() {
return this.date.clone().startOf('month').format();
},
/**
* url of the chart for this date
*/
url: function(date, attr) {
var userID = this.userID;
return Sisse.root + 'reports/daily/' + userID + '/' + date.month() + '/' +
date.year() + '?m=' + attr;
}
});
P.views.ReportsDailyLayout.Route = function(userID, month, year) {
var model = new P.models.workouts.Report();
var view = new P.views.ReportsDailyLayout({
userID: userID,
month: month,
year: year,
model: model
});
this.render(view);
};
|
/**
* A utility function to make a network api call
*
* @param {string} apiUrl
* @return {Promise<Object>}
*/
export async function request(apiUrl) {
return fetch(apiUrl).then((resp) => resp.json());
}
|
import React from 'react';
const Ul = ({ listChildren }) => {
return <ul>{listChildren}</ul>;
};
export default Ul;
|
const HtmlWebPackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const path = require('path');
const TailwindCss = require('tailwindcss')
const Autoprefixer = require('autoprefixer');
const plugins = [
new MiniCssExtractPlugin({
filename: "styles.css",
chunkFilename: "[name]-[chunkhash].css"
}),
new HtmlWebPackPlugin({
template: "./src/index.html",
filename: "./index.html"
}),
];
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve('public'),
filename: '[name]-[chunkhash].bundle.js',
publicPath: '/'
},
module: {
rules: [
{
test: /\.css$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: [
TailwindCss,
Autoprefixer
]
}
}
}
],
},
{
test: [/\.js$/, /\.jsx$/],
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: ['@babel/plugin-transform-runtime'],
},
},
],
}
]
},
optimization: {
splitChunks: {
chunks: 'all',
minSize: 10000,
maxSize: 1000000,
minChunks: 1,
maxAsyncRequests: 5,
maxInitialRequests: 3,
automaticNameDelimiter: '~',
automaticNameMaxLength: 30,
name: true,
cacheGroups: {
vendors: {
test: /[\\/]node_modules[\\/]/,
priority: -10
},
default: {
minChunks: 2,
priority: -20,
reuseExistingChunk: true
}
}
}
},
plugins: plugins
};
|
// Create new graph class and override some methods
function TracerouteGraph () {
this.link_distance = 150;
this.node_charge = -20;
}
// Override methods
TracerouteGraph.prototype = new D3Graph("d3-explain-graph");
// Add new graph
d3DirectedGraph = new TracerouteGraph();
force = d3DirectedGraph.getForce();
d3DirectedGraph.init();
// Tell graph it should behave like a tree
d3DirectedGraph.setTree(true);
d3DirectedGraph.setSelf(d3DirectedGraph);
// Create controller
graph = new D3GraphController(d3DirectedGraph);
// Add some dummy nodes and links
node_netgrafio = {"id":"netgrafio", "class": "netgrafio", "name": "netgrafio" }
node_websocket = {"id":"websocket", "class": "websocket", "name": "Web Socket" }
node_tcpsocket = {"id":"tcpsocket", "class": "tcpsocket", "name": "TCP Socket" }
node_webapp = {"id":"webapp", "class": "webapp", "name": "netgrafio web application" }
node_data = {"id":"data", "class": "data", "name":"Data source"}
graph.addNode(node_netgrafio)
graph.addNode(node_websocket)
graph.addNode(node_tcpsocket)
graph.addNode(node_webapp)
graph.addNode(node_data)
// Create links
graph.addLink({"source": "netgrafio", "target": "websocket"});
graph.addLink({"source": "netgrafio", "target": "tcpsocket"});
graph.addLink({"source": "websocket", "target": "netgrafio"});
graph.addLink({"source": "tcpsocket", "target": "netgrafio"});
graph.addLink({"source": "webapp", "target": "websocket"})
graph.addLink({"source": "websocket", "target": "webapp"})
graph.addLink({"source": "data", "target": "tcpsocket"})
graph.addLink({"source": "tcpsocket", "target":"data"})
// Add tipsy tooltips
$(".node.netgrafio").tipsy({
//gravity: $.fn.tipsy.autoNS,
gravity: "e",
fade: true,
html: true,
title: function() {
var hover = "<div class='hoverPopUp'>";
hover += "<p>This is the main application. Once started it will create several sockets (WebSocket, TCPSocket) and fire up the web application. </p>";
hover += "</div>";
return hover;
}
});
$(".node.tcpsocket").tipsy({
//gravity: $.fn.tipsy.autoNS,
gravity: "e",
fade: true,
html: true,
title: function() {
var hover = "<div class='hoverPopUp'>";
hover += "<p>This socket will listen for incoming packets (JSON) and forward them to the main application.</p>";
hover += "</div>";
return hover;
}
});
$(".node.websocket").tipsy({
//gravity: $.fn.tipsy.autoNS,
gravity: "e",
fade: true,
html: true,
title: function() {
var hover = "<div class='hoverPopUp'>";
hover += "<p>The web socket is mainly used by the web application itself in order to communicate with <b>netgrafio</b>. Once connected to it, it will wait for incoming packets and forward them to the web application.</p>";
hover += "</div>";
return hover;
}
});
$(".node.data").tipsy({
//gravity: $.fn.tipsy.autoNS,
gravity: "e",
fade: true,
html: true,
title: function() {
var hover = "<div class='hoverPopUp'>";
hover += "<p>The data source (command line, script whatever) will send packets to the <b>TCP socket</b>.</p>";
hover += "</div>";
return hover;
}
});
$(".node.webapp").tipsy({
//gravity: $.fn.tipsy.autoNS,
gravity: "e",
fade: true,
html: true,
title: function() {
var hover = "<div class='hoverPopUp'>";
hover += "<p>The web application will process the incoming packets (through the <b>web socket</b>) and visualize them in a previously defined way.</p>";
hover += "</div>";
return hover;
}
});
|
import React from 'react';
// Using map, filter, reduce
export class MapFilterReduce extends React.Component {
render() {
const users = [
{ name: 'Robin', isDeveloper: true },
{ name: 'Markus', isDeveloper: false },
];
const showUsers = false;
// if (!showUsers) {
// return null; // this is valid in React
// }
return (
<div>
{
showUsers && (
<ul>
{users.map(user => <li>{user.name}</li>)}
</ul>
)
}
</div>
);
}
}
// Transforming arrays into lists of elements
// https://reactjs.org/docs/lists-and-keys.html
// Component that accepts an array of numbers and outputs an unordered list of elements.
function ListItem(props) {
// Correct! There is no need to specify the key here:
return <li>{props.value}</li>;
}
function NumberList(props) {
const numbers = props.numbers;
// A good rule of thumb is that elements inside the map() call need keys.
const listItems = numbers.map((number) => (
{
/*
<li key={number.toString()}> //Key should be specified inside the array.
{number}
</li>
*/
},
// Or like this if we use another component -> Extracting Components with Keys
<ListItem
key={number.toString()}
value={number}
/>
));
return (
<ul>{listItems}</ul>
);
}
const numbers = [1, 2, 3, 4, 5];
export class List extends React.Component {
constructor(props) {
super(props);
this.state = {
name: 'Zoki'
}
}
render() {
return (
<div>
<NumberList numbers={numbers}/>
</div>
);
}
}// end of CLASS
// Keys
// Keys help React identify which items have changed, are added, or are removed.
// Keys should be given to the elements inside the array to give the elements a stable identity:
// The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.
// Most often you would use IDs from your data as keys:
// const todoItems = todos.map((todo) =>
// <li key={todo.id}>
// {todo.text}
// </li>
// );
// For more info check DOCS!!!
function Blog(props) {
const posts = props.posts;
const listItems = posts.map((post) =>
<li key={post.id}>
{post.title}
</li>
);
const sidebar = (
<div>
<p>Sadrzaj:</p>
<ul>
{listItems}
</ul>
</div>
);
const content = posts.map((post) =>
<div key={post.id}>
<h3>{post.title}</h3>
<p>{post.content}</p>
</div>
);
return (
<div>
{sidebar}
<hr/>
{content}
</div>
)
}
const posts = [
{id: 1, title: 'Hello World', content: 'Welcome to learning React!'},
{id: 2, title: 'Installation', content: 'You can install React from npm.'},
{id: 3, title: 'Test', content: 'Test Lists and Keys.'}
];
export class Posts extends React.Component {
render() {
return (
<div>
<Blog posts={posts}/>
</div>
);
}
}// end of class
|
/**
* Created by iyobo on 2016-04-24.
*
* For Common Nunjuck filters
* @param nunjucksEnv
*/
module.exports = function(nunjucksEnv){
nunjucksEnv.addFilter('shorten', function(str, count) {
return str.slice(0, count || 5);
});
nunjucksEnv.addFilter('showError', function(str) {
if(str){
return '<span class="error">'+str+'</span>'
}
else
return ""
});
nunjucksEnv.addFilter('stringify', function(obj) {
return JSON.stringify(obj);
});
}
|
(function (src) {
var ctx = App.Model.Sound.context();
var _pitch = 0
, _speed = 1;
var player =
{ status: 'loading'
, position: null
, duration: null
, cuePoint: 0
, startedAt: null
, startedFrom: null
, updateTimer: null
, updateFPS: 30
, onupdate: null
, voices: [ newVoice().then(init) ]
, output: ctx.createGain()
, play: play
, stop: stop
, seek: seek
, get speed () { return _speed }
, set speed (rate) { return _speed = updateAllVoices('playbackRate', rate) }
, get pitch () { return _pitch }
, set pitch (rate) { return _pitch = updateAllVoices('detune', rate) }
, constructor: true }; // fool is-plain-object
return player;
function updateAllVoices (param, value) {
player.voices.map(function (promisedVoice) {
promisedVoice.then(function (voice) {
voice[param] = value;
});
});
return value;
}
function newVoice () {
return _.buffer(src).then(function (buffer) {
var v = ctx.createBufferSource();
v.buffer = buffer;
v.playbackRate = _speed;
v.detune = _pitch;
v.onended = stop;
v.connect(player.output);
return v;
}).catch(function (error) {
console.error('could not create voice for', src);
console.log(error);
})
}
function init (voice) {
player.duration = voice.buffer.duration;
player.status = 'stopped';
update();
return voice;
}
function play () {
return player.voices[0].then(function (voice) {
voice.start(0, player.cuePoint);
player.status = 'playing';
player.startedAt = ctx.currentTime;
player.startedFrom = player.cuePoint;
update();
return voice;
});
}
function stop (unend) {
return player.voices.shift().then(function (voice) {
if (unend) voice.onended = null;
try { voice.stop() } catch (e) {}
player.voices.push(newVoice());
player.status = 'stopped';
player.cuePoint = player.position;
player.updateTimer = clearTimeout(player.updateTimer);
update();
return voice;
})
}
function seek (t) {
if (player.status === 'playing') {
return stop(true).then(function () { player.cuePoint = player.position = t }).then(play);
} else {
return new Promise(function (win) { player.cuePoint = player.position = t; win() });
}
}
function update () {
if (player.startedAt) {
var elapsed = ctx.currentTime - player.startedAt;
player.position = player.startedFrom + elapsed * _speed;
}
if (player.status === 'playing') {
player.updateTimer = setTimeout(update, 1000 / player.updateFPS);
}
if (player.onupdate) player.onupdate(player);
}
})
|
import React from 'react'
import { faDiscord, faReddit } from '@fortawesome/free-brands-svg-icons'
import Icon from 'src/components/Icon'
export default () => (
<div className="progress section">
<h1 className="title">Where We're At</h1>
<h2 className="subTitle">We're currently hard at work developing this website, the exchange, and GarliCoin itself! Check on our discord and reddit for more updates.</h2>
<div className="progressLinks">
<a href="https://discord.gg/nZWHe33" target="_blank" rel="noopener noreferrer" className="discordLink">
<Icon icon={faDiscord} />
</a>
<a href="https://garlicoin.reddit.com" target="_blank" rel="noopener noreferrer" className="redditLink">
<Icon icon={faReddit} />
</a>
</div>
</div>
);
|
//1
let transport = prompt('Выберите транспорт');
if (transport == "а"){
alert("210")
}
else if (transport == "в") {
alert("60")
}
иначе если (транспорт == "м") {
alert("325")
}
else if (transport == "с") {
alert("1120")
}
else if (transport == "п") {
alert("300")
}
//2
номер функции(x){
пусть arr = [];
для (пусть i = 0; i < x; i++){
arr.push(+prompt("Введите число",""));
}
пусть min = Math.min(...arr);
тревога(мин);
}
number(+prompt("Введите кол-во чисел", ""));
|
import React, { useEffect, useState } from 'react';
import PropTypes from 'prop-types';
import './CarouselX.css';
function CarouselX(props) {
const { id: uniqueID } = props;
const [activeSlide, setActiveSlide] = useState(0);
const [scrollPosition, setScrollPosition] = useState(0);
const [qtyPerPage, setQtyPerPage] = useState(props.qtyPerPage);
useEffect(() => {
function handleQtyPerPageAccordingWindowSize() {
if (window.innerWidth <= 992) setQtyPerPage(1);
if (window.innerWidth > 992) setQtyPerPage(props.qtyPerPage);
};
window.addEventListener('resize', () => handleQtyPerPageAccordingWindowSize());
handleQtyPerPageAccordingWindowSize();
return () => window.removeEventListener('resize', () => handleQtyPerPageAccordingWindowSize());
}, []);
// Função de movimentação
function scrollCarousel({ target }) {
const { value, name, id } = target;
let normalization;
if (name === `scroll-bar-${uniqueID}` ) {
normalization = value/7.5;
} else {
normalization = parseInt(id.split('nav')[1]);
}
const screenWidth = document
.querySelector('.app-container').clientWidth;
const distance = normalization * screenWidth;
const slides = document.querySelectorAll(`.${uniqueID}`);
for (let i=0; i < slides.length; i += 1) {
slides[i].style.transform = `translateX(-${distance}px)`;
}
setScrollPosition(normalization * 7.5);
setActiveSlide(normalization);
}
// Montagem elementos
const cards = props.children;
const qtyOfItems = cards.length;
const qtyOfSlides = qtyOfItems / qtyPerPage;
const cardWidth = `${100 / qtyPerPage}%`;
const slidesConfig = `repeat(${qtyOfSlides}, 100%)`;
let slidesNavigators = [];
let slides = [];
for (let i=0; i < qtyOfSlides; i += 1) {
slidesNavigators[i] =
<div
className={ i === activeSlide ? 'active' : '' }
key={ `nav${i}${uniqueID}` }
id={ `nav${i}` }
name="index-navigator"
onClick={ (e) => scrollCarousel(e) }
/>;
slides[i] = [];
for(let j=0; j < qtyPerPage; j += 1) {
slides[i].push(
<div
className="card"
id={ `card${j}${uniqueID}` }
key={ `card${j}${uniqueID}` }
style={{ width: cardWidth }}
>
{ cards[i*qtyPerPage + j] }
</div>
);
}
}
return (
<div className="carousel">
<div
className="carousel-slides"
style={{ gridTemplateColumns: slidesConfig }}
>
{ slides.map((slide, index) =>
<div
key={ `slide-${index}-${uniqueID}` }
id={ `slide${index}` }
className={ `slide ${uniqueID}` }
>
{ slide }
</div>
) }
</div>
{ qtyOfSlides !== 1 &&
(
<div className="carousel-navigators-container">
<div className="carousel-navigators">
<div className="circles-navigator">
{ slidesNavigators }
</div>
<input
name={ `scroll-bar-${uniqueID}` }
type="range"
min="0"
max={ 7.5 * (qtyOfSlides - 1)}
step={ 7.5 }
value={ scrollPosition }
className={ `scroll-navigator ${uniqueID}` }
onChange={ (e) => scrollCarousel(e) }
/>
</div>
</div>
)}
</div>
);
}
export default CarouselX;
CarouselX.defaultProps = {
qtyPerPage: 3,
}
CarouselX.propTypes = {
qtyPerPage: PropTypes.number,
id: PropTypes.string.isRequired,
}
|
import axios from 'axios'
import firebase from 'firebase'
import * as Actions from '../actions/actionType'
firebase.initializeApp({
apiKey: "AIzaSyBOJwx3pKj--PkRrGJWKKoyCbnfeeu4X0o",
authDomain: "recipe-46932.firebaseapp.com",
databaseURL: "https://recipe-46932.firebaseio.com",
projectId: "recipe-46932",
storageBucket: "recipe-46932.appspot.com",
messagingSenderId: "159950088877"
});
let db=firebase.firestore();
let authRef= firebase.auth();
export const storeToDatabase = (name,email,phone) =>{
let payload= {
name:name,
email:email,
phone:phone
};
return dispatch =>{
let user =authRef.currentUser;
console.log('user: :'+user);
authRef.setPersistence(firebase.auth.Auth.Persistence.LOCAL).then(()=>{
authRef.signInWithEmailAndPassword('a@gmail.com','123456').then(()=>{
console.log('User Signed In');
})
});
db.collection('users').doc('employees').get()
.then((empleyee)=>{
console.log(empleyee.data());
db.collection('users').add(payload)
.then(()=>{
dispatch({type:Actions.SAVE_DATABASE , saved:true})
})
.catch((error)=>{
console.log('could not save: '+error);
})
});
}
};
export const getUsers = () =>{
return dispatch =>{
db.collection('users').get()
.then((users)=>{
users.forEach((user)=>{
// console.log(user.id);
//console.log(user.data());
})
dispatch({users:users, type:Actions.GET_DATABASE})
})
}
};
|
/**
* Module dependencies
*/
var _ = require('lodash');
var Promise = require('bluebird');
module.exports = {
search: function(where, Model) {
var settings = Model.description.settings;
if (!where.q || settings.search.length === 0) return Promise.resolve(where);
var table = Model.adapter.identity;
var search = Promise.promisify(User.query);
var searchString = '';
_.forEach(settings.search, function(column, index) {
searchString += '"' + table + '"."' + column + '"';
if (index < settings.search.length - 1) searchString += ' || \' \' || ';
});
var query = 'SELECT "' + table + '"."id" FROM "' + table + '" WHERE ' + searchString + ' ILIKE \'%\'||$1||\'%\'';
return search(query, [where.q])
.then(function(results) {
where.id = _.pluck(results.rows, 'id');
delete where.q;
return where;
});
}
};
|
var readlinesync = require('readline-sync');
score = 0;
var uname = readlinesync.question ("what's your name? ");
console.log ("welcome : " + uname + " Let's play the Quiz!!");
//function
function play (question,answer)
{
var userans = readlinesync.question(question);
if (userans == answer)
{
console.log ("right !");
score = score + 1;
}
else
{
console.log ("you are wrong !");
score = score - 1;
}
console.log("here is your score :" + score);
console.log ("------------------------------");
}
//calling the function
var question = [{
question : 'National Song of India: ',
answer : 'vande mataram',
},{
question : 'National Motto of India: ',
answer : 'satyameva jayate',
},{
question : 'India\'s Largest City by Population: ',
answer : 'mumbai',
},
{
question : 'Golden Temple is situated in: ',
answer : 'amritsar'
}]
//loop
for (var i = 0 ; i<question.length ; i++)
{
var currentquestion = question[i];
play(currentquestion.question , currentquestion.answer)
}
console.log('\n');
console.log('Congratulations,' +uname +' your Total Score is: ',score);
|
const binarySearchRecursion = (target, array, startIdx = 0, endIdx = array.length - 1) => {
if (startIdx > endIdx) return -1;
const middleIdx = Math.floor((startIdx + endIdx) / 2);
if (array[middleIdx] === target) return middleIdx;
else if (array[middleIdx] < target) return binarySearchRecursion(target, array, middleIdx + 1, endIdx);
else return binarySearchRecursion(target, array, startIdx, middleIdx - 1);
};
const arr = [6, 7, 8, 9, 10, 11, 14, 15, 17, 19, 22, 23, 25, 28, 30];
console.log(binarySearchRecursion(19, arr));
|
// 常量 恒量
const name = 'hanfei'
// name 不能重新赋值
const obj = {}
obj = {} // TypeError: Assignment to constant variable.
|
import React from 'react'
import { Component } from 'react'
import { remote } from 'electron'
import path from 'path'
import { api } from './electron-backend'
const { dialog, Menu, MenuSample } = remote
import Workspace from '../gatekeeper-frontend/containers/workspace-container.jsx'
import GatingErrorModal from '../gatekeeper-frontend/containers/gating-error-modal-container.jsx'
import PopulationMatchingModal from '../gatekeeper-frontend/containers/population-matching-modal-container.jsx'
export default class Application extends Component {
constructor (props) {
super(props)
const template = [
{
label: 'File',
submenu: [
{label: 'New Workspace', accelerator: 'Cmd+Shift+N', click: this.newWorkspace.bind(this) },
// {label: 'Save Workspace', accelerator: 'Cmd+S' },//, click: this.showSaveWorkspaceAsDialogBox.bind(this) },
{label: 'Open FCS or CSV File(s)', accelerator: 'Cmd+Shift+O', click: this.showOpenFCSFileDialog.bind(this) },
// {label: 'Open Workspace(s)', accelerator: 'Cmd+O' }//, click: this.showOpenWorkspacesDialog.bind(this) }
]
},
{
label: 'Edit',
submenu: [
{role: 'undo'},
{role: 'redo'},
{type: 'separator'},
{role: 'cut'},
{role: 'copy'},
{role: 'paste'},
{role: 'pasteandmatchstyle'},
{role: 'delete'},
{role: 'selectall'}
]
},
// {
// label: 'Auto Gating',
// submenu: [
// {
// label: 'Recursive Gating',
// submenu: [
// { label: 'Persistant Homology' }
// ]
// }
// ]
// },
{
label: 'View',
submenu: [
{role: 'reload'},
{role: 'forcereload'},
{role: 'toggledevtools'},
{type: 'separator'},
{role: 'resetzoom'},
{role: 'zoomin'},
{role: 'zoomout'},
{type: 'separator'},
{role: 'togglefullscreen'}
]
},
{
role: 'window',
submenu: [
{role: 'minimize'},
{role: 'close'}
]
},
{
role: 'help',
submenu: [
{
label: 'Learn More'
}
]
}
]
if (process.platform === 'darwin') {
template.unshift({
label: remote.app.getName(),
submenu: [
{role: 'about'},
{type: 'separator'},
{role: 'services', submenu: []},
{type: 'separator'},
{role: 'hide'},
{role: 'hideothers'},
{role: 'unhide'},
{type: 'separator'},
{role: 'quit'}
]
})
// Edit menu
template[2].submenu.push(
{type: 'separator'},
{
label: 'Speech',
submenu: [
{role: 'startspeaking'},
{role: 'stopspeaking'}
]
}
)
// Windows menu
template[5].submenu = [
{role: 'close'},
{role: 'minimize'},
{role: 'zoom'},
{type: 'separator'},
{role: 'front'}
]
}
// Create the file menu with open, etc
const menu = Menu.buildFromTemplate(template)
Menu.setApplicationMenu(menu)
this.state = {
editingWorkspaceTitleId: null,
editingWorkspaceTitleText: null
}
}
newWorkspace () {
api.createWorkspace({
title: "New Workspace"
})
}
selectWorkspace (workspaceId) {
api.selectWorkspace(workspaceId)
}
closeWorkspace (workspaceId, event) {
api.removeWorkspace(workspaceId)
// Stop propagation to prevent the selectWorkspace event from firing
event.stopPropagation()
}
onDropFile (event) {
event.preventDefault();
for (let file of event.dataTransfer.files) {
if (file.path.match(/\.fcs/) || file.path.match(/\.csv/)) {
this.addNewFCSFilesToWorkspace([file.path])
}
}
return false;
}
addNewFCSFilesToWorkspace (filePaths) {
// Open one or more FCS files and add them to the workspace
if (filePaths) {
// Loop through if multiple files were selected
for (let filePath of filePaths) {
if (!filePath) { console.log("Error: undefined FCS file passed to readFCSFileData"); continue }
const FCSFile = {
filePath: filePath,
title: filePath.split(path.sep).slice(-1)[0], // Returns just the filename without the path
description: 'FCS File',
}
api.createFCSFileAndAddToWorkspace(FCSFile)
}
}
}
enableWorkspaceTitleEditing (workspaceId, workspaceText, event) {
this.setState({
editingWorkspaceTitleId: workspaceId,
editingWorkspaceTitleText: workspaceText
})
}
saveWorkspaceTitle () {
api.updateWorkspace(this.state.editingWorkspaceTitleId, { title: this.state.editingWorkspaceTitleText })
this.setState({
editingWorkspaceTitleId: null,
editingWorkspaceTitleText: null
})
}
updateWorkspaceTitleText (event) {
this.setState({ editingWorkspaceTitleText: event.target.value })
}
// TODO
// openWorkspaceFiles (filePaths) {
// const toReturn = []
// if (filePaths) {
// // Loop through if multiple files were selected
// for (let filePath of filePaths) {
// const workspace = JSON.parse(fs.readFileSync(filePath))
// workspace.filePath = filePath
// toReturn.push(workspace)
// }
// }
// return toReturn
// }
// TODO
// showSaveWorkspaceAsDialogBox () {
// let workspace = _.find(this.props.workspaces, workspace => workspace.id === this.props.selectedWorkspaceId)
// dialog.showSaveDialog({ title: `Save Workspace As:`, message: `Save Workspace As:`, defaultPath: workspace.replace(/\ /g, '-').toLowerCase() + '.json' }, (filePath) => {
// if (filePath) {
// // Prevent runtime state information such as running commands and stdout from being saved to the workspace file
// for (let sample of workspace.samples) {
// sample.toJSON = function () {
// return _.omit(this, [ 'filePath', 'runningCommand', 'running', 'error', 'output', 'status', 'stdinInputValue'])
// };
// }
// fs.writeFile(filePath, JSON.stringify(workspace, null, 4), function (error) {
// if (error) {
// return console.log(error);
// }
// console.log("The file was saved!");
// });
// }
// })
// }
// TODO
// showOpenWorkspacesDialog () {
// dialog.showOpenDialog({ title: `Open Workspace File`, filters: [{ name: 'CLR workspace templates', extensions: ['json']}], message: `Open Workspace File`, properties: ['openFile'] }, (filePaths) => {
// const workspace = this.openWorkspaceFiles(filePaths)[0]
// this.props.workspaces.push(workspace)
// this.setState({ workspaces: this.props.workspaces }, this.saveSessionState.bind(this))
// })
// }
showOpenFCSFileDialog () {
dialog.showOpenDialog({ title: `Open Sample File`, filters: [{ name: 'Cytometry Data Files', extensions: ['fcs', 'csv']}], message: `Open Sample File`, properties: ['openFile', 'multiSelections'] }, (filePaths) => {
this.addNewFCSFilesToWorkspace(filePaths)
})
}
render () {
if (this.props.sessionBroken) {
return (
<div className='container' onDrop={this.onDropFile.bind(this)}>
<div className='broken-message'>
<div className='text'>There was an error trying to load your previous session. This could have been caused by a version upgrade.</div>
<div className='text'>We apologise for any inconvenience. If you find time, please report this bug on our Trello board.</div>
<div className='button' onClick={api.resetSession}><i className='lnr lnr-cross-circle' />Click here to reset your session</div>
</div>
</div>
)
}
const workspaceTabs = this.props.openWorkspaces.map((workspace) => {
let tabText
// if (this.state.editingWorkspaceTitleId === workspace.id) {
// tabText = <input type="text" value={this.state.editingWorkspaceTitleText} onChange={this.updateWorkspaceTitleText.bind(this)} onBlur={this.saveWorkspaceTitle.bind(this)} autoFocus onFocus={(event) => { event.target.select() }} onKeyPress={(event) => { event.key === 'Enter' && event.target.blur() }} />
// } else {
//onClick={this.enableWorkspaceTitleEditing.bind(this, workspace.id, workspace.title)}
tabText = <div className='text'>{workspace.title}</div>
// }
return (
<div className={`tab${this.props.selectedWorkspace && this.props.selectedWorkspace.id === workspace.id ? ' selected' : ''}`} key={workspace.id} onClick={this.selectWorkspace.bind(this, workspace.id)}>
{tabText}
<div className='close-button' onClick={this.closeWorkspace.bind(this, workspace.id)}><i className='lnr lnr-cross' /></div>
</div>
)
})
return (
<div className='container' onDrop={this.onDropFile.bind(this)}>
<div className={`loader-outer maxIndex opaque${this.props.sessionLoading ? ' active' : ''}`}><div className='loader'></div><div className='text'>Loading session and starting workers...</div></div>
<div className='tab-bar'>
{workspaceTabs}
</div>
<div className='container-inner'>
<Workspace />
</div>
{/*<GatingErrorModal />*/}
{/*<PopulationMatchingModal />*/}
</div>
)
}
}
|
const fs = require('fs');
// Uncomment below for learnyounode
// console.log(fs.readFileSync(process.argv[2]).toString().match(/\n/g).length);
module.exports = filePath => fs.readFileSync(filePath).toString().match(/\n/g);
|
import {
calculateMediaRequirements,
validateMedia,
MediaRequirements,
} from './mappings/mediaRequirementsMapping';
export {
calculateMediaRequirements,
validateMedia,
MediaRequirements,
};
export default MediaRequirements;
|
import React from 'react';
import PropTypes from 'prop-types';
import {withStyles} from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardMedia from '@material-ui/core/CardMedia';
import CardContent from '@material-ui/core/CardContent';
import Avatar from '@material-ui/core/Avatar';
import Typography from '@material-ui/core/Typography';
import red from '@material-ui/core/colors/red';
import Link from 'next/link';
const styles = theme => ({
card: {
maxWidth: 400,
},
media: {
height: 0,
paddingTop: '56.25%', // 16:9
},
actions: {
display: 'flex',
},
expand: {
transform: 'rotate(0deg)',
marginLeft: 'auto',
transition: theme.transitions.create('transform', {
duration: theme.transitions.duration.shortest,
}),
},
expandOpen: {
transform: 'rotate(180deg)',
},
avatar: {
backgroundColor: red[500],
},
});
class PortfolioCard extends React.Component {
state = {expanded: false};
handleExpandClick = () => {
this.setState(state => ({expanded: !state.expanded}));
};
render() {
const {classes, title, description, cover, author, date, slug} = this.props;
return (
<Link prefetch href={{pathname: '/post', query: {slug: slug}}}>
<Card className={classes.card}>
<CardHeader
avatar={
<Avatar aria-label="Recipe" className={classes.avatar}>
<img src={`https://media.graphcms.com/resize=width:60/${author.image.handle}`}/>
</Avatar>
}
title={author.name}
subheader={date}
/>
<CardMedia
className={classes.media}
image={`https://media.graphcms.com/resize=width:400/${cover}`}
title="Paella dish"
/>
<CardContent>
<Typography component="p" variant='h6'>
{title}
</Typography>
<Typography component="p">
{description}
</Typography>
</CardContent>
</Card>
</Link>
);
}
}
PortfolioCard.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(PortfolioCard);
|
/*!
* SAP.${maven.build.timestamp} UI development toolkit for HTML5 (SAPUI5) (c) Copyright
* 2009-2014 SAP SE. All rights reserved
*/
/* ----------------------------------------------------------------------------------
* Hint: This is a derived (generated) file. Changes should be done in the underlying
* source files only (*.control, *.js) or they will be lost after the next generation.
* ---------------------------------------------------------------------------------- */
// Provides control sap.uxap.ObjectPageSubSection.
jQuery.sap.declare("sap.uxap.ObjectPageSubSection");
jQuery.sap.require("sap.uxap.library");
jQuery.sap.require("sap.uxap.ObjectPageSectionBase");
/**
* Constructor for a new ObjectPageSubSection.
*
* Accepts an object literal <code>mSettings</code> that defines initial
* property values, aggregated and associated objects as well as event handlers.
*
* If the name of a setting is ambiguous (e.g. a property has the same name as an event),
* then the framework assumes property, aggregation, association, event in that order.
* To override this automatic resolution, one of the prefixes "aggregation:", "association:"
* or "event:" can be added to the name of the setting (such a prefixed name must be
* enclosed in single or double quotes).
*
* The supported settings are:
* <ul>
* <li>Properties
* <ul>
* <li>{@link #getMode mode} : sap.uxap.ObjectPageSubSectionMode (default: sap.uxap.ObjectPageSubSectionMode.Collapsed)</li></ul>
* </li>
* <li>Aggregations
* <ul>
* <li>{@link #getBlocks blocks} <strong>(default aggregation)</strong> : sap.ui.core.Control[]</li>
* <li>{@link #getMoreBlocks moreBlocks} : sap.ui.core.Control[]</li>
* <li>{@link #getActions actions} : sap.ui.core.Control[]</li></ul>
* </li>
* <li>Associations
* <ul></ul>
* </li>
* <li>Events
* <ul></ul>
* </li>
* </ul>
*
*
* In addition, all settings applicable to the base type {@link sap.uxap.ObjectPageSectionBase#constructor sap.uxap.ObjectPageSectionBase}
* can be used as well.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* A SubSection in the ObjectPage layout is a container for Objectpage Blocks
* @extends sap.uxap.ObjectPageSectionBase
* @version 1.26.6
*
* @constructor
* @public
* @name sap.uxap.ObjectPageSubSection
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
sap.uxap.ObjectPageSectionBase.extend("sap.uxap.ObjectPageSubSection", { metadata : {
publicMethods : [
// methods
"refreshSeeMoreVisibility"
],
library : "sap.uxap",
properties : {
"mode" : {type : "sap.uxap.ObjectPageSubSectionMode", group : "Appearance", defaultValue : sap.uxap.ObjectPageSubSectionMode.Collapsed}
},
defaultAggregation : "blocks",
aggregations : {
"_grid" : {type : "sap.ui.core.Control", multiple : false, visibility : "hidden"},
"blocks" : {type : "sap.ui.core.Control", multiple : true, singularName : "block"},
"moreBlocks" : {type : "sap.ui.core.Control", multiple : true, singularName : "moreBlock"},
"actions" : {type : "sap.ui.core.Control", multiple : true, singularName : "action"}
}
}});
/**
* Creates a new subclass of class sap.uxap.ObjectPageSubSection with name <code>sClassName</code>
* and enriches it with the information contained in <code>oClassInfo</code>.
*
* <code>oClassInfo</code> might contain the same kind of informations as described in {@link sap.ui.core.Element.extend Element.extend}.
*
* @param {string} sClassName name of the class to be created
* @param {object} [oClassInfo] object literal with informations about the class
* @param {function} [FNMetaImpl] constructor function for the metadata object. If not given, it defaults to sap.ui.core.ElementMetadata.
* @return {function} the created class / constructor function
* @public
* @static
* @name sap.uxap.ObjectPageSubSection.extend
* @function
*/
/**
* Getter for property <code>mode</code>.
* Mode of subsection (propagated to the children blocks and moreBlocks modes)
* Blocks of moreBlocks aggregation are getting displayed only when SubSection mode is set to Expanded.
*
* Default value is <code>Collapsed</code>
*
* @return {sap.uxap.ObjectPageSubSectionMode} the value of property <code>mode</code>
* @public
* @name sap.uxap.ObjectPageSubSection#getMode
* @function
*/
/**
* Setter for property <code>mode</code>.
*
* Default value is <code>Collapsed</code>
*
* @param {sap.uxap.ObjectPageSubSectionMode} oMode new value for property <code>mode</code>
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#setMode
* @function
*/
/**
* Getter for aggregation <code>blocks</code>.<br/>
* controls to display in the subsection
*
* <strong>Note</strong>: this is the default aggregation for ObjectPageSubSection.
* @return {sap.ui.core.Control[]}
* @public
* @name sap.uxap.ObjectPageSubSection#getBlocks
* @function
*/
/**
* Inserts a block into the aggregation named <code>blocks</code>.
*
* @param {sap.ui.core.Control}
* oBlock the block to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the block should be inserted at; for
* a negative value of <code>iIndex</code>, the block is inserted at position 0; for a value
* greater than the current size of the aggregation, the block is inserted at
* the last position
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#insertBlock
* @function
*/
/**
* Adds some block <code>oBlock</code>
* to the aggregation named <code>blocks</code>.
*
* @param {sap.ui.core.Control}
* oBlock the block to add; if empty, nothing is inserted
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#addBlock
* @function
*/
/**
* Removes an block from the aggregation named <code>blocks</code>.
*
* @param {int | string | sap.ui.core.Control} vBlock the block to remove or its index or id
* @return {sap.ui.core.Control} the removed block or null
* @public
* @name sap.uxap.ObjectPageSubSection#removeBlock
* @function
*/
/**
* Removes all the controls in the aggregation named <code>blocks</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.ui.core.Control[]} an array of the removed elements (might be empty)
* @public
* @name sap.uxap.ObjectPageSubSection#removeAllBlocks
* @function
*/
/**
* Checks for the provided <code>sap.ui.core.Control</code> in the aggregation named <code>blocks</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.ui.core.Control}
* oBlock the block whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.uxap.ObjectPageSubSection#indexOfBlock
* @function
*/
/**
* Destroys all the blocks in the aggregation
* named <code>blocks</code>.
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#destroyBlocks
* @function
*/
/**
* Getter for aggregation <code>moreBlocks</code>.<br/>
* Additional controls to display when the show more / see all button is pressed
*
* @return {sap.ui.core.Control[]}
* @public
* @name sap.uxap.ObjectPageSubSection#getMoreBlocks
* @function
*/
/**
* Inserts a moreBlock into the aggregation named <code>moreBlocks</code>.
*
* @param {sap.ui.core.Control}
* oMoreBlock the moreBlock to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the moreBlock should be inserted at; for
* a negative value of <code>iIndex</code>, the moreBlock is inserted at position 0; for a value
* greater than the current size of the aggregation, the moreBlock is inserted at
* the last position
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#insertMoreBlock
* @function
*/
/**
* Adds some moreBlock <code>oMoreBlock</code>
* to the aggregation named <code>moreBlocks</code>.
*
* @param {sap.ui.core.Control}
* oMoreBlock the moreBlock to add; if empty, nothing is inserted
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#addMoreBlock
* @function
*/
/**
* Removes an moreBlock from the aggregation named <code>moreBlocks</code>.
*
* @param {int | string | sap.ui.core.Control} vMoreBlock the moreBlock to remove or its index or id
* @return {sap.ui.core.Control} the removed moreBlock or null
* @public
* @name sap.uxap.ObjectPageSubSection#removeMoreBlock
* @function
*/
/**
* Removes all the controls in the aggregation named <code>moreBlocks</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.ui.core.Control[]} an array of the removed elements (might be empty)
* @public
* @name sap.uxap.ObjectPageSubSection#removeAllMoreBlocks
* @function
*/
/**
* Checks for the provided <code>sap.ui.core.Control</code> in the aggregation named <code>moreBlocks</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.ui.core.Control}
* oMoreBlock the moreBlock whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.uxap.ObjectPageSubSection#indexOfMoreBlock
* @function
*/
/**
* Destroys all the moreBlocks in the aggregation
* named <code>moreBlocks</code>.
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#destroyMoreBlocks
* @function
*/
/**
* Getter for aggregation <code>actions</code>.<br/>
* Actions available for this subSection
*
* @return {sap.ui.core.Control[]}
* @public
* @name sap.uxap.ObjectPageSubSection#getActions
* @function
*/
/**
* Inserts a action into the aggregation named <code>actions</code>.
*
* @param {sap.ui.core.Control}
* oAction the action to insert; if empty, nothing is inserted
* @param {int}
* iIndex the <code>0</code>-based index the action should be inserted at; for
* a negative value of <code>iIndex</code>, the action is inserted at position 0; for a value
* greater than the current size of the aggregation, the action is inserted at
* the last position
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#insertAction
* @function
*/
/**
* Adds some action <code>oAction</code>
* to the aggregation named <code>actions</code>.
*
* @param {sap.ui.core.Control}
* oAction the action to add; if empty, nothing is inserted
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#addAction
* @function
*/
/**
* Removes an action from the aggregation named <code>actions</code>.
*
* @param {int | string | sap.ui.core.Control} vAction the action to remove or its index or id
* @return {sap.ui.core.Control} the removed action or null
* @public
* @name sap.uxap.ObjectPageSubSection#removeAction
* @function
*/
/**
* Removes all the controls in the aggregation named <code>actions</code>.<br/>
* Additionally unregisters them from the hosting UIArea.
* @return {sap.ui.core.Control[]} an array of the removed elements (might be empty)
* @public
* @name sap.uxap.ObjectPageSubSection#removeAllActions
* @function
*/
/**
* Checks for the provided <code>sap.ui.core.Control</code> in the aggregation named <code>actions</code>
* and returns its index if found or -1 otherwise.
*
* @param {sap.ui.core.Control}
* oAction the action whose index is looked for.
* @return {int} the index of the provided control in the aggregation if found, or -1 otherwise
* @public
* @name sap.uxap.ObjectPageSubSection#indexOfAction
* @function
*/
/**
* Destroys all the actions in the aggregation
* named <code>actions</code>.
* @return {sap.uxap.ObjectPageSubSection} <code>this</code> to allow method chaining
* @public
* @name sap.uxap.ObjectPageSubSection#destroyActions
* @function
*/
/**
* Refresh the seeMore button visibility
*
* @name sap.uxap.ObjectPageSubSection#refreshSeeMoreVisibility
* @function
* @type
* @public
* @ui5-metamodel This method also will be described in the UI5 (legacy) designtime metamodel
*/
// Start of sap/uxap/ObjectPageSubSection.js
jQuery.sap.require("sap.uxap.ObjectPageSubSectionLayout");
jQuery.sap.require("sap.ui.layout.Grid");
jQuery.sap.require("sap.uxap.ObjectPageSubSectionMode");
jQuery.sap.require("sap.ui.core.CustomData");
/**
* @private
*/
sap.uxap.ObjectPageSubSection.prototype.init = function () {
sap.uxap.ObjectPageSectionBase.prototype.init.call(this);
//i18n: load once for every subsections
if (!sap.uxap.i18nModel) {
sap.uxap.i18nModel = new sap.ui.model.resource.ResourceModel({
bundleUrl: jQuery.sap.getModulePath("sap.uxap.i18n.i18n", ".properties")
});
}
this.oResourceBundle = sap.uxap.i18nModel.getResourceBundle();
//build private aggregations
this._oGrid = new sap.ui.layout.Grid({
id: this.getId() + "-innerGrid",
defaultSpan: "L12 M12 S12",
hSpacing: 1,
vSpacing: 1,
width: "100%"
});
this.setAggregation("_grid", this._oGrid);
//build inner controls
this._buildSeeMoreControl();
this._iResizeId = undefined; //resize handler if needed
//proxy public aggregations
this._bRenderedFirstTime = false;
this._aAggregationProxy = {blocks: [], moreBlocks: []};
//dom reference
this._$spacer = [];
//switch logic for the default mode
this._switchSubSectionMode(this.getMode());
};
sap.uxap.ObjectPageSubSection.prototype.connectToModels = function () {
var aBlocks = this.getBlocks() || [],
aMoreBlocks = this.getMoreBlocks() || [];
if (aBlocks.length > 0) {
jQuery.each(aBlocks, jQuery.proxy(function (iBlockIndex, oBlock) {
if (oBlock instanceof sap.uxap.BlockBase) {
if (!oBlock.getMode()) {
oBlock.setMode(this.getMode());
}
oBlock.connectToModels();
}
}, this));
}
if (aMoreBlocks.length > 0 && this.getMode() == sap.uxap.ObjectPageSubSectionMode.Expanded) {
jQuery.each(aMoreBlocks, jQuery.proxy(function (iBlockIndex, oMoreBlock) {
if (oMoreBlock instanceof sap.uxap.BlockBase) {
if (!oMoreBlock.getMode()) {
oMoreBlock.setMode(this.getMode());
}
oMoreBlock.connectToModels();
}
}, this));
}
};
sap.uxap.ObjectPageSubSection.prototype.exit = function () {
if (this._oSeeMoreButton) {
this._oSeeMoreButton.destroy();
this._oSeeMoreButton = null;
}
if (this._iResizeId) {
sap.ui.core.ResizeHandler.deregister(this._iResizeId);
}
if (sap.uxap.ObjectPageSectionBase.prototype.exit) {
sap.uxap.ObjectPageSectionBase.prototype.exit.call(this);
}
};
sap.uxap.ObjectPageSubSection.prototype.onAfterRendering = function () {
if (sap.uxap.ObjectPageSectionBase.prototype.onAfterRendering) {
sap.uxap.ObjectPageSectionBase.prototype.onAfterRendering.call(this);
}
if (this._getObjectPageLayout()) {
switch (this._getObjectPageLayout().getSubSectionLayout()) {
case sap.uxap.ObjectPageSubSectionLayout.TitleOnLeft:
this._afterRenderingTitleOnLeftLayout();
break;
default:
/* nothing */
}
this._$spacer = jQuery.sap.byId(this._getObjectPageLayout().getId() + "-spacer");
}
};
sap.uxap.ObjectPageSubSection.prototype.onBeforeRendering = function () {
if (sap.uxap.ObjectPageSectionBase.prototype.onBeforeRendering) {
sap.uxap.ObjectPageSectionBase.prototype.onBeforeRendering.call(this);
}
var aVisibleBlocks, sLayout;
//proxy aggregations
this._setAggregationProxy();
this._oGrid.removeAllContent();
//build layouts
try {
//propagate subSectionLayout from objectPageLayout subSections
var iColumnLayout;
if (this._getObjectPageLayout()) {
sLayout = this._getObjectPageLayout().getSubSectionLayout();
}
//layout specific configuration
switch (sLayout) {
case sap.uxap.ObjectPageSubSectionLayout.TitleOnLeft:
this._oGrid.setContainerQuery(false);
iColumnLayout = 2;
break;
default:
this._oGrid.setContainerQuery(true);
iColumnLayout = 3;
}
//apply the layouting information
aVisibleBlocks = this._calcBlockColumnLayout(this.getBlocks(), iColumnLayout);
jQuery.each(aVisibleBlocks, jQuery.proxy(function (iIndex, oBlock) {
//propagate section state to blocks
this._setBlockMode(oBlock, this.getMode());
this._oGrid.addContent(oBlock);
}, this));
//also add the more blocks defined for being visible in expanded mode only
if (this.getMode() === sap.uxap.ObjectPageSubSectionMode.Expanded) {
//apply the layouting information
aVisibleBlocks = this._calcBlockColumnLayout(this.getMoreBlocks(), iColumnLayout);
jQuery.each(aVisibleBlocks, jQuery.proxy(function (iIndex, oMoreBlock) {
//propagate section state to blocks
this._setBlockMode(oMoreBlock, sap.uxap.ObjectPageSubSectionMode.Expanded);
this._oGrid.addContent(oMoreBlock);
}, this));
}
}
catch (sError) {
jQuery.sap.log.error("ObjectPageSubSection :: error while building layout " + sLayout + ": " + sError);
}
this.refreshSeeMoreVisibility();
};
sap.uxap.ObjectPageSubSection.prototype.refreshSeeMoreVisibility = function () {
var bBlockHasMore = jQuery.isArray(this.getMoreBlocks()) && this.getMoreBlocks().length > 0; //we have moreBlocks therefore we always display the seeMore
if (!bBlockHasMore) {
jQuery.each(this.getBlocks(), jQuery.proxy(function (iIndex, oBlock) {
//check if the block ask for the global see more the rule is
//by default we don't display the see more
//if one control is visible and ask for it then we display it
if (oBlock instanceof sap.uxap.BlockBase && oBlock.getVisible() && oBlock.getShowSubSectionMore()) {
bBlockHasMore = true;
}
return !bBlockHasMore;
}, this));
}
//if the subsection is already rendered, don't rerender it all for showing a more button
if (this.$().length > 0) {
this.$().toggleClass("sapUxAPObjectPageSubSectionWithSeeMore", bBlockHasMore);
}
this.toggleStyleClass("sapUxAPObjectPageSubSectionWithSeeMore", bBlockHasMore);
if (this._oSeeMoreButton.$().length > 0) {
this._oSeeMoreButton.$().toggleClass("sapUxAPSubSectionSeeMoreButtonVisible", bBlockHasMore);
}
this._oSeeMoreButton.toggleStyleClass("sapUxAPSubSectionSeeMoreButtonVisible", bBlockHasMore);
return bBlockHasMore;
};
sap.uxap.ObjectPageSubSection.prototype.setMode = function (sMode) {
if (this.getMode() !== sMode) {
this._switchSubSectionMode(sMode);
if (this._bRenderedFirstTime) {
this.rerender();
}
}
return this;
};
/*************************************************************************************
* generic block layout calculation
************************************************************************************/
/**
* calculate the layout data to use for subsection blocks
* Aligned with PUX specifications as of Oct 14, 2014
*/
sap.uxap.ObjectPageSubSection.prototype._calcBlockColumnLayout = function (aBlocks, iColumnLayout) {
var iRemainingL,
iRemainingM,
aVisibleBlocks = [];
//step 1: get only visible blocks into consideration
jQuery.each(aBlocks, jQuery.proxy(function (iIndex, oBlock) {
//if this is the first rendering and a layout has been defined by the subsection developer,
//we remove it and let the built-in mechanism decide on the layouting aspects
if (!this._bRenderedFirstTime && oBlock.getLayoutData()) {
oBlock.destroyLayoutData();
jQuery.sap.log.warning("ObjectPageSubSection :: forbidden use of layoutData for block " + oBlock.getMetadata().getName(), "layout will be set by subSection");
}
if (!oBlock.getVisible || oBlock.getVisible()) {
aVisibleBlocks.push(oBlock);
}
}, this));
//step 2: set layout for each blocks based on their columnLayout configuration
//As of Oct 14, 2014, the default behavior is:
//on phone, blocks take always the full line
//on tablet, desktop:
//1 block on the line: takes 3/3 columns
//2 blocks on the line: takes 1/3 columns then 2/3 columns
//3 blocks on the line: takes 1/3 columns then 1/3 columns and last 1/3 columns
//rules for translating auto: LL2 grammar
//1 by default
//fills the line if the next 2 blocks permit it
iRemainingL = iColumnLayout;
iRemainingM = 2;
jQuery.each(aVisibleBlocks, jQuery.proxy(function (iIndex, oBlock) {
var iSizeL, iSizeM;
iSizeL = this._calculatedSize(oBlock, iRemainingL, aVisibleBlocks[iIndex + 1], aVisibleBlocks[iIndex + 2], iColumnLayout);
if (iColumnLayout == 3) {
iSizeM = this._calculatedSize(oBlock, iRemainingM, aVisibleBlocks[iIndex + 1], aVisibleBlocks[iIndex + 2], 2);
}
else {
iSizeM = iSizeL;
}
//set block layout based on resolution and break to a new line if necessary
oBlock.setLayoutData(new sap.ui.layout.GridData({
spanS: 12,
spanM: iSizeM * (12 / 2), //iColumnLayout is 2 already
spanL: iSizeL * (12 / iColumnLayout),
linebreakM: (iIndex > 0 && iRemainingM === 2), //iColumnLayout is 2 already
linebreakL: (iIndex > 0 && iRemainingL === iColumnLayout)
}));
iRemainingL -= iSizeL;
if (iRemainingL <= 0) {
iRemainingL = iColumnLayout;
}
if (iColumnLayout !== 1) {
iRemainingM -= iSizeM;
if (iRemainingM <= 0) {
iRemainingM = 2;
}
}
}, this));
return aVisibleBlocks;
};
sap.uxap.ObjectPageSubSection.prototype._calculatedSize = function (oBlock, iRemaining, oNext, oFollowing, iMax) {
var iCalculatedSize, iCalc;
if (!this._hasAutoLayout(oBlock)) {
iCalculatedSize = Math.min(iMax, window.parseInt(oBlock.getColumnLayout(), 10));
}
else {
iRemaining -= 1;
iCalc = this._calcLayout(oNext);
if (iCalc <= iRemaining) {
iRemaining -= iCalc;
iCalc = this._calcLayout(oFollowing);
if (iCalc <= iRemaining) {
iRemaining -= iCalc;
}
}
iCalculatedSize = iRemaining + 1;
}
return iCalculatedSize;
};
sap.uxap.ObjectPageSubSection.prototype._calcLayout = function (oBlock) {
var iLayoutCols = 1;
if (!oBlock) {
iLayoutCols = 0;
}
else if (oBlock instanceof sap.uxap.BlockBase && oBlock.getColumnLayout() != "auto") {
iLayoutCols = window.parseInt(oBlock.getColumnLayout(), 10);
}
return iLayoutCols;
};
sap.uxap.ObjectPageSubSection.prototype._hasAutoLayout = function (oBlock) {
return !(oBlock instanceof sap.uxap.BlockBase) || oBlock.getColumnLayout() == "auto";
};
/*************************************************************************************
* TitleOnLeft layout
************************************************************************************/
/**
* on after rendering actions for the titleOnLeft Layout
* @private
*/
sap.uxap.ObjectPageSubSection.prototype._afterRenderingTitleOnLeftLayout = function () {
this._$standardHeader = jQuery.sap.byId(this.getId() + "-header");
this._$grid = this._oGrid.$();
if (!this._iResizeId) {
this._iResizeId = sap.ui.core.ResizeHandler.register(this, jQuery.proxy(this._titleOnLeftSynchronizeLayouts, this));
}
this._titleOnLeftSynchronizeLayouts();
};
sap.uxap.ObjectPageSubSection.prototype._titleOnLeftSynchronizeLayouts = function () {
jQuery.sap.delayedCall(50 /* dom painting */, this, function () {
this._$standardHeader.toggleClass("titleOnLeftLayout", this._$grid.hasClass("sapUiRespGridMedia-Std-Desktop"));
});
};
/*************************************************************************************
* blocks & moreBlocks aggregation proxy
* getter and setters works with _aAggregationProxy instead of the blocks aggregation
************************************************************************************/
sap.uxap.ObjectPageSubSection.prototype._setAggregationProxy = function () {
if (this._bRenderedFirstTime) {
return;
}
//empty real aggregations and feed internal ones at first rendering only
jQuery.each(this._aAggregationProxy, jQuery.proxy(function (sAggregationName, aValue) {
this._setAggregation(sAggregationName, this.removeAllAggregation(sAggregationName));
}, this));
this._bRenderedFirstTime = true;
};
sap.uxap.ObjectPageSubSection.prototype.hasProxy = function (sAggregationName) {
return this._bRenderedFirstTime && this._aAggregationProxy.hasOwnProperty(sAggregationName);
};
sap.uxap.ObjectPageSubSection.prototype._getAggregation = function (sAggregationName) {
return this._aAggregationProxy[sAggregationName];
};
sap.uxap.ObjectPageSubSection.prototype._setAggregation = function (sAggregationName, aValue) {
this._aAggregationProxy[sAggregationName] = aValue;
this._notifyObjectPageLayout();
this.invalidate();
return this._aAggregationProxy[sAggregationName];
};
sap.uxap.ObjectPageSubSection.prototype.addAggregation = function (sAggregationName, oObject) {
if (this.hasProxy(sAggregationName)) {
var aAggregation = this._getAggregation(sAggregationName);
aAggregation.push(oObject);
this._setAggregation(aAggregation);
return this;
}
return sap.uxap.ObjectPageSectionBase.prototype.addAggregation.apply(this, arguments);
};
sap.uxap.ObjectPageSubSection.prototype.insertAggregation = function (sAggregationName, oObject, iIndex) {
if (this.hasProxy(sAggregationName)) {
jQuery.sap.log.warning("ObjectPageSubSection :: used of insertAggregation for " + sAggregationName + " is not supported, will use addAggregation instead");
return this.addAggregation(sAggregationName, oObject);
}
return sap.uxap.ObjectPageSectionBase.prototype.insertAggregation.apply(this, arguments);
};
sap.uxap.ObjectPageSubSection.prototype.removeAllAggregation = function (sAggregationName) {
if (this.hasProxy(sAggregationName)) {
var aInternalAggregation = this._getAggregation(sAggregationName);
var aItems = aInternalAggregation.slice(0, aInternalAggregation.length - 1);
this._setAggregation(sAggregationName, []);
return aItems;
}
return sap.uxap.ObjectPageSectionBase.prototype.removeAllAggregation.apply(this, arguments);
};
sap.uxap.ObjectPageSubSection.prototype.removeAggregation = function (sAggregationName, oObject) {
if (this.hasProxy(sAggregationName)) {
var bRemoved = false, aInternalAggregation = this._getAggregation(sAggregationName);
jQuery.each(aInternalAggregation, jQuery.proxy(function (iIndex, oObjectCandidate) {
if (oObjectCandidate.getId() === oObject.getId()) {
aInternalAggregation.splice(iIndex, 1);
this._setAggregation(aInternalAggregation);
bRemoved = true;
}
return !bRemoved;
}, this));
return (bRemoved ? oObject : null);
}
return sap.uxap.ObjectPageSectionBase.prototype.removeAggregation.apply(this, arguments);
};
sap.uxap.ObjectPageSubSection.prototype.indexOfAggregation = function (sAggregationName, oObject) {
if (this.hasProxy(sAggregationName)) {
var iIndexFound = -1, aInternalAggregation = this._getAggregation(sAggregationName);
jQuery.each(aInternalAggregation, jQuery.proxy(function (iIndex, oObjectCandidate) {
if (oObjectCandidate.getId() === oObject.getId()) {
iIndexFound = iIndex;
}
return (iIndexFound < 0);
}, this));
return iIndexFound;
}
return sap.uxap.ObjectPageSectionBase.prototype.indexOfAggregation.apply(this, arguments);
};
sap.uxap.ObjectPageSubSection.prototype.getAggregation = function (sAggregationName) {
if (this.hasProxy(sAggregationName)) {
return this._getAggregation(sAggregationName);
}
return sap.uxap.ObjectPageSectionBase.prototype.getAggregation.apply(this, arguments);
};
sap.uxap.ObjectPageSubSection.prototype.destroyAggregation = function (sAggregationName) {
if (this.hasProxy(sAggregationName)) {
var aInternalAggregation = this._getAggregation(sAggregationName);
jQuery.each(aInternalAggregation, function (iIndex, oObject) {
oObject.destroy();
});
this._setAggregation(sAggregationName, []);
return this;
}
return sap.uxap.ObjectPageSectionBase.prototype.destroyAggregation.apply(this, arguments);
};
/*************************************************************************************
* Private section : should overridden with care
************************************************************************************/
/**
* build the control that will used internally for the see more / see less
* @private
*/
sap.uxap.ObjectPageSubSection.prototype._buildSeeMoreControl = function () {
this._oSeeMoreButton = new sap.m.Button(this.getId() + "--seeMore", {
type: sap.m.ButtonType.Transparent,
iconFirst: false,
press: jQuery.proxy(this._onSeeMorePress, this)
}).addStyleClass("sapUxAPSubSectionSeeMoreButton");
};
/**
* called when a user clicks on the see more or see all button
* @param oEvent
* @private
*/
sap.uxap.ObjectPageSubSection.prototype._onSeeMorePress = function (oEvent) {
var sCurrentMode = this.getMode(),
sTargetMode,
aMoreBlocks = this.getMoreBlocks() || [];
//we just switch the layoutMode for the underlying blocks
if (sCurrentMode === sap.uxap.ObjectPageSubSectionMode.Expanded) {
sTargetMode = sap.uxap.ObjectPageSubSectionMode.Collapsed;
}
else {/* we are in Collapsed */
sTargetMode = sap.uxap.ObjectPageSubSectionMode.Expanded;
if (aMoreBlocks.length > 0) {
jQuery.each(aMoreBlocks, jQuery.proxy(function (iBlockIndex, oMoreBlock) {
if (oMoreBlock instanceof sap.uxap.BlockBase) {
if (!oMoreBlock.getMode()) {
oMoreBlock.setMode(this.getMode());
}
oMoreBlock.connectToModels();
}
}, this));
}
}
this._switchSubSectionMode(sTargetMode);
//avoid to reapply the focus after rendering on tablet and desktop (finalizeRendering)
if (!jQuery.device.is.phone) {
oEvent.getSource().$().blur();
}
//in case of the last subsection of an objectpage we need to compensate its height change while rerendering)
if (this._$spacer.length > 0) {
this._$spacer.height(this._$spacer.height() + this.$().height());
}
//need to re-render the subsection in order to render all the blocks with the appropriate mode & layout
//0000811842 2014
this.rerender();
};
/**
* switch the state for the subsection
* @param sSwitchToMode
* @private
*/
sap.uxap.ObjectPageSubSection.prototype._switchSubSectionMode = function (sSwitchToMode) {
sSwitchToMode = this.validateProperty("mode", sSwitchToMode);
if (sSwitchToMode === sap.uxap.ObjectPageSubSectionMode.Collapsed) {
this.setProperty("mode", sap.uxap.ObjectPageSubSectionMode.Collapsed, true);
this._oSeeMoreButton.setText(this.oResourceBundle.getText("SEE_MORE"));
}
else {
this.setProperty("mode", sap.uxap.ObjectPageSubSectionMode.Expanded, true);
this._oSeeMoreButton.setText(this.oResourceBundle.getText("SEE_LESS"));
}
};
/**
* set the mode on a control if there is such mode property
* @param oBlock
* @param sMode
* @private
*/
sap.uxap.ObjectPageSubSection.prototype._setBlockMode = function (oBlock, sMode) {
if (oBlock instanceof sap.uxap.BlockBase) {
oBlock.setMode(sMode);
}
else {
jQuery.sap.log.debug("ObjectPageSubSection :: cannot propagate mode " + sMode + " to " + oBlock.getMetadata().getName());
}
};
|
import React, { Component } from "react";
import { Redirect } from "react-router-dom";
import { connect } from "react-redux";
//import * as actionType from "../../store/actions/actionTypes";
import { add_product } from "../../store/actions/productAction";
import {
Button,
Form,
FormGroup,
Label,
Input,
FormText,
Container
} from "reactstrap";
class AdminForm extends Component {
// componentDidMount() {
// this.props.addProduct();
// }
state = {
title: "",
description: "",
price: 0,
picture: null
};
handleSubmit = e => {
e.preventDefault();
if (this.state.picture === null) {
alert("You have not selected a framework picture");
return;
} else {
const formData = new FormData();
formData.append("title", this.state.title);
formData.append("description", this.state.description);
formData.append("price", this.state.price);
formData.append("file", this.state.picture);
this.setState({
title: "",
description: "",
price: 0,
picture: null
});
//console.log(formData);
document.getElementById("File").value = "";
this.props.addProduct(formData);
}
};
handleInput = e => {
this.setState({
[e.target.id]: e.target.value
});
};
fileInputHandler = e => {
const file = e.target.files[0];
this.setState({ picture: file });
};
render() {
let content;
if (this.props.authAdmin.userInfo.hasOwnProperty("admin")) {
content = (
<Container className="page" style={{ marginTop: "30px" }}>
<Form onSubmit={this.handleSubmit} style={{ margin: "0 auto" }}>
<FormGroup>
<Label
style={{ display: "block", textAlign: "center" }}
for="framework title"
>
Title
</Label>
<Input
onChange={this.handleInput}
value={this.state.title}
style={{ width: "80%", margin: "auto" }}
type="text"
name="title"
id="title"
placeholder="Framework title"
/>
</FormGroup>
<FormGroup>
<Label
style={{ display: "block", textAlign: "center" }}
for="description"
>
Description
</Label>
<Input
onChange={this.handleInput}
value={this.state.description}
style={{ width: "80%", margin: "auto" }}
type="text"
name="description"
id="description"
placeholder="Description"
/>
</FormGroup>
<FormGroup>
<Label
style={{ display: "block", textAlign: "center" }}
for="price"
>
Price
</Label>
<Input
value={this.state.price}
onChange={this.handleInput}
style={{ width: "80%", margin: "auto" }}
type="number"
name="price"
id="price"
placeholder="$ Price"
/>
</FormGroup>
<FormGroup>
<Label
style={{ display: "block", textAlign: "center" }}
for="exampleFile"
>
Frame Work Picture
</Label>
<Input
onChange={this.fileInputHandler}
style={{ width: "80%", margin: "auto" }}
type="file"
name="file"
id="File"
/>
<FormText style={{ width: "80%", margin: "auto" }} color="muted">
This is some placeholder block-level help text for the above
input. It's a bit lighter and easily wraps to a new line.
</FormText>
</FormGroup>
<div className="row justify-content-center">
<Button type="submit">Submit</Button>
</div>
</Form>
</Container>
);
} else {
content = <Redirect to="/products" />;
}
return content;
}
}
const mapDispatchToProps = dispatch => {
return {
addProduct: formData => dispatch(add_product(formData))
};
};
const mapStateToProps = state => {
return {
authAdmin: state.auth
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(AdminForm);
|
$('#signupBtn').click(event => {
const email = $('#inputEmail').val();
$.ajax({
url: `http://tiny.cc/cl-email-api-test/?email=${email}`,
dataType: 'jsonp',
jsonpCallback: 'jsonCallback',
}).then(response => {
const { message } = response;
if (message.status_code === 200) {
$('#successAlert').show()
} else if (message.status_code === 400) {
$('#failAlert').show()
}
}).catch(error => {
console.log(error.status)
});
event.preventDefault();
});
$('.form-control').blur(function(event) {
const $input = $(this);
const $message = $(this).parent().next();
if ($input.val() !== '') {
$input.removeClass('is-invalid');
$input.addClass('is-valid');
$message.hide();
} else {
$input.removeClass('is-valid');
$input.addClass('is-invalid');
$message.show();
}
$('#signupBtn').prop('disabled', !validateForm())
});
const validateForm = () => (
$('.form-control.is-valid').length === 3 ? true : false
);
|
import React from "react";
import GlobalStyle from "./styles/global";
import Header from "./components/Header";
import Main from "./components/Main";
const myStyle = {
padding: "15px 0",
textAlign: "center",
fontSize: "2em",
fontWeight: "700",
martinTop: "100",
};
function App() {
return (
<>
<Header />
<Main />
<h1 style={myStyle}>Continue...</h1>
<GlobalStyle />
</>
);
}
export default App;
|
define([
'underscore',
'marionette',
'text!Templates/Bookmark/List.html'
],function(_, Marionette, template) {
var view = Marionette.ItemView.extend({
template: _.template(template),
events:{
},
initialize:function(options){
this.collection = options.collection;
this.listenTo(this.collection, {
'sync': this._renderList
}, this);
},
onRender: function() {
console.log('render event run');
},
serializeData:function(){
return {
collection: this.collection.toJSON()
}
},
_renderList: function() {
this.render();
}
});
return view;
});
|
import {PERCENTAGE_MAX} from "../../../constants"
import PropTypes from "prop-types"
import React from "react"
const getPercent = (number) => `${String(PERCENTAGE_MAX * number)}%`
const Hashtag = props =>
<div className="tweetItem hashtag">
<p>
<span className="bold">{props.title}</span> · <span className="greyText">{props.count}</span>
</p>
<div className="bar" style={{width: getPercent(props.barLength)}} />
</div>
Hashtag.propTypes = {
barLength: PropTypes.number.isRequired,
count: PropTypes.number.isRequired,
title: PropTypes.string.isRequired
}
export default Hashtag
|
let express = require('express');
let router = express.Router();
let User = require('../models/User');
let Department = require('../models/Department');
let Company = require('../models/Company');
let Post = require('../models/Post');
let Ids = require('../models/IdsNext');// 引入模型
// --------------------------------新增用户-----------------------------
router.post('/add', function (req, res) {
console.log('-------------添加用户-----------------------')
let cn = req.body;
let id = Ids.findByIdAndUpdate(
{_id: 'userId'},
{$inc: {sequence_value: 1}});
id.then(data => {
let user = new User({
_id: data.sequence_value,
name: cn.name,
sex: cn.sex,
startDate: cn.startDate,
tellphone: cn.tellphone,
eMail: cn.eMail,
address: cn.address,
post: cn.post,
department: cn.department,
company: cn.company,
remark: cn.remark
})
user.save((err, doc) => {
if (err) {
res.send({msg: '添加失败!', state: '99'})
} else {
res.send({msg: '添加成功!', state: '200'})
}
})
})
});
// --------------------------根据Id查询用户编辑-----------------------
router.get('/findById', (req, res) => {
console.log('-----------------根据Id查询用户------------------')
let query = {
_id: req.query._id
}
User.findById(query, (err,doc)=>{
res.send({msg: 'sucess', state: '200', data: doc})
})
});
//--------------------- 更新用户-----------------------------
router.post('/update',(req,res) =>{
console.log('-----------------更新用户------------------');
let cn = req.body;
let query = {
_id: req.body._id
}
let param = {
name: cn.name,
sex: cn.sex,
startDate: cn.startDate,
tellphone: cn.tellphone,
eMail: cn.eMail,
address: cn.address,
post: cn.post,
company: cn.company,
department: cn.department,
remark: cn.remark
}
User.findOneAndUpdate(query,{ $set: param},(err,doc)=>{
res.send({msg: 'sucess', state: '200'})
})
});
// -----------------显示用户列表【根据条件】------------------------------
router.get('/list', (req, res, next) => {
console.log('----------显示用户列表---------')
let cn = req.query;
let page = cn.curPage;
let rows = cn.rows;
let qc = {},
name = cn.name,
sex=cn.sex,
company = cn.company,
department = cn.department,
post = cn.post;
let name_pattern = new RegExp("^.*"+name+".*$");
let post_pattern = new RegExp("^.*"+post+".*$");
let department_pattern = new RegExp("^.*"+department+".*$");
let company_pattern = new RegExp("^.*"+company+".*$");
if(name !== '' && name !== undefined){
qc.name = name_pattern
}
if(sex !== '' && sex !== undefined){
qc.sex = sex
}
if(company !=='' && company !== undefined){
qc.company = company_pattern
}
if(post !== '' && post !== undefined){
qc.post = post_pattern
}
if(department !== '' && department !== undefined){
qc.department = department_pattern
}
let query = User.find(qc);
query.skip((page-1)*rows);
query.limit(parseInt(rows));
let result = query.exec();
result.then((data)=>{
console.log(data)
// 获取总条数
User.find(qc,(err,rs)=>{
res.send({msg: 'sucess', state: '200', data: data,total:rs.length})
})
})
});
// -----------------------根据条件删除一个用户--------------------------
router.post('/delete', (req, res) => {
let ids = req.body._ids.split(',');
let query = {
_id: ids
};
console.log('-------------删除用户--------------');
User.deleteMany(query, (err, doc) => {
if (err) {
res.send({msg: '删除失败', state: '99'})
} else {
res.send({msg: '删除成功', state: '200', data: doc})
}
})
});
// --------------------------查询岗位列表-------------------------------
router.get('/postList', (req, res) => {
console.log('----------显示岗位列表---------')
Post.find({},(err,rs)=>{
res.send({msg: 'success', state: '200', data: rs})
})
});
//---------------------- 查询部门列表----------------------------
router.get('/departmentList', (req, res) => {
console.log('----------显示部门列表---------')
Department.find({},(err,rs)=>{
res.send({msg: 'success', state: '200', data: rs})
})
});
// -----------------------查询公司列表------------------------
router.get('/companyList', (req, res) => {
console.log('----------显示公司列表---------')
Company.find({},(err,rs)=>{
res.send({msg: 'success', state: '200', data: rs})
})
});
module.exports = router;
|
/*global ODSA */
// Inseh1234 slideshow
$(document).ready(function() {
"use strict";
var av_name = "ProofOfWork";
var config = ODSA.UTILS.loadConfig({av_name: av_name}),
interpret = config.interpreter; // get the code object
var av = new JSAV(av_name);
var topMargin = 50;
var leftMargin = 390;
let leftAdding = 54;
var blocktop = 17;
var blockchain = av.ds.list({top: blocktop + 0, left: "550px", nodegap: 10});
var blockchain2 = av.ds.list({top: blocktop + 50, left: "550px", nodegap: 10});
var blockchain3 = av.ds.list({top: blocktop + 100, left: "550px", nodegap: 10});
var blockchain4 = av.ds.list({top: blocktop + 150, left: "550px", nodegap: 10});
var graph = av.ds.graph({visible: true, left: -10, top: blocktop, height: 375, width: 425 });
// this code is the starting state of the graph
graph.css({"font-size": "11px"});
const a = graph.addNode('1', { "left": "200px", "top":"700px"});
const d = graph.addNode('2', {"left": "25px", "top":"150px"});
const g = graph.addNode('3', {"left": "200px", "top":"300px"});
const j = graph.addNode('4', {"left": "375px", "top":"150px"});
const m1 = graph.addNode('M1', {"left": "100px", "top":"50px"});
const m2 = graph.addNode('M2', {"left": "300px", "top":"250px"});
const m3 = graph.addNode('M3', {"left": "100px", "top":"250px"});
const m4 = graph.addNode('M4', {"left": "300px", "top":"50px"});
const f1 = graph.addNode('F1', {"left": "100px", "top":"150px"});
const f2 = graph.addNode('F2', {"left": "165px", "top":"150px"});
const f3 = graph.addNode('F3', {"left": "235px", "top":"150px"});
const f4 = graph.addNode('F4', {"left": "300px", "top":"150px"});
const f1Chain = graph.addNode('F1', {"left": "500px", "top":blocktop - 10});
const f2Chain = graph.addNode('F2', {"left": "500px","top":blocktop + 40});
const f3Chain = graph.addNode('F3', {"left": "500px", "top":blocktop + 90});
const f4Chain = graph.addNode('F4', {"left": "500px", "top":blocktop + 140});
m1.addClass('brownnode')
m2.addClass('brownnode')
m3.addClass('brownnode')
m4.addClass('brownnode')
f1.addClass('bluenode')
f2.addClass('bluenode')
f3.addClass('bluenode')
f4.addClass('bluenode')
f1Chain.addClass('bluenode')
f2Chain.addClass('bluenode')
f3Chain.addClass('bluenode')
f4Chain.addClass('bluenode')
av.g.line(450, 10, 450, 300);
graph.addClass('backward'); //move the graph behind the new proposed blocks
graph.layout();
//-----------------------------------------------
// Slide 1
av.umsg("Brown squares labeled (M1-M4) are mining nodes, Blue Circles labeled (F1-F4) are full nodes, White circles represent thin nodes");
blockchain.addFirst("Blk 2").addFirst("Blk 1");
blockchain2.addFirst("Blk 2").addFirst("Blk 1");
blockchain3.addFirst("Blk 2").addFirst("Blk 1");
blockchain4.addFirst("Blk 2").addFirst("Blk 1");
let forkMargin = 163; //the distance we want in the fork
blockchain.layout({updateTop: false});
blockchain2.layout({updateTop: false});
blockchain3.layout({updateTop: false});
blockchain4.layout({updateTop: false});
av.displayInit();
//-----------------------------------------------
// Slide 2
av.umsg("Thin node 7 has a new transaction it wants to broadcast. It begins telling all the nodes nearby. Orange lines denote an UNCONFIRMED transaction being broadcast to various nodes throughout the network.");
g.addClass("orangenode");
const gm2Edge = graph.addEdge(g, m2).addClass("orangeedge");
const gm3Edge = graph.addEdge(g, m3).addClass("orangeedge");
const gf2Edge = graph.addEdge(g, f2).addClass("orangeedge");
const gf3Edge = graph.addEdge(g, f3).addClass("orangeedge");
av.step();
//-----------------------------------------------
// Slide 3
av.umsg("Transactions continue to propagate throughout the network via each node that receives them in transmission.");
const m2f1Edge = graph.addEdge(m2, f1).addClass("orangeedge");
const m2f2Edge = graph.addEdge(m2, f2).addClass("orangeedge");
const m3f3Edge = graph.addEdge(m3, f3).addClass("orangeedge");
const m3f4Edge = graph.addEdge(m3, f4).addClass("orangeedge");
const f1m1Edge = graph.addEdge(f1, m1).addClass("orangeedge");
const f2m1Edge = graph.addEdge(f2, m1).addClass("orangeedge");
const f3m4Edge = graph.addEdge(f3, m4).addClass("orangeedge");
const f4m4Edge = graph.addEdge(f4, m4).addClass("orangeedge");
av.step();
//-----------------------------------------------
// Slide 4
av.umsg("An important note is that no other thin node can broadcast transactions on behalf of someone else. Each thin node can ONLY broadcast transactions when it holds the private key for the sending wallet. This prevents fake transactions from being sent on behalf of someone else.");
//@TODO: Reword the private key usage
//@TODO:
//Animate a lock icon next to thin node 7 as to denote that it must hold its own private key
av.step();
//-----------------------------------------------
// Slide 5
av.umsg("As shown below, each mining node now maintains its own ledger of unconfirmed transactions denoted A1-A4. It is important to recognize that each mining node will have slightly different ledgers of unconfirmed transactions as not all transactions are propagated at the same speed across the network.");
gm2Edge.hide();
gm3Edge.hide();
gf2Edge.hide();
gf3Edge.hide();
m2f1Edge.hide();
m2f2Edge.hide();
m3f3Edge.hide();
m3f4Edge.hide();
f1m1Edge.hide();
f2m1Edge.hide();
f3m4Edge.hide();
f4m4Edge.hide();
g.removeClass("orangenode");
var m1Bundle = av.ds.list({"left": "40px", "top":"60px", nodegap: 10}).addFirst("A1");
var m2Bundle = av.ds.list({"left": "360px", "top":"280px", nodegap: 10}).addFirst("A2");
var m3Bundle = av.ds.list({"left": "40px", "top":"280px", nodegap: 10}).addFirst("A3");
var m4Bundle = av.ds.list({"left": "360px", "top":"60px", nodegap: 10}).addFirst("A4");
av.step();
//-----------------------------------------------
// Slide 6
av.umsg("As now evident by the orange block A1, M1 has received enough transactions for it to begin proposing solutions to the block. This process of hashing is described in 3.1.");
av.step();
//-----------------------------------------------
// Slide 7
av.umsg("M1 now has arrived at a valid solution which it proposes to the full node, F2. Because this is the first solution to be proposed and it is valid, the solution is accepted by F2 and begins to get propagated throughout the network. Notice how the state of F2's chain has been updated but the other full nodes still have the original chain. Currently this network lacks consensus.");
// Be more specific about what a valid solution is
f2m1Edge.removeClass("orangeedge");
f2m1Edge.addClass("greenedge");
f2m1Edge.show();
f2.removeClass("bluenode");
f2.addClass("greennode");
f2Chain.removeClass("bluenode");
f2Chain.addClass("greennode");
// @TODO:
// Is there a way to just append to existing chain rather than hiding it and making a copy?
blockchain2.hide();
var blockchain2_1 = av.ds.list({top: blocktop + 50, left: "550px", nodegap: 10});
blockchain2_1.addFirst("A1").addFirst("Blk2").addFirst("Blk1");
blockchain2_1.layout({updateTop: false});
av.step();
//-----------------------------------------------
// Slide 8
av.umsg("F2 will begin to propagate its valid solution to other neighboring full nodes.");
const f2f3Edge = graph.addEdge(f2, f3).addClass("greenedge");
const f2f1Edge = graph.addEdge(f2, f1).addClass("greenedge");
const f3f4Edge = graph.addEdge(f3, f4).addClass("greenedge");
f1.removeClass("bluenode");
f1.addClass("greennode");
f3.removeClass("bluenode");
f3.addClass("greennode");
f4.removeClass("bluenode");
f4.addClass("greennode");
blockchain.hide();
blockchain3.hide();
blockchain4.hide();
var blockchain1_1 = av.ds.list({top: blocktop + 0, left: "550px", nodegap: 10});
var blockchain3_1 = av.ds.list({top: blocktop + 100, left: "550px", nodegap: 10});
var blockchain4_1 = av.ds.list({top: blocktop + 150, left: "550px", nodegap: 10});
blockchain1_1.addFirst("A1").addFirst("Blk2").addFirst("Blk1");
blockchain3_1.addFirst("A1").addFirst("Blk2").addFirst("Blk1");
blockchain4_1.addFirst("A1").addFirst("Blk2").addFirst("Blk1");
blockchain1_1.layout({updateTop: false});
blockchain3_1.layout({updateTop: false});
blockchain4_1.layout({updateTop: false});
f1Chain.removeClass("bluenode");
f1Chain.addClass("greennode");
f3Chain.removeClass("bluenode");
f3Chain.addClass("greennode");
f4Chain.removeClass("bluenode");
f4Chain.addClass("greennode");
av.step();
//-----------------------------------------------
// Slide 9
av.umsg("At this point, all full nodes have accepted the solution of M1. The network has reached consensus on the current state of the blockchain.");
f2m1Edge.hide();
f2f1Edge.hide();
f2f3Edge.hide();
f3f4Edge.hide();
av.recorded();
});
|
import Characters from './characters';
import CharacterDetail from './characterDetail';
export { Characters, CharacterDetail };
|
import React from "react";
import styled from "styled-components";
import Token from "./Token";
const Card = styled.div`
width: 100%;
display: flex;
flex-wrap: wrap;
flex-direction: row;
justify-content: center;
`;
const TokenContainer = styled.div`
width: 90%;
display: flex;
flex-wrap: wrap;
flex-direction: row;
justify-content: center;
`;
const TokenList = (props) => {
let tokenList = props.tokenList;
let tokenRender = tokenList.map((value, index) => {
const key = value.symbol + index;
return <Token key={key} value={value} chosenToken={props.chosenToken} />;
});
return (
<Card>
<TokenContainer>{tokenRender}</TokenContainer>
</Card>
);
};
export default TokenList;
|
import React from 'react';
import PropTypes from 'prop-types';
import './Agree.css';
import AgreeModal from './AgreeModal.jsx';
const Agree = (props) => (
<div className="Agree">
<AgreeModal permissions={props.permissions} acceptPermissions={props.acceptPermissions} />
</div>
);
Agree.propTypes = {
appId: PropTypes.string,
permissions: PropTypes.shape({
name: PropTypes.string,
endpoints: PropTypes.array,
}),
acceptPermissions: PropTypes.func.isRequired,
};
export default Agree;
|
test("Hello World", () => {
})
// // test("This should Fail", () => {
// // throw new Error("Failure!")
// // })
// const calculateTip = (total, tipPercent = 0.25) => total + (total * tipPercent)
// test("Should calculate total with tip" , () =>{
// const total = calculateTip(10, 0.3)
// expect(total).toBe(13)
// })
// // test("Async test demo" , (done) => {
// // setTimeout(() => {
// // expect(1).toBe(1)
// // done()
// // }, 2000)
// // })
// const add = (a, b) => new Promise((resolve, reject) => {
// setTimeout(() => {
// if(a < 0 || b < 0)
// return reject("Numbers must be non-negative")
// resolve(a + b)
// }, 2000)
// })
// test("Should add two numbers" , (done) => {
// add(2,3).then((sum) => {
// expect(sum).toBe(5)
// done()
// })
// })
// test("Should add two numbers async/await" , async () => {
// const sum = await add(2,3)
// expect(sum).toBe(5)
// })
|
import React from 'react';
// use the isNaN method (is Not a Number). For example: isNaN(+"35") is false, isNaN(+"hello") is true
const Number = (props) => {
console.log("this is "+ props.id);
if (isNaN(props.id)) {
return <h1>The word is: {props.id}</h1>;
}
return <h1>The number is: {props.id}</h1>;
}
export default Number;
|
/**
* A basic Hello World function
* @param {string} name Who you're saying hello to
* @param {any} data The object to be parsed
* @returns {string}
*/
module.exports = (name = 'world', data = {}, context, callback) =>
{
const method = context.http.method,
result = `webhook ${method} success`;
if (method === 'POST')
console.log(`data: ${JSON.stringify(data)}`);
else if (method === 'GET')
console.log(`params: ${JSON.stringify(context.params)}`);
callback(null, result);
};
|
function sum (array){
let sum = 0
for(let i = 0; i < array.length; i++)
{
sum = sum + array[i];
}
console.log(sum)
}
//Maximum number
function max(array)
{
let maxnumber= 0;
for( let i = 0; i < array.length; i++)
{
if(array[i] < maxnumber)
{
maxnumber= array[i];
}
}
console.log(" the maximum number of this array " +maxnumber);
}
function reversenum(array){
let x;
for(let i=array.length;i>=0; i--)
{
console.log(array[i])
}
}
function printStar(num){
for(let i=1; i <= num; i++)
{
//inner loop
for( let j=0; j<=i; j++)
{
console.log('*');
}
}
}
function primenum (){
let i=2;
let flag=false;
while (i<=number/2) {
if (number%i==0){
flag=true;
break;
}
i++;
}
if (!flag){
console.log("true")}
else{
console.log("false")
}
}
|
// Date
// Não é possivel instanciar uma data de forma literal no JavaScript.
// 1 Contrutor vazio
var hoje = new Date();
// new Date(), sem parametro, retorna a data de hoje, porem esta data é manipulavel,
// pois é pegada do browser, que por sua vez a pega do sistema operacional.
hoje.getTime(); //1429446304392
// 2 Tempo em milisegundos como parametro
var natal = new Date(1419465600000);
// Pode ser passado um parametro para o contrutor Date() para que a data seja
// adicionada de maneira fixa. No exemplo é criada a data do natal de 2014.
console.log(natal); //Wed Dec 2014 22:00:00 GMT-0200 (BRST)
// 3 String de data comum como parametro
new Date('2014/12/25');
// Thu Dec 25 2014 00:00:00 GMT-0200 (BRST)
new Date('12/25/2014');
// Thu Dec 25 2014 00:00:00 GMT-0200 (BRST)
new Date('25/12/2014');
// Invalid Date
Date.parse('2014/12/25'); //1419472800000
// 4 String RFC 2822 como parametro
new Date('Thu Dec 25 2014'); // Thu Dec 25 2014 00:00:00 GMT-0200 (BRST)
new Date('Thu Dec 25 2014 10:30:00'); // Thu Dec 25 2014 10:30:00 GMT-0200 (BRST)
// 5 String ISO 8601 como parametro
new Date('2014-12-25'); // Wed Dec 24 2014 22:00:00 GMT-0200 (BRST)
new Date('2014-12-25T10:30:00'); // Thu Dec 25 2014 08:30:00 GMT-0200 (BRST)
new Date('2014-12-25T10:30:00Z'); // Thu Dec 25 2014 08:30:00 GMT-0200 (BRST)
new Date('2014-12-25T10:00:00-02:00'); // Thu Dec 25 2014 10:30:00 GMT-0200 (BRST)
// 6 Passando valores da data como parametro no contrutor.
new Date(2014, 11, 25); // Thu Dec 25 2014 00:00:00 GMT-0200 (BRST)
new Date(2014, 11, 25, 10, 30, 00); // Thu Dec 25 2014 10:30:00 GMT-0200 (BRST)
// API Date
var natal = new Date(2014, 11, 25);
// getYear
natal.getYear(); // 114
// Como o JavaScript é uma linguagem da decada de 90, como era muito comum dizer que
// o ano atual era 91, 92, etc, com a virada de 2000 ele continuou a incrementar o valor
// da mesma forma, por isso 114 no exemplo.
// getFullYear
natal .getFullYear(); // 2014
// Melhor alternativa a getYear, pois retorna o ano completo.
// getMonth
natal.getMonth(); // 11
// Começa em 0, por isso o exemplo retornou 11 e não 12
// getDay
natal.getDay(); // 4
// getDay retorna o dia da semana.
// Tambem começa em 0, por isso a quinta feira esta representada como 4 no exemplo.
// getDate
natal.getDate(); // 25
// Retorna o dia do mes.
// Referencia
// Date Mozilla Developer
// https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Date
|
(function () {
angular.module('app').controller('navbarController', function ($rootScope, $scope, AuthService) {
var credentials = $scope.credentials = $rootScope.currentUser.credentials;
function permission(permissions_ids){
return permissions_ids.includes(credentials.group_permissions_id[0])
}
$scope.menu = [
{
label: 'Home',
hide: !permission([1]),
sref: "home"
},
{
label: 'Upload Aquivos',
hide: !permission([1]),
sub: [
{
label: 'Loto Facil',
sref: "facil"
},
{
label: 'Mega Sena',
sref: "mega"
},
]
},
{
label: 'Numeros Gerados',
hide: !permission([1]),
sub: [
{
label: 'Loto Facil',
sref: "number-facil"
},
{
label: 'Mega Sena',
sref: "number-mega"
},
]
}
]
$scope.logout = function () {
AuthService.logout();
}
$scope.editPass = function () {
$('#modalUserEditPass').modal('show')
}
})
})();
|
import { Body, Container, Icon, List, ListItem } from 'native-base';
import React from 'react';
import { ScrollView, StyleSheet, Text, View } from 'react-native';
import { connect } from "react-redux";
import { buscarMedicamentos, onChangeField } from "../../actions/medicamentos/MedicamentosAction";
import EstilosComuns, { BRANCO, FUNDO_ESCURO } from '../../assets/estilos/estilos';
import { BotaoFecharHeader } from '../../components/botao/Botao';
import Loading from "../../components/comuns/Loading";
import { InputTexto } from "../../components/input/InputTexto";
import { MensagemInformativa } from "../../components/mensagens/Mensagens";
import { TELA_DETALHE_MEDICAMENTO, TELA_LISTA_MEDICAMENTOS } from '../../constants/AppScreenData';
class ListaMedicamentos extends React.Component {
static navigationOptions = ({ navigation }) => ({
title: TELA_LISTA_MEDICAMENTOS.title,
headerLeft: (
<BotaoFecharHeader navigation={navigation}/>
)
});
constructor(props){
super(props);
}
gotoPeriodicidade(remedio){
this.props.navigation.navigate(TELA_DETALHE_MEDICAMENTO.name, {medicamento: remedio})
}
buscarMedicamento(){
if (this.props.nomeMedicamento.trim().length == 0){
MensagemInformativa('Informe o nome do medicamento para pesquisar!');
return false;
}
if (this.props.nomeMedicamento.trim().length < 3){
MensagemInformativa('Informe pelo menos 3 letras do nome do medicamento para pesquisar!');
return false;
}
this.props.buscarMedicamentos(this.props.nomeMedicamento);
}
renderRemedios(){
if (this.props.listaMedicamentos.length == 0){
return (
<View>
<Text style={[{padding: 20}, EstilosComuns.corVerde, EstilosComuns.textoCentralizado]}>
Nenhum medicamento foi listado
</Text>
</View>
)
}
return this.props.listaMedicamentos.map(remedio => {
return (
<ListItem thumbnail selected button style={styles.containerRemedioResultado} onPress={() => this.gotoPeriodicidade(remedio) } >
{/* <Left>
<Thumbnail circular source={imgComparacao} />
</Left> */}
<Body>
<Text style={[styles.dadosMedicamento, EstilosComuns.negrito]} >{remedio.nomeMedicamento}</Text>
<Text note>{remedio.nomePrincipioAtivo}</Text>
</Body>
</ListItem>
)
})
}
render() {
return (
<View style={EstilosComuns.container}>
<View style={styles.containerBusca}>
<View style={{flex: 9}}>
<InputTexto placeholder="Pesquise por um remédio" maxLength={40}
onChangeInput={value => this.props.onChangeField('nomeMedicamento', value)}
autoCapitalize="none"
/>
</View>
<View style={{flex: 1}}>
<Icon name="search" color={BRANCO} size={25} onPress={() => this.buscarMedicamento()} />
</View>
</View>
<Loading bolAtivo={this.props.loadingBusca}/>
<Container style={styles.containerResultado}>
<List>
<ScrollView>
{this.renderRemedios()}
</ScrollView>
</List>
</Container>
<View style={styles.containerRodape}>
<Text style={[EstilosComuns.corVerde, EstilosComuns.textoCentralizado]}>
Clique sobre o remédio para ver as dosagens e demais detalhes sobre o medicamento selecionado
</Text>
</View>
</View>
)
};
}
const styles= StyleSheet.create({
containerBusca: {
flex: 1,
padding: 5,
flexDirection:'row',
justifyContent: 'space-between',
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: FUNDO_ESCURO
},
containerResultado: {
flex: 8,
fontSize: 20,
fontWeight: 'bold',
},
containerRemedioResultado: {
borderBottomColor: FUNDO_ESCURO,
borderBottomWidth:1,
},
containerRodape: {
flex: 1,
padding: 5
},
dadosMedicamento: {
fontSize: 14,
fontWeight: 'bold',
},
dadosMedicamentoItalico:{
fontStyle: 'italic'
}
})
const mapStateToProps = state => ({
nomeMedicamento: state.medicamentoReducer.nomeMedicamento,
mensagemFalha: state.medicamentoReducer.mensagemFalha,
loadingBusca: state.medicamentoReducer.loadingBusca,
listaMedicamentos: state.medicamentoReducer.listaMedicamentos
})
export default connect(mapStateToProps, {onChangeField, buscarMedicamentos})(ListaMedicamentos);
|
import {mapValues, uniq, take} from 'lodash'
// local libs
import {PropTypes, assertPropTypes, plainProvedGet as g} from 'src/App/helpers'
import {galleryModel, openGraphDataModel} from 'src/App/VideoPage/models'
const
galleryModelProps = process.env.NODE_ENV === 'production' ? null : Object.freeze({
id: PropTypes.string, // but actually a number
id_class: PropTypes.string, // but actually a number
title: PropTypes.string,
embed_code: PropTypes.string,
id_sponsor: PropTypes.string,
url: PropTypes.string,
published: PropTypes.string, // but actually a number (of seconds, unix time)
length: PropTypes.string, // but actually a number (of seconds, unix time)
thumb_url: PropTypes.string,
thumbs: PropTypes.arrayOf(PropTypes.string), // but actually an array of numbers
thumb_top: PropTypes.string,
tags: PropTypes.arrayOf(PropTypes.string),
}),
pageUrlModel = process.env.NODE_ENV === 'production' ? null : PropTypes.string,
// actually a list of two elements
publishedTemplateItemModel = process.env.NODE_ENV === 'production' ? null :
PropTypes.exactTuple([
PropTypes.string, // singular, example: "1 year ago"
PropTypes.string, // multiple, example: "%d years ago"
]),
publishedTemplateModelProps = process.env.NODE_ENV === 'production' ? null : Object.freeze({
y: publishedTemplateItemModel,
m: publishedTemplateItemModel,
d: publishedTemplateItemModel,
w: publishedTemplateItemModel,
h: publishedTemplateItemModel,
i: publishedTemplateItemModel,
s: publishedTemplateItemModel,
})
export const
incomingGalleryModel = process.env.NODE_ENV === 'production' ? null :
PropTypes.shape(galleryModelProps),
publishedTemplateModel = process.env.NODE_ENV === 'production' ? null :
PropTypes.shape(publishedTemplateModelProps),
sponsorsModel = process.env.NODE_ENV === 'production' ? null :
PropTypes.objectOf(PropTypes.shape({name: PropTypes.string}))
const
// {foo: 'foo', bar: 'bar'}
galleryModelPropsKeys = process.env.NODE_ENV === 'production' ? null :
Object.freeze(mapValues(galleryModelProps, (x, k) => k)),
// get incoming property by verified key (which must be presented in the model)
getProp = process.env.NODE_ENV === 'production' ? g :
(src, propKey, ...xs) => g(src, g(galleryModelPropsKeys, propKey), ...xs),
// {foo: 'foo', bar: 'bar'}
publishedTemplateModelPropsKeys = process.env.NODE_ENV === 'production' ? null :
Object.freeze(mapValues(publishedTemplateModelProps, (x, k) => k)),
// get incoming property of "publishedTemplate" by verified key
// (which must be presented in the model)
getPubTplProp = process.env.NODE_ENV === 'production' ? g :
(src, propKey, ...xs) => g(src, g(publishedTemplateModelPropsKeys, propKey), ...xs)
export default (data, pageUrl, publishedTemplate, sponsors) => {
if (process.env.NODE_ENV !== 'production') {
assertPropTypes(incomingGalleryModel, data, 'getGallery', 'original source gallery data')
assertPropTypes(pageUrlModel, pageUrl, 'getGallery', 'page url')
assertPropTypes(
publishedTemplateModel,
publishedTemplate,
'getGallery',
'published template'
)
assertPropTypes(sponsorsModel, sponsors, 'getGallery', 'sponsors')
}
const
publishedDate = new Date(Date.now() - getProp(data, 'published') * 1000),
years = publishedDate.getFullYear() - 1970,
months = publishedDate.getMonth(),
days = publishedDate.getDate(),
hours = publishedDate.getHours(),
minutes = publishedDate.getMinutes(),
published
= years && years === 1
? getPubTplProp(publishedTemplate, 'y', 0)
: years
? getPubTplProp(publishedTemplate, 'y', 1).replace('%d', years)
: months && months === 1
? getPubTplProp(publishedTemplate, 'm', 0)
: months
? getPubTplProp(publishedTemplate, 'm', 1).replace('%d', months)
: days && days === 1
? getPubTplProp(publishedTemplate, 'd', 0)
: days === 7
? getPubTplProp(publishedTemplate, 'w', 0)
: days === 14
? getPubTplProp(publishedTemplate, 'w', 1).replace('%d', days / 7)
: days === 21
? getPubTplProp(publishedTemplate, 'w', 1).replace('%d', days / 7)
: days === 28
? getPubTplProp(publishedTemplate, 'w', 1).replace('%d', days / 7)
: days
? getPubTplProp(publishedTemplate, 'd', 1).replace('%d', days)
: hours && hours === 1
? getPubTplProp(publishedTemplate, 'h', 0)
: hours
? getPubTplProp(publishedTemplate, 'h', 1).replace('%d', hours)
: minutes && minutes === 1
? getPubTplProp(publishedTemplate, 'm', 0)
: minutes
? getPubTplProp(publishedTemplate, 'm', 1).replace('%d', minutes)
: getPubTplProp(publishedTemplate, 's', 0),
length = Number(getProp(data, 'length')),
result = {
id: Number(getProp(data, 'id')),
classId: Number(getProp(data, 'id_class')),
title: getProp(data, 'title'),
urlForIframe: g(getProp(data, 'embed_code').match(/src="([\S]+)"/), 1),
sponsorName: g(sponsors, getProp(data, 'id_sponsor'), 'name'),
sponsorLink: `${g(sponsors, getProp(data, 'id_sponsor'), 'name')} porn`,
sponsorUrl: getProp(data, 'url'),
published,
// The following data is used for ADD_VIDEO_TO_FAVORITE action:
thumb: getProp(data, 'thumb_url'),
thumbMask: getProp(data, 'thumb_url').replace(/-\d+.jpg/, '-{num}.jpg'),
thumbs: getProp(data, 'thumbs').map(x => Number(x)),
firstThumb: Number(getProp(data, 'thumb_top')),
tags: uniq(getProp(data, 'tags')),
// This is for very small string under a video preview,
// it's usually only one single tag.
tagsShort: take(getProp(data, 'tags'), 3),
duration: `${
Math.floor(length / 60)
}:${
length % 60 < 10 ? '0' + length % 60 : length % 60
}`,
videoPageRef: Number(pageUrl.match(/\/vid-(\d+)\//)[1]),
}
if (process.env.NODE_ENV !== 'production')
assertPropTypes(galleryModel, result, 'getGallery', 'result gallery data')
return result
}
export const
getOpenGraphData = (data, swfPlugUrl) => {
if (process.env.NODE_ENV !== 'production') {
assertPropTypes(
incomingGalleryModel,
data,
'getOpenGraphData',
'original source gallery data'
)
}
const
result = {
id: Number(getProp(data, 'id')),
title: getProp(data, 'title'),
thumb: getProp(data, 'thumb_url'),
tags: getProp(data, 'tags'),
duration: Number(getProp(data, 'length')),
swfPlugUrl,
}
if (process.env.NODE_ENV !== 'production')
assertPropTypes(openGraphDataModel, result, 'getOpenGraphData', 'result gallery data')
return result
}
|
import axios from "axios"
const appProvider = axios.create({
baseURL: process.env.REACT_APP_BACKEND_API_URL
})
export default appProvider;
|
const request = require('request')
module.exports.forecast = (data, callback)=>{
const latitude = data.latitude;
const longitude = data.longitude;
console.log(latitude , longitude)
const weatherURL = 'https://api.darksky.net/forecast/b9d32216d290e072d1e1d71078c1ac6e/'+latitude+','+longitude;
request({url :weatherURL, json : true}, function(err, response){
if(err){
callback(error, undefined)
}
if(response.body.currently){
const result = " The temperature is " + response.body.currently.temperature +
" with a precipitation of " +response.body.currently.precipProbability;
callback(undefined, result)
}
})
}
|
import React from 'react';
import {Button} from 'react-bootstrap';
class TextInput extends React.Component{
constructor(props){
super(props);
this.state = { newMessageText: '', messageCharactersLimit: this.props.charactersLimit || 200};
}
messageType = (messageText) => {
if(messageText.length <= this.state.messageCharactersLimit){
this.setState({newMessageText: messageText});
}
};
sendPost = (message) => {
this.props.onSend(message);
this.setState({newMessageText: ""});
};
render(){
const {newMessageText, messageCharactersLimit} = this.state;
return (
<div className="new-message-container">
<textarea value={newMessageText}
onChange={(e) => this.messageType(e.target.value)} />
<div className="symbol-count">
{messageCharactersLimit - newMessageText.length} symbols left
</div>
<Button bsStyle="info" onClick={() => this.sendPost(newMessageText)}>
{ this.props.btnText ? this.props.btnText : "Send"}
</Button>
</div>
)}
}
export default TextInput;
|
'use strict';
import Button from 'react-native-button';
import React, {
StyleSheet,
View,
Platform,
ScrollView,
Text,
Image,
WebView
} from 'react-native';
export default function () {
return (
<ScrollView style={styles.container}>
{(this.state.item.source) ?
<WebView
ref="youtubePlayer"
automaticallyAdjustContentInsets={true}
url={'https://www.youtube.com/embed/'+this.state.item.source}
javaScriptEnabledAndroid={true}
style={styles.video}/>
: <View /> }
<View style={styles.detail}>
<Text style={styles.title}>{this.state.item.title}</Text>
<Text style={styles.description}>{this.state.item.description}</Text>
<View style={styles.buttons}>
<Button style={styles.button}><Image style={styles.buttonImage} source={require('../../../images/btn-circle-download.png')} /></Button>
<Button style={styles.button}><Image style={styles.buttonImage} source={require('../../../images/btn-circle-share.png')} /></Button>
</View>
</View>
</ScrollView>
);
}
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#363744'
},
detail: {
padding: 20
},
title: {
color: 'white',
fontSize: 18,
fontWeight: '400',
paddingBottom: 20
},
description: {
fontSize: 14,
fontWeight: '200',
color: 'white'
},
video: {
alignSelf: 'stretch',
height: 250
},
buttons: {
flex: 1,
marginTop: 20,
flexDirection: 'row'
},
button: {
width: 40,
height: 40
},
buttonImage: {
width: 40,
height: 40,
marginRight: 10
}
});
|
const {
time,
loadFixture,
} = require("@nomicfoundation/hardhat-network-helpers");
const { anyValue } = require("@nomicfoundation/hardhat-chai-matchers/withArgs");
const { expect } = require("chai");
const { BigNumber } = require("ethers");
async function deployVerifierFixture() {
const Verifier = await ethers.getContractFactory("MockVerifier");
const verifier = await Verifier.deploy();
await verifier.deployed();
return verifier;
}
const prompt = ethers.utils.toUtf8Bytes("test");
const aigcData = ethers.utils.toUtf8Bytes("test");
const uri = '"name": "test", "description": "test", "image": "test", "aigc_type": "test"';
const validProof = ethers.utils.toUtf8Bytes("valid");
const invalidProof = ethers.utils.toUtf8Bytes("invalid");
const tokenId = BigNumber.from("70622639689279718371527342103894932928233838121221666359043189029713682937432");
describe("ERC7007.sol", function () {
async function deployERC7007Fixture() {
const verifier = await deployVerifierFixture();
const ERC7007 = await ethers.getContractFactory("ERC7007");
const erc7007 = await ERC7007.deploy("testing", "TEST", verifier.address);
await erc7007.deployed();
return erc7007;
}
describe("mint", function () {
it("should mint a token", async function () {
const erc7007 = await deployERC7007Fixture();
const [owner] = await ethers.getSigners();
await erc7007.mint(prompt, aigcData, uri, validProof);
expect(await erc7007.balanceOf(owner.address)).to.equal(1);
});
it("should not mint a token with invalid proof", async function () {
const erc7007 = await deployERC7007Fixture();
await expect(erc7007.mint(prompt, aigcData, uri, invalidProof)).to.be.revertedWith("ERC7007: invalid proof");
});
it("should not mint a token with same data twice", async function () {
const erc7007 = await deployERC7007Fixture();
await erc7007.mint(prompt, aigcData, uri, validProof);
await expect(erc7007.mint(prompt, aigcData, uri, validProof)).to.be.revertedWith("ERC721: token already minted");
});
it("should emit a Mint event", async function () {
const erc7007 = await deployERC7007Fixture();
await expect(erc7007.mint(prompt, aigcData, uri, validProof))
.to.emit(erc7007, "Mint")
});
});
describe("metadata", function () {
it("should return token metadata", async function () {
const erc7007 = await deployERC7007Fixture();
await erc7007.mint(prompt, aigcData, uri, validProof);
expect(await erc7007.tokenURI(tokenId)).to.equal('{"name": "test", "description": "test", "image": "test", "aigc_type": "test", "prompt": "test", "aigc_data": "test"}');
});
});
});
describe("ERC7007Enumerable.sol", function () {
async function deployERC7007EnumerableFixture() {
const verifier = await deployVerifierFixture();
const ERC7007Enumerable = await ethers.getContractFactory("MockERC7007Enumerable");
const erc7007Enumerable = await ERC7007Enumerable.deploy("testing", "TEST", verifier.address);
await erc7007Enumerable.deployed();
await erc7007Enumerable.mint(prompt, aigcData, uri, validProof);
return erc7007Enumerable;
}
it("should return token id by prompt", async function () {
const erc7007Enumerable = await deployERC7007EnumerableFixture();
expect(await erc7007Enumerable.tokenId(prompt)).to.equal(tokenId);
});
it("should return token prompt by id", async function () {
const erc7007Enumerable = await deployERC7007EnumerableFixture();
expect(await erc7007Enumerable.prompt(tokenId)).to.equal("test");
});
});
|
const mongoose = require('mongoose');
const User = mongoose.model('User');
const Appointment = mongoose.model('Appointment');
const Meeting = mongoose.model('Meeting');
const SysFunction = mongoose.model('SysFunction');
const models = [User, Appointment, Meeting, SysFunction];
exports.clearAll = async (ctx, next) => {
const index = parseInt(ctx.params.id);
await models[index].remove();
try {
ctx.body = {
success: true,
}
}
catch (e) {
ctx.body = {
success: false
}
return next
}
}
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamp');
const eventSchema = new Schema({
participants:[{
user: {type: Schema.Types.ObjectId, ref: 'User'},
role: {type: String, enum: ['organizer', 'sponsor', 'performer', 'staff', 'security']}
}],
organization: {type: Schema.Types.ObjectId, ref: 'Organization', required: true},
name: {type: String, required: true, unique: true},
type: {type: String, required: true},
location: {type: String, required: true},
startTime: {type: Date, required: true},
endTime: {type: Date, required: true},
status: {type: String, enum: ['confirmed', 'pending', 'cancelled'],default: 'pending'},
pictures: [{type: String}],
reviews: [{type: Schema.Types.ObjectId, ref: 'Review'}],
mainPhoto: {type: String, default: '/assets/images/event_placeholder.png'}
});
eventSchema.plugin(timestamps);
const Event = mongoose.model('Event', eventSchema);
module.exports = Event;
|
function createComment(sequelize, DataTypes) {
const Comment = sequelize.define('Comment', {
text: {
type: DataTypes.STRING,
},
}, {
classMethods: {
associate: (models) => {
Comment.belongsTo(models.User, { as: 'commenter' });
},
},
});
return Comment;
}
export default createComment;
|
/* variables locales de T_PRYCTGITHJLHU_357*/
|
var gens = {
fname: "Fname",
lname: "Lname",
cell: {
home: [],
mobile: ["9088836373", "9393327262"]
},
email: "fname.lname@google.com",
address: {
line1: "test block", //spread arr
city: "test city",
state: "test state",
zip: "303328",
country: "TestCountry"
},
exit: "",
assets: [
{
id: "10202",
name: "asset1",
date: "12.3.2004",
type: "delicate",
category: "v2",
returnDate: "30.3.2004"
},
{
id: "10203",
name: "asset2",
date: "12.3.2004",
type: "delicate",
category: "v1",
returnDate: "30.3.2004"
},
{
id: "10205",
name: "asset1",
date: "12.3.2004",
type: "delicate",
category: "v3",
returnDate: "30.3.2004"
},
{
id: "10207",
name: "asset1",
date: "12.3.2004",
type: "delicate",
category: "v2",
returnDate: ""
}
]
};
document.getElementById("t1").innerHTML = returnAsset();
const returnAsset = (function() {
"use strict";
return function returnAsset({ exit }) {
return "Today";
};
})();
const profileUpdate = ({ name, age, nationality, location }) => {
/* do something with these fields */
};
|
document.addEventListener("DOMContentLoaded",()=>{
if(window.innerWidth<701){
document.querySelector(".major").className = "col-12 major";
document.querySelector(".minor").className = "col-12 minor collapse";
}else{
document.querySelector(".major").className = "col-9 major";
document.querySelector(".minor").className = "col-3 minor";
}
window.addEventListener("resize",()=>{
if(window.innerWidth<701){
document.querySelector(".major").className = "col-12 major";
document.querySelector(".minor").className = "col-12 minor collapse";
}else{
document.querySelector(".major").className = "col-9 major";
document.querySelector(".minor").className = "col-3 minor";
}
});
document.querySelector("#username").innerHTML = localStorage.getItem("username");
document.querySelector("#user").innerHTML = localStorage.getItem("username");
document.querySelector("#logout").onclick = ()=>{
localStorage.removeItem("username");
window.location.href = "http://localhost:5000/";
};
document.querySelector("#password-Invalid").style.display = "none";
document.querySelector("#username-Invalid").style.display = "none";
document.querySelector("#change-info").style.display = "none";
document.querySelector("#edit-profile").onclick = ()=>{
document.querySelector("#change-info").style.display = "block";
document.querySelector("#show-info").style.display = "none";
};
document.querySelector("#password2-Invalid").style.display = "none";
document.querySelector("#channelname-Invalid").style.display = "none";
document.querySelector("#create-channel2").style.display = "none";
document.addEventListener("click",event=>{
const ele = event.target;
if(ele.className === "create-channel btn btn-success"){
document.querySelector("#create-channel2").style.display = "block";
document.querySelector("#show-info").style.display = "none";
document.querySelector("#change-info").style.display = "none";
}else if(ele.className === "back btn btn-success"){
document.querySelector("#change-info").style.display = "none";
document.querySelector("#create-channel2").style.display = "none";
document.querySelector("#show-info").style.display = "table";
}
if(ele.className === "btn btn-link channelLink"){
let name = ele.innerHTML;
localStorage.setItem("channel",name);
window.location.href = "http://localhost:5000/channel";
}
});
const template = Handlebars.compile(document.querySelector("#channellist").innerHTML);
var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
socket.on("connect",()=>{
socket.emit("get channels");
socket.emit("ask details",{"username":localStorage.getItem("username")});
document.querySelector("#uploadpic1").onclick = ()=>{
document.querySelector("#pic1").click();
};
document.querySelector("#pic1").onchange = ()=>{
var x = document.querySelector("#pic1");
if('files' in x){
if(x.files.length>0){
var file = x.files[0];
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = ()=>{
var buff = reader.result;
socket.emit("upload image",{"filename":file.name,"binary":buff,"username":localStorage.getItem("username")});
};
}
}
};
document.querySelector("#change-info").onsubmit = ()=>{
let hasusername = false;
let username = document.querySelector("#username2").value;
let haspassword = false;
let password = document.querySelector("#password").value;
let hasaddress = false;
let address = document.querySelector("#address2").value;
let hascompany = false;
let company = document.querySelector("#company2").value;
let checkpassword = document.querySelector("#cpassword").value;
if( username.length>0){
hasusername = true;
}
if(password.length>0){
haspassword = true;
}
if(address.length>0){
hasaddress = true;
}
if(company.length>0){
hascompany = true;
}
socket.emit("editprofile",{"confirm_username":localStorage.getItem("username"),"username":{"has":hasusername,"value":username},"password":{"has":haspassword,"value":password},"address":{"has":hasaddress,"value":address},"company":{"has":hascompany,"value":company},"confirm_password":checkpassword});
return false;
};
document.querySelector("#mode").onchange = ()=>{
if(document.querySelector("#mode").value === "private"){
document.querySelector("#passwordchannel").disabled = false;
document.querySelector("#passwordchannel").required = true;
}else{
document.querySelector("#passwordchannel").disabled = true;
document.querySelector("#passwordchannel").required = false;
}
};
document.querySelector("#create-channel2").onsubmit = ()=>{
let name = document.querySelector("#channelname").value;
let mode = document.querySelector("#mode").value;
let password = document.querySelector("#passwordchannel").value;
let checkpassword = document.querySelector("#cpassword2").value;
socket.emit("create channel",{"confirm_username":localStorage.getItem("username"),"name":name,"mode":mode,"password":password,"confirm_password":checkpassword});
return false;
};
});
socket.on("create channel fail",data=>{
if(!data.passwordsuccess)
document.querySelector("#password2-Invalid").style.display = "block";
if(!data.channelsuccess)
document.querySelector("#channelname-Invalid").style.display = "block";
});
socket.on("create channel success",data=>{
document.querySelector("#create-channel2").style.display = "none";
document.querySelector("#show-info").style.display = "table";
let channels = [];
channels.push(data.name);
const content = template({"values":channels});
document.querySelector("#dekstopchannels").innerHTML += content;
});
socket.on("success-edit",data=>{
document.querySelector("#change-info").style.display = "none";
document.querySelector("#show-info").style.display = "table";
localStorage.setItem("username",data.username)
document.querySelector("#address").innerHTML = data.address;
document.querySelector("#company").innerHTML = data.company;
document.querySelector("#username").innerHTML = localStorage.getItem("username");
document.querySelector("#user").innerHTML = localStorage.getItem("username");
});
socket.on("fail-edit",data=>{
if(!data.passwordsuccess){
document.querySelector("#password-Invalid").style.display = "block";
}else if(!data.usersuccess){
document.querySelector("#username-Invalid").style.display = "block";
}
});
socket.on("get details",data=>{
if(!data.success){
alert("ERROR WHILE LOADING press ctrl+Shift+R");
}else{
document.querySelector("#name").innerHTML = data.name;
document.querySelector("#email").innerHTML = data.email;
document.querySelector("#address").innerHTML = data.address;
document.querySelector("#company").innerHTML = data.company;
var d = new Date();
var str = d.getTime();
document.querySelector("#profile").src = `/static/uploads/profile/${data.pic}?rnd=${str}`;
}
});
socket.on("send image",data=>{
var d = new Date();
var str = d.getTime();
document.querySelector("#profile").src = `/static/uploads/profile/${data.pic}?rnd=${str}`;
});
socket.on("send channels",data=>{
const content = template({"values":data.channels});
document.querySelector("#dekstopchannels").innerHTML = content;
});
});
|
// D.A.J. Hiep.
// Image turner function that takes urls as a parameter.
function imageturner(urls) {
// Select image and store in a variable called image.
var image = $(".test-image img");
// Image is hidden if not loaded.
image.removeClass("hidden");
// Create variable called turnNumber and set it's value to 0.
var turnNumber = 0;
// Creates array with the image urls which are used if Europeana images are not loaded.
if(!urls) urls = [ 'http://xiostorage.com/wp-content/uploads/2015/10/test.png',
'https://s-media-cache-ak0.pinimg.com/736x/4b/10/f4/4b10f471c25e2a70dc9fb01ac4bd4311.jpg',
'http://www.bbtoystore.com/mm5/beanies/PL_danglesLARGE.jpg'
];
// Create variable called imgNumber and set it's value to 0.
var imgNumber = 0;
// Turn-button function gets called on click.
$(".turn-button").click(function() {
// Keeps track of how many times the image has turned and resets after 3 times.
turnNumber = (turnNumber + 1)%4;
// Toggles appropriate Class to turn image.
switch (turnNumber){
case 1: image.toggleClass("test-image-turned-1"); break;
case 2: image.toggleClass("test-image-turned-1");
image.toggleClass("test-image-turned-3");
case 3: image.toggleClass("test-image-turned-2");
default: image.toggleClass("test-image-turned-3");
}
});
// Guess function gets called on click.
$(".guess").click(function() {
alert(turnNumber === 0 ? "Good guess!" : "Wrong! Please try again.");
});
var next = function() {
// Keeps track of how many times the image has changed and resets after urls.length times.
imgNumber = (imgNumber +1)%urls.length;
// Toggles image urls.
image.attr('src', urls[imgNumber]);
};
// Next function gets called on click.
$(".next").click(next);
// Also execute next on first load.
next();
}
|
import React from 'react'
class Tag extends React.Component {
tagClick = () => {
}
tagHover = () => {
}
render () {
return (
<div className='tag' onClick={this.tagClick} onMouseOver={this.tagHover}>
<i className="fas fa-tag"/>
<p>{this.props.name}</p>
</div>
);
}
}
export default Tag;
|
const { User } = require("../models");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const moment = require("moment");
//회원가입하기
exports.createUser = async (req, res, next) => {
const { userId, password, ...rest } = req.body;
try {
//이미 해당 유저가 존재할 경우
const exUser = await User.findOne({ where: { userId } });
if (exUser) {
const error = new Error("이미 해당 아이디의 유저가 존재합니다.");
error.status = 409;
const errBody = {
success: false,
message: error.message,
};
return res.send(errBody);
}
//비번 암호화
const hash = await bcrypt.hash(password, 12);
//유저 생성
const newUser = await User.create({
name: rest.name,
userId: userId,
password: hash,
});
const status = 200;
const resBody = {
success: true,
newUser,
};
return res.status(status).send(resBody);
} catch (error) {
return next(error);
}
};
//로그인하기
exports.loginUser = async (req, res, next) => {
try {
const { userId, password } = req.body;
//요청된 아이디를 데이터베이스에서 있는지 찾는다.
const user = await User.findOne({ where: { userId } });
if (!user) {
//요청된 아이디가 데이터베이스에서 없다면
const error = new Error("해당 유저가 존재하지 않습니다.");
error.status = 401;
const errBody = {
success: false,
message: error.message,
};
return res.send(errBody);
}
//요청된 아이디가 데이터베이스에 있다면 비밀번호가 맞는 비밀번호인지 확인
const result = await bcrypt.compare(password, user.password);
if (!result) {
//비밀번호가 틀리다면
const error = new Error("비밀번호가 틀립니다.");
error.status = 401;
const errBody = {
success: false,
message: error.message,
};
return res.send(errBody);
}
//비밀번호까지 맞다면 토큰을 생성하기
//jsonwebtoken을 이용해서 token 생성
try {
//user.id 와 process.env.COOKIE_SECRET을 붙여서 토큰을 만들어준다. (토큰 인코딩)
//반대로 토큰에서 process.env.COOKIE_SECRET을 빼면 user.id가 나오겠지! (토큰 디코딩)
const token = jwt.sign(user.id, process.env.COOKIE_SECRET);
//DB에 유저에게 할당한 토큰 업데이트
await User.update(
{ token },
{
where: { id: user.id },
}
);
//유저에게 돌려보낼 body
const resBody = {
success: true,
userId: user.id,
};
//유저에게 돌려보낼 때 토큰을 쿠키에 저장해서 쿠키를 같이 보낸다.
res.cookie("x_auth", token).status(200).send(resBody);
} catch (error) {
error.status = 400;
const errBody = {
success: false,
message: error.message,
};
return res.send(errBody);
}
} catch (error) {
return next(error);
}
};
//유저 로그아웃하기
exports.logoutUser = async (req, res, next) => {
try {
await User.update(
{ token: "" },
{
where: { id: req.user.id },
}
);
const resBody = {
success: true,
};
res.status(200).send(resBody);
} catch (error) {
return next(error);
}
};
//유저 인증하기
exports.authUser = async (req, res, next) => {
try {
const resBody = {
isAuth: true,
user: req.user,
};
res.status(200).send(resBody);
} catch (error) {
return next(error);
}
};
|
window.addEventListener("load", function(){
// LET'S SAY THAT WE HAVE A SIMPLE FLAT ARRAY
var data = ["marco", "occhetta", "1G", "15", "matteo", "colombo", "3A", "12"];
// DRAW HTML TABLE
var perrow = 4, // 3 items per row
count = 0, // Flag for current cell
table = document.createElement("table"),
row = table.insertRow();
for (var i of data) {
var cell = row.insertCell();
cell.innerHTML = i;
// You can also attach a click listener if you want
cell.addEventListener("click", function(){
alert("FOO!");
});
// Break into next row
count++;
if (count%perrow==0) {
row = table.insertRow();
}
}
// ATTACH TABLE TO CONTAINER
document.getElementById("container").appendChild(table);
});
|
const params = {
MaxResults: 10,
};
export default params;
|
const { Client } = require("klasa");
const permissionLevels = require("./utils/PermissionLevels.js");
const config = require("./config.json");
const Raven = require("raven");
const RawEventStore = require("./utils/RawEventStore.js");
const Logger = require("./utils/Logger.js");
const capcon = require('capture-console');
const {
defaultGuildSchema,
defaultClientSchema,
defaultUserSchema,
defaultMemberSchema
} = require("./utils/DefaultSchemas.js");
Raven.config(config.sentry, { captureUnhandledRejections: true }).install();
class RemixBot extends Client {
constructor() {
super({
pieceDefaults: { rawEvents: { enabled: true } },
prefix: "r.",
regexPrefix: /^((Hey|Hey )RemixBot(!|! |,|, | )|(r\.|r\. ))/i,
commandEditing: true,
typing: true,
providers: { default: "PostgreSQL", postgresql: { user: config.postgreUser, password: config.postgrePass } },
permissionLevels: permissionLevels,
readyMessage: (client) => `${client.user.tag} ready with ${client.guilds.size} guilds!`,
defaultGuildSchema,
defaultClientSchema,
defaultUserSchema,
defaultMemberSchema
});
this.config = require("./config.json");
this.utils = new (require("./utils/Utils.js"))(this);
this.audioManager = null;
this.logger = new Logger(this, "log.txt");
this.website = null;
this.tttGames = new Map();
this.rawEvents = new RawEventStore(this);
this.registerStore(this.rawEvents);
capcon.startCapture(process.stdout, (stdout) => {
this.logger.write(stdout);
});
capcon.startCapture(process.stderr, (stdout) => {
this.logger.write(stdout);
});
}
}
Raven.context(() => new RemixBot().login(config.token));
|
import { fireEvent } from '@testing-library/react-native';
import React from 'react';
import Profile from 'components/Profile';
import UserController from 'controllers/UserController';
import strings from 'localization';
import { renderWithProviders } from 'test-utils/render';
jest.mock('controllers/UserController', () => ({
logout: jest.fn(() => {
return Promise.resolve();
}),
}));
describe('Profile', () => {
test('should render the title and logout button', () => {
const { getByText } = renderWithProviders(<Profile />);
const profileTitle = getByText(strings.profile);
const logoutButton = getByText(strings.logout);
expect(profileTitle).toBeTruthy();
expect(logoutButton).toBeTruthy();
});
test('should logout the user', async () => {
const { getByText } = renderWithProviders(<Profile />);
const logoutButton = getByText(strings.logout);
fireEvent.press(logoutButton);
expect(UserController.logout).toHaveBeenCalledTimes(1);
});
});
|
import React, { Component } from "react";
import { Route, Redirect, Switch } from "react-router-dom";
import { ToastContainer } from "react-toastify";
import NavBar from "./components/UI/NavBar/NavBar";
import Movies from "./containers/Movies/Movies";
import LoginForm from "./components/UI/Form/LoginForm/LoginForm";
import RegisterForm from "./components/UI/Form/RegisterForm/RegisterForm";
import MovieForm from "./components/UI/Form/MovieForm/MovieForm";
import Customers from "./containers/Customers/Customers";
import Rentals from "./containers/Rentals/Rentals";
import LoginOut from "./components/LogOut/LogOut";
import NotFound from "./components/NotFound/NotFound";
import auth from "./services/authService";
import "bootstrap/dist/css/bootstrap.css";
import "react-toastify/dist/ReactToastify.css";
import "./App.css";
class App extends Component {
state = {};
componentDidMount() {
const user = auth.getCurrentUser();
this.setState({ user });
}
render() {
const { user } = this.state;
return (
<div >
<div style={{ backgroundColor: "#f8f9fa", height: '60px', width: '100%', padding: 'none', margin: 'none' }}></div>
<ToastContainer />
<NavBar user={user} admin={user && user.isAdmin} />
<main className="container" data-test='MainContainer'>
<Switch>
<Route path="/login" component={LoginForm} />
<Route path="/logout" component={LoginOut} />
<Route path="/customers" component={Customers} />
<Route path="/rentals" component={Rentals} />
<Route path="/register" component={RegisterForm} />
<Route
path="/movies/:id"
render={props => {
if (!user) return <Redirect to="/login" />;
return <MovieForm {...props} />;
}}
/>
<Route
path="/movies"
render={props => (
<Movies {...props} user={user} admin={user && user.isAdmin} />
)}
/>
<Redirect from="/" exact to="/movies" />
<Redirect from="/profile" exact to="/movies" />
<Route path="/not-found" component={NotFound} />
<Redirect path="/" to="/not-found" />
</Switch>
</main>
</div>
);
}
}
export default App;
|
//D3 DEMO
//begin script when window loads
window.onload = setMap();
//set up choropleth map
function setMap(){
//set width, height
var width=1050, height=550;
//use queue.js to parallelize asynchronous data loading
var q = d3_queue.queue();
.defer(d3.csv, "data/StateData.csv") //load attributes from csv
.defer(d3.json, "data/USAStates.topojson") //load choroplethspatial data
.await(callback);
function callback(error, csvData, europe, france){
console.log(error);
console.log(csvData);
console.log(europe);
console.log(france);
};
};
|
module.exports = function (grunt) {
grunt.initConfig({
copy: {
build: {
cwd: 'src',
// Modernizr loads in head, and JQuery tried to load first from CDN
src: ['**', '!**/*.scss', '!**/*.css', '!**/*.js', '!**/*.map', '!**/head.php', '!**/foot.php', '!sass', '**/modernizr-2.8.3-respond-1.4.2.min.js','**/jquery-1.11.2.min.js'],
dest: 'dist',
expand: true
},
},
clean: {
build: {
src: ['dist']
},
},
compass: {
dist: {
options: {
sassDir: 'src/sass',
cssDir: 'src/css'
}
}
},
/*minify and concat all css*/
cssmin: {
build: {
files: {
'dist/css/styles.min.css': ['src/**/*.css']
}
}
},
/*minify and concat all js except JQuery and Modernizr*/
uglify: {
build: {
options: {
mangle: true
},
files: {
'dist/js/main.min.js': ['src/**/*.js','!**/modernizr-2.8.3-respond-1.4.2.min.js','!**/jquery-1.11.2.min.js']
}
}
},
watch: {
stylesheets: {
files: 'src/**/*.scss',
tasks: ['compass', 'copy'],
options: {
livereload: true,
},
},
scripts: {
files: ['src/**/*.js'],
options: {
livereload: true,
},
},
html: {
files: ['src/*.html', 'src/**/*.html', 'src/**/*.php'],
options: {
livereload: true,
},
},
},
processhtml: {
// options: {
// data: {
// message: 'Hello world!'
// }
// },
dist: {
files: {
'dist/includes/head.php': ['src/includes/head.php'],
'dist/includes/foot.php': ['src/includes/foot.php']
}
}
},
});
// load the tasks
grunt.loadNpmTasks('grunt-contrib-copy');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-processhtml');
// define the tasks
grunt.registerTask('default',
'compiles SASS to CSS if necessary, and calls LiveReload', ['watch']);
grunt.registerTask(
'build',
'Cleans dist directory, processes HTML, compiles SASS to CSS, minifies CSS and JS, and copies all remaining files from src to dist', ['compass', 'clean', 'copy', 'cssmin', 'uglify', 'processhtml']
);
};
|
/**
* @param {string} S
* @param {string} T
* @return {string}
*/
var customSortString = function(S, T) {
let charToFreq = [];
for( let i = 0; i < T.length; i++) {
let c = T[i];
charToFreq[getCharIndex(c)] = charToFreq[getCharIndex(c)] ? charToFreq[getCharIndex(c)] + 1 : 1;
}
let afterString = "";
for(let i = 0; i< S.length; i++) {
let c = S[i];
if(charToFreq[getCharIndex(c)] > 0) {
let freq = charToFreq[getCharIndex(c)];
for(let j = 0; j < freq; j++) {
afterString += c;
}
charToFreq[getCharIndex(c)] = 0;
}
}
for(let i = 0; i < T.length; i++) {
let c = T[i];
if(charToFreq[getCharIndex(c)] > 0) {
let freq = charToFreq[getCharIndex(c)];
for(let j = 0; j < freq; j++) {
afterString += c;
}
}
charToFreq[getCharIndex(c)] = 0;
}
return afterString;
};
function getCharIndex(c) {
return c.charCodeAt(0) - 97;
}
|
// eslint-disable-next-line
import React, { Component } from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import AppForm from './forms/AppForm';
class Applied extends Component {
constructor(props) {
super(props);
this.state = {
showComponent: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(prevState => ({
showComponent: !prevState.showComponent
}));
}
render() {
const { data } = this.props;
const aForm = <AppForm />;
const actions = ['Applied','Communications','Denied','Interview','Networking','Offer'];
let actionButton;
var newForm = this.state.showComponent ? <AppForm /> : null;
const listActions = actions.map((action, i) => {
console.log('list each one and I', action);
console.log('list I', i);
return (
<li id={i}>
<RaisedButton onClick={this.handleClick} label={action} />
</li>
)
// return [actionButton, i];
})
console.log('find I', { listActions });
return (
)
}
}
// module.exports = AppForm;
export default Applied;
// <li id="1" >
// <RaisedButton onClick={this.handleClick} label="Applied" />
//
// {newForm}
// </li>
|
jest.mock('@lodgify/fetch-helpers');
jest.mock('../utils/getUrl');
jest.mock('./utils/getAdaptedPath');
jest.mock('./utils/getAdaptedHost');
jest.mock('../utils/setFunctionName');
import {
postJSON,
// eslint-disable-next-line import/named
postJSONReturnValue,
} from '@lodgify/fetch-helpers';
import { ORIGIN } from '../constants';
import { getUrl } from '../utils/getUrl';
import { setFunctionName } from '../utils/setFunctionName';
import { PATHNAME, RESOURCE_NAME } from './constants';
import { getAdaptedHost } from './utils/getAdaptedHost';
import { getAdaptedPath } from './utils/getAdaptedPath';
const { post } = require('./post');
const host = 'someHost';
const path = 'someUrl';
const cookie = 'someCookie';
const URL = 'URL';
const ADAPTED_PATH = 'ADAPTED_PATH';
const ADAPTED_HOST = 'ADAPTED_HOST';
getUrl.mockImplementation(() => URL);
getAdaptedPath.mockImplementation(() => ADAPTED_PATH);
getAdaptedHost.mockImplementation(() => ADAPTED_HOST);
describe(`${PATHNAME}/post`, () => {
beforeAll(() => {
post(host, path, cookie);
});
it('should call `getUrl` with the correct arguments', () => {
expect(getUrl).toHaveBeenCalledWith(ORIGIN, PATHNAME);
});
it('should call `getAdaptedPath` with the correct arguments', () => {
expect(getAdaptedPath).toHaveBeenCalledWith(path);
});
it('should call `getAdaptedHost` with the correct arguments', () => {
expect(getAdaptedHost).toHaveBeenCalledWith(host);
});
it('should call `postJSON` with the correct arguments', () => {
expect(postJSON).toHaveBeenCalledWith(
URL,
{
host: ADAPTED_HOST,
path: ADAPTED_PATH,
},
{
Cookie: cookie,
}
);
});
it('should return whatever `postJSON` returns', () => {
const actual = post();
expect(actual).toBe(postJSONReturnValue);
});
it('should call `setFunctionName` with the right arguments', () => {
expect(setFunctionName).toHaveBeenCalledWith(post, RESOURCE_NAME);
});
});
|
/* eslint-disable class-methods-use-this */
import { View, Text, Button } from 'react-native';
import React from 'react';
import Toast from 'react-native-root-toast';
export default class ToastPlayground extends React.Component {
constructor(props) {
super(props);
this.onPress = this.onPress.bind(this);
}
onPress() {
// Add a Toast on screen.
Toast.show('测试信息', {
duration: Toast.durations.SHORT,
position: Toast.positions.CENTER,
shadow: true,
animation: true,
hideOnPress: true,
delay: 0,
});
}
render() {
return (
<View style={{ flex: 1 }}>
<Text>Toast test</Text>
<Button title="Pressme" onPress={this.onPress} />
</View>
);
}
}
|
var express = require('express');
var route = express.Router();
var passport = require('passport');
var path = require('path');
route.post('/userLogin',
passport.authenticate('local', {
successRedirect: '/#/main',
failureRedirect: '/#/loginFail'
}) // end passport.authenticate
); // end userLogin
module.exports = route;
|
import React from 'react';
import { shallow } from 'enzyme';
import Card from '../Card';
import { mockTossup } from '../../utils/mockData';
describe('Card', () => {
it('should match snapshot', () => {
const wrapper = shallow(<Card {...mockTossup} />);
expect(wrapper).toMatchSnapshot();
});
});
|
{
"class" : "Page::ring::ringpage"
}
|
export default {
beauties: [
{
id: 'CI2lhaFHlm3',
instagram: 'carinalee1105',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/131395236_393878958336083_7893744875791018468_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=bgRwOKOjNrkAX9KzNOm&tp=1&oh=c20faa1cd865b36f6b340e7fee5622fd&oe=602359CD'
]
},
{
id: 'CI14BE-HLHt',
instagram: 'melissasaxxiv',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/131309202_219488809761039_4852130068397171630_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=r1_3Q8fhxIQAX_R78XL&tp=1&oh=e3a46379e42fe08e8db776d1c82650e8&oe=60216105'
]
},
{
id: 'CIxeF2LHfuT',
instagram: 'verakaooo',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/130890848_213935566953142_8133463908173772544_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=epr__j2fkf8AX9Xr04f&tp=1&oh=7ffb295e602bf57616f8298ce1ce34eb&oe=602218AC'
]
},
{
id: 'CIxcyuLnYsF',
instagram: 'b__728ao',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/131009315_226982622352783_1898524146415062367_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=107&_nc_ohc=Wj8hdJRHTFIAX-mlQ7e&tp=1&oh=72d2f62a7790eadb172365b31685aba4&oe=60227759'
]
},
{
id: 'CIxcoGqn-5Z',
instagram: 'yannnnn_9',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/131336012_152145189589501_7128272952715557031_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=SI-pnatIf14AX-3B2AZ&tp=1&oh=095b1b1af150a15ac3ab7242378b565e&oe=6020E97A'
]
},
{
id: 'CIptittn7r-',
instagram: 'peipei___j',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/130442320_164612498691582_4080692155480166718_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=106&_nc_ohc=ZcEurVYpv68AX9d7tvv&tp=1&oh=ec844ab267b9a40e9bfee406a08034b4&oe=6021D36F'
]
},
{
id: 'CIn0VcmH-eT',
instagram: 'kristina6.23',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/130117511_174890051048164_3725753661346970517_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=104&_nc_ohc=lfmGLfe_FqgAX8NnaKb&tp=1&oh=153f8c2fdc4588a50a97d03d9a6d375a&oe=6022FC4E'
]
},
{
id: 'CIkl0_wHLHl',
instagram: '993a9',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/130453120_374293930539024_8636544064152452062_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=100&_nc_ohc=IhdRHHgQHWUAX9X6Ejy&tp=1&oh=192f0848c4314aa8c7854e3ce26f5689&oe=6020A73B'
]
},
{
id: 'CIh_FJhniEe',
instagram: 'tammyxu_1015',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/130423357_190767439377860_3785195638661499445_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=108&_nc_ohc=pvjpwsbfGsEAX8m-_nD&tp=1&oh=e2e6b0df35e63f1fc6d387fdb5971667&oe=6023544B'
]
},
{
id: 'CIfar9ZnIu6',
instagram: 'tsaiyoyo0728',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/129790846_384216276219771_6271027194454684085_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=e0jZxm-IXhAAX-Ltu3t&tp=1&oh=342266677142880d55707297812f9d3d&oe=60221E0D'
]
},
{
id: 'CIfLE4knkdF',
instagram: 'oh_kiyomi',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/130090865_1087469625028833_8599711034213846053_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=109&_nc_ohc=Yvl5oI_lsUMAX_z6pz6&tp=1&oh=3cc58a4cc3e18feb6cbcb69bbb6b3e0a&oe=6021A07B'
]
},
{
id: 'CIadv62n97Y',
instagram: 'jiahsinhsu',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/129048379_437476327245145_7645122037223957206_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=m0EKcOV7mXQAX-_lbuU&tp=1&oh=efd75430e282db45ba59da1e762e828a&oe=602293B9'
]
},
{
id: 'CIXr0jzHd8a',
instagram: 'qoo.kimmy',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/129086906_823661331764362_1245653512683751353_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=pY-7Jk0DZPgAX9Ccmx5&tp=1&oh=c934fbe70df591a0c6e8d8d531011d09&oe=60219E7A'
]
},
{
id: 'CIVHsLNHfK0',
instagram: 'rachellievava',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/128958185_3456311907757847_8362672217021368336_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=AyaDLxEP_uUAX-fZLEZ&tp=1&oh=3b838c13a609dcfe2de63b6962c35be8&oe=60202EF1'
]
},
{
id: 'CISiepmHqdB',
instagram: 'kziiee',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/128467014_131153028591841_6161495877222459235_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=oOX7B4QGPdUAX8_FzKp&tp=1&oh=86dba94c95464ac4929ffe439bf4aada&oe=601FFF73'
]
},
{
id: 'CIP93Enn1sk',
instagram: 'tu1519',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/128271478_2073509589452894_4713776431105007392_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=102&_nc_ohc=On-SsVK5HPcAX8EUttK&tp=1&oh=a17141561ef6fc849ab47b4de8601957&oe=6020157D'
]
},
{
id: 'CINammWnJKc',
instagram: 'angiewan1120',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/127764244_221069509429366_3330904439129549721_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=6uu4kf-s14sAX_Xq04J&tp=1&oh=2dd3aec557d191c21c1eb15c684eabe6&oe=6021B3F5'
]
},
{
id: 'CILILPan8-4',
instagram: 'catherine__0723',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/128049571_418339342523394_7631087936465821398_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=106&_nc_ohc=EnHMWnwrffwAX-oy_Gy&tp=1&oh=e07fc5a510c7943ac61e6d62d5c08307&oe=601F93A6'
]
},
{
id: 'CIIdeQJH8HP',
instagram: '_chore_',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/127609929_293436198669844_649513454305910907_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=104&_nc_ohc=_wWNzQjrxfYAX_ppo-N&tp=1&oh=effcda22c7446745bcc6170e61cadbc2&oe=6021C18F'
]
},
{
id: 'CIFz5rXHfpX',
instagram: 'irennn.e',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/127822893_800826930648043_9001176962434505314_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=107&_nc_ohc=KB-_aCQ8aKcAX8f-LwG&tp=1&oh=f1f070dbd0b9d3d763cf94c6d812d771&oe=601FA3BB'
]
},
{
id: 'CIDNq-ZnfHO',
instagram: 'littlesshine_030',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/127134056_817309589018664_8116980940655278215_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=100&_nc_ohc=k8RW-kUIrH4AX9j-XRw&tp=1&oh=99f9db0556f5b95f8b9b9d23ce1a2313&oe=601FAB2D'
]
},
{
id: 'CICY16FHco4',
instagram: 'flywith_savannah',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/127153892_672744240278998_5210052207068794649_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=skXdXbbjT2wAX902_-L&tp=1&oh=29f71a79d1f66ae83095669734974b33&oe=6020422D'
]
},
{
id: 'CIAnjGLHotM',
instagram: 'yuting0116_a',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/127018710_737618697109871_6312166895299158733_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=MsPWZFF4nAEAX_wzTCq&tp=1&oh=9b54eae9619b8adc78e2ad4d080b8eb0&oe=601FBA25'
]
},
{
id: 'CH98VuNHsdw',
instagram: 'june_night_',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/126858333_732909200671432_4288179092775728596_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=104&_nc_ohc=TYHwk7HOLFgAX_sdvM7&tp=1&oh=9f7d654400191974f114e37d68e3b63f&oe=60205D5E'
]
},
{
id: 'CJumf-mHGH6',
instagram: 'jessica01_20',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/135884890_730627777837766_1707925729520418932_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=102&_nc_ohc=38f3bBnsOnYAX_0pnOd&tp=1&oh=2f97fbf808d330add19c3708db61a8fc&oe=6020F824'
]
},
{
id: 'CJsA2QzHgjT',
instagram: 'pennywu1109',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e15/135107488_1139968643127884_4792623981090132555_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=108&_nc_ohc=z6S_bS-GjC4AX-utq7t&tp=1&oh=39c51429ebfca577fe132d2fbdc22899&oe=602218BB'
]
},
{
id: 'CJph3D-HwrI',
instagram: 'chloee.tw',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/135337215_629557421126313_3375693850875318992_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=109&_nc_ohc=YqkJwhl_kxUAX-aZu9i&tp=1&oh=926f03ca861fce499f557b756b15ef9d&oe=6021EE53'
]
},
{
id: 'CJm99Punf5R',
instagram: 'nicalin0707',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/133852809_823622258485938_371339567555113004_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=106&_nc_ohc=DCCtHKKQEiYAX9rKPLN&tp=1&oh=085e665b0c878818efd3696c9ad9f599&oe=6020A3BB'
]
},
{
id: 'CJcqR6EnZAR',
instagram: 'minge0117',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e15/133926322_401284867966748_5484383274139750733_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=108&_nc_ohc=3P7CqV7IaUQAX_pouj6&tp=1&oh=e011b8fde5d85a77fd16bab4ba17a0b9&oe=6020EFA3'
]
},
{
id: 'CJaomh9Hx7M',
instagram: 'pockydic_akb48teamtp',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e15/133636341_1013956079124581_5876226010831210020_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=105&_nc_ohc=u0IHcINp-S0AX-MuSxq&tp=1&oh=bf3897334733ca9feddb8ac0c79409fa&oe=60231DBD'
]
},
{
id: 'CJXfVm5Hses',
instagram: 'dunn.en',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/133351119_156479965878549_2994966764679096837_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=109&_nc_ohc=QZFnGNo7vn0AX9hxe0z&tp=1&oh=22e3ed2451b644edbd96e4fbe93999b1&oe=60232405'
]
},
{
id: 'CJSQcr-nOAO',
instagram: 'peggykuo1123',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e15/132654836_419220089254996_3688642407840149558_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=104&_nc_ohc=3n2DwuL9LOgAX9FWbQt&tp=1&oh=155cc9fc97baa02a4128e2a87b5b9278&oe=6020E867'
]
},
{
id: 'CJPuJ3aHc-n',
instagram: 'deskycutie',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/132596344_872141643612657_3720009826461557836_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=109&_nc_ohc=rtWQMVtcpskAX-j0Nw5&tp=1&oh=77700ca7d1ab570f314ec94743f84c60&oe=6021E3C6'
]
},
{
id: 'CJKoqyFnVij',
instagram: '_54.ccc',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/s1080x1080/132206366_1291824977861959_2772124189114908809_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=107&_nc_ohc=O7Zq4mgVoZ4AX9Q8Cpr&tp=1&oh=a434c6196ab783324443550b60d78f88&oe=60228662'
]
},
{
id: 'CJIEhRQnH0w',
instagram: 'cynthia_514',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/132267301_175300384279191_1244592491726147229_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=RZIYZogPy-8AX8RAy0y&tp=1&oh=de6e88714375ad0dfb7f3d027b49d607&oe=6021A553'
]
},
{
id: 'CJFgUcoHwIQ',
instagram: 'the_elainetone',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/132202409_403975927367283_3559748591233476706_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=ZfkrZ4KkVGYAX8alzdF&tp=1&oh=50becfa3f0d545f9127194819524fc68&oe=60214680'
]
},
{
id: 'CJC6NcMnLcH',
instagram: '8.15jm',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e15/132016962_117446643560856_6555069295885094810_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=100&_nc_ohc=i0E5OzGpT14AX_p21gG&tp=1&oh=66c9383ab9a3a979c38f52df24413a76&oe=602151AA'
]
},
{
id: 'CJANvV6nZQe',
instagram: 'deskycutie',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/131020258_828395484620643_7394351802207796983_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=ZKqXmAV-L1IAX8Xy61Z&tp=1&oh=66c896b3d50eb0cf408543551db1a712&oe=602272AC'
]
},
{
id: 'CI4xpEzHJuD',
instagram: 'yyururu',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/131466509_425468042006035_7133872638537789351_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=107&_nc_ohc=sOJGQcKS2x8AX84ikAb&tp=1&oh=4c7eb7e287612982d9aaa2f2335e3ac4&oe=6021376C'
]
},
{
id: 'CI4a07HnAuz',
instagram: 'capital.lanlan',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/131372816_2507699596043107_459778379000970814_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=107&_nc_ohc=LaLdRpsDfCIAX8zE_Be&tp=1&oh=da748f1a1963cf0d6e6325deeb7698b4&oe=602069C5'
]
},
{
id: 'CI1_hr6HGdh',
instagram: 'meimeilcc',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/131424210_306861033908000_5462833634931230564_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=108&_nc_ohc=4xjnvmodDHUAX-yqcAT&tp=1&oh=50630fbee2ceac0478a3047d98aa7962&oe=6021C7BB'
]
},
{
id: 'CIzcbLUHhF9',
instagram: 'yuyuchang.c',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/131055172_1111017839356141_7820670153278513135_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=IETP7gDOlc8AX_xhI1w&tp=1&oh=e5121836e3f758ac0b346ba6be8edffb&oe=602059DD'
]
},
{
id: 'CIxx27Fnmp3',
instagram: 'hou_queenie',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e15/130877279_134690831783003_938626262275690821_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=HU-8lRCwkDQAX_S6jRz&tp=1&oh=ed7343e6ea2b516d668a12966f9f08be&oe=602228C4'
]
},
{
id: 'CIwzoa9HfTr',
instagram: 'antien_cheng',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/131036170_194463718986892_1180680092351964811_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=104&_nc_ohc=XoM0QNWyW18AX9SpH5J&tp=1&oh=125035002eb3528df4efd7b5a6c91457&oe=60226D02'
]
},
{
id: 'CIuHqEBH5B-',
instagram: 'lsfbbaoa2.0',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e15/130943784_381287156309662_312790952841753962_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=1s9Xs5CU7HYAX8zYatE&tp=1&oh=ae393b668ce9e670145673ce96e95a6f&oe=601F60CF'
]
},
{
id: 'CIm43ygHpbG',
instagram: 'jenny0704199',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e15/130162332_690739481624113_6048638809375103325_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=Uwitpgl9HQIAX-aWNIE&tp=1&oh=6acacd9fa2dcfad95ab79bbd0741317a&oe=6020AE0E'
]
},
{
id: 'CImi6iIHVWg',
instagram: 'capital.lanlan',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e15/130155346_688234362081965_8342615084085197617_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=105&_nc_ohc=uW-VWsDcKGAAX8eL-US&tp=1&oh=28dab126f22545ef4441efef1fc9a6e9&oe=601FE585'
]
},
{
id: 'CIj9aUrnzos',
instagram: 'u_ting221',
images: [
'https://instagram.ftpe12-1.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/129745327_665427261003150_1268165138661069468_n.jpg?_nc_ht=instagram.ftpe12-1.fna.fbcdn.net&_nc_cat=106&_nc_ohc=sAKnMsQHPsQAX-mWsuK&tp=1&oh=773dc84cd3a4a6438740285a631b2fc7&oe=6020C9E6'
]
},
{
id: 'CKBucZnHhoU',
instagram: 'mini147.5',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e15/138414003_1090370548094764_7318856630137797737_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=104&_nc_ohc=gdpvrqQwuIMAX-Y0QpD&tp=1&oh=d83f6a6b4d183dfc60d3a51645ca8dce&oe=602B95B8'
]
},
{
id: 'CJ-KZPTHGd7',
instagram: 'personal_trainer_julia',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/137545781_216947866716134_8285783843389395284_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=102&_nc_ohc=V4U5_h7IuXoAX9ijUqU&tp=1&oh=b0bb232e786cd337a4794bc15305f07d&oe=602AA7C7'
]
},
{
id: 'CJ7kik2HsSv',
instagram: 'tsukiyina',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e15/137080871_424259968991816_6505743751864672553_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=108&_nc_ohc=7A05HCIAEjoAX_b6xMs&tp=1&oh=73fb39503e7e52846bca1ef18ab502eb&oe=602C96D2'
]
},
{
id: 'CJ4_m1Un6ie',
instagram: 'hi_0______0',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e15/136735868_109464204424383_1355707357510184993_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=103&_nc_ohc=c2Bs8JeAgv4AX_J_Jah&tp=1&oh=88d1d5d4aaced30ed728d5d9e1cb10e5&oe=602BEC0F'
]
},
{
id: 'CJ3jTIMnI7G',
instagram: 'nicalin0707',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e15/137628505_400995190976314_7416677783481599082_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=T9BxIguMlD8AX-4dw3e&tp=1&oh=89eba653cf1928b4488eb78519f3a6f0&oe=602B10C9'
]
},
{
id: 'CJ2TvHDngDo',
instagram: 'irachen',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/136986455_1298665463832275_6539538473832272117_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=-rFHynVxt3QAX-GXppW&tp=1&oh=db4472ad521589a5494a4e634f3815ef&oe=602B70D9'
]
},
{
id: 'CKiIrmtHPBf',
instagram: 'wen.ting.7',
images: [
'https://instagram.ftpe7-1.fna.fbcdn.net/v/t51.2885-15/e15/143257740_2881084452148584_5473615402911509684_n.jpg?_nc_ht=instagram.ftpe7-1.fna.fbcdn.net&_nc_cat=100&_nc_ohc=-Id52-WJp4oAX9_FB6j&tp=1&oh=d04fd15c0b4cba5285dfefd653cff1ab&oe=60393E91'
]
},
{
id: 'CKfnS1znhqb',
instagram: 'miss.serene',
images: [
'https://instagram.ftpe7-1.fna.fbcdn.net/v/t51.2885-15/e15/141949735_3621822404598822_7927923040863796835_n.jpg?_nc_ht=instagram.ftpe7-1.fna.fbcdn.net&_nc_cat=106&_nc_ohc=A-jZk9ZQu4cAX-TDrjf&tp=1&oh=65b5fc71780751fa39af2396c501a93c&oe=603A66B5'
]
},
{
id: 'CKdAbYgnFLf',
instagram: 'betty030303',
images: [
'https://instagram.ftpe7-4.fna.fbcdn.net/v/t51.2885-15/e35/s1080x1080/141876108_167009111547043_5157093949390866564_n.jpg?_nc_ht=instagram.ftpe7-4.fna.fbcdn.net&_nc_cat=107&_nc_ohc=zpw4KGps_M8AX9dnZcO&tp=1&oh=f94a29292aa59798d68fb764e47cbcc8&oe=603B0EFB'
]
},
{
id: 'CKSvOjQnuON',
instagram: 'lin820713',
images: [
'https://instagram.ftpe7-4.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/140092935_444782416678229_7261730522166238753_n.jpg?_nc_ht=instagram.ftpe7-4.fna.fbcdn.net&_nc_cat=105&_nc_ohc=jciz6yMyjdMAX_AmSu0&tp=1&oh=1f3545ad8477c0b2aea8a1470b935adf&oe=603C8792'
]
},
{
id: 'CKQK8TGnRXq',
instagram: 'darapxx',
images: [
'https://instagram.ftpe7-2.fna.fbcdn.net/v/t51.2885-15/fr/e15/s1080x1080/139474956_191132006098773_4877471230067240334_n.jpg?_nc_ht=instagram.ftpe7-2.fna.fbcdn.net&_nc_cat=109&_nc_ohc=m9YdzYPU_rEAX_6zcPp&tp=1&oh=64cfc1f7f9aab179bfc8f854cd967494&oe=603A0765'
]
},
{
id: 'CKNlf98nov1',
instagram: 'miag778',
images: [
'https://instagram.ftpe7-1.fna.fbcdn.net/v/t51.2885-15/e15/139541746_513911432912040_9057590702510872606_n.jpg?_nc_ht=instagram.ftpe7-1.fna.fbcdn.net&_nc_cat=100&_nc_ohc=SZeNuHQTSlEAX99GnD6&tp=1&oh=1ed67fef830b31e161934aa4999b603f&oe=603A2731'
]
},
{
id: 'CKI21UInFUc',
instagram: 'hi_0______0',
images: [
'https://instagram.ftpe7-4.fna.fbcdn.net/v/t51.2885-15/e15/139213774_1288589538244493_8412186148845875960_n.jpg?_nc_ht=instagram.ftpe7-4.fna.fbcdn.net&_nc_cat=105&_nc_ohc=BAsoUCEz9U0AX-UJAfi&tp=1&oh=6ca69e8199e3fd042227f62b589e7c94&oe=603A9700'
]
},
{
id: 'CKgSMfbHrlZ',
instagram: 'ikeeeea1993',
images: [
'https://instagram.ftpe7-2.fna.fbcdn.net/v/t51.2885-15/e35/141866649_687989075201219_8533202341832518388_n.jpg?_nc_ht=instagram.ftpe7-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=8FRGlYuRsRcAX_cuFDo&tp=1&oh=a10bab10a88e883237c29bb886794f3f&oe=603B4108'
]
},
{
id: 'CKgNLE-nldj',
instagram: 'yangrjo',
images: [
'https://instagram.ftpe7-2.fna.fbcdn.net/v/t51.2885-15/e35/s1080x1080/142221587_419179486069564_4113257446622648800_n.jpg?_nc_ht=instagram.ftpe7-2.fna.fbcdn.net&_nc_cat=104&_nc_ohc=X8dJjrTz5bMAX89IxJ4&tp=1&oh=81e0627f88bfee29a2353e171b7f82ae&oe=603CA7E4'
]
},
{
id: 'CKd7bB5HdT6',
instagram: 'zoelin0107',
images: [
'https://instagram.ftpe7-4.fna.fbcdn.net/v/t51.2885-15/e35/s1080x1080/141815036_135492455057725_4067842344477815857_n.jpg?_nc_ht=instagram.ftpe7-4.fna.fbcdn.net&_nc_cat=101&_nc_ohc=hU7bsD0z2vQAX_he2Hd&tp=1&oh=39edcb4920eded0f253d80a6190a270d&oe=603AB0FC'
]
},
{
id: 'CKdr74bn7Fy',
instagram: 'vivimimi087029',
images: [
'https://instagram.ftpe7-1.fna.fbcdn.net/v/t51.2885-15/e35/141406162_241047884065656_945787305976591349_n.jpg?_nc_ht=instagram.ftpe7-1.fna.fbcdn.net&_nc_cat=100&_nc_ohc=oPbdNdzP5vMAX-eweKF&tp=1&oh=6a6a9746686903d82f5d28c2c0ac7488&oe=6038D886'
]
},
{
id: 'CKWMYn6npY9',
instagram: 'qq_0604',
images: [
'https://instagram.ftpe7-2.fna.fbcdn.net/v/t51.2885-15/e35/140544808_680612232626339_1884126133257480859_n.jpg?_nc_ht=instagram.ftpe7-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=xbLC0TgEQMAAX9hSMQe&tp=1&oh=5573caf3fce87a30d90fe7cfee8dee4e&oe=60393EF8'
]
},
{
id: 'CKV91ApnZ8E',
instagram: 'woah_jeean',
images: [
'https://instagram.ftpe7-1.fna.fbcdn.net/v/t51.2885-15/e35/140628837_151456946622720_9120669264509304705_n.jpg?_nc_ht=instagram.ftpe7-1.fna.fbcdn.net&_nc_cat=100&_nc_ohc=T4KIZSiGVlAAX-KohfQ&tp=1&oh=43d5bb3e20e09cae92374aa57297c92c&oe=603BDB38'
]
},
{
id: 'CKTVf5hH7lH',
instagram: 'simplelife._.li',
images: [
'https://instagram.ftpe7-4.fna.fbcdn.net/v/t51.2885-15/e35/s1080x1080/140508623_2744954725818301_385999937032316596_n.jpg?_nc_ht=instagram.ftpe7-4.fna.fbcdn.net&_nc_cat=101&_nc_ohc=Ar0K9vY0SKgAX-r7B1u&tp=1&oh=1e459ab1915b8d811ac56dfec26914f9&oe=603A7D71'
]
},
{
id: 'CKk2PTinSoG',
instagram: 'ettolrahc1998',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/143259884_1026273447862987_934139628253002737_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=Gh8W-1QfP6YAX87DOAB&tp=1&oh=e7e57b2fbccd3c662c89bb245a5811ff&oe=603D50AD'
]
},
{
id: 'CKjW7MPnbOF',
instagram: 'hsuxx219',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/143424761_433846961190847_9029307354299769597_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=GIhZZJVGZvYAX_6yj9P&tp=1&oh=ad4378eb7c05ef2617377f7db00a97d4&oe=603D4F3F'
]
},
{
id: 'CKiPnuBrefE',
instagram: 'yuan_0705_',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/142596787_434852120969581_5504195229637312276_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=5DOT2VK7DpgAX8In2Cc&tp=1&oh=c2428be64df53b2b7761e91a73557b66&oe=603E2BF8'
]
},
{
id: 'CKgvhT1LZ2n',
instagram: 'u.u_121',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/142400454_733577937530812_4081742495366352268_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=104&_nc_ohc=Yfce0hfNwqAAX8gQxoF&tp=1&oh=e0086d95b69c50e5c314665665eac31d&oe=603DAEBF'
]
},
{
id: 'CKfnbM8oOyz',
instagram: 'min0926',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/141997127_882328879199534_2166040374237443276_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=102&_nc_ohc=AF4TOfkOCmcAX_wIFJM&tp=1&oh=24be8e2b6c775294e105d91590c42f49&oe=603D52D7'
]
},
{
id: 'CKeRlxOL43g',
instagram: 'littlesshine_haruko',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/141859814_3543825119049060_6255132975403039691_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=100&_nc_ohc=Ef1pyEsieN8AX9emCnd&tp=1&oh=d63ab19a2b152bdd21a33171fc6f6803&oe=603ECC8D'
]
},
{
id: 'CKbzMfhHIvq',
instagram: 'qaws_1109',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/141379429_228301848776939_3059417474077427039_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=OaldCl4UYG4AX8O7xT8&tp=1&oh=f73c77dd6195e8bffc6242424c6ac1e1&oe=603E00FD'
]
},
{
id: 'CKbQ_G3HFOm',
instagram: 'wdj_530',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/140980880_403560457605365_3067137438458160998_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=KekzNsTb0rsAX9P-N-l&tp=1&oh=0990deb68ddb19ce2c8280cd452c9dd3&oe=603F5FD4'
]
},
{
id: 'CKZqNZ4noUc',
instagram: 'nenetvt',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/141276968_168232704727470_4817344337504546639_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=106&_nc_ohc=7U_0o45yvdgAX8_uVRO&tp=1&oh=122c204f0775bc34bb8c883f83bd0889&oe=603C7D42'
]
},
{
id: 'CKXxImdHFKU',
instagram: 'amy.amycheng',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/140849219_843887819786524_4978241119185803330_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=104&_nc_ohc=TMrZx2g3FRcAX_ve_G4&tp=1&oh=8e3a4a1761b7cfc43af9a13e96a293d7&oe=603C964B'
]
},
{
id: 'CKVZzQ2HH99',
instagram: 'pyingtan',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/139765566_486992252290220_3271848971506515713_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=108&_nc_ohc=C_MgAwCa6KsAX9iaNTY&tp=1&oh=f15e8e9a7dfd37c50d9ec26e539a1c7e&oe=603C41B5'
]
},
{
id: 'CKUCH3KnSpY',
instagram: 'liu_yu_chiao',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/140657234_1161786340922933_3059797130023396131_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=z7RM7z5_LEYAX-acjx8&tp=1&oh=aea16acfcae8bbb4dba4b933eeb1a4fc&oe=603B8BF0'
]
},
{
id: 'CKTK5mggXYu',
instagram: 'wen_821018',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/141070367_827539844771299_7739641074673666804_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=7lFdTCNCmVMAX8fhM7k&tp=1&oh=89f6ec9eaf09dda0af62c53f6265a97c&oe=603E33C7'
]
},
{
id: 'CKShsO1LULf',
instagram: 'conancream',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/140325199_316943186409387_1538149808689455268_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=103&_nc_ohc=rDmf-UsL358AX_6pn0r&tp=1&oh=4495efbc9592761d9e644cf99d6a6495&oe=603D5C56'
]
},
{
id: 'CKQP4QWHklE',
instagram: 'unalo0125',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/139772575_819121405535522_8665323381230766899_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=102&_nc_ohc=kEfniqCuinQAX8P7lKu&tp=1&oh=975fda4be754cd7b9a7e0fb2cc09b259&oe=603CCBCC'
]
},
{
id: 'CKPIkD-rPQV',
instagram: 'only_____won',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/139979885_1408357656184828_227807228763407145_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=104&_nc_ohc=3RkJD-97o-YAX_LhIbD&tp=1&oh=246de160e35a9691435843e3b8a45582&oe=603DA8DE'
]
},
{
id: 'CKNtGALnV3V',
instagram: 'miyo_7890',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/140868549_246428117006545_1092270662510940174_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=WM5VELfQa7UAX9waOqP&tp=1&oh=b7db9b775468b6db57f229a5e6613228&oe=603E946B'
]
},
{
id: 'CKMD2SunsEV',
instagram: 'meimeilcc',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/139465988_3413530978755306_1668597055117399947_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=106&_nc_ohc=0SNJ9Sn0Qk0AX86wzDZ&tp=1&oh=13a8468575b41b21da7d444922b3405a&oe=603EBEE5'
]
},
{
id: 'CKLLa90H9kL',
instagram: 'borusushi',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/139404723_259258585562054_8287386156623742993_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=102&_nc_ohc=dNYsA3dsCM8AX8TdEOo&tp=1&oh=7aa46a1478304c002999103c26509788&oe=603CCA3F'
]
},
{
id: 'CKJnAvln-Q0',
instagram: 'yunshi_1208',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/139147124_313839153381180_8716244317557887069_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=100&_nc_ohc=1IrMwNiFuFkAX_6prfq&tp=1&oh=6707c897f0bbded3e20fd890cf916116&oe=603D34D1'
]
},
{
id: 'CKIfshGnha7',
instagram: 'modd.ph',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/139095362_3883943121650956_4713920638288436854_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=104&_nc_ohc=o1wYlgJIFlkAX-U3_My&tp=1&oh=dd8603fa1f157bfdf709fbb2421c901c&oe=603D1BA9'
]
},
{
id: 'CKdvsBsHDDY',
instagram: 'rain_clean_',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/s1080x1080/142448783_1804201486407559_5616790655490055257_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=td-Xz90ow4gAX_HNlK0&tp=1&oh=a401024dcc1e47c2fed1a022786519f8&oe=603EB6C6'
]
},
{
id: 'CHhz1UhHnnT',
instagram: 'z_fk_z',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/124982909_2422870061354124_1904458591425407297_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=100&_nc_ohc=DPuX5rk8yPkAX-m794-&tp=1&oh=41c3dba8df1c7b3295384f89a8f3a77d&oe=603B7F15'
]
},
{
id: 'CHfTzlLBFFI',
instagram: 'janice.koh',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/124415295_1015655515526619_4158327052753992756_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=103&_nc_ohc=wH-yI7aE8wMAX95g-4A&tp=1&oh=4bed0e136b6b5fbb41f4b25f79ab9b7e&oe=603CC8D1'
]
},
{
id: 'CHZJCFynqIK',
instagram: '_momo_ching',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/124104439_2807050009621713_6220703178027609253_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=109&_nc_ohc=RYjIpALr75AAX_ShF0B&tp=1&oh=65260fa547cdba88e01b3ee32afc05cc&oe=603D719F'
]
},
{
id: 'CHWl-tcHAwt',
instagram: 'huang_0929',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/124128506_4118902884792596_2441064164811532755_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=108&_nc_ohc=u3MwoIEkhKAAX-G7Hfh&tp=1&oh=9c50d611316540c69239fcc43f17c579&oe=603D8C58'
]
},
{
id: 'CHPy6RFnPBt',
instagram: 'zzz1504ling',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/123547483_3502320613219927_2222317941312725722_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=hAugRtUXsREAX8rVsms&tp=1&oh=7d387215fff3402d34b52ae5d399da34&oe=603C5CB8'
]
},
{
id: 'CHM2N5nHDTj',
instagram: 'yanwen.jane',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/123807783_2767579950235895_2044946353513752887_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=qcgACspFr_MAX_oycqW&tp=1&oh=1ea6595ce109cb129438d100e2474e9c&oe=603C1129'
]
},
{
id: 'CHIKEePn943',
instagram: 'fangru_0603',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/123480873_158170839303449_5602064225189688044_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=HNbSQ4QYXXUAX9Ltivs&tp=1&oh=b3eb4745cf05b1447aa92244f47230ba&oe=603E6A7E'
]
},
{
id: 'CHFSfzrHLcP',
instagram: 'chna.y',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/123372737_395887778234033_2143223601340838948_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=WnDt66PiqaoAX8FF8sA&tp=1&oh=d26ccd42ecb70989908c71440a9c0a24&oe=603BC15A'
]
},
{
id: 'CG_hxZznU8c',
instagram: 'leeesovely',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/123132077_993337657828571_6129399386902827617_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=Wd1HircCzmAAX_K1dJ1&tp=1&oh=2418eba50a0933eed6a928f95e1aecee&oe=603DC554'
]
},
{
id: 'CG7Gqxcn6tp',
instagram: 'yo_jie_629',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/123036742_231013391689003_8484813767200032527_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=r1t6h3oLsrsAX895Fsg&tp=1&oh=baf0d5e9f84764d47bf31a639da22df7&oe=603E408F'
]
},
{
id: 'CG4MMbxHjwS',
instagram: 'mini.ari',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/123119246_429552154726760_1948683555428396590_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=108&_nc_ohc=hYe3Pdga-toAX-npWMU&tp=1&oh=b722eec3a1fdefa9e7722eec9b9df675&oe=603DFE23'
]
},
{
id: 'CG1NiUzn8Vb',
instagram: 'meon0613',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/122938151_362329888304623_1492153224297627161_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=7ypRlN0QFrgAX-JORtI&tp=1&oh=8b9e3f41352a9fc32ab8bc491296bec9&oe=603C8EA1'
]
},
{
id: 'CGyoI5cHLeD',
instagram: 'sosamy520369',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/122750671_355382622468401_2510027519400235715_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=EXwy9UsaI3MAX9AhUDy&tp=1&oh=a7d6843f27c0c0704e252a7ac7fba62b&oe=603EAD34'
]
},
{
id: 'CGpDbvUHGMd',
instagram: 'meon0613',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/122087533_191255582569447_5746449034042491800_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=6zMbs6c3Z1gAX-OmA9n&tp=1&oh=004fc61c9e729f601882f2d0236a3613&oe=603EA34D'
]
},
{
id: 'CGmcB9yHv01',
instagram: 'lebaby0v0',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/121485468_667796774105641_1131589444315687796_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=jv-Gi0b-rjcAX_R7S3Y&tp=1&oh=696eb3cc068d0ee36463f7421d897402&oe=603D47F1'
]
},
{
id: 'CGj-FSgnVNa',
instagram: 'miss01todai2020',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/122127410_227177012073398_5304038772878723361_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=102&_nc_ohc=37sWnVAYjPkAX-Y_ZEH&tp=1&oh=5b5b2815f9fea4e1feb32a6358ea2d9d&oe=603EC158'
]
},
{
id: 'CGhEj-9nFFM',
instagram: 'kikuchanj',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/121966734_1516818571860447_4443241391595084617_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=103&_nc_ohc=F7t7FSQ2TNsAX_wF7Aw&tp=1&oh=74fed108015cc36c5ab855d8cc804394&oe=603CA932'
]
},
{
id: 'CGbmG1vndEi',
instagram: 'munkawchaosgirl',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/121589018_175677427501801_1567392489031411272_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=Kz0lYqpsGScAX_ZUoAf&tp=1&oh=e0b37f872d17851b56d3b3b2eef174ce&oe=603F5DF5'
]
},
{
id: 'CGY3OnjnwO_',
instagram: 'bominism71',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/121638286_349249849525553_8329292296267890802_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=K70ATmOFmL8AX8YqnlU&tp=1&oh=ca569ec4d6c5376fa5c4bb8feecac821&oe=603C5F2B'
]
},
{
id: 'CGWVDwuHPav',
instagram: 'xxmm0911',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/121663926_345059303449642_8391907067368184730_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=WWIYmnon_loAX9fpnb8&tp=1&oh=94ee1fb78f2c9adc008bd9151caae616&oe=603E10AB'
]
},
{
id: 'CKtkRTJnOSn',
instagram: 'kairin_1010',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/145143833_867762287128282_7723958521903631311_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=y0LwcIZMtowAX9wn1tf&tp=1&oh=0e99a9bda407ffd24b36eb5bdacd585e&oe=603F49FF'
]
},
{
id: 'CKso_JVnqA0',
instagram: 'xiangling_c',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/143804160_109039544515081_8151235049278013781_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=PSIe0b18iZ8AX-fmrAp&tp=1&oh=28addf16ba19005299fe87eb9f960e82&oe=6043019D',
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/143956997_446825609853041_8075681272692228175_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=IMJIk47TDyYAX8k8uWG&tp=1&oh=3b39290a9590c49c22b5f6fe81b6e615&oe=60429F0C'
]
},
{
id: 'CKqshH9HvQA',
instagram: 'irachen',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/143345514_882251332590845_7376133769673994365_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=hzTgH70AE_gAX-E-XSY&tp=1&oh=9538a57eb4f93de754bf76cbcd275ab8&oe=60429C24',
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/143818057_102546881766157_8142609401842239356_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=NrV1h12h5gUAX9DjKY8&tp=1&oh=4def3fb064ad2f73f689d89cdb5a2453&oe=603F5270'
]
},
{
id: 'CKqYJlvHLrl',
instagram: 'kellygirlchen',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/143341899_2579020429058111_1343773441000627886_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=ksCp9F_T2GIAX-VI16H&tp=1&oh=33cd943ce5280d4a10c9d060c80bdbf9&oe=6040EE88',
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/144185166_238255871141924_3866183948112732407_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=108&_nc_ohc=yOKWHydG4iIAX9z7c-2&tp=1&oh=6d45bf3adc1f89ec481fccecf8bf6ca5&oe=6040434B'
]
},
{
id: 'CKp7nTCn0B6',
instagram: 'kiki_hsieh',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/144308905_458007735561432_8354222187759227460_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=100&_nc_ohc=wyWf9jalE2kAX93W6y_&tp=1&oh=ef3a77ece8f5a3de545452a579a24aa6&oe=6040ED35'
]
},
{
id: 'CKoQvVLHDbF',
instagram: 'shark_same',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/143151219_416265589482063_6209783347781304041_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=103&_nc_ohc=7u0qu98z8QYAX8G4uWd&tp=1&oh=d94c3dfad985c7fc3bb2006ed89fc0ef&oe=603F1F52',
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/143849588_2061840627450752_7194907697431127846_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=108&_nc_ohc=QnMcZTsarbAAX93015z&tp=1&oh=4f7ce052f72b808fb6a301046932eb79&oe=603F3A37'
]
},
{
id: 'CKnsZIznbLg',
instagram: 'tianzaige',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/144140571_426855301851562_4431606568615668649_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=110&_nc_ohc=xygSOL1hRlQAX8sY0MK&tp=1&oh=9c7240f1443d354ea524846ea612d86f&oe=603F9AFE'
]
},
{
id: 'CKnVt8Ony3h',
instagram: 'kiwi.322',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/142948823_212612997227920_9204408524863847559_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=104&_nc_ohc=XSVYS4JLKu8AX_AhzoN&tp=1&oh=1c4a428e6bddb059fc7ef39ba83e1bb8&oe=603F6555',
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/144319097_455860162439450_4135307016357242798_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=102&_nc_ohc=uZcJS58KxX8AX92DnWO&tp=1&oh=b9d69970da660cd3aec7ef0d3c995bd1&oe=6040022C'
]
},
{
id: 'CKla3u7nQLD',
instagram: 'bitnara1105',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/142987167_799553347267227_3676892856149732736_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=103&_nc_ohc=mGsYYuj4E7sAX939Wjz&tp=1&oh=69a0796fc42bcd87926830ee7b901b51&oe=604305E6',
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/142857249_171820880998052_8227775107685471085_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=108&_nc_ohc=wUmqh3rRNiYAX8KdUsO&tp=1&oh=64d5743e5a85738725c2e9470cd10e72&oe=604259A3'
]
},
{
id: 'CKk1gNGH7FT',
instagram: 'cr_renee24',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/142777861_863362707561966_1852075770153836567_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=106&_nc_ohc=Q9WCH1j6_XsAX9104b_&tp=1&oh=a58be75e6d78efdc2e18ac1dedee254f&oe=603F836D',
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/143438388_2056272357849179_8096923885492878097_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=111&_nc_ohc=9YNctaoMPqIAX9LGvpC&tp=1&oh=be5e34f8e08835aab462065f0be194c8&oe=6040B15F'
]
},
{
id: 'CKjEVWpH26_',
instagram: 'annacheng.1219',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/142590011_460904028399865_3042236443484425631_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=101&_nc_ohc=KubWCrKOYHAAX_lTHS7&tp=1&oh=3207de404bf3130c30f0647d55bf531a&oe=603F9541'
]
},
{
id: 'CBC7S54pCl5',
instagram: 'x___e',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/101548691_282774576196097_3328162201522291064_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=105&_nc_ohc=dRaMDdn35C0AX-vSFKg&tp=1&oh=92f347e094262d072738b80cd9f15c1c&oe=6040C7EC'
]
},
{
id: 'CIfwJyunkfo',
instagram: 'pinklady0119',
images: [
'https://instagram.ftpe12-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/128425912_951342942062875_2785928208644485832_n.jpg?_nc_ht=instagram.ftpe12-2.fna.fbcdn.net&_nc_cat=107&_nc_ohc=P_rWOnxjJ0MAX9JfnLY&tp=1&oh=cb90d05f7bc60f1187344831470d615f&oe=60401C2E'
]
}
]
}
|
import React from "react";
import { shallow } from "enzyme";
import { requestPasswordReset } from "../../../apiCalls/auth/requestPasswordResetActions";
jest.mock("../../../apiCalls/auth/requestPasswordResetActions");
import {
REQUESTPASSWORDRESET_ERROR_MESSAGE,
REQUESTPASSWORDRESET_SUCCESS_MESSAGE
} from "../../../constants";
import { RequestPasswordResetCt } from "../../auth/RequestPasswordResetContainer";
describe("RequestPasswordResetContainer handleRequestPasswordReset", () => {
let wrapper;
const email = "test_email@email.com";
beforeEach(() => {
wrapper = shallow(
<RequestPasswordResetCt
values={{ email }}
setSubmitting={jest.fn()}
resetForm={jest.fn()}
/>
);
});
it("sets the state of success_message after succesful fetch", async () => {
expect.assertions(2);
await wrapper
.instance()
.handleRequestPasswordReset({ preventDefault: jest.fn() });
expect(wrapper.state().success_message).toBe(
REQUESTPASSWORDRESET_SUCCESS_MESSAGE
);
expect(wrapper.state().err).toBeNull();
});
it("calls registerAction with the correct parameters", async () => {
expect.assertions(1);
await wrapper
.instance()
.handleRequestPasswordReset({ preventDefault: jest.fn() });
expect(requestPasswordReset).toHaveBeenCalledWith(email);
});
it("sets the state of err to Error after erroneous fetch", async () => {
expect.assertions(2);
await wrapper
.instance()
.handleRequestPasswordReset({ preventDefault: jest.fn() });
expect(wrapper.state().err.message).toBe(
REQUESTPASSWORDRESET_ERROR_MESSAGE
);
expect(wrapper.state().success_message).toBe("");
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.