text stringlengths 7 3.69M |
|---|
/*jslint browser: true, undef: true, white: false, laxbreak: true *//*global Ext, MyRetirement, MyRetirementRemote*/
Ext.define('MyRetirement.view.DataPanel', {
extend: 'Ext.panel.Panel'
,xtype: 'datapanel'
,requires: [
'Jarvus.layout.container.Raw'
]
,layout: 'raw'
,componentCls: 'data-panel'
,bodyCls: 'data-panel-body'
}); |
// @flow
import * as React from 'react';
import classNames from 'classnames';
import _ from 'lodash';
import InputAutosize from './InputAutosize';
import { getWidth } from 'dom-lib';
import {
reactToString,
filterNodesOfTree,
findNodeOfTree,
shallowEqual
} from 'rsuite-utils/lib/utils';
import {
defaultProps,
prefix,
getUnhandledProps,
createChainedFunction,
tplTransform,
getDataGroupBy
} from '../utils';
import {
DropdownMenu,
DropdownMenuItem,
DropdownMenuCheckItem,
getToggleWrapperClassName,
onMenuKeyDown,
PickerToggle,
MenuWrapper,
PickerToggleTrigger
} from '../_picker';
import InputSearch from './InputSearch';
import Tag from '../Tag';
import type { Placement } from '../utils/TypeDefinition';
type DefaultEvent = SyntheticEvent<*>;
type DefaultEventFunction = (event: DefaultEvent) => void;
type Props = {
data: any[],
cacheData?: any[],
locale: Object,
classPrefix?: string,
className?: string,
container?: HTMLElement | (() => HTMLElement),
containerPadding?: number,
block?: boolean,
toggleComponentClass?: React.ElementType,
menuClassName?: string,
menuStyle?: Object,
menuAutoWidth?: boolean,
disabled?: boolean,
disabledItemValues?: any[],
maxHeight?: number,
valueKey: string,
labelKey: string,
value?: any | any[],
defaultValue?: any | any[],
renderMenu?: (menu: React.Node) => React.Node,
renderMenuItem?: (itemLabel: React.Node, item: Object) => React.Node,
renderMenuGroup?: (title: React.Node, item: Object) => React.Node,
renderValue?: (value: any, item: Object, selectedElement: React.Node) => React.Node,
renderExtraFooter?: () => React.Node,
onChange?: (value: any, event: DefaultEvent) => void,
onSelect?: (value: any, item: Object, event: DefaultEvent) => void,
onGroupTitleClick?: DefaultEventFunction,
onSearch?: (searchKeyword: string, event: DefaultEvent) => void,
onClean?: (event: DefaultEvent) => void,
onOpen?: () => void,
onClose?: () => void,
onHide?: () => void,
onEnter?: () => void,
onEntering?: () => void,
onEntered?: () => void,
onExit?: () => void,
onExiting?: () => void,
onExited?: () => void,
/**
* group by key in `data`
*/
groupBy?: any,
sort?: (isGroup: boolean) => (a: any, b: any) => number,
placeholder?: React.Node,
searchable?: boolean,
cleanable?: boolean,
open?: boolean,
defaultOpen?: boolean,
placement?: Placement,
style?: Object,
creatable?: boolean,
multi?: boolean
};
type State = {
data?: any[],
value?: any | any[],
// Used to focus the active item when trigger `onKeydown`
focusItemValue?: any,
searchKeyword: string,
open?: boolean,
newData: any[],
maxWidth: number
};
class Dropdown extends React.Component<Props, State> {
static defaultProps = {
data: [],
cacheData: [],
disabledItemValues: [],
maxHeight: 320,
valueKey: 'value',
labelKey: 'label',
locale: {
placeholder: 'Select',
noResultsText: 'No results found',
newItem: 'New item',
createOption: 'Create option "{0}"'
},
searchable: true,
cleanable: true,
menuAutoWidth: true,
placement: 'bottomLeft'
};
static getDerivedStateFromProps(nextProps: Props, prevState: State) {
if (nextProps.data && !shallowEqual(nextProps.data, prevState.data)) {
return {
data: nextProps.data,
focusItemValue: _.get(nextProps, `data.0.${nextProps.valueKey}`)
};
}
return null;
}
constructor(props: Props) {
super(props);
const { defaultValue, groupBy, valueKey, labelKey, defaultOpen, multi, data } = props;
const value: any = multi ? defaultValue || [] : defaultValue;
const focusItemValue = multi ? _.get(value, 0) : defaultValue;
this.state = {
data,
value,
focusItemValue,
searchKeyword: '',
newData: [],
open: defaultOpen,
maxWidth: 100
};
if (groupBy === valueKey || groupBy === labelKey) {
throw Error('`groupBy` can not be equal to `valueKey` and `labelKey`');
}
}
componentDidMount() {
if (this.toggleWrapper) {
const maxWidth = getWidth(this.toggleWrapper);
this.setState({ maxWidth });
}
}
getFocusableMenuItems = () => {
const { labelKey } = this.props;
const { menuItems } = this.menuContainer;
if (!menuItems) {
return [];
}
const items = Object.values(menuItems).map((item: any) => item.props.getItemData());
return filterNodesOfTree(items, item => this.shouldDisplay(item[labelKey]));
};
getValue() {
const { value, multi } = this.props;
const nextValue = _.isUndefined(value) ? this.state.value : value;
if (multi) {
return _.clone(nextValue) || [];
}
return nextValue;
}
getAllData() {
const { data } = this.props;
const { newData } = this.state;
return [].concat(data, newData);
}
getAllDataAndCache() {
const { cacheData } = this.props;
const data = this.getAllData();
return [].concat(data, cacheData);
}
getLabelByValue(value: any) {
const { renderValue, placeholder, valueKey, labelKey } = this.props;
// Find active `MenuItem` by `value`
const activeItem = findNodeOfTree(this.getAllDataAndCache(), item =>
shallowEqual(item[valueKey], value)
);
let displayElement = placeholder;
if (_.get(activeItem, labelKey)) {
displayElement = _.get(activeItem, labelKey);
if (renderValue) {
displayElement = renderValue(value, activeItem, displayElement);
}
}
return {
isValid: !!activeItem,
displayElement
};
}
createOption(value: string) {
const { valueKey, labelKey, groupBy, locale } = this.props;
if (groupBy) {
return {
create: true,
[groupBy]: locale.newItem,
[valueKey]: value,
[labelKey]: value
};
}
return {
create: true,
[valueKey]: value,
[labelKey]: value
};
}
menuContainer = {
menuItems: null
};
bindMenuContainerRef = (ref: React.ElementRef<*>) => {
this.menuContainer = ref;
};
input = null;
bindInputRef = (ref: React.ElementRef<*>) => {
this.input = ref;
};
focusInput() {
if (!this.input) return;
this.input.focus();
}
blurInput() {
if (!this.input) return;
this.input.blur();
}
trigger = null;
bindTriggerRef = (ref: React.ElementRef<*>) => {
this.trigger = ref;
};
toggleWrapper = null;
bindToggleWrapperRef = (ref: React.ElementRef<*>) => {
this.toggleWrapper = ref;
};
toggle = null;
bindToggleRef = (ref: React.ElementRef<*>) => {
this.toggle = ref;
};
getToggleInstance = () => {
return this.toggle;
};
position = null;
bindPositionRef = (ref: React.ElementRef<*>) => {
this.position = ref;
};
/**
* Index of keyword in `label`
* @param {node} label
*/
shouldDisplay(label: any, searchKeyword?: string) {
const word = typeof searchKeyword === 'undefined' ? this.state.searchKeyword : searchKeyword;
if (!_.trim(word)) {
return true;
}
const keyword = word.toLocaleLowerCase();
if (typeof label === 'string' || typeof label === 'number') {
return `${label}`.toLocaleLowerCase().indexOf(keyword) >= 0;
} else if (React.isValidElement(label)) {
const nodes = reactToString(label);
return (
nodes
.join('')
.toLocaleLowerCase()
.indexOf(keyword) >= 0
);
}
return false;
}
findNode(focus: Function) {
const items = this.getFocusableMenuItems();
const { valueKey } = this.props;
const { focusItemValue } = this.state;
for (let i = 0; i < items.length; i += 1) {
if (shallowEqual(focusItemValue, items[i][valueKey])) {
focus(items, i);
return;
}
}
focus(items, -1);
}
focusNextMenuItem = () => {
const { valueKey } = this.props;
this.findNode((items, index) => {
const focusItem = items[index + 1];
if (!_.isUndefined(focusItem)) {
this.setState({ focusItemValue: focusItem[valueKey] });
}
});
};
focusPrevMenuItem = () => {
const { valueKey } = this.props;
this.findNode((items, index) => {
const focusItem = items[index - 1];
if (!_.isUndefined(focusItem)) {
this.setState({ focusItemValue: focusItem[valueKey] });
}
});
};
updatePosition() {
if (this.position) {
this.position.updatePosition(true);
}
}
handleKeyDown = (event: SyntheticKeyboardEvent<*>) => {
if (!this.menuContainer) {
return;
}
const { multi } = this.props;
onMenuKeyDown(event, {
down: this.focusNextMenuItem,
up: this.focusPrevMenuItem,
enter: multi ? this.selectFocusMenuCheckItem : this.selectFocusMenuItem,
esc: this.closeDropdown,
del: multi ? this.removeLastItem : this.handleClean
});
};
handleClick = () => {
this.focusInput();
};
selectFocusMenuItem = (event: DefaultEvent) => {
const { focusItemValue, searchKeyword } = this.state;
const { valueKey, data, disabledItemValues } = this.props;
if (!focusItemValue || !data) {
return;
}
// If the value is disabled in this option, it is returned.
if (disabledItemValues && disabledItemValues.some(item => item === focusItemValue)) {
return;
}
// Find active `MenuItem` by `value`
let focusItem = findNodeOfTree(this.getAllData(), item =>
shallowEqual(item[valueKey], focusItemValue)
);
if (!focusItem && focusItemValue === searchKeyword) {
focusItem = this.createOption(searchKeyword);
}
this.setState({ value: focusItemValue, searchKeyword: '' });
this.handleSelect(focusItemValue, focusItem, event);
this.handleChange(focusItemValue, event);
this.closeDropdown();
};
selectFocusMenuCheckItem = (event: DefaultEvent) => {
const { valueKey, disabledItemValues } = this.props;
const { focusItemValue } = this.state;
const value: any = this.getValue();
const data = this.getAllData();
if (!focusItemValue || !data) {
return;
}
// If the value is disabled in this option, it is returned.
if (disabledItemValues && disabledItemValues.some(item => item === focusItemValue)) {
return;
}
if (!value.some(v => shallowEqual(v, focusItemValue))) {
value.push(focusItemValue);
} else {
_.remove(value, itemVal => shallowEqual(itemVal, focusItemValue));
}
let focusItem: any = data.find(item => shallowEqual(_.get(item, valueKey), focusItemValue));
if (!focusItem) {
focusItem = this.createOption(focusItemValue);
}
this.setState({ value, searchKeyword: '' }, this.updatePosition);
this.handleSelect(value, focusItem, event);
this.handleChange(value, event);
};
handleItemSelect = (value: any, item: Object, event: DefaultEvent) => {
const nextState = {
value,
focusItemValue: value,
searchKeyword: ''
};
this.setState(nextState);
this.handleSelect(value, item, event);
this.handleChange(value, event);
this.closeDropdown();
};
handleCheckItemSelect = (
nextItemValue: any,
item: Object,
event: DefaultEvent,
checked: boolean
) => {
const value: any = this.getValue();
if (checked) {
value.push(nextItemValue);
} else {
_.remove(value, itemVal => shallowEqual(itemVal, nextItemValue));
}
const nextState = {
value,
searchKeyword: '',
focusItemValue: nextItemValue
};
this.setState(nextState, this.updatePosition);
this.handleSelect(value, item, event);
this.handleChange(value, event);
this.focusInput();
};
handleSelect = (value: any, item: Object, event: DefaultEvent) => {
const { onSelect, creatable } = this.props;
const { newData } = this.state;
onSelect && onSelect(value, item, event);
if (creatable && item.create) {
delete item.create;
this.setState({
newData: newData.concat(item)
});
}
};
handleSearch = (searchKeyword: string, event: DefaultEvent) => {
const { onSearch, labelKey, valueKey } = this.props;
const filteredData = filterNodesOfTree(this.getAllData(), item =>
this.shouldDisplay(item[labelKey], searchKeyword)
);
const nextState = {
searchKeyword,
focusItemValue: filteredData.length ? filteredData[0][valueKey] : searchKeyword
};
this.setState(nextState, this.updatePosition);
onSearch && onSearch(searchKeyword, event);
};
closeDropdown = () => {
if (this.trigger) {
this.trigger.hide();
}
};
handleChange = (value: any, event: DefaultEvent) => {
const { onChange } = this.props;
onChange && onChange(value, event);
};
handleClean = (event: DefaultEvent) => {
const { disabled } = this.props;
if (disabled) {
return;
}
const nextState = {
value: null,
focusItemValue: null,
searchKeyword: ''
};
this.setState(nextState, () => {
this.handleChange(null, event);
this.updatePosition();
});
};
handleEntered = () => {
const { onOpen } = this.props;
onOpen && onOpen();
};
handleExited = () => {
const { onClose, multi } = this.props;
const value: any = this.getValue();
const nextState: Object = {
focusItemValue: multi ? _.get(value, 0) : value
};
if (multi) {
/**
在多选的情况下, 当 searchKeyword 过长,在 focus 的时候会导致内容换行。
把 searchKeyword 清空是为了,Menu 在展开时候位置正确。
*/
nextState.searchKeyword = '';
}
onClose && onClose();
this.setState(nextState);
};
handleEnter = () => {
this.focusInput();
this.setState({ open: true });
};
handleExit = () => {
this.blurInput();
this.setState({ open: false });
};
handleRemoveItemByTag = (tag: string, event: DefaultEvent) => {
event.stopPropagation();
const value = this.getValue();
_.remove(value, itemVal => shallowEqual(itemVal, tag));
this.setState({ value }, this.updatePosition);
this.handleChange(value, event);
};
removeLastItem = (event: SyntheticInputEvent<*>) => {
const tagName = _.get(event, 'target.tagName');
if (tagName !== 'INPUT') {
this.focusInput();
return;
}
if (tagName === 'INPUT' && event.target.value) {
return;
}
const value: any = this.getValue();
value.pop();
this.setState({ value }, this.updatePosition);
this.handleChange(value, event);
};
addPrefix = (name: string) => prefix(this.props.classPrefix)(name);
renderMenuItem = (label, item) => {
const { locale, renderMenuItem } = this.props;
const newLabel = item.create ? <span>{tplTransform(locale.createOption, label)}</span> : label;
return renderMenuItem ? renderMenuItem(newLabel, item) : newLabel;
};
renderDropdownMenu() {
const {
labelKey,
groupBy,
placement,
locale,
renderMenu,
renderExtraFooter,
menuClassName,
menuStyle,
menuAutoWidth,
creatable,
valueKey,
multi,
sort
} = this.props;
const { focusItemValue, searchKeyword } = this.state;
const menuClassPrefix = this.addPrefix(multi ? 'check-menu' : 'select-menu');
const classes = classNames(
menuClassPrefix,
menuClassName,
this.addPrefix(`placement-${_.kebabCase(placement)}`)
);
const allData = this.getAllData();
let filteredData = filterNodesOfTree(allData, item => this.shouldDisplay(item[labelKey]));
if (
creatable &&
searchKeyword &&
!findNodeOfTree(allData, item => item[valueKey] === searchKeyword)
) {
filteredData = [...filteredData, this.createOption(searchKeyword)];
}
// Create a tree structure data when set `groupBy`
if (groupBy) {
filteredData = getDataGroupBy(filteredData, groupBy, sort);
} else if (typeof sort === 'function') {
filteredData = filteredData.sort(sort(false));
}
const menuProps = _.pick(
this.props,
DropdownMenu.handledProps.filter(
name => !['className', 'style', 'classPrefix'].some(item => item === name)
)
);
const value = this.getValue();
const menu = filteredData.length ? (
<DropdownMenu
{...menuProps}
classPrefix={menuClassPrefix}
dropdownMenuItemClassPrefix={`${menuClassPrefix}-item`}
dropdownMenuItemComponentClass={multi ? DropdownMenuCheckItem : DropdownMenuItem}
ref={this.bindMenuContainerRef}
activeItemValues={multi ? value : [value]}
focusItemValue={focusItemValue}
data={filteredData}
group={!_.isUndefined(groupBy)}
onSelect={multi ? this.handleCheckItemSelect : this.handleItemSelect}
renderMenuItem={this.renderMenuItem}
/>
) : (
<div className={this.addPrefix('none')}>{locale.noResultsText}</div>
);
return (
<MenuWrapper
autoWidth={menuAutoWidth}
className={classes}
style={menuStyle}
getToggleInstance={this.getToggleInstance}
onKeyDown={this.handleKeyDown}
>
{renderMenu ? renderMenu(menu) : menu}
{renderExtraFooter && renderExtraFooter()}
</MenuWrapper>
);
}
renderSingleValue() {
const value = this.getValue();
return this.getLabelByValue(value);
}
renderMultiValue() {
const { multi, disabled } = this.props;
if (!multi) {
return null;
}
const tags = this.getValue() || [];
return tags
.map(tag => {
const { isValid, displayElement } = this.getLabelByValue(tag);
if (!isValid) {
return null;
}
return (
<Tag
key={tag}
closable={!disabled}
title={typeof displayElement === 'string' ? displayElement : undefined}
onClose={this.handleRemoveItemByTag.bind(this, tag)}
>
{displayElement}
</Tag>
);
})
.filter(item => item !== null);
}
renderInputSearch() {
const { multi } = this.props;
const props: Object = {
componentClass: 'input'
};
if (multi) {
props.componentClass = InputAutosize;
// 52 = 55 (right padding) - 2 (border) - 6 (left padding)
props.inputStyle = { maxWidth: this.state.maxWidth - 63 };
}
return (
<InputSearch
{...props}
inputRef={this.bindInputRef}
onChange={this.handleSearch}
value={this.state.open ? this.state.searchKeyword : ''}
/>
);
}
render() {
const {
disabled,
cleanable,
locale,
toggleComponentClass,
style,
onEnter,
onEntered,
onExit,
onExited,
onClean,
searchable,
multi,
...rest
} = this.props;
const unhandled = getUnhandledProps(Dropdown, rest);
const { isValid, displayElement } = this.renderSingleValue();
const tagElements = this.renderMultiValue();
const hasValue = multi ? !!_.get(tagElements, 'length') : isValid;
const classes = getToggleWrapperClassName('input', this.addPrefix, this.props, hasValue, {
[this.addPrefix('tag')]: multi,
[this.addPrefix('focused')]: this.state.open
});
const searching = !!this.state.searchKeyword && this.state.open;
const displaySearchInput = searchable && !disabled;
return (
<PickerToggleTrigger
pickerProps={this.props}
innerRef={this.bindTriggerRef}
positionRef={this.bindPositionRef}
trigger="active"
onEnter={createChainedFunction(this.handleEnter, onEnter)}
onEntered={createChainedFunction(this.handleEntered, onEntered)}
onExit={createChainedFunction(this.handleExit, onExit)}
onExited={createChainedFunction(this.handleExited, onExited)}
speaker={this.renderDropdownMenu()}
>
<div
className={classes}
style={style}
onKeyDown={this.handleKeyDown}
onClick={this.handleClick}
ref={this.bindToggleWrapperRef}
>
<PickerToggle
{...unhandled}
ref={this.bindToggleRef}
componentClass={toggleComponentClass}
onClean={createChainedFunction(this.handleClean, onClean)}
cleanable={cleanable && !disabled}
hasValue={hasValue}
>
{searching || (multi && hasValue) ? null : displayElement || locale.placeholder}
</PickerToggle>
<div className={this.addPrefix('tag-wrapper')}>
{tagElements}
{displaySearchInput && this.renderInputSearch()}
</div>
</div>
</PickerToggleTrigger>
);
}
}
const enhance = defaultProps({
classPrefix: 'picker'
});
export default enhance(Dropdown);
|
/**
* Created by bahubali on 19/1/17.
*/
my.sayHello();
your.sayHi();
/*
(function (name) {
console.log("Hello "+ name);
}("coursera"));*/
|
var express = require('express');
var mongoose = require("mongoose");
mongoose.connect('mongodb://localhost:27017/vmm');
var mongoSchema = mongoose.Schema;
// create schema
var userSchema = {
"userEmail" : String,
"userPassword" : String
};
// create model if not exists.
var mongoOp = mongoose.model('user',userSchema);
var router = express.Router();
/* GET users listing. */
router
.get('/', function(req,res){
var response = {};
mongoOp.find({},function(err,data){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
response = {"error" : false,"message" : data};
}
res.json(response);
});
})
.post('/', function(req,res){
var db = new mongoOp();
var response = {};
db.userEmail = req.body.email;
db.userPassword = require('crypto')
.createHash('sha1')
.update(req.body.password)
.digest('base64');
db.save(function(err){
if(err) {
response = {"error" : true,"message" : "Error adding data"};
} else {
response = {"error" : false,"message" : "Data added"};
}
res.json(response);
});
});
router
.get("/:id", function(req,res){
var response = {};
mongoOp.findById(req.params.id,function(err,data){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
response = {"error" : false,"message" : data};
}
res.json(response);
});
})
.put("/:id", function(req,res){
var response = {};
mongoOp.findById(req.params.id,function(err,data){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
if(req.body.userEmail !== undefined) {
data.userEmail = req.body.userEmail;
}
if(req.body.userPassword !== undefined) {
data.userPassword = req.body.userPassword;
}
data.save(function(err){
if(err) {
response = {"error" : true,"message" : "Error updating data"};
} else {
response = {"error" : false,"message" : "Data is updated for "+req.params.id};
}
res.json(response);
})
}
});
})
.delete("/:id", function(req,res){
var response = {};
mongoOp.findById(req.params.id,function(err,data){
if(err) {
response = {"error" : true,"message" : "Error fetching data"};
} else {
mongoOp.remove({_id : req.params.id},function(err){
if(err) {
response = {"error" : true,"message" : "Error deleting data"};
} else {
response = {"error" : true,"message" : "Data associated with "+req.params.id+"is deleted"};
}
res.json(response);
});
}
});
});
module.exports = router;
|
const { ObjectID } = require("mongodb");
const { mongoose } = require("./../server/db/mongoose.js");
const { Todo } = require("./../server/models/todo.js");
const { User } = require("./../server/models/user.js");
let id = "5aecbe14005bcf284c30c0ef";
let user = "5aec6f67963da1293c954607";
// See mongoDB docs for ObjectID method .isValid
if (!ObjectID.isValid(id)) {
// could do same thing with user
console.log("Id is not valid");
}
Todo.find({
_id: id
}).then(todos => {
console.log("Todos", todos);
});
// Query returns all documents in an array
// ...if no results returns empty array
Todo.findOne({
_id: id
}).then(todo => {
console.log("Todo", todo);
});
// Query returns one result as a document
// ...if no results, returns null
// ...the same for .findById()
Todo.findById(id)
.then(todo => {
if (!todo) {
return console.log("Id not found");
}
console.log("Todo by Id", todo);
})
.catch(e => console.log(e));
// NOTE: The app user will be supplying the id, thus we can use
// this data for error handling without breaking our app
User.findById(user)
.then(user => {
if (!user) {
return console.log("User not found");
}
console.log("User by Id", user);
})
.catch(e => console.log(e));
|
import './CharacterPages.scss'
import CardComponent from '../../Components/Card/CardComponent'
export default function CharacterPages() {
return (
<div className="CharacterPages">
<CardComponent/>
</div>
)
}
|
/* See license.txt for terms of usage */
// ********************************************************************************************* //
// Tooltip Controller
/**
* The object is responsible for registering 'popupshowing' listeners and safe clean up.
* The clean up is important since it must happen even if the test doesn't finish.
*/
var TooltipController =
{
listeners: [],
addListener: function(listener)
{
var tooltip = FW.Firebug.chrome.$("fbTooltip");
tooltip.addEventListener("popupshowing", listener, false);
this.listeners.push(listener);
},
removeListener: function(listener)
{
var tooltip = FW.Firebug.chrome.$("fbTooltip");
tooltip.removeEventListener("popupshowing", listener, false);
FW.FBL.remove(this.listeners, listener);
},
cleanUp: function()
{
// Remove all listeners registered by the current test.
while (this.listeners.length)
this.removeListener(this.listeners[0]);
}
};
// ********************************************************************************************* //
// Clean up
window.addEventListener("unload", function testSelectionUnload()
{
TooltipController.cleanUp();
}, true);
|
/*!
* SAP 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.viz.ui5.types.Datatransform_dataSampling.
jQuery.sap.declare("sap.viz.ui5.types.Datatransform_dataSampling");
jQuery.sap.require("sap.viz.library");
jQuery.sap.require("sap.viz.ui5.core.BaseStructuredType");
/**
* Constructor for a new ui5/types/Datatransform_dataSampling.
*
* 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 #getEnable enable} : boolean (default: false)</li>
* <li>{@link #getSizeFactor sizeFactor} : int (default: 1)</li>
* <li>{@link #getNumberPrecondition numberPrecondition} : int (default: 3000)</li></ul>
* </li>
* <li>Aggregations
* <ul>
* <li>{@link #getGrid grid} : sap.viz.ui5.types.Datatransform_dataSampling_grid</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.viz.ui5.core.BaseStructuredType#constructor sap.viz.ui5.core.BaseStructuredType}
* 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
* Settings for the data sampling algorithm
* @extends sap.viz.ui5.core.BaseStructuredType
* @version 1.26.6
*
* @constructor
* @public
* @since 1.7.2
* @experimental Since version 1.7.2.
* Charting API is not finished yet and might change completely
* @name sap.viz.ui5.types.Datatransform_dataSampling
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
sap.viz.ui5.core.BaseStructuredType.extend("sap.viz.ui5.types.Datatransform_dataSampling", { metadata : {
library : "sap.viz",
properties : {
"enable" : {type : "boolean", group : "", defaultValue : false},
"sizeFactor" : {type : "int", group : "", defaultValue : 1},
"numberPrecondition" : {type : "int", group : "", defaultValue : 3000}
},
aggregations : {
"grid" : {type : "sap.viz.ui5.types.Datatransform_dataSampling_grid", multiple : false}
}
}});
/**
* Creates a new subclass of class sap.viz.ui5.types.Datatransform_dataSampling 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.viz.ui5.types.Datatransform_dataSampling.extend
* @function
*/
/**
* Getter for property <code>enable</code>.
* Set whether data sampling is enabled.
*
* Default value is <code>false</code>
*
* @return {boolean} the value of property <code>enable</code>
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#getEnable
* @function
*/
/**
* Setter for property <code>enable</code>.
*
* Default value is <code>false</code>
*
* @param {boolean} bEnable new value for property <code>enable</code>
* @return {sap.viz.ui5.types.Datatransform_dataSampling} <code>this</code> to allow method chaining
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#setEnable
* @function
*/
/**
* Getter for property <code>sizeFactor</code>.
* Set the data point percentage in the original dataset
*
* Default value is <code>1</code>
*
* @return {int} the value of property <code>sizeFactor</code>
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#getSizeFactor
* @function
*/
/**
* Setter for property <code>sizeFactor</code>.
*
* Default value is <code>1</code>
*
* @param {int} iSizeFactor new value for property <code>sizeFactor</code>
* @return {sap.viz.ui5.types.Datatransform_dataSampling} <code>this</code> to allow method chaining
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#setSizeFactor
* @function
*/
/**
* Getter for property <code>numberPrecondition</code>.
* If the data point is larger than this value, data sampling is triggered.
*
* Default value is <code>3000</code>
*
* @return {int} the value of property <code>numberPrecondition</code>
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#getNumberPrecondition
* @function
*/
/**
* Setter for property <code>numberPrecondition</code>.
*
* Default value is <code>3000</code>
*
* @param {int} iNumberPrecondition new value for property <code>numberPrecondition</code>
* @return {sap.viz.ui5.types.Datatransform_dataSampling} <code>this</code> to allow method chaining
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#setNumberPrecondition
* @function
*/
/**
* Getter for aggregation <code>grid</code>.<br/>
* add documentation for aggregation grid
*
* @return {sap.viz.ui5.types.Datatransform_dataSampling_grid}
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#getGrid
* @function
*/
/**
* Setter for the aggregated <code>grid</code>.
* @param {sap.viz.ui5.types.Datatransform_dataSampling_grid} oGrid
* @return {sap.viz.ui5.types.Datatransform_dataSampling} <code>this</code> to allow method chaining
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#setGrid
* @function
*/
/**
* Destroys the grid in the aggregation
* named <code>grid</code>.
* @return {sap.viz.ui5.types.Datatransform_dataSampling} <code>this</code> to allow method chaining
* @public
* @name sap.viz.ui5.types.Datatransform_dataSampling#destroyGrid
* @function
*/
// Start of sap/viz/ui5/types/Datatransform_dataSampling.js
sap.viz.ui5.types.Datatransform_dataSampling.prototype.getGrid = function() {
return this._getOrCreate("grid");
}
|
var searchData=
[
['width_130',['width',['../class_u_i_enforce_constraints.html#a44c5224158fa4f7714e0ce8fc80da151',1,'UIEnforceConstraints']]]
];
|
'use strict';
module.exports = function ( app, routes ) {
var
path = require( 'path' ),
express = require( 'express' ),
root = path.join( __dirname, './..' );
// Static Paths
app.use( '/lib', express.static( path.join( root, '/lib' ) ) );
app.use( '/', express.static( path.join( root, '/public' ) ) );
for( var folder in routes ) {
app.use( '/' + routes[ folder ], express.static( path.join( root, '/public/' + folder ) ) );
}
}; |
const mongoose = require('../../config/DbConfig');
const Schema = mongoose.Schema;
const UserCourseSchema = new Schema({
courseId: {type: String},
userId: {type: String}
});
module.exports = mongoose.model("userCourse", UserCourseSchema); |
import Dexie from 'dexie';
class iDB {
static init(databseName) {
return new Dexie(databseName);
}
}
export default iDB; |
"use strict";
function _createForOfIteratorHelper(e, t) {
var r;
if ("undefined" == typeof Symbol || null == e[Symbol.iterator]) {
if (Array.isArray(e) || (r = _unsupportedIterableToArray(e)) || t && e && "number" == typeof e.length) {
r && (e = r);
var o = 0,
t = function () {};
return {
s: t,
n: function () {
return o >= e.length ? {
done: !0
} : {
done: !1,
value: e[o++]
}
},
e: function (e) {
throw e
},
f: t
}
}
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")
}
var a, n = !0,
i = !1;
return {
s: function () {
r = e[Symbol.iterator]()
},
n: function () {
var e = r.next();
return n = e.done, e
},
e: function (e) {
i = !0, a = e
},
f: function () {
try {
n || null == r.return || r.return()
} finally {
if (i) throw a
}
}
}
}
function _unsupportedIterableToArray(e, t) {
if (e) {
if ("string" == typeof e) return _arrayLikeToArray(e, t);
var r = Object.prototype.toString.call(e).slice(8, -1);
return "Object" === r && e.constructor && (r = e.constructor.name), "Map" === r || "Set" === r ? Array.from(e) : "Arguments" === r || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r) ? _arrayLikeToArray(e, t) : void 0
}
}
function _arrayLikeToArray(e, t) {
(null == t || t > e.length) && (t = e.length);
for (var r = 0, o = new Array(t); r < t; r++) o[r] = e[r];
return o
}
function _typeof(e) {
return (_typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (e) {
return typeof e
} : function (e) {
return e && "function" == typeof Symbol && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e
})(e)
}! function (e) {
var t, r, o;
"function" == typeof define && define.amd && (define(e), t = !0), "object" === ("undefined" == typeof exports ? "undefined" : _typeof(exports)) && (module.exports = e(), t = !0), t || (r = window.Cookies, (o = window.Cookies = e()).noConflict = function () {
return window.Cookies = r, o
})
}(function () {
function d() {
for (var e = 0, t = {}; e < arguments.length; e++) {
var r, o = arguments[e];
for (r in o) t[r] = o[r]
}
return t
}
function u(e) {
return e.replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
}
return function e(s) {
function i() {}
function r(e, t, r) {
if ("undefined" != typeof document) {
"number" == typeof (r = d({
path: "/"
}, i.defaults, r)).expires && (r.expires = new Date(+new Date + 864e5 * r.expires)), r.expires = r.expires ? r.expires.toUTCString() : "";
try {
var o = JSON.stringify(t);
/^[\{\[]/.test(o) && (t = o)
} catch (e) {}
t = s.write ? s.write(t, e) : encodeURIComponent(String(t)).replace(/%(23|24|26|2B|3A|3C|3E|3D|2F|3F|40|5B|5D|5E|60|7B|7D|7C)/g, decodeURIComponent), e = encodeURIComponent(String(e)).replace(/%(23|24|26|2B|5E|60|7C)/g, decodeURIComponent).replace(/[\(\)]/g, escape);
var a, n = "";
for (a in r) r[a] && (n += "; " + a, !0 !== r[a] && (n += "=" + r[a].split(";")[0]));
return document.cookie = e + "=" + t + n
}
}
function t(e, t) {
if ("undefined" != typeof document) {
for (var r = {}, o = document.cookie ? document.cookie.split("; ") : [], a = 0; a < o.length; a++) {
var n = o[a].split("="),
i = n.slice(1).join("=");
t || '"' !== i.charAt(0) || (i = i.slice(1, -1));
try {
var d = u(n[0]),
i = (s.read || s)(i, d) || u(i);
if (t) try {
i = JSON.parse(i)
} catch (e) {}
if (r[d] = i, e === d) break
} catch (e) {}
}
return e ? r[e] : r
}
}
return i.set = r, i.get = function (e) {
return t(e, !1)
}, i.getJSON = function (e) {
return t(e, !0)
}, i.remove = function (e, t) {
r(e, "", d(t, {
expires: -1
}))
}, i.defaults = {}, i.withConverter = e, i
}(function () {})
}),
function (i, d) {
var s = d("body"),
u = d("head"),
l = "#skin-theme",
c = ".nk-header",
n = ["demo4", "subscription"],
a = ["style", "header", "header_opt", "skin", "mode"],
f = "light-mode",
m = "dark-mode",
p = ".nk-opt-item",
y = ".nk-opt-list",
h = {
demo4: {
header: "is-light",
header_opt: "nk-header-fixed",
style: "ui-default"
},
subscription: {
header: "is-light",
header_opt: "nk-header-fixed",
style: "ui-default"
}
};
i.Demo = {
save: function (e, t) {
Cookies.set(i.Demo.apps(e), t)
},
remove: function (e) {
Cookies.remove(i.Demo.apps(e))
},
current: function (e) {
return Cookies.get(i.Demo.apps(e))
},
apps: function (e) {
var t, r = window.location.pathname.split("/").map(function (e, t, r) {
return e.replace("-", "")
}),
o = _createForOfIteratorHelper(n);
try {
for (o.s(); !(a = o.n()).done;) {
var a = a.value;
0 <= r.indexOf(a) && (t = a)
}
} catch (e) {
o.e(e)
} finally {
o.f()
}
return e ? e + "_" + t : t
},
style: function (e, t) {
var r = {
mode: f + " " + m,
style: "ui-default ui-softy",
header: "is-light is-default is-theme is-dark",
header_opt: "nk-header-fixed"
};
return "all" === e ? r[t] || "" : "any" === e ? r.mode + " " + r.style + " " + r.header : "body" === e ? r.mode + " " + r.style : "is-default" === e || "ui-default" === e || "is-regular" === e ? "" : e
},
skins: function (e) {
return !e || "default" === e ? "theme" : "theme-" + e
},
defs: function (e) {
var t = i.Demo.apps(),
t = h[t][e] || "";
return i.Demo.current(e) ? i.Demo.current(e) : t
},
apply: function () {
i.Demo.apps();
var t = _createForOfIteratorHelper(a);
try {
for (t.s(); !(r = t.n()).done;) {
var e, r, o = r.value;
"header" !== o && "header_opt" !== o && "style" !== o || (e = i.Demo.defs(o), d(r = "header" !== o && "header_opt" !== o ? s : c).removeClass(i.Demo.style("all", o)), "ui-default" !== e && "is-default" !== e && d(r).addClass(e)), "mode" === o && i.Demo.update(o, i.Demo.current("mode")), "skin" === o && i.Demo.update(o, i.Demo.current("skin"))
}
} catch (e) {
t.e(e)
} finally {
t.f()
}
i.Demo.update("dir", i.Demo.current("dir"))
},
locked: function (e) {
!0 === e ? (d(p + "[data-key=header]").add(p + "[data-key=skin]").addClass("disabled"), i.Demo.update("skin", "default", !0), d(p + "[data-key=skin]").removeClass("active"), d(p + "[data-key=skin][data-update=default]").addClass("active")) : d(p + "[data-key=header]").add(p + "[data-key=skin]").removeClass("disabled")
},
update: function (e, t, r) {
var o, a = i.Demo.style(t, e),
n = i.Demo.style("all", e);
i.Demo.apps();
"header" !== e && "header_opt" !== e || (d(o = "header" == e || "header_opt" == e ? c : "").removeClass(n), d(o).addClass(a)), "mode" === e && (s.removeClass(n).removeAttr("theme"), a === m ? (s.addClass(a).attr("theme", "dark"), i.Demo.locked(!0)) : (s.addClass(a).removeAttr("theme"), i.Demo.locked(!1))), "style" === e && (s.removeClass(n), s.addClass(a)), "skin" === e && (n = i.Demo.skins(a), a = d("#skin-default").attr("href").replace("theme", "skins/" + n), "theme" === n ? d(l).remove() : 0 < d(l).length ? d(l).attr("href", a) : u.append('<link id="skin-theme" rel="stylesheet" href="' + a + '">')), !0 === r && i.Demo.save(e, t)
},
reset: function () {
var t = i.Demo.apps();
s.removeClass(i.Demo.style("body")).removeAttr("theme"), d(p).removeClass("active"), d(l).remove(), d(c).removeClass(i.Demo.style("all", "header"));
var e, r = _createForOfIteratorHelper(a);
try {
for (r.s(); !(e = r.n()).done;) {
var o = e.value;
d("[data-key='" + o + "']").each(function () {
var e = d(this).data("update");
"header" !== o && "header_opt" !== o && "style" !== o || e === h[t][o] && d(this).addClass("active"), "mode" !== o && "skin" !== o || e !== f && "default" !== e || d(this).addClass("active")
}), i.Demo.remove(o)
}
} catch (e) {
r.e(e)
} finally {
r.f()
}
d("[data-key='dir']").each(function () {
d(this).data("update") === i.Demo.current("dir") && d(this).addClass("active")
}), i.Demo.apply()
},
load: function () {
i.Demo.apply(), 0 < d(p).length && d(p).each(function () {
var e = d(this).data("update"),
t = d(this).data("key");
"header" !== t && "header_opt" !== t && "style" !== t || e === i.Demo.defs(t) && (d(this).parent(y).find(p).removeClass("active"), d(this).addClass("active")), "mode" !== t && "skin" !== t && "dir" !== t || e != i.Demo.current("skin") && e != i.Demo.current("mode") && e != i.Demo.current("dir") || (d(this).parent(y).find(p).removeClass("active"), d(this).addClass("active"))
})
},
trigger: function () {
d(p).on("click", function (e) {
e.preventDefault();
var t = d(this),
r = t.parent(y),
o = t.data("update"),
e = t.data("key");
i.Demo.update(e, o, !0), r.find(p).removeClass("active"), t.addClass("active"), "dir" == e && setTimeout(function () {
window.location.reload()
}, 100)
}), d(".nk-opt-reset > a").on("click", function (e) {
e.preventDefault(), i.Demo.reset()
})
},
init: function (e) {
i.Demo.load(), i.Demo.trigger()
}
}, i.coms.docReady.push(i.Demo.init)
}(NioApp, jQuery); |
"use strict";
jQuery(function () {
$("#fixBox").load("index.html .fixBox");
$(".g_footer").load("index.html #footer");
$(".g_header").load("index.html #header", function () {
$.getScript("js/common.js", function () {
dl();
dongtai(comId);
addCar(comId);
xhr2();
});
var comId = location.search.slice(1).split("=")[1];
$.ajax({
url: "api/commodity.php",
data: { id: comId },
success: function success(res) {
render(JSON.parse(res));
}
});
$(".listpic").on("mouseover", function () {
$(".datu").children("img").prop("src", $(this).children("img")[0].src);
});
$(".datu").mouseover(function () {
$(".datuBtn").show();
$(".glassImg img").prop("src", $(this).children("img")[0].src);
$(".glassImg").show();
});
$(".datu").mouseout(function () {
$(".datuBtn").hide();
$(".glassImg").hide();
});
$(".datu").mousemove(function (e) {
var etop = e.pageY - $(this).offset().top - $(".datuBtn").height() / 2;
var eleft = e.pageX - $(this).offset().left - $(".datuBtn").width() / 2;
var thisX = $(this).width() - $(".datuBtn").width();
var thisY = $(this).height() - $(".datuBtn").height();
if (eleft < 0) {
eleft = 0;
} else if (eleft > thisX) {
eleft = thisX;
}
if (etop < 0) {
etop = 0;
} else if (etop > thisY) {
etop = thisY;
}
$(".datuBtn").css("left", eleft);
$(".datuBtn").css("top", etop);
var pX = eleft / thisX;
var pY = etop / thisY;
$(".glassImg img").css({
"left": -pX * ($(".glassImg img").width() - $(".glassImg").width()),
"top": -pY * ($(".glassImg img").height() - $(".glassImg").height())
});
});
});
function render(obj) {
$(".datu").children("img").prop("src", obj[0].com_img);
$(".select").children("img").prop("src", obj[0].com_img);
$(".msg_top").children("h3").text(obj[0].com_name);
$(".ps_money").text(obj[0].com_price);
$(".pj").children("span").text(obj[0].com_eval);
}
function dongtai() {
$(".jia").on("click", function () {
var val = $(".c_count").val();
$(".c_count").val(Number(val) + 1);
});
$(".jian").on("click", function () {
var val = $(".c_count").val();
if (val != 1) {
$(".c_count").val(Number(val) - 1);
}
});
}
function addCar(comId) {
var user = $("#login_name").text();
$(".m_addCar").on("click", function () {
var count = $(".c_count").val();
$.ajax({
url: "api/add_car.php",
data: { id: comId, user: user, count: count },
success: function success(res) {
console.log(res);
if (res == 1) {
$.ajax({
url: "api/ready_car.php",
data: { user: user, type: 0 },
success: function success(res) {
var obj = JSON.parse(res);
var count = 0;
$.each(obj, function (idx, item) {
count += Number(item.count);
});
$(".count").text(count);
}
});
}
}
});
});
}
function xhr2() {
$.ajax({
url: "api/list.php",
data: { page: 5, qty: 4 },
success: function success(res) {
obj = JSON.parse(res);
render2(obj.data);
}
});
}
function render2(obj) {
$(".tj_ul").html($.map(obj, function (item) {
return "<li data-id=\"" + item.com_id + "\">\n <a class=\"go_goods clearfix\">\n <img src=\"" + item.com_img + "\" alt=\"\">\n <div class=\"fl\">\n <p>" + item.com_name + "</p>\n <span>\uFFE5<span class=\"t_money\">" + item.com_price + "</span></span>\n </div>\n </a>\n </li>";
}));
$(".lsc2").children("img").prop("src", obj[0].com_img);
$(".lsc3").children("img").prop("src", obj[1].com_img);
$(".lsc4").children("img").prop("src", obj[2].com_img);
$(".last").children("img").prop("src", obj[3].com_img);
$(".go_goods").on("click", function () {
var id = $(this).parents("li").attr("data-id");
location.href = "html/goods.html?comId=" + id;
});
}
}); |
module.exports = {
profile(req, res, next) {
res.status(200).send({success: true, profile: {username: req.user.global.username, email: req.user.global.email}});
}
} |
var app = angular.module('blog', []);
app.controller('MainCtrl', function($scope,PostsService) {
PostsService.getPosts().then(function(response) {
$scope.posts = response.data.map(function(element) {
return element.table;
});
});
})
app.component('post', {
bindings: {
data: '=',
},
controller: function (PostsService) {
this.showFullPost = false;
this.readPost = function (post) {
PostsService.getPostInfo(post.id).then(function(response){
post.text = response.data.text;
});
this.showFullPost = true;
}
},
templateUrl: 'templates/page_template.html'
});
app.service('PostsService', function($http,backendUrl) {
return {
getPosts: function() {
return $http.get(backendUrl+'/postspreview.json').then($http.getDataFromResult)
},
getPostInfo: function(id) {
return $http.get(backendUrl+'/posts/'+id).then($http.getDataFromResult)
}
}
});
app.constant('backendUrl','http://localhost:3000')
|
import DS from 'ember-data';
var Story = DS.Model.extend({
title: DS.attr('string'),
url: DS.attr('string'),
story_content: DS.attr('string')
});
export default Story; |
//全局变量
//标识verifyCode方法返回值
var verifyCodeFlag = false;
var reg = /^(((13[0-9]{1})|(14[4-7]{1})|(15[0-9]{1})|(170)|(17[1-8]{1})|(18[0-9]{1}))+\d{8})$/;// 手机号码判断正则
window.onload = function() {
$('.next').click(function() {
var n = $('.next').index(this);
if (n == 0) {
return changePs(n);
} else if (n == 1) {
return changePass(n);
}
});
$(document).keydown(function(event) {
if (event.keyCode == 13) {
verifyCode();
}
});
sendTelrand();
check();
}// window.onload end
function check() {
/**
* 输入手机号 焦点失去事件
*/
$('#phone').keyup(function() {
var r = reg.test($(this).val());
if (!r) {
$(this).next().text('请输入正确的手机号');
} else if ($(this).val() == '') {
$(this).next().text('请输入手机号');
} else {
$(this).next().text('');
}
});
$('#phone').click(function() {
$(this).next().text('');
});
$('#code').click(function() {
$(this).next().text('');
});
$('#code').keyup(function() {
$(this).next().text('');
});
$('#pass').click(function() {
$('#one').text('');
});
$('#inpass').click(function() {
$('#two').text('');
});
$('#pass').keyup(function() {
$('#one').text('');
});
$('#inpass').keyup(function() {
$('#two').text('');
});
}
/**
* 发送验证码
*/
function sendTelrand() {
$('.codeBtn').click(function() {
var telephone = $('#phone').val();
if (telephone == "") {
$('#msgTel').text("请输入账号");
return false;
}
if (!reg.test(telephone)) {
$('#msgTel').text("请输入正确的手机号");
return false;
}
if (reg.test(telephone) && telephone != "") {
$.ajax({
type:'post',
url : basePath+"/ProtalUserManage/check",
data:{
telephone:telephone
},
success:function(data){
if(data=="false"){
$('#msgTel').text("");
sendTelCode();
coundDown($('.codeBtn'), 60)
}else{
$('#msgTel').text("账户未注册,请先去注册您的wifi账户");
return false;
}
}
});
}
});
}
//检验用户是否存在
function checkUserIsHave(telephone){
$.ajax({
type:'post',
url : basePath+"/ProtalUserManage/check",
data:{
telephone:telephone
},
success:function(data){
if(data=="false"){
$('#msgTel').text("");
}else{
$('#msgTel').text("账户未注册,请注册wifi账户");
return false;
}
}
});
}
// 修改密码
function changePs(n) {
var telephone = $('#phone').val();
var phonecode = $('#code').val();
if (telephone == "") {
$('#msgTel').text("请输入账号");
return false;
} else {
$('#msgTel').text("");
}
if (!reg.test(telephone)) {
$('#msgTel').text("请输入正确的手机号");
return false;
} else {
$('#msgTel').text("");
}
if (phonecode == "") {
$(".gif").css('display', 'none');
$('#rand').text("请输入验证码");
return false;
} else {
$('#rand').text("");
}
$.ajax({
type : 'post',
url : basePath + "/ProtalUserManage/checkRandCodeForPC",
async : false,
data : {
telephone : telephone,
phonecode : phonecode,
},
success : function(data) {
data = JSON.parse(data);
if (data.code == 200) {
if (n < 1) {
setTimeout(function() {
boxMove(n);
}, 400);
}
} else {
$('#rand').text(data.msg);
return false;
}
}
});
}
/**
* 发送验证码
*/
function sendTelCode() {
$.ajax({
type : 'post',
url : basePath + "/TelCodeManage/sendTelCode",
data : {
tel : $('#phone').val(),
templateCode:"SMS_12891467"
},
success : function(data) {
if (data == -1) {
$('#rand').text("验证码发送失败");
return false;
}
if (data == -2) {
$('#rand').text("请不要频繁发送验证码");
return false;
}
}
});
}
/**
* 修改密码
*/
function changePass(n) {
var password1 = $('#pass').val();
var password = $('#inpass').val();
var tele = $("#phone").val();
$(".gif").css('display', 'block');
if (password1 == '' || password1 == null) {
$('#one').text('请输入密码');
$(".gif").css('display', 'none');
return;
} else {
$('#one').text('');
}
if (password == '' || password == null) {
$('#two').text('请输入密码');
$(".gif").css('display', 'none');
return;
} else {
$('#two').text('');
}
if (password1 != password) {
$('#two').text('两次密码不一致');
$(".gif").css('display', 'none');
return;
} else {
$('#two').text('');
}
$.ajax({
type : 'post',
url : basePath + "/ProtalUserManage/changePsForget",
async : false,
data : {
telphone : tele,
password : password
},
success : function(data) {
$(".gif").css('display', 'none');
if (data == 'true') {
window.location.href = 'http://www.gonet.cc';
} else {
$('#two').next().text('修改失败');
return;
}
}
});
}
function boxMove(n) {
$('.content').css('display', 'none');
$('.content').eq(n + 1).css('display', 'block');
}
function coundDown(obj, n) {
obj.css('background', '#ccc');
obj.attr('disabled', true);
obj.text(n + '秒后重新获取');
var timer = setInterval(function() {
n--;
if (n == 0) {
clearInterval(timer);
obj.css('background', '#47a4dc');
obj.attr('disabled', false);
obj.text('获取验证码');
} else {
obj.text(n + '秒后重新获取');
}
}, 1000);
}
|
// key转换函数
function toMapName (origin, target, maps) {
for (const key in maps) {
if (key in origin) {
const newKey = maps[key]
target[newKey] = origin[key]
}
}
}
function styleStringify (selector, style) {
const styleTextArr = []
for (const key in style) {
styleTextArr.push(`${key}: ${style[key]};`)
}
return `${selector} {
${styleTextArr.join('')}
}`
}
function createStyleElement (styleText) {
var style = document.createElement('style')
style.innerText = styleText
document.head.appendChild(style)
}
export {
toMapName,
styleStringify,
createStyleElement
}
|
#!/usr/bin/env node
var mysql = require('mysql')
, q = require('q')
, sql
;
sql = {
connect: function(config, db, force){
sql.config = config;
if(typeof sql.config.connections[db].port == "object"){
sql.config.connections[db].port = sql.config.connections[db].port.oustide
}
if(force){
try {
if(sql.connection) sql.connection.end()
}catch(e){}
sql.connection = mysql.createConnection(sql.config.connections[db]);
}else{
sql.connection = (sql.connection || mysql.createConnection(sql.config.connections[db]));
}
return sql;
}
, query: function(query){
return q.ninvoke(sql.connection, 'query', query)
.then(function(rows){
return rows[0];
});
}
, kill: function(query){
sql.connection.end();
delete sql.connection
}
, getDBState: function(){
return sql.query("SELECT "+sql.config.state_field+" FROM "+sql.config.state_table)
.then(function(rows){
return ((rows[0]&&+(rows[0][sql.config.state_field])) || 0);
})
.catch(function(err){
if(err.code == 'ER_NO_SUCH_TABLE'){
return sql.initializeStateTable()
.then(function(){
return sql.getDBState();
});
}else{
// error out if there was some other reason for the state retrieval error
console.log('lib/sql'.red, 'line 33:'.red, err.message);
throw err;
}
});
}
, batch: function(state, statements, skip){
if((!statements || statements.length == 0) || skip){
return true;
}
var statement = statements.shift()
, table_name = sql.config.state_table
, field_name = sql.config.state_field
;
console.log("\t"+statement.yellow);
return sql.query(statement)
.then(function(){
return sql.query("UPDATE "+table_name+" SET "+field_name+"= '"+state+"'");
})
.then(function(){
return sql.batch(state, statements);
})
.catch(function(err){
console.log("\t\tlib/sql".red, "line 58:".red, err.message);
console.log(err);
throw err;
})
}
, initializeStateTable: function(){
var table_name = sql.config.state_table
, field_name = sql.config.state_field
;
console.log("creating "+table_name+" table with an integer field named '"+field_name+"'");
// if no state table is found, attempt to create it
return sql.query(
"CREATE TABLE "+table_name+"("+field_name+" VARCHAR(255), updated_at DATETIME)"
)
.then(function(){
console.log("inserting initial values into "+table_name);
// and then populate it with an appropriate first row
return sql.query("INSERT INTO "+table_name+"("+field_name+", updated_at) VALUES(0, NOW())");
})
.catch(function(err){
// error out if no state table was found and it was unable to be corrected
console.log("lib/sql".red, "line 52:".red, err.message);
throw err;
});
}
};
module.exports = sql;
|
/**
* Created by andy on 1/2/15.
*/
$(document).ready(function(){
var comp = new GrantTopo.Component();
comp.displayTopo();
});
|
import React, { useState, useReducer } from "react";
import Tile from "../tile/Tile";
import classes from "./Game.module.scss";
import reducer, {
SET_REVEALED,
SET_FLAG,
REMOVE_FLAG
} from "../../reducers/gameBoard";
import { initiateBoard, revealBoard, checkWin } from "../../helpers/selectors";
const classNames = require("classnames");
function Game() {
// Set up board
const dimensions = [16, 16];
const gameArray = initiateBoard(dimensions);
// State Declarations
const [minesRemaining, setMinesRemaining] = useState(40);
const [gameBoard, dispatch] = useReducer(reducer, gameArray);
const [gameStatus, setGameStatus] = useState("Playing");
// Define class names
const statusClass = classNames(
gameStatus === "You lose!" ? classes.game_title_lose : null,
gameStatus === "You win!!!" ? classes.game_title_win : null
);
// Handle Functions
const handleClick = (x, y) => {
if (gameBoard[x][y].isRevealed || gameBoard[x][y].isFlagged) {
return null;
}
if (gameBoard[x][y].isMine) {
setGameStatus("You lose!");
revealBoard(gameBoard);
} else if (checkWin(gameBoard)) {
setGameStatus("You win!!!");
}
let updatedBoard = gameBoard;
updatedBoard[x][y].isRevealed = true;
dispatch({ type: SET_REVEALED });
};
const handleContextMenu = (event, x, y) => {
event.preventDefault();
let updatedBoard = gameBoard;
let mines = minesRemaining;
if (updatedBoard[x][y].isRevealed) return;
if (updatedBoard[x][y].isFlagged) {
updatedBoard[x][y].isFlagged = false;
dispatch({ type: REMOVE_FLAG });
mines++;
} else {
updatedBoard[x][y].isFlagged = true;
dispatch({ type: SET_FLAG });
mines--;
if (checkWin(gameBoard)) {
setGameStatus("You win!!!");
}
}
};
// Create tile components based on gameArray
const renderBoard = array => {
return array.map(row => {
return row.map(item => {
return (
<div key={item.x * row.length + item.y} className={classes.game_grid}>
<Tile
onClick={() => handleClick(item.x, item.y)}
cMenu={e => handleContextMenu(e, item.x, item.y)}
value={item}
x={item.x}
y={item.y}
gameBoard={gameBoard}
/>
</div>
);
});
});
};
const tiles = renderBoard(gameArray);
return (
<div className={classes.game}>
<div className={classes.game_title}>
<h3>Flags Remaining: {minesRemaining}</h3>
<h4 className={statusClass}>Status: {gameStatus}</h4>
<button
className={classes.game_button}
onClick={() => window.location.reload(false)}
>
Reset Board
</button>
</div>
<div className={classes.game_grid}>{tiles}</div>
</div>
);
}
export default Game;
|
import styles from "./Overview.module.css";
function Overview(){
return(
<div className={styles.overview}>
<div className="row">
<div className="col-lg-5 col-md-8 col-sm-12" style={{margin: "2% auto"}}> <a href="/"><img className={styles.viewImg} src="https://jagdishfarshan.com/Content/img/home/home-offer_1.jpg" alt="overview" /></a> </div>
<div className="col-lg-5 col-md-8 col-sm-12" style={{margin: "2% auto"}}> <a href="/"> <img className={styles.viewImg} src="https://jagdishfarshan.com/Content/img/home/home-offer_2.jpg" alt="overview" /></a></div>
<div className="col-lg-5 col-md-8 col-sm-12" style={{margin: "2% auto"}}> <a href="/"> <img className={styles.viewImg} src="https://jagdishfarshan.com/Content/img/home/home-offer_3.jpg" alt="overview" /> </a></div>
<div className="col-lg-5 col-md-8 col-sm-12" style={{margin: "2% auto"}}> <a href="/"><img className={styles.viewImg} src="https://jagdishfarshan.com/Content/img/home/home-offer_4.jpg" alt="overview" /></a></div>
</div>
</div>
)
}
export default Overview; |
import C from '../constants/actions';
export default function favoritePairs(state = [], action) {
switch (action.type) {
case C.TOGGLE_USER_FAVOURITE_PAIR_ID:
return state.includes(action.payload)
? state.filter(item => item !== action.payload)
: [...state, action.payload];
case C.SET_USER_FAVOURITE_PAIR_IDS:
return action.payload;
case C.ADD_USER_FAVOURITE_PAIR_ID:
return state.includes(action.payload)
? state
: [...state, action.payload];
case C.REMOVE_USER_FAVOURITE_PAIR_ID:
return state.filter(item => item !== action.payload);
default:
return state;
}
}
|
/* To install node modules:
npm init
If it doesn't work, enter the following lines:
npm install express --save
npm install socket.io --save
npm install cannon --save
npm install nodemon --save-dev -g
Start with command: nodemon app */
// Server requirements
var express = require('express');
var socket = require('socket.io');
// Game requirements
var Hub = require('./resources/objects/Hub.js');
// Starting app
var app = express();
// Starting server and socket.io module
var server = app.listen(process.env.PORT || 80, console.log('Currently listening to port 4000'));
var io = socket(server);
// Folders the server uses
app.use('/styles', express.static('public/resources/styles'));
app.use('/objects', express.static('public/resources/objects'));
app.use('/images', express.static('public/resources/images'));
app.use('/javascript', express.static('public/resources/javascript'));
app.use('/views', express.static('public/views'));
// Starting game manager
var hub = new Hub(io);
// When client asks for /join page
app.get('/join', function(request, response) {
response.sendFile(__dirname + '/public/views/join.html');
});
// When client asks for /play page (to either directly join a new game or resume one)
app.get('/play/rooms/:id/players/:name', function(request, response) {
// Store request parameters
var name = request.params.name, id = request.params.id;
// Invokes the connection manager and sends its redirection file
var redirect = hub.requestHandler(name, id);
response.sendFile(__dirname + redirect);
});
// When the player socket connects (on play page), must be called outside app.get to avoid function duplication
io.on('connection', function(socket) {
hub.connectionHandler(socket);
});
// End of file
|
const webdriver = require('selenium-webdriver');
const {debugToast} = require("./index");
const {setStoryDisplayText} = require("./index");
const {BehaviorSubject, Subject} = require('rxjs');
const fs = require('fs')
const {parseSentence} = require("./index");
const {executeSentences} = require("./index");
const {insertDefinitionIntoStory} = require("./index");
const {insertActionIntoStory} = require("./index");
const {loadJavascript} = require("./index");
const input = require('selenium-webdriver/lib/input');
const {createSentenceListAndInputBox} = require('./ui');
const command = require('selenium-webdriver/lib/command');
const sleep = n => new Promise(resolve => setTimeout(resolve, n));
class SeleniumContext {
constructor() {
this.story$ = new BehaviorSubject('');
this.keydown$ = new Subject();
this.click$ = new Subject();
this.addAction$ = new Subject();
this.addDefinition$ = new Subject();
this.executeStory$ = new Subject();
this.unit_test_bh$ = new BehaviorSubject('');
this.uniqueNameMap$ = new BehaviorSubject('{}');
// There is a nicer way to do this with combineLatest
this.story$.subscribe(v => {
const uniqueMap = {};
if (!v.split) {
console.info()
}
v.split('\n')
.filter(v => v)
.map(parseSentence)
.filter(({type}) => type === 'definition')
.forEach(({varName, selector}) => uniqueMap[selector] = varName);
let value = JSON.stringify(uniqueMap);
this.uniqueNameMap$.next(value);
});
Object.keys(this).forEach(k => {
this[k].subscribe(v => console.log(`${k} updated to ${v}`))
}
)
}
}
class DriverObs {
/**
*
* @param d {WebDriver}
* @param story
*/
constructor(d, story) {
let f = d.executeScript;
this.seleniumContext = new SeleniumContext();
/**
* @type {WebDriver}
*/
this.driver = d;
}
async setup() {
await loadJavascript(this.driver);
await setupMessagePasser(this.driver, this.seleniumContext);
await this.driver.executeScript('console.log(window.seleniumContext)');
await createSentenceListAndInputBox(this.driver);
this.seleniumContext.story$.subscribe(s => {
fs.writeFileSync('./story.txt', s);
debugToast(this.driver, 'Updated story');
});
// TODO use combineLatest here
this.seleniumContext.addAction$.subscribe(v => {
this.seleniumContext.story$.next(insertActionIntoStory(v, this.seleniumContext.story$.getValue()));
});
this.seleniumContext.addDefinition$.subscribe( v => {
this.seleniumContext.story$.next(insertDefinitionIntoStory(v, this.seleniumContext.story$.getValue()));
});
this.seleniumContext.executeStory$.subscribe(v => {
executeSentences(this.driver, this.seleniumContext.story$.getValue().split('\n').filter(v => v.trim()));
});
await setupRecorder(this.driver);
}
}
const allEventTypes = [
'ACTION',
'EXECUTE_STORY',
'NAME_SELECTOR',
];
async function setupMessagePasser(driver, seleniumContext) {
// Create window.seleniumContext with all the keys of seleniumContext
const setupObservables = () => {
// This function creates a "fake" behaviorSubject
function sendMessageToNode(sender, msg) {
const el = document.createElement('div');
el.id = `selenium-event-a${counter}`;
counter++;
el.className = 'selenium-event';
el.style = 'top: -1000';
el.textContent = JSON.stringify({sender, message: msg});
document.body.appendChild(el);
}
window.sendMessageToNode = sendMessageToNode;
function getObs(name, v = '') {
const subject$ = {
v,
subscribers: [],
next(v = '', sendToSelenium = true) {
if (!v) v = '';
if (typeof v !== 'string') {
throw new Error(`Can only send strings through the seleniumContext! not ${typeof v} ${JSON.stringify(v)}`)
}
if (this.v !== v) {
this.v = v;
$.toast(`${name} changed to ${v}`);
this.subscribers.forEach(f => f(v, sendToSelenium));
}
},
subscribe(cb) {
this.subscribers.push(cb);
}
};
subject$.subscribe((v, sendToSelenium = true) => {
if (!sendToSelenium) {
return;
}
window.sendMessageToNode(
name,
v
)
}
)
return subject$;
}
// getObs uses this function to send messages to the observables on the other side
let counter = 0;
// Set up the seleniumContext
window.seleniumContext = {};
const seleniumContext = JSON.parse(arguments[0]);
// Fill up window.seleniumContext
Object.entries(seleniumContext)
.forEach(([key, initValue]) => window.seleniumContext[key] = getObs(key, initValue));
$.toast(`New seleniumContext ${JSON.stringify(window.seleniumContext, null, '\t')}`)
};
const stringContext = {};
Object.keys(seleniumContext).map(k => stringContext[k] = stringContext.getValue ? stringContext.getValue() : '');
await driver.executeScript(
setupObservables,
JSON.stringify(stringContext)
);
// Start scanning for messages from selenium. Once you get them pass them to our seleniumContext
setInterval(async () => {
const els = await driver.findElements(webdriver.By.className('selenium-event'));
for (let i = 0; i < els.length; i++) {
const el = els[i];
let msg = await el.getText();
let id = await el.getAttribute('id');
removeElement(driver, id);
const {sender, message} = JSON.parse(msg);
debugToast(driver, `sender: ${sender} message: ${message}`);
seleniumContext[sender].next(message); // Tell it not to send the message back
}
}, 500);
// Whenever we update one of our keys in node, update the same one in the browser
Object.keys(seleniumContext).forEach(k => {
seleniumContext[k].subscribe(v => {
driver.executeScript(
`
const [k, v] = JSON.parse(arguments[0]);
if (window.seleniumContext[k].v !== v) {
window.seleniumContext[k].next(v, false);
}
`, JSON.stringify([k, v])
);
})
});
}
/**
* I don't think this is used
* @param driver
* @param type
* @param message
* @returns {Promise<void>}
*/
async function passMessageToBrowser(driver, type, message) {
const f = () => {
const {type, message} = arguments[0];
let s = `$${type}`;
if (!seleniumContext[s]) {
let message1 = `Unknown context key ${s}`;
window.prompt(message1);
}
$.toast(`${type} ${message}`);
window.seleniumContext[s].next(message);
}
}
/**
*
* @param driver {Driver}
* @param id
*/
function removeElement(driver, id) {
driver.executeScript(`
const [id] = arguments;
document.getElementById(id).remove();
`, id);
}
module.exports = {
DriverObs
};
|
// pages/teacherdetail/teacherdetail.js
Page({
/**
* 页面的初始数据
*/
data: {
imgUrls: [
// "../image/invitefr.jpg",
// "../image/invitefr.jpg",
// "../image/invitefr.jpg",
// "../image/invitefr.jpg",
],
imageav1:"https://qczby.oss-cn-shenzhen.aliyuncs.com/others/2-1.jpg",
imageav2:"https://qczby.oss-cn-shenzhen.aliyuncs.com/others/2-2.jpg",
imageav3:"https://qczby.oss-cn-shenzhen.aliyuncs.com/others/2-3.jpg",
sw:"https://qczby.oss-cn-shenzhen.aliyuncs.com/advertising/swiper1.jpg"
},
// show: function () {
// this.setData({ flag: false })
// },
// hide: function () {
// this.setData({ flag: true })
// },
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.getStorage({
key: 'openid',
fail: () => { wx.redirectTo({ url: '../index/index', }) },
})
// console.log(options.tid)
var that=this
wx.getStorage({
key: 'openid',
success: function (res) {
console.log(res)
console.log(res.data)
that.setData({
openid: res.data
})
},
});
// let url = "https://qczby.oss-cn-shenzhen.aliyuncs.com/advertising/swiper1.jpg"
// wx.downloadFile({
// url: url,
// success: (res) => {
// let temp = res.tempFilePath
// console.log(res)
// that.setData({
// sw: temp
// })
// // that.imgUrls.push(temp);
// // console.log(temp)
// // console.log(that.data.resumepng)
// }
// })
// that.setData({
// tid:options.tid
// })
// wx.request({
// url: 'https://www.lieyanwenhua.com/coach_comment',
// header: { "Content-Type": "application/x-www-form-urlencoded" },
// method: 'POST',
// data: {
// tid: that.data.tid
// },
// success: function(res){
// console.log(res)
// var comments= res.data.comment_user;
// that.setData({
// comments: comments
// })
// }
// })
// },
// commentcome: function () {
// var that = this;
// wx.request({
// url: 'https://www.lieyanwenhua.com/coach_comment',
// method: 'POST',
// data: {
// "tid": that.data.tid
// },
// header: {
// 'content-type': 'application/x-www-form-urlencoded'
// },
// success: function (res) {
// console.log(res.data);
// that.setData({
// comments: res.data.comment_user
// })
// },
// fail: function (res) {
// console.log(res);
// }
// })
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
var that = this
console.log(that.data.openid)
//这里每次显示的时候,通过openID请求所有数据,包括头像等信息
wx.request({
url: 'https://www.lieyanwenhua.com/getmyteacher',
method: 'POST',
data: {
"openid": that.data.openid
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
success: function (res) {
console.log(res.data);
if(res.data==""){
that.setData({
bindis:0
})
}
else {
that.setData({
bindis:1,
teachers: res.data
})
}
},
fail: function (res) {
console.log(res);
}
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
var that=this
// that.commentcome();
// 在这里通过openid请求评论人物的头像和昵称信息
// wx.request({
// url: 'https://www.lieyanwenhua.com/userqueryByid',
// method: 'POST',
// data: {
// "openid":
// },
// header: {
// 'content-type': 'application/x-www-form-urlencoded'
// },
// success: function (res) {
// console.log(res.data);
// that.setData({
// comments: res.data.comment_user
// })
// },
// fail: function (res) {
// console.log(res);
// }
// })
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
enterMenberThinking: function() {
wx.navigateTo({
// url: '../menberThinking/menberThinking',
url:'../webview/webview',
})
},
enterTeacherThinking: function() {
wx.navigateTo({
// url: '../teacherThinking/teacherThinking',
url: '../webview/webview',
})
},
enterCooperate: function() {
wx.navigateTo({
// url: '../enterCooperate/enterCooperate',
url: '../webview/webview',
})
}
}) |
import React, {useState} from 'react';
import { View, StyleSheet, Text, Button, Image, Alert } from 'react-native';
import Colors from '../../constants/Colors';
import * as ImagePicker from 'expo-image-picker';
import * as Permissions from 'expo-permissions'
const ImgPicker = props => {
const [pickedImage, setPickedImage] = useState()
const verifyPermissions = async () => {
const resutl = await Permissions.askAsync(Permissions.CAMERA, Permissions.CAMERA_ROLL)
if (resutl.status !== 'granted') {
Alert.alert(
'No Cam Permission',
'You need to grant camera permission first',
[{ text: 'Okay' }])
return false;
}
return true;
}
const takeImageHandler = async () => {
const hasPermission = await verifyPermissions();
if(!hasPermission){
return;
}
const image = await ImagePicker.launchCameraAsync({
allowsEditing: true,
aspect: [16, 9 ],
quality: 0.5
})
setPickedImage(image.uri)
};
return (
<View style={styles.imagePicker}>
<View style={styles.imagePreview} >
{!pickedImage ? ( <Text>No Image Pick up yet.</Text>) :
<Image style={styles.image} source={{ uri: pickedImage}} />}
</View>
<Button title='take a pic' color={Colors.primary} onPress={takeImageHandler} />
</View>
)
}
const styles = StyleSheet.create({
imagePicker: {
},
imagePreview: {
width: '100%',
height: 200,
alignItems: 'center',
justifyContent: 'center'
},
image: {
width: '100%',
height: '100%'
}
})
export default ImgPicker; |
const startBtn = document.querySelector('.start') ;
const screens =document.querySelectorAll('.screen') ;
const timeBtn = document.querySelector('.time-list') ;
const gameTime = document.querySelector('#time') ;
const board = document.querySelector('.board') ;
const colors = ['red' , 'blue' , 'yellow' , 'purple' , 'white'] ;
let time ;
let score = 0 ;
// document.addEventListener('click' , (event) => {
// if (event.target.closest('.start')){
// event.preventDefault() ;
// screens[0].classList.add('up') ;
// }
// })
startBtn.addEventListener('click' , (ev)=> {
ev.preventDefault() ;
screens[0].classList.add('up') ;
})
timeBtn.addEventListener('click' , (ev)=> {
if (ev.target.closest('.time-btn')) {
time = +ev.target.dataset.time ;
screens[1].classList.add('up') ;
startGame() ;
}
})
board.addEventListener('click' , ev=>{
if(ev.target.closest('.circle')){
score++ ;
ev.target.remove () ;
randomTarget() ;
}
})
function startGame () {
setInterval(timer , 1000) ;
randomTarget() ;
gameTime.innerHTML = `00:${time}` ;
}
function timer () {
if ( time > 0){
--time ;
if (time <10) time = `0${time}` ;
gameTime.innerHTML = `00:${time}` ;
} else {
finishGame() ;
}
}
function finishGame () {
board.innerHTML = `<h1>Cчет : <span class = "primary"> ${score}</span></h1>` ;
gameTime.parentNode.classList.add('hide') ;
}
function randomTarget() {
const target = document.createElement('div') ;
let size = randomNumber(10 , 60) ;
let colorIndex = randomNumber(0 , colors.length-1 ) ;
target.style.backgroundColor = colors[colorIndex] ;
const {width , height} = board.getBoundingClientRect() ;
const x = randomNumber(0 , width-size) ;
const y = randomNumber(0 , height-size) ;
target.classList.add('circle') ;
target.style.width = `${size}px` ;
target.style.height = `${size}px` ;
target.style.top = `${x}px` ;
target.style.left = `${y}px` ;
board.append(target) ;
}
function randomNumber(min = 0 , max) {
return(Math.round(Math.random() * (max - min) + min) ) ;
}
|
'use strict';
/**
* @ngdoc function
* @name photosApp.controller:EditCtrl
* @description
* # EditCtrl
* Controller of the photosApp
*/
angular.module('photosApp')
.controller('EditCtrl', function ($scope, $location, API) {
var id = $location.path().split('/').slice(-2)[0];
API.getPhoto(id, function(photo){
photo.tags = photo.tags.map(function(tag){
return tag.name;
});
$scope.photo = photo;
});
$scope.tags = [];
$scope.update = function(){
var tags = $scope.tags.map(function(tag){
return tag.text;
});
API.updatePhoto(id, tags, function(response){
console.log(response);
});
};
});
|
$(function(){
$('.items').on('focus', 'input[type="text"]', function(){
$(this).addClass('active');
});
$('.items').on('blur', 'input[type="text"]', function(){
$(this).removeClass('active');
});
$('.addField').on('click', function(){
var $div = $('<div/>').addClass('item');
$('<input>').attr('type', 'text').addClass('check').appendTo($div);
$('.items').append($div);
});
}); |
"use strict";
var px = require("../px");
var etg = require("../etg");
var gfx = require("../gfx");
var ui = require("../uiutil");
var chat = require("../chat");
var sock = require("../sock");
var Cards = require("../Cards");
var etgutil = require("../etgutil");
var options = require("../options");
module.exports = function(arena, acard, startempty) {
if (!Cards.loaded) return;
if (arena && (!sock.user || arena.deck === undefined || acard === undefined)) arena = false;
function updateField(renderdeck){
if (deckimport){
deckimport.value = etgutil.encodedeck(decksprite.deck) + "01" + etg.toTrueMark(editormark);
deckimport.dispatchEvent(new Event("change"));
}
}
function sumCardMinus(cardminus, code){
var sum = 0;
for (var i=0; i<2; i++){
for (var j=0; j<2; j++){
sum += cardminus[etgutil.asShiny(etgutil.asUpped(code, i==0), j==0)] || 0;
}
}
return sum;
}
function processDeck() {
for (var i = decksprite.deck.length - 1;i >= 0;i--) {
if (!(decksprite.deck[i] in Cards.Codes)) {
var index = etg.fromTrueMark(decksprite.deck[i]);
if (~index) {
editormark = index;
}
decksprite.deck.splice(i, 1);
}
}
marksprite.className = "Eicon E"+editormark;
if (decksprite.deck.length > 60) decksprite.deck.length = 60;
decksprite.deck.sort(etg.cardCmp);
if (sock.user) {
cardsel.cardminus = cardminus = {};
for (var i = decksprite.deck.length - 1;i >= 0;i--) {
var code = decksprite.deck[i], card = Cards.Codes[code];
if (card.type != etg.PillarEnum) {
if (sumCardMinus(cardminus, code) == 6) {
decksprite.deck.splice(i, 1);
continue;
}
}
if (!card.isFree()) {
if ((cardminus[code] || 0) < (cardpool[code] || 0)) {
px.adjust(cardminus, code, 1);
} else {
code = etgutil.asShiny(code, !card.shiny);
card = Cards.Codes[code];
if (card.isFree()){
decksprite.deck[i] = code;
}else if ((cardminus[code] || 0) < (cardpool[code] || 0)) {
decksprite.deck[i] = code;
px.adjust(cardminus, code, 1);
} else {
decksprite.deck.splice(i, 1);
}
}
}
}
if (arena){
decksprite.deck.unshift(acard, acard, acard, acard, acard);
}
}
updateField();
decksprite.renderDeck(0);
}
function setCardArt(code){
cardArt.texture = gfx.getArt(code);
cardArt.visible = true;
}
function incrpool(code, count){
if (code in Cards.Codes && (!arena || (!Cards.Codes[code].isOf(Cards.Codes[acard].asUpped(false).asShiny(false))) && (arena.lv || !Cards.Codes[code].upped))){
if (code in cardpool) {
cardpool[code] += count;
} else {
cardpool[code] = count;
}
}
}
var saveToQuick = false;
function quickDeck(number) {
return function() {
if (saveToQuick) {
saveButton();
sock.userEmit("changequickdeck", { number: number, name: tname.textcache });
sock.user.quickdecks[number] = tname.textcache;
fixQuickButtons();
saveToQuick = false;
quickNum.className = quickNum.className.replace(/(?:^|\s)selectedbutton(?!\S)/g, '')
}
else {
loadDeck(sock.user.quickdecks[number]);
}
}
}
function saveTo() {
saveToQuick ^= true;
if (saveToQuick) this.className += " selectedbutton"
else this.className = this.className.replace(/(?:^|\s)selectedbutton(?!\S)/g, '')
}
function fixQuickButtons(){
for (var i = 0;i < 10;i++) {
if (sock.user.selectedDeck == sock.user.quickdecks[i]) buttons[i].className += " selectedbutton";
else buttons[i].className = buttons[i].className.replace(/(?:^|\s)selectedbutton(?!\S)/g, '')
}
}
function saveDeck(force){
var dcode = etgutil.encodedeck(decksprite.deck) + "01" + etg.toTrueMark(editormark);
var olddeck = sock.getDeck();
if (decksprite.deck.length == 0){
sock.userEmit("rmdeck", {name: sock.user.selectedDeck});
delete sock.user.decknames[sock.user.selectedDeck];
}else if (olddeck != dcode){
sock.user.decknames[sock.user.selectedDeck] = dcode;
sock.userEmit("setdeck", { d: dcode, name: sock.user.selectedDeck });
}else if (force) sock.userEmit("setdeck", {name: sock.user.selectedDeck });
}
function loadDeck(x){
if (!x) return;
saveDeck();
deckname.value = sock.user.selectedDeck = x;
tname.text = x;
fixQuickButtons();
decksprite.deck = etgutil.decodedeck(sock.getDeck());
processDeck();
}
function importDeck(){
var dvalue = options.deck.trim();
decksprite.deck = ~dvalue.indexOf(" ") ? dvalue.split(" ") : etgutil.decodedeck(dvalue);
processDeck();
}
var cardminus, cardpool;
if (sock.user){
cardminus = {};
cardpool = {};
etgutil.iterraw(sock.user.pool, incrpool);
etgutil.iterraw(sock.user.accountbound, incrpool);
}else cardpool = null;
var editorui = px.mkView(function(){cardArt.visible = false}), dom = [[8, 32, ["Clear", function(){
if (sock.user) {
cardsel.cardminus = cardminus = {};
}
decksprite.deck.length = arena?5:0;
decksprite.renderDeck(decksprite.deck.length);
}]]];
function sumscore(){
var sum = 0;
for(var k in artable){
sum += arattr[k]*artable[k].cost;
}
return sum;
}
function makeattrui(y, name){
function modattr(x){
arattr[name] += x;
if (arattr[name] >= (data.min || 0) && (!data.max || arattr[name] <= data.max)){
var sum = sumscore();
if (sum <= arpts){
bv.text = arattr[name];
curpts.text = (arpts-sum)/45;
return;
}
}
arattr[name] -= x;
}
y = 128+y*20;
var data = artable[name];
var bv = px.domText(arattr[name]);
var bm = px.domButton("-", modattr.bind(null, -(data.incr || 1)));
var bp = px.domButton("+", modattr.bind(null, data.incr || 1));
bm.style.width = bp.style.width = "14px";
dom.push([4, y, name], [38, y, bm], [56, y, bv], [82, y, bp]);
}
function switchDeckCb(x){
return function() {
loadDeck(x.toString());
}
}
function saveButton() {
if (deckname.value) {
sock.user.selectedDeck = deckname.value;
fixQuickButtons();
tname.text = sock.user.selectedDeck;
saveDeck();
}
}
var tutspan;
function tutorialClick() {
if (tutspan) {
document.body.removeChild(tutspan);
tutspan = null;
return;
}
//100, 272, 800, 328
var span = document.createElement("span");
[[100, 32, 624, 198, "This is where the deck you are building shows up. Use the buttons to the left to save and load your deck: " +
"\nClear: Erase this deck \nSave & Exit: Save the current deck and return to the main menu \nImport: Import a deck code from the import box \nSave: Save the current deck to the name in the name box in the top left" +
"\nLoad: Load the deck wih the name you have typed in the name box in the top left \nSave to #: Save the current deck and name to one of the quickload slots \nTip: Use one of the quickdeck buttons as a \"New Deck\" button, and then save any decks you make there to a proper name"],
[298, 6, 426, 24, "Clicking a quickload slot will instantly load the deck saved there"],
[100, 232, 418, 38, "Choose a mark. You will gain 1 quantum per turn of that element. Mark of Chroma gives 3 random quanta."],
[520, 234, 320, 24, "The import box shows the deck code of the deck"],
[2, 350, 250, 100, "Click the element buttons to show cards of that element.\nThe rarity filters will only show cards of that rarity, except pillar filter which will show all cards.", ],
[300, 350, 320, 48, "Clicking a card will add it to your deck. A number after a / shows how many shiny cards you have."],
[80, 530, 310, 22, ": Shows all cards, including those you don't own"],
[80, 575, 160, 22, ": Don't show shiny cards"]].forEach(function(info) {
var div = px.domBox(info[2], info[3], "tutorialbox");
div.style.position = "absolute";
div.style.left = info[0] + "px";
div.style.top = info[1] + "px";
var text = px.domText(info[4]);
text.style.color = "#000000";
text.style.position = "absolute";
text.style.left = 5 + "px";
text.style.top = "50%";
text.style.transform = "translateY(-50%)";
div.appendChild(text);
span.appendChild(div);
});
//40, 270, 620, 168,
tutspan = span;
document.body.appendChild(span);
}
var buttons;
if (arena){
dom.push([8, 58, ["Save & Exit", function() {
if (decksprite.deck.length < 35 || sumscore()>arpts) {
chat("35 cards required before submission");
return;
}
var data = { d: etgutil.encodedeck(decksprite.deck.slice(5)) + "01" + etg.toTrueMark(editormark), lv: arena.lv };
for(var k in arattr){
data[k] = arattr[k];
}
if (!startempty){
data.mod = true;
}
sock.userEmit("setarena", data);
chat("Arena deck submitted");
startMenu();
}]], [8, 84, ["Exit", function() {
require("./ArenaInfo")(arena);
}]]);
var arpts = arena.lv?515:425, arattr = {hp:parseInt(arena.hp || 200), mark:parseInt(arena.mark || 2), draw:parseInt(arena.draw || 1)};
var artable = {
hp: { min: 65, max: 200, incr: 45, cost: 1 },
mark: { cost: 45 },
draw: { cost: 135 },
};
var curpts = new px.domText((arpts-sumscore())/45);
dom.push([4, 188, curpts])
makeattrui(0, "hp");
makeattrui(1, "mark");
makeattrui(2, "draw");
} else {
var quickNum = px.domButton("Save to #", saveTo);
dom.push([8, 58, ["Save & Exit", function() {
if (sock.user) saveDeck(true);
startMenu();
}]], [8, 84, ["Import", importDeck]]);
if (sock.user) {
var tutorialbutton = px.domEButton(13,tutorialClick);
dom.push([4,220,tutorialbutton]);
var tname = px.domText(sock.user.selectedDeck);
dom.push([100, 8, tname],
[8, 110, ["Save", saveButton
]], [8, 136, ["Load", function() {
loadDeck(deckname.value);
}]], [8, 162, ["Exit", function() {
if (sock.user) sock.userEmit("setdeck", { name: sock.user.selectedDeck });
startMenu();
}]], [220, 8, quickNum]);
buttons = new Array(10);
for (var i = 0;i < 10;i++) {
var b = px.domButton(i+1, quickDeck(i));
b.style.width = "32px";
dom.push([300 + i*36, 8, b]);
buttons[i] = b;
}
fixQuickButtons();
}
}
var marksprite = document.createElement("span");
dom.push([66, 200, marksprite]);
var editormark = 0;
for (var i = 0;i < 13;i++) {
(function(_i) {
dom.push([100 + i * 32, 234,
px.domEButton(i, function() {
editormark = _i;
marksprite.className = "Eicon E"+_i;
updateField();
})
]);
})(i);
}
var decksprite = new px.DeckDisplay(60, setCardArt,
function(i){
var code = decksprite.deck[i], card = Cards.Codes[code];
if (!arena || code != acard){
if (sock.user && !card.isFree()) {
px.adjust(cardminus, code, -1);
}
decksprite.rmCard(i);
updateField();
}
}, arena ? (startempty ? [] : etgutil.decodedeck(arena.deck)) : etgutil.decodedeck(sock.getDeck())
);
editorui.addChild(decksprite);
var cardsel = new px.CardSelector(dom, setCardArt,
function(code){
if (decksprite.deck.length < 60) {
var card = Cards.Codes[code];
if (sock.user && !card.isFree()) {
if (!(code in cardpool) || (code in cardminus && cardminus[code] >= cardpool[code]) ||
(card.type != etg.PillarEnum && sumCardMinus(cardminus, code) >= 6)) {
return;
}
px.adjust(cardminus, code, 1);
}
decksprite.addCard(code, arena?5:0);
updateField();
}
}, !arena, !!cardpool
);
cardsel.cardpool = cardpool;
cardsel.cardminus = cardminus;
editorui.addChild(cardsel);
var cardArt = new PIXI.Sprite(gfx.nopic);
cardArt.position.set(734, 8);
editorui.addChild(cardArt);
if (!arena){
if (sock.user){
var deckname = document.createElement("input");
deckname.id = "deckname";
deckname.style.width = "80px";
deckname.placeholder = "Name";
deckname.value = sock.user.selectedDeck;
deckname.addEventListener("keydown", function(e){
if (e.keyCode == 13) {
loadDeck(this.value);
}
});
deckname.addEventListener("click", function(e){
this.setSelectionRange(0, 99);
});
dom.push([4, 4, deckname]);
}
var deckimport = document.createElement("input");
deckimport.id = "deckimport";
deckimport.style.width = "190px";
deckimport.style.height = "20px";
deckimport.placeholder = "Deck";
deckimport.addEventListener("click", function(){this.setSelectionRange(0, 333)});
deckimport.addEventListener("keydown", function(e){
if (e.keyCode == 13){
this.blur();
importDeck();
}
});
options.register("deck", deckimport);
dom.push([520, 238, deckimport]);
}
function resetCardArt() { cardArt.visible = false }
document.addEventListener("mousemove", resetCardArt, true);
px.refreshRenderer({ view: editorui, editdiv: dom, endnext: function() { document.removeEventListener("mousemove", resetCardArt, true); if (tutspan) document.body.removeChild(tutspan); } });
if (!arena){
deckimport.focus();
deckimport.setSelectionRange(0, 333);
}
processDeck();
}
var startMenu = require("./MainMenu"); |
const test = require('tape')
const vhosts = require('../lib/vhosts')
const httpMocks = require('node-mocks-http')
test('load full subdomain directory if present', function (t) {
t.plan(2)
const req = httpMocks.createRequest({
method: 'GET',
url: '/',
hostname: 'subdomain2.example.com'
})
const res = httpMocks.createResponse()
const handler = vhosts({root: `${__dirname}/data/`})
handler(req, res, function (err) {
t.error(err)
t.equal(req.url, '/subdomain2.example.com/')
})
})
test('allow just the subdomain as a subfolder', function (t) {
t.plan(2)
const req = httpMocks.createRequest({
method: 'GET',
url: '/',
hostname: 'subdomain1.example.com'
})
const res = httpMocks.createResponse()
const handler = vhosts({root: `${__dirname}/data/`})
handler(req, res, function (err) {
t.error(err)
t.equal(req.url, '/subdomain1/')
})
})
test('allow multiple levels in a subdomain', function (t) {
t.plan(2)
const req = httpMocks.createRequest({
method: 'GET',
url: '/',
hostname: 'subB.subA.example.com'
})
const res = httpMocks.createResponse()
const handler = vhosts({root: `${__dirname}/data/`})
handler(req, res, function (err) {
t.error(err)
t.equal(req.url, '/subA/subB/')
})
})
test("don't die if it's just an ip address and not a regular domain name", function (t) {
t.plan(2)
const req = httpMocks.createRequest({
method: 'GET',
url: '/',
hostname: '127.0.0.1'
})
const res = httpMocks.createResponse()
const handler = vhosts({root: `${__dirname}/data/`})
handler(req, res, function (err) {
t.error(err)
t.equal(req.url, '/')
})
})
test('work with localhost subdomain', function (t) {
t.plan(2)
const req = httpMocks.createRequest({
method: 'GET',
url: '/',
hostname: 'subdomain1.localhost'
})
const res = httpMocks.createResponse()
const handler = vhosts({root: `${__dirname}/data/`})
handler(req, res, function (err) {
t.error(err)
t.equal(req.url, '/subdomain1/')
})
})
test("send 404 immediately if the hostname isn't found", function (t) {
t.plan(2)
const req = httpMocks.createRequest({
method: 'GET',
url: '/',
hostname: 'nope.example.com'
})
const res = httpMocks.createResponse()
const handler = vhosts({root: `${__dirname}/data/`})
handler(req, res, function (err) {
t.ok(err)
t.equal(err.status, 404)
})
})
test("don't worry about specific files existing, just the dir", function (t) {
t.plan(2)
const req = httpMocks.createRequest({
method: 'GET',
url: '/index',
hostname: 'subdomain1.example.com'
})
const res = httpMocks.createResponse()
const handler = vhosts({root: `${__dirname}/data/`})
handler(req, res, function (err) {
t.error(err)
t.equal(req.url, '/subdomain1/index')
})
})
|
import React, {Component} from "react";
import {ActivityIndicator, ScrollView, View, StyleSheet} from "react-native";
import {getAuthedAPI} from "../api";
import {connect} from "react-redux";
import {ListItem, Text, Button} from "react-native-elements";
import HeaderWithBackButton from "./HeaderWithBackButton";
import {AvailabilitySchedule} from "../util";
import ScheduleViewer from "./ScheduleViewer";
import moment from "moment-timezone";
import {boundMethod} from "autobind-decorator";
import {Actions} from "react-native-router-flux";
import strings from "../strings";
import {sprintf} from "sprintf-js";
import DateTimePicker from "react-native-modal-datetime-picker";
class PossibleAppointment {
constructor(moment) {
this.moment = moment;
}
}
const APPOINTMENT_TIME_FORMAT = "ddd, MMMM Do, h:mm a";
class AppointmentScheduler extends Component {
constructor(props) {
super(props);
this.state = {
schedules: undefined,
possibleAppointments: undefined,
startDate: moment(),
endDate: moment().add(7, "days"),
startDatePickerVisible: false,
endDatePickerVisible: false,
searchDateValidationError: null,
appointmentRequests: null
};
}
componentDidMount() {
// Fetch availability schedules
getAuthedAPI()
.getAvailabilitySchedules(this.props.provider.uuid)
.then((response) => {
const schedules = response.result.map((serverObj) => AvailabilitySchedule.fromServerObject(serverObj));
this.setState({
schedules
})
});
// Fetch appointment requests
getAuthedAPI()
.getAppointmentRequests()
.then((requests) => {
this.setState({
appointmentRequests: requests
})
});
this.updateSearch();
}
@boundMethod
onAppointmentSelect(appointment) {
Actions.push("confirmPrompt", {
title: strings.pages.appointmentScheduler.confirmAppointment,
subtitle: sprintf(
strings.pages.appointmentScheduler.confirmSubtitle,
appointment.moment.format(APPOINTMENT_TIME_FORMAT)
),
onConfirm: () => {
getAuthedAPI()
.requestAppointment(appointment.moment)
.then(() => {
alert("Appointment requested successfully. You will be notified when your provider accepts the request.");
Actions.refresh({key: Math.random()})
})
},
onCancel: () => {}
});
}
@boundMethod
toggleStartDatePicker() {
this.setState((oldState) => {
return {
startDatePickerVisible: !oldState.startDatePickerVisible
}
})
}
@boundMethod
toggleEndDatePicker() {
this.setState((oldState) => {
return {
endDatePickerVisible: !oldState.endDatePickerVisible
}
})
}
calcSearchDateValidationError(dateEnd, dateStart) {
let searchDateValidationError = null;
if (dateEnd.diff(dateStart, "days") > 7) {
searchDateValidationError = strings.pages.appointmentScheduler.searchDatesTooFarApart;
}
return searchDateValidationError;
}
@boundMethod
onSelectStartDate(date) {
const startMoment = moment(date);
const searchDateValidationError = this.calcSearchDateValidationError(this.state.endDate, startMoment);
this.setState({
possibleAppointments: undefined,
startDate: startMoment,
startDatePickerVisible: false,
searchDateValidationError
}, searchDateValidationError === null ? this.updateSearch : undefined);
}
@boundMethod
onSelectEndDate(date) {
const endMoment = moment(date);
const searchDateValidationError = this.calcSearchDateValidationError(endMoment, this.state.startDate);
this.setState({
possibleAppointments: undefined,
endDate: endMoment,
endDatePickerVisible: false,
searchDateValidationError
}, searchDateValidationError === null ? this.updateSearch : undefined);
}
@boundMethod
onDateSelectCancel() {
this.setState({
startDatePickerVisible: false,
endDatePickerVisible: false
})
}
@boundMethod
updateSearch() {
getAuthedAPI()
.getAvailableAppointments(this.state.startDate, this.state.endDate)
.then((response) => {
const times = response.result;
const possibleAppointments = [];
times.forEach((time) => {
possibleAppointments.push(new PossibleAppointment(moment.utc(time).local()))
});
this.setState({
possibleAppointments
});
})
}
@boundMethod
cancelRequest(uuid) {
getAuthedAPI()
.declineAppointmentRequest(uuid)
.then(() => {
alert("Appointment request canceled successfully.");
Actions.refresh({key: Math.random()});
})
}
render() {
return (
<ScrollView>
<HeaderWithBackButton headerText={strings.pages.appointmentScheduler.headerText} />
<View style={{margin: 20, marginBottom: 0}}>
<Text h4>Your appointment requests:</Text>
{this.state.appointmentRequests === null &&
<Text>Loading</Text> ||
<View>
{this.state.appointmentRequests.length &&
this.state.appointmentRequests.map((request, i) =>
<View style={{display: "flex", flexDirection: "row", justifyContent: "space-between", marginTop: 10}} key={i}>
<Text style={style.appointmentRequest}>{moment.utc(request.start_time).local().format("ddd, MM/DD @ h:mma")}</Text>
<Button
title="Cancel"
buttonStyle={{backgroundColor: "red"}}
onPress={() => this.cancelRequest(request.uuid)}
/>
</View>
) ||
<Text>You do not have any pending appointment requests. You can create one by selecting a time below.</Text>
}
</View>
}
<Text h4 style={{marginTop: 10}}>{strings.pages.appointmentScheduler.yourProvidersSchedule}</Text>
<Text>All times are displayed in {moment().tz(moment.tz.guess()).format('z')}.</Text>
<ScheduleViewer
schedules={this.state.schedules}
/>
<View style={{marginTop: 20, marginBottom: 0}}>
<Text h4 style={{marginBottom: 10}}>Search</Text>
<View style={{display: "flex", flexDirection: "row", justifyContent: "space-between", alignItems: "center"}}>
<Text>Start date:</Text>
<Button
title={this.state.startDate.format("M-D-YYYY")}
onPress={this.toggleStartDatePicker}
/>
<DateTimePicker
isVisible={this.state.startDatePickerVisible}
mode="date"
date={this.state.startDate.toDate()}
onConfirm={this.onSelectStartDate}
onCancel={this.onDateSelectCancel}
/>
<Text>End date:</Text>
<Button
title={this.state.endDate.format("M-D-YYYY")}
onPress={this.toggleEndDatePicker}
/>
<DateTimePicker
isVisible={this.state.endDatePickerVisible}
mode="date"
date={this.state.startDate.toDate()}
onConfirm={this.onSelectEndDate}
onCancel={this.onDateSelectCancel}
/>
</View>
{this.state.searchDateValidationError &&
<Text style={{color: "red"}}>{this.state.searchDateValidationError}</Text>
}
</View>
</View>
{this.state.possibleAppointments !== undefined &&
this.state.possibleAppointments.map((appointment, i) => {
return (
<ListItem
key={i}
bottomDivider
onPress={() => this.onAppointmentSelect(appointment)}
>
<ListItem.Content>
<ListItem.Title>
{appointment.moment.format(APPOINTMENT_TIME_FORMAT)}
</ListItem.Title>
</ListItem.Content>
<ListItem.Chevron />
</ListItem>
);
})
||
<ActivityIndicator style={{marginTop: 20}} />
}
</ScrollView>
);
}
}
const style = StyleSheet.create({
appointmentRequest: {
marginTop: 10,
marginBottom: 10,
fontSize: 18
}
});
function mapStateToProps(state) {
return {
provider: state.provider
}
}
export default connect(mapStateToProps)(AppointmentScheduler);
|
import React, { Component } from 'react'
import { Link } from 'react-router'
import FontAwesome from 'react-fontawesome'
import Loading from '../../../components/Loading'
import styles from './Wallet.scss'
export default class Wallet extends Component {
componentDidMount() {
const { fetchWallet } = this.props
fetchWallet()
}
render() {
const {
wallet: {
address,
confirmed,
unconfirmed,
history,
fetching,
error
}
} = this.props
return (
<div className={styles.wallet}>
{
fetching ?
<Loading />
:
<div className={styles.content}>
<section className={styles.header}>
<div className={styles.icon}>
<span className={styles.helper} />
<FontAwesome name='btc' />
</div>
<h2 className={styles.confirmedbtc}>
{confirmed}
<span className={styles.currency}>
btc
</span>
</h2>
</section>
</div>
}
</div>
);
}
}
|
import React, { useContext } from 'react';
import { NavBarContext } from './context';
const Navbar = () => {
const [name] = useContext(NavBarContext)
return (
<div className="row">
<div className="col bg-info p-5">
<div className="float-left h3">Hi {name}</div>
</div>
</div>
);
};
export default Navbar; |
require.config({
shim: {
'fullcalendar': ['moment', 'jquery'],
},
paths: {
'fullcalendar': 'static/plugins/fullcalendar/js/fullcalendar.min',
'moment': 'static/plugins/fullcalendar/js/moment.min',
}
}); |
/* eslint-disable no-console */
/* eslint-disable consistent-return */
import AWS from 'aws-sdk';
import listParams from './params/params.medialive.list';
import inputParams from './params/params.medialive.input';
import channelParams from './params/params.medialive.channel';
// Instantiate AWS SDK here
const ML = new AWS.MediaLive();
const S3 = new AWS.S3();
const params = {};
const delChParams = {
ChannelId: '3062781' /* required */
};
// Generic function to handle user input, params modification and route management
function paramsCheck(importParams, req) {
let params = importParams;
console.log("req.body length is :", Object.keys(req.body).length)
if (Object.keys(req.body).length == 0) {
return importParams
} else {
Object.keys(req.body).map(key => {
console.log("key is ", key);
if (key in params) {
params[key] = req.body[key]
}
})
return params
}
}
function insertInputToChannel(channelParams, id) {
console.log("id in insertInputToChannel is::: ",id)
try {
const params = channelParams;
params['InputAttachments'] = [{
'InputId': id,
'InputSettings': {
'SourceEndBehavior': 'CONTINUE',
'NetworkInputSettings': {}
}
}]
return params;
} catch (e) {
console.log(e)
}
}
export async function workflow(req, res) {
const workflowData = {};
console.log("req.body is", req.body)
try {
await ML.createInput(paramsCheck(inputParams,req), (err, inputData) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(inputData); // successful response
workflowData['inputData'] = inputData;
console.log("inputData.Id is:: ", inputData.Input.Id)
try {
ML.createChannel(paramsCheck(insertInputToChannel(channelParams, inputData.Input.Id), req), (err, channelData) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(channelData); // successful response
workflowData['channelData'] =channelData
return res.status(200).send({
message: workflowData,
});
});
} catch (e) {
return res.status(400).end(e);
}
});
} catch (e) {
console.log(e)
}
}
/*
* Create Media Live Input
*/
export async function createInput(req, res) {
const dataToSend = {};
console.log('req in create/input is :', req.body);
try {
await ML.createInput(paramsCheck(inputParams, req), (err, inputData) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(inputData); // successful response
console.log("inputData.Id is:: ", inputData.Input.Id)
dataToSend['inputData'] =inputData
return res.status(200).send({
message: dataToSend,
});
});
} catch (e) {
return res.status(400).end(e);
}
}
/*
* Create Media Live Channel
*/
export async function createChannel(req, res) {
const dataToSend = {};
console.log('req in create/channel is :', req.body);
try {
await ML.createChannel(paramsCheck(channelParams,req), (err, channelData) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(channelData); // successful response
dataToSend['channelData'] =channelData
return res.status(200).send({
message: dataToSend,
});
});
} catch (e) {
return res.status(400).end(e);
}
}
/*
* Delete Media Live Channel
*/
export async function deleteChannel(req, res) {
try {
await ML.deleteChannel(delChParams, (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
return res.status(200).send({
message: data,
});
});
} catch (e) {
return res.status(400).end(e);
}
}
/*
* Get Media Live Channel List
*/
export async function getChannelList(req, res) {
console.log('req in list/channel is :', req.body);
try {
await ML.listChannels(paramsCheck(listParams, req), (err, data) => {
console.log('modified param list is ', listParams);
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
return res.status(200).send({
message: data,
});
});
} catch (e) {
return res.status(400).end(e);
}
}
/*
* Get S3 Bucket List
*/
export async function getBucketList(req, res) {
console.log('req in list/bucket is :', req.body);
try {
await S3.listBuckets(paramsCheck(params, req), (err, data) => {
if (err) console.log(err, err.stack); // an error occurred
else console.log(data); // successful response
return res.status(200).send({
message: data,
});
});
} catch (e) {
return res.status(400).end(e);
}
}
|
var path = require('path')
, expect = require('expect.js')
, fun = require(path.resolve(__dirname, '..', 'src', 'chapter-9-3.js'))
describe('Chapter 9.3', function() {
it("works", function() {
var input = [15,16,19,20,1,3,4,5,7,10,14]
, needle = 5
, output = 8
expect(fun(input, needle)).to.eql(output)
})
})
|
import React, { Component } from 'react';
import UserAPI from 'UserAPI';
import UsersTable from './components/UsersTable';
export default class AdminViewUsersPage extends Component {
constructor (props) {
super(props);
this.state = {
users: [],
};
}
componentDidMount () {
UserAPI.getAllUsers()
.then((data) => {
if (data.success) {
this.setState({ users: data.users });
}
})
.catch((error) => {
console.log(error);
})
}
handleOnChangeUserStatus = (id) => {
// console.log('@@@@@@@@ id', id);
UserAPI.toggleUserStatus(id)
.then((res) => {
if (res.success) { return UserAPI.getAllUsers(); }
else { throw Error(res); }
})
.then((data) => {
if (data.success) { this.setState({ users: data.users }); }
else { throw Error(res); }
})
.catch((error) => {
console.log(error);
})
}
render () {
let {users} = this.state;
return (
<div className="">
<UsersTable users={users} onChange={this.handleOnChangeUserStatus} />
</div>
);
}
};
|
var pages = require('../../client/pages');
module.exports = {
path: '/',
component: pages.App,
indexRoute: {
component: pages.Home
},
childRoutes: [{
path: 'confirm-email',
component: pages.EmailConfirmPage
}, {
path: 'login',
component: pages.Login
}, {
path: 'register',
component: pages.Register
}]
}
|
/**
* Your task is to find the first element of an array that is not consecutive.
By not consecutive we mean not exactly 1 larger than the previous element of the array.
E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number.
If the whole array is consecutive then return null2.
The array will always have at least 2 elements1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too!
If you like this Kata, maybe try this one next: https://www.codewars.com/kata/represent-array-of-numbers-as-ranges
*/
function firstNonConsecutive (arr) {
//loop from idx
for(let i = 1; i < arr.length; i++){
//check first index for be previous index value
if(arr[i-1] !== (arr[i]-1)){
console.log(arr[i], (arr[i]-1))
return arr[i];
}
}
return null;
}
firstNonConsecutive([1,2,3,4,6,7,8]) //6 |
import React from 'react';
import styled from 'styled-components';
import PropTypes from 'prop-types';
const ErrorBody = styled.div`
position: absolute;
display: block;
pointer-events: none
padding: 10px;
color: #ff5a5f;
width: 100%;
text-align: center;
bottom: 65px;
background-color: rgba(255, 255, 255, 0.7);
`;
const ErrorPrompt = ({ validationMessage }) => <ErrorBody>{validationMessage}</ErrorBody>;
ErrorPrompt.propTypes = {
validationMessage: PropTypes.string.isRequired,
};
export default ErrorPrompt;
|
export const API_KEY = '59fce579ddc5abcc2eec6bada8fb6819'
|
import { createContext } from "react";
export const ThreadContext = createContext();
|
var express = require('express');
var app = express();
//var router = express.Router();
var cors = require('cors');
app.use(cors());
app.use(express.urlencoded({extended: true}));
app.use(express.json())
const https = require('https');
//const wss = require('wss');
const fs = require('fs');
const PORT = 2443;
const options = {
key: fs.readFileSync("/etc/letsencrypt/live/tester2.kaist.ac.kr/privkey.pem"),
cert: fs.readFileSync("/etc/letsencrypt/live/tester2.kaist.ac.kr/cert.pem"),
ca: fs.readFileSync("/etc/letsencrypt/live/tester2.kaist.ac.kr/chain.pem")
};
const path = require("path");
var controller_main = require("./server/login-controller");
/*
router.post("/login", async function(req,res){
var result = await controller_main.SignIn(req,res); res.send(result);
});
// logout
router.get("/logout", function(req,res){
console.log("clear cookie");
res.clearCookie('userid');
res.clearCookie('usertype');
console.log("destroy session");
req.session.destroy();
res.sendFile(path.join(__dirname , "../public/login.html"));
});
*/
// regsiter
app.route("/register").post(async function (req,res) {
//console.log("route accepted ", req.body);
var result = await controller_main.SignUp(req, res);
res.send(result);
});
app.use(function(req, res, next) {
//console.log(req);
res.status(404).send('Unable to find the requested resource!');
});
//app.use(router);
var https_server = https.createServer(options, app);
https_server.listen(PORT);
console.log("listening..."); |
/*
Display User Detail and allow editing
Created by dgarrett on 11/21/13.
*/
RamModule
// Common functions for Meeting Vote Controller
.factory('meetingVoteCommon', function(meetingsDao, dataCache, utilityService, logging) {
var meetingVoteCommon = {};
var thisModule = 'meetingVoteCommon';
logging.info('starting module',thisModule);
// Common read of Meeting by VoteId
meetingVoteCommon.readScopeMeetingByVoteId = function(scope,voteId,callback){
dataCache.vote = {};
scope.editableDetail = {};
scope.errorMessage = '';
if (!voteId) return;
voteId = utilityService.removeNonNumeric(voteId);
scope.errorMessage = 'reading meeting...';
meetingsDao.readMeetingByVoteId(voteId,function(err){
if (err){
scope.errorMessage = utilityService.parseErrorMessage(err);
}
else {
scope.errorMessage = '';
logging.inspect(dataCache.vote);
scope.editableDetail = dataCache.vote;
callback();
}
});
};
return meetingVoteCommon;
})
// Allow entry of a vote for voteId: /vote/:voteID
.controller('voteController',
function ($scope, $routeParams, $location, meetingsDao, meetingVoteCommon, dataCache, utilityService, logging) {
var thisModule = 'voteController';
logging.info('starting module',thisModule);
$scope.voteId = $routeParams.voteId;
$scope.defaultUserFromSession(); // if user not cached, try to read user via session
$scope.setStatusMessage('');
$scope.errorMessage = undefined;
$scope.prompt = 'Enter Meeting Number and Select Rating';
$scope.verifyMeeting = function(){
meetingVoteCommon.readScopeMeetingByVoteId($scope,$scope.voteId,function(){
$scope.prompt = 'Select a Rating for this meeting';
});
};
$scope.verifyMeeting();
$scope.saveVote = function(vote){
logging.info('in saveVote',thisModule);
$scope.errorMessage = '';
if (!$scope.voteForm.$valid){
logging.info('invalid form',thisModule);
$scope.errorMessage = 'Please enter a meeting number';
return;
}
$scope.errorMessage = 'submitting rating';
var voteId = $scope.voteId;
/*
var dashLoc = voteId.indexOf('-');
if (dashLoc > 0 && dashLoc < voteId.length- 1){
voteId = voteId.substring(0,dashLoc) + voteId.substring(dashLoc+1);
}
*/
voteId = utilityService.removeNonNumeric(voteId);
meetingsDao.submitVote(voteId, vote, function(data){
if (data.status && data.status === 404){
$scope.errorMessage = 'meeting not found or not available for rating';
return;
}
if (!data.itemId){
$scope.errorMessage = utilityService.parseErrorMessage(data.err);
logging.error('error: '+$scope.prompt,thisModule);
return;
}
// vote submission complete
$location.path('/confirmVote/'+voteId+'/vote/'+vote+'/item/'+data.itemId);
});
};
})
// Confirm rating submitted
.controller('confirmVoteController',
function ($scope, $routeParams, $location, meetingVoteCommon, meetingsDao, dataCache, utilityService, logging) {
var thisModule = 'confirmVoteController';
logging.info('starting module',thisModule);
$scope.defaultUserFromSession(); // if user not cached, try to read user via session
$scope.undoVote = function(){
// TODO: add code to undo using voteId and itemId
// from dataCache.vote
// then go back to voting page
$scope.setStatusMessage('Sorry... this function is not yet implemented.');
};
$scope.goHome = function(){
$location.path('/');
};
// Set up Detail Meeting Fields
$scope.setStatusMessage('');
$scope.fieldDisabled = true;
$scope.buttons =
[ {name: 'Home Page', function: $scope.goHome},
{name: 'Change Rating', function: $scope.undoVote} ];
dataCache.detailView = meetingsDao.voteResultView;
meetingVoteCommon
.readScopeMeetingByVoteId($scope,$routeParams.voteId,function(){
$scope.editableDetail.vote = $routeParams.vote;
$scope.setStatusMessage('Thank you for your rating!');
});
})
; |
import React from 'react';
import {View, StyleSheet, Text} from 'react-native';
import colors from '../constants/colors';
const CardTextField = props => {
const condRender = () => {
// if no number, just show the text
if (props.exerciseDuration === '') {
return (
<View style={styles.section}>
<Text style={styles.text}>{props.exerciseName}</Text>
</View>
);
}
//show both text and number
return (
<>
<View style={styles.section}>
<Text style={{...styles.text, ...props.style}}>
{props.exerciseName}
</Text>
</View>
<View style={styles.section}>
<Text style={{...styles.text, ...props.style}}>
{props.exerciseDuration}
</Text>
</View>
</>
);
};
return <>{condRender()}</>;
};
const styles = StyleSheet.create({
section: {
width: '100%',
height: '35%',
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 32,
color: colors.PRIMARY_COLOR,
fontWeight: 'bold',
},
});
export default CardTextField;
|
var searchData=
[
['plane',['plane',['../structplane.html',1,'']]],
['point',['point',['../structpoint.html',1,'']]]
];
|
const path = require('path')
const webpack = require('webpack')
const merge = require('webpack-merge')
const baseConfig = require('./webpack.config.base')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin') // 分离css
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin') // css压缩
const utils = require('../config/utils')
let devConfig
devConfig = merge(baseConfig, {
resolve: {
alias: {
'@': path.resolve(__dirname, '../src'),
'vue$': 'vue/dist/vue.esm.js'
},
extensions: ['*', '.js', '.vue', '.json']
},
devServer: utils.devServer(),
performance: {
hints: false
},
module: { // eslint
rules: [
{
test: /\.(vue|js)$/,
loader: 'eslint-loader',
exclude: [
/node_modules/,
'../src/assets/'
],
enforce: 'pre'
}
]
},
plugins: [
new ExtractTextPlugin('assets/css/main.css?[hash]'),
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
new HtmlWebpackPlugin({ // 打包输出HTML
title: 'Hello World app',
minify: { // 压缩HTML文件
removeComments: true, // 移除HTML中的注释
collapseWhitespace: true, // 删除空白符与换行符
minifyCSS: true// 压缩内联css
},
filename: 'index.html',
template: 'index.html'
}),
new CleanWebpackPlugin(['dist']), // 清空打包文件
new webpack.LoaderOptionsPlugin({
minimize: true
}),
new webpack.optimize.CommonsChunkPlugin({
name: 'common', // 选择入口处打包的文件名称
filename: 'assets/js/[name]-[id].js?[hash:8]' // 被打包好的文件路径及公共模块名称
}),
new webpack.SourceMapDevToolPlugin({
filename: '[file].map',
include: ['main.js'],
exclude: ['vendor.js'],
column: false
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"development"'
},
'process.__DEV__': JSON.stringify(process.env.NODE_ENV)
})
]
})
module.exports = devConfig
|
"use strict";
var express = require('express');
var router = express.Router();
var sdk = require('@ekhanei/sdk');
var utils = require('@ekhanei/utils');
var _ = require('lodash');
var moment = require('moment');
var adMiddleware = require("../middleware/ad-middleware");
var adHelpers = require("../lib/helpers/ad-helper");
var imageHelper = require('../lib/helpers/image-helper');
var surveyUrls = require('../config/surveyurl');
/**
* Builds the proper phone information to show on the view
* @param ad
* @return {{full: *, pretty: *}}
*/
function phoneNumber(ad) {
if (!adHelpers.isFromBlocket(ad)) {
return {
full: ad["account"]["phone"][0],
pretty: utils.prettyPhoneNumber(ad["account"]["phone"][0])
}
}
//Special care for those ads that are from blocket
return {
full: ad["parameters"]["blocket_phone"],
pretty: utils.prettyPhoneNumber(ad["parameters"]["blocket_phone"])
}
}
/**
* Builds the image array depending on where the ad comes from
* @param ad
* @return {Array}
*/
function adImages(ad) {
if (!adHelpers.hasBlocketImages(ad)) {
//Normal images way of working
return _.map(ad.images, function (image, i) {
var filename = image["original"]["src"].split('/').pop();
var imageId = filename.split('.').shift().replace(/_/g, '-');
return imageHelper.getListImage(imageId, i, 'medium');
});
}
//Special care for blocket ads just get the images out
return _.map(ad.images, function (image) {
//XXX: This is and UGLY hack but blocket ads will leave only 30 days so i don't care
return image["original"]["src"];
});
}
/**
* Builds the thumbs array images
* @param ad
* @return {Array}
*/
function adThumbs(ad) {
if (!adHelpers.hasBlocketImages(ad)) {
//Normal images way of working
return _.map(ad.images, function (image, i) {
var filename = image["original"]["src"].split('/').pop();
var imageId = filename.split('.').shift().replace(/_/g, '-');
return imageHelper.getListImage(imageId, i, 'square');
});
}
//Special care for blocket ads just get the images out
return _.map(ad.images, function (image) {
//XXX: This is and UGLY hack but blocket ads will leave only 30 days so i don't care
return image["original"]["src"].replace("/images/", "/thumbs/");
});
}
/**
* Returns URL for survey
* @param category id
* @return {string}
*/
function surveyUrl (cat){
// Serve survey moneky fashion url
if(cat === 2) {
return surveyUrls.buyers.fashion.url;
}
// Serve survey moneky bike url
else if(cat === 6) {
return surveyUrls.buyers.bike.url;
}
// Serve survey moneky other url
else {
return surveyUrls.buyers.others.url;
}
}
/**
* Ad view
*/
router.get('/ad/:slug', adMiddleware, function (req, res, next) {
var ad = req.ad.attributes;
ad.id = req.ad.id;
// Add line breaks to ad description
ad.description = ad.description.replace(/(?:\r\n|\r|\n)/g, '<br />');
ad.list_time = moment(ad.list_time).calendar(null, {
sameElse: 'DD/MM/YYYY'
});
// Construct array of image ids from the sources
var images = adImages(ad),
thumbnails = adThumbs(ad),
ogImage = images[0].replace('medium','opengraph');
var viewData = {
title: ad.title,
scripts: ['/js/ad-view.js'],
adSlug: req.params.slug,
ad: ad,
phoneNumber: phoneNumber(ad),
images: images,
thumbnails: thumbnails,
multipleImages: (images.length > 1),
ogImage: ogImage,
chatLink: '/messages/' + req.ad.id,
isOwn: (req.user && ad.account.account_id === req.user.id),
isFromBlocket: adHelpers.isFromBlocket(ad),
hasBlocketImages: adHelpers.hasBlocketImages(ad),
surveyUrl: surveyUrl(ad.category.id) || '/'
};
// Render the view
res.render('ads/single', viewData);
});
module.exports = router;
|
import 'css-modules-require-hook/preset';
import express from 'express';
import React from 'react';
import path from 'path'
import { renderToString } from 'react-dom/server'
import { StaticRouter, BrowserRouter, Route, Switch } from 'react-router-dom';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import Homepage from './components/homepage';
import AboutUs from './components/about-us';
import Navigation from './components/navigation';
import Login from './components/login-form';
import ClassList from './components/class-list';
import { authenticationReducer } from './reducers';
import buildPath from '../build/asset-manifest.json';
const app = express();
const store = createStore(combineReducers({
isAuthenticated: authenticationReducer
}));
app.use((request, response, next) => {
if (request.url.startsWith('/static')) {
return next();
}
const appString = renderToString(
<Provider store={store}>
<StaticRouter context={{}} location={request.url}>
<div>
<Navigation />
<Switch>
<Route exact path="/" component={Homepage} />
<Route path="/about" component={AboutUs} />
<Route path="/login" component={Login} />
<Route path="/classes" component={ClassList} />
</Switch>
</div>
</StaticRouter>
</Provider>
);
const html = `<html><body><div id="root">${appString}</div><script src="/${buildPath['main.js']}"></script></body></html>`;
response.send(html);
});
app.use('/', express.static(path.resolve('build')));
app.listen('9000', () => console.log('SSR Server started')); |
/*
* @lc app=leetcode.cn id=495 lang=javascript
*
* [495] 提莫攻击
*/
// @lc code=start
/**
* @param {number[]} timeSeries
* @param {number} duration
* @return {number}
*/
// 倒序遍历
// [1, 2, 3, 4] duration: 2
// [1, 4] duration: 2
var findPoisonedDuration = function(timeSeries, duration) {
if (timeSeries.length == 0) return 0;
var res = duration;
for (var i = timeSeries.length - 2; i>=0; i--) {
if (timeSeries[i] + duration > timeSeries[i + 1]) {
res += (timeSeries[i + 1] - timeSeries[i])
} else {
res += duration;
}
}
return res;
};
var findPoisonedDuration = function(timeSeries, duration) {
var res = 0;
for (let i = 0; i < timeSeries.length; i++) {
if (i === timeSeries.length - 1) {
res+=duration;
break;
} else if (timeSeries[i+1] > timeSeries[i] + duration) {
res += duration;
} else {
res += timeSeries[i + 1] - timeSeries[i];
}
}
return res;
};
// @lc code=end
|
import React from 'react';
export default class Cell extends React.Component{
render(){
let className = "cell" + (this.props.value.isChecked ? " checked" : " notChecked");
return(
<div ref="cell" onClick={this.props.onClick} className={className} onContextMenu={this.props.cMenu}>
{this.props.value.text}
</div>
);
}
}
|
import React, { Component } from 'react';
import './styles/App.scss';
import Research from './research';
import InformationArchitecture from './informationArchitecture';
import Design from './design';
import planitLogo from './resources/images/planit-logo.png';
import sketchFile from './resources/planit.sketch';
import resume from './resources/Nicole Keister Resume.pdf'
// images
import brushstroke from './resources/images/brushstroke.png';
import tripItinFull from './resources/planitScreens/trip-itin-hifi-2.png';
import tripListFull from './resources/planitScreens/trip-list-hifi-2.png';
import tripDocuments from './resources/planitScreens/trip-documents-hifi.png';
class App extends Component {
render() {
const intro = () => {return(
<p className={'center'} style={{marginTop: '2.5em'}}>
Hi! I’m Nicole Keister, a UX Designer and Software Engineer.<br/><br/>
I would love to chat about job opportunities, so please contact me!<br/>
<a href={'https://linkedin.com/in/nicolekeister'} target='_blank' rel='noopener noreferrer'>LinkedIn</a>
<span className={'inlineDivider'}>|</span>
NicoleRKeister@gmail.com
<span className={'inlineDivider'}>|</span>
<a href={resume} download={'Nicole Keister Resume.pdf'}>Resume Download</a><br/><br/>
Take a look at my most in-depth design project…
</p>
);};
const planitIntro = () => {return(
<p className={'description'}>
I found that travelers needed a simple way to organize their information because they often have to
make their own time-intensive documents to record trip details or store details in their emails,
which they easily lose.<br/><br/>
Planit is a travel planning mobile app—the solution to the chaos of organizing a complicated trip.
</p>
);};
return (
<div>
<div className={'header'}>
<img src={brushstroke} className={'brushstroke'} alt='Brushstroke' />
</div>
<div className={'contact'}>
<div>
<a href={'https://linkedin.com/in/nicolekeister'}
target='_blank' rel='noopener noreferrer'>linkedin</a>
</div>
<div style={{marginTop: '1em'}}>
<a href={'https://invis.io/TXPRKQZ6HZ7#/338472500_Trip_List_-_Empty'}
target='_blank' rel='noopener noreferrer'>invision</a>
</div>
<div style={{marginTop: '1em'}}>
<a href={'https://github.com/nrkeister/portfolio'}
target='_blank' rel='noopener noreferrer'>github</a>
</div>
</div>
{intro()}
<div className={'planitLogo'}><img src={planitLogo} style={{width: '100%'}} alt="Planit Logo with spaceship"/></div>
{planitIntro()}
<div className={'planitScreenContainer'}>
<img src={tripListFull} className={'planitScreen'} alt="Full trip list"/>
<img src={tripItinFull} className={'planitScreen'} alt="Full trip itinerary"/>
<img src={tripDocuments} className={'planitScreen'} alt="Trip documents"/>
</div>
<h1>Research</h1>
<Research />
<h1>Information Architecture</h1>
<InformationArchitecture />
<h1>Design</h1>
<Design />
<h1 style={{marginTop: '2em'}}>The Final Design</h1>
<p className={'description center'}>
<br/><br/>
check out my prototype on inVision<br/>
<a href={'https://invis.io/TXPRKQZ6HZ7#/338472500_Trip_List_-_Empty'}
target='_blank' rel='noopener noreferrer'>empty state</a>
<span className={'inlineDivider'}>|</span>
<a href={'https://invis.io/TXPRKQZ6HZ7#/338472498_Trip_Itinerary_-_Full'}
target='_blank' rel='noopener noreferrer'>full state</a>
<br/><br/>
or
<br/><br/>
<a href={sketchFile} download={'Nicole Keister Planit.sketch'}>download my sketch file</a><br/>
which includes even more full state designs
</p>
<div className={'divider'}/>
<p className={'description center'}>
Thanks for reading! If you liked what you saw or would like to know more, please contact me!<br/><a
href={'https://linkedin.com/in/nicolekeister'} target='_blank' rel='noopener noreferrer'>LinkedIn</a>
<span className={'inlineDivider'}>|</span>
NicoleRKeister@gmail.com
<span className={'inlineDivider'}>|</span>
<a href={resume} download={'Nicole Keister Resume.pdf'}>Resume Download</a>
</p>
</div>
);
}
}
export default App;
|
import React, {Component} from 'react';
import styled from 'styled-components';
// Create a Title component that'll render an <h1> tag with some styles
export default styled.h1`
font-family: ${({ theme }) => theme.bodyFontFamily};
text-align: left
font-size: 1.7rem;
text-decoration: underline;
color: ${({ theme }) => theme.accentColor};
&: link {
color: ${({ theme }) => theme.accentColor};
}
&: hover {
color: blue;
}
`
// border: 1px outset blue;
// background-color: lightBlue;
// height:50px;
// width:50px;
// cursor:pointer;
// background-color: blue;
// color:white; |
$('ul').on('click', 'li', function(){
$(this).toggleClass('completed');
});
$('ul').on('click', '#todos', function(e){
$(this).parent().fadeOut(500, function(){
$this.remove();
});
e.stopPropagation();
});
$("input[type='text']").keypress(function(event){
if(event.which === 13){
let newTodo = $(this).val();
$(this).val('');
$('ul').append('<li><span id="todos"><i class="fas fa-trash-alt"></i></span> ' + newTodo + '</li>');
}
});
$('#add-todo').click(function(){
$("input[type='text']").fadeToggle();
}); |
/**
* Validate oneOf
* @param {Array} vals 枚举值
* @return {Function} Vue的validator方法
*/
export default function oneOf(vals) {
return val => vals.indexOf(val) !== -1;
}
|
class Cell {
constructor(a, b, populated=false) {
this.coordinates = [a,b]
this.populated = populated;
}
neighbors() {
const a = this.coordinates[0]
const b = this.coordinates[1]
return ([
[a, b - 1],
[a, b + 1],
[a - 1, b],
[a + 1, b],
[a - 1, b - 1],
[a - 1, b + 1],
[a + 1, b - 1],
[a + 1, b + 1]
]);
}
}
module.exports = Cell;
|
const getHash = () =>
location.hash.slice(1).toLocaleLowerCase().split('/')[1] || '/'
//* ['','1',''] <--- Estamos trayendo el elemento 1, el ID
export default getHash |
const router = require('express').Router();
const Review = require('../db').model('review');
const Product = require('../db').model('product');
const User = require('../db').model('user');
const Order = require('../db').model('order')
var stripe = require("stripe")(process.env.STRIPE_KEY)
router.post('/checkout', function (req, res, next){
stripe.charges.create(req.body)
.then(charge => {
let stripeChargeId = charge.id;
return Order.update({stripeChargeId})
})
})
module.exports = router;
|
var _ = require('lodash');
var moody = require('..');
var expect = require('chai').expect;
describe('Models', function() {
var my;
before('config', ()=> require('./config'));
before('setup moody', ()=> moody.connect().then(res => my = res))
after('disconnect', ()=> my.disconnect());
var callCount = 0;
before('create a base schema', ()=> my.schema('people', {
id: {type: 'oid', index: 'primary'},
firstName: 'string',
middleName: 'string',
lastName: {type: 'string'},
edited: { // Set edited to a Unix Epoch (+3 ms precision because its JavaScript)
type: 'number',
value: doc => new Promise(resolve => setTimeout(()=>
resolve(Date.now() + callCount++) // Falsify the date slightly so its always incrementing, just in case we have a very fast response from the server
, 100)),
},
}, {deleteExisting: true}));
before('create test documents', ()=> my.models.people.createMany([
{firstName: 'Joe', lastName: 'Nothing'},
{firstName: 'Jane', middleName: 'Oliver', lastName: 'Random'},
{firstName: 'John', lastName: 'Random'},
], {lean: true}));
before('add a custom static', ()=> my.models.people.static('countPeople', ()=>
my.models.people.count()
));
it('should be able to call a custom static method', ()=>
my.models.people.countPeople()
.then(res => expect(res).to.equal(3))
);
before('add a custom method', ()=> my.models.people.method('getName', function() {
// Force this method to act like a promise
return Promise.resolve([this.firstName, this.middleName, this.lastName].filter(i => i).join(' '));
}));
it('should be able to call a custom document method', ()=>
my.models.people.find()
.then(people => Promise.all(people.map(p =>
p.getName()
.then(fullName => p.fullName = fullName)
.then(()=> p)
)))
.then(people => {
expect(people).to.be.an('array');
expect(people).to.have.length(3);
people.forEach(person => {
expect(person).to.have.property('firstName');
expect(person).to.have.property('lastName');
expect(person).to.have.property('fullName');
expect(person.fullName).to.be.a('string');
expect(person.fullName).to.have.length.above(5);
});
})
);
before('add a custom virtual', ()=> my.models.people.virtual('initials', function() {
return [this.firstName, this.middleName, this.lastName]
.filter(i => i)
.map(i => i.substr(0, 1).toUpperCase())
.join('');
}));
it('should add a virtual getter', ()=>
my.models.people.find()
.then(people => {
expect(people).to.be.an('array');
expect(people).to.have.length(3);
people.forEach(person => {
expect(person).to.have.property('initials');
expect(person.initials).to.be.a('string');
expect(person.initials).to.have.length.above(1);
});
})
);
it('should retrive the virtual getting during a select', ()=>
my.models.people.find()
.select('initials')
.then(people => {
expect(people).to.be.an('array');
expect(people).to.have.length(3);
people.forEach(person => {
expect(Object.keys(person).sort()).to.deep.equal(['id', 'initials']);
expect(person.initials).to.have.length.above(1);
});
})
);
it('should have populated the `edited` value field in each case', ()=> {
var joes = []; // All times we have pulled the "joes" record from the DB
return my.models.people.find()
.then(people => {
expect(people).to.be.an('array');
expect(people).to.have.length(3);
people.forEach(person => {
// Edited should not have been set as we have not written this object before
expect(person).not.to.have.property('edited');
});
return people;
})
.then(people => Promise.all(people.map(person => person.toObject()))) // Flatten back into a plain object
.then(people => {
firstPeopleSet = people;
people.forEach(person => {
// Edit should have been set during the `toObject()` phrase
expect(person).to.have.property('edited');
// Remove middleName as it may not bre present, ignore initials because its a virtual
expect(Object.keys(person).sort().filter(i => i != 'middleName')).to.deep.equal(['edited', 'firstName', 'id', 'lastName']);
});
joes.push(people.find(p => p.firstName == 'Joe'));
})
.then(()=> my.models.people.findOneByID(joes[0].id).update({firstName: 'Joseph'}))
.then(changedPerson => {
expect(changedPerson).to.have.property('firstName', 'Joseph');
expect(changedPerson).to.have.property('edited');
expect(changedPerson.edited).to.be.a('number');
joes.push(changedPerson);
})
.then(()=> my.models.people.findOneByID(joes[0].id).update({firstName: 'Joseph2'})) // Write again to test edited updates
.then(changedPerson => {
expect(changedPerson).to.have.property('firstName', 'Joseph2');
expect(changedPerson).to.have.property('edited');
expect(changedPerson.edited).to.be.above(joes[1].edited);
joes.push(changedPerson);
})
.then(()=> my.models.people.findOneByID(joes[0].id)) // Check the data did actually write
.then(person => {
expect(person).to.have.property('firstName', 'Joseph2');
expect(person).to.have.property('edited');
expect(person.edited).to.be.equal(joes[2].edited);
})
});
});
|
"use strict";
/**
* @param router
* @return {{getRouter: getRouter, bindActions: bindActions}}
* @constructor
*/
function BaseController(router) {
var routesController = router;
return {
getRouter: function () {
return routesController;
},
bindActions: function () {
throw new Error("Controller must implement this method");
}
}
}
module.exports = BaseController;
|
const config = require('../config');
const request = require('request');
var rp = require('request-promise');
var url = config.base_url + '/users';
exports.getUsers = function (userCallback) {
request(url, function (error, response, body) {
userCallback(error, JSON.parse(body));
});
}
exports.updateUsers = function (userCallback) {
request(url, function (error, response, body) {
userCallback(error, JSON.parse(body));
});
}
/**
* Return a Promise instead of using callback
*/
exports.getUsersPromise = function () {
return rp(url)
.then(function (body) {
return JSON.parse(body);
})
.catch(function (err) {
return err;
});
}
/**
* Return a Promise instead of using callback
*/
exports.getUsersByIdPromise = function (userId) {
return rp(url + '/' + userId)
.then(function (body) {
return JSON.parse(body);
})
.catch(function (err) {
console.log(err);
});
} |
app.controller('resourcesCtrl', function ($scope, resourcesSvc, errorMngrSvc, confirmSvc) {
$scope.resources = [];
$scope.deleteResource = function (resourceId) {
if (confirmSvc.confirm('Are you sure you want to delete this item?')) {
resourcesSvc.deleteResource(resourceId)
.then(function (data) {
loadResources();
}, function (error) {
errorMngrSvc.handleError(error);
})
}
};
init();
function init() {
loadResources();
}
function loadResources() {
resourcesSvc.getResources().then(function (data) {
$scope.resources = data;
$scope.loaded = true;
$scope.haveContent = data.length == 0;
}, function (reason) {
errorMngrSvc.handleError(reason);
});
}
}); |
import React, { useContext } from "react";
import { globalState } from '../context/GlobalState';
const IncomeExpense = () => {
const { transactions } = useContext(globalState);
const income = transactions.filter((transaction) => transaction.amount > 0);
const expense = transactions.filter((transaction) => transaction.amount < 0);
return (
<div className="income-expense">
<div className="income">
<h3>INCOME</h3>
<p className="amount">₹ {income.reduce((acc, transaction) => {
return acc + parseInt(transaction.amount);
}, 0)}</p>
</div>
<div className="expense">
<h3>EXPENSE</h3>
<p className="amount">₹ {expense.reduce((acc, transaction) => {
return acc + Math.abs(transaction.amount);
}, 0)}</p>
</div>
</div>
);
};
export default IncomeExpense;
|
// pages/teacherPage/teacherPage.js
Page({
/**
* 页面的初始数据
*/
data: {
openid:'',
trainingid: null,
coachList: [],
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.getStorage({
key: 'openid',
fail: () => { wx.redirectTo({ url: '../index/index', }) },
})
this.setData({trainingid: options.id})
wx.request({
url: 'https://www.qczyclub.com/getcoachbycarid',
method: 'POST',
data:{'carid': options.id},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success:(res)=>{
this.setData({
'coachList': res.data
})
console.log(this.data)
},
fail: function () {
console.log('fail')
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
wx.getStorage({
key: 'openid',
success: (res) => {this.setData({openid: res.data})},
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
bindCoach: function(e) {
let tid = e.currentTarget.dataset.id
wx.request({
url: 'https://www.qczyclub.com/bindmyteacher',
method: 'POST',
data: {
'openid': this.data.openid ,
'tid': tid
},
header: {
"Content-Type": "application/x-www-form-urlencoded"
},
success: (res) => {
if(res.data == 1){
wx.showToast({
title: '成功选择教练',
duration: 1500
})
} else if(res.data == 2){
wx.showToast({
title: '已经选择教练请勿重复操作',
icon: 'none',
duration: 1500
})
} else {
wx.showToast({
title: '选择教练失败!',
icon: 'none',
duration: 1500
})
}
},
fail: function () {
console.log('fail')
}
})
}
}) |
import React, { useState } from 'react';
import Styled from 'styled-components/native';
import Input from '~/Components/Input';
import Button from '~/Components/Button';
import Tab from '~/Components/Tab';
import Lock from '~/Assets/Images/lock.png';
const Container = Styled.SafeAreaView`
flex: 1;
background-color: #FEFFFF;
`;
const FormContainer = Styled.View`
flex: 1;
width: 100%;
align-items: center;
padding: 32px;
`;
const LockImageContainer = Styled.View`
padding: 24px;
border-width: 2px;
border-color: #292929;
border-radius: 80px;
margin-bottom: 24px;
`;
const LockImage = Styled.Image``;
const Title = Styled.Text`
font-size: 16px;
margin-bottom: 16px;
`;
const Description = Styled.Text`
text-align: center;
margin-bottom: 16px;
color: #292929;
`;
const TabContainer = Styled.View`
flex-direction: row;
margin-bottom: 16px;
`;
const HelpLabel = Styled.Text`
color: #3796EF;
`
const Footer = Styled.View`
width: 100%;
border-top-width: 1px;
border-color: #D3D3D3;
padding: 8px;
`;
const GoBack = Styled.Text`
color: #3796EF;
text-align: center;
`;
const PasswordReset = ({ navigation }) => {
const [ tabIndex, setTabIndex ] = useState(0);
const tabs = ['사용자 이름', '전화번호'];
const tabDescriptions = [
'사용자 이름 또는 이메일을 입력하면 다시 계정에 로그인 할 수 있는 링크를 보내준다.',
'전화번호를 입력하면 계정에 다시 엑세스할 수 있는 코드를 보내준다.',
];
const placeholders = ['사용자 이름 또는 이메일', '전화번호'];
return (
<Container>
<FormContainer>
<LockImageContainer>
<LockImage style={{ width: 20, height: 20 }} source={Lock}/>
</LockImageContainer>
<Title>로그인에 문제가 있나요?</Title>
<Description>{tabDescriptions[tabIndex]}</Description>
<TabContainer>
{tabs.map((label, index) => (
<Tab
key={`tab-${index}`}
selected={tabIndex === index}
label={label}
onPress={() => setTabIndex(index)}
/>
))}
</TabContainer>
<Input
style={{ marginBottom: 16 }}
placeholders={placeholders[tabIndex]}
/>
<Button label="다음" style={{ marginBottom: 24 }} />
<HelpLabel>도움이 더 필요해요?</HelpLabel>
</FormContainer>
<Footer>
<GoBack onPress={()=> navigation.goBack()}>
로그인으로 돌아가기
</GoBack>
</Footer>
</Container>
);
};
PasswordReset.navigationOptions = {
headerShown: false,
};
export default PasswordReset; |
describe('pixi/core/Ellipse', function () {
'use strict';
var expect = chai.expect;
var Ellipse = PIXI.Ellipse;
it('Module exists', function () {
expect(Ellipse).to.be.a('function');
});
it('Confirm new instance', function () {
var obj = new Ellipse();
expect(obj).to.be.an.instanceof(Ellipse);
expect(obj).to.respondTo('clone');
expect(obj).to.respondTo('contains');
expect(obj).to.respondTo('getBounds');
expect(obj).to.have.property('x', 0);
expect(obj).to.have.property('y', 0);
expect(obj).to.have.property('width', 0);
expect(obj).to.have.property('height', 0);
});
});
|
// @flow
import * as React from "react";
import sortBy from "lodash/sortBy";
import { SingleFileContainer } from "./SingleFileContainer.jsx";
const defaultOptions =
{
// URL, куда отправлять файлы
actionURL: null,
// Префикс адресов для файлов
filesLocationPrefix: null,
// // Префикс для имени
// "data_input_name": null,
// // Максимальное количество файлов, которые мы можем загрузить (выбрать), включая загруженные ранее (перечисленные в current_files)
// // Если мы достигли максимального числа файлов, то к контейнеру, указанному в "add_file_block_class" должен подставиться класс,
// // указанный в "add_file_block_disable_class" и контейнер должен перестать реагировать на клик и drag&drop.
// // Если мы какой-то файл удаляем, то контейнер, указанный в "add_file_block_class" должен снова стать рабочим и у него
// // снимется класс, указанный в "add_file_block_disable_class".
limitFiles: 50,
// // Минимальный и максимальный объемы каждого файла в Кб
// "limit_size_min": 20, // 20 Кб для каждого файла
// "limit_size_max": 10000, // 10 Мб для каждого файла
// // Производить ли загрузку файлов сразу же, как только пользователь выбрал файл?
// // Если true, то пока картинка не загрузится на сервер, мы вместо картинки показываем прелоадер
// // Если false, то превьюшка показывается сразу
autoupload: true,
// // Использовать ли квадратные скобки при задании имен для инпутов
// "multiple_style_names": true,
// // Множественный выбор файлов, т.е. можно ли выделить и загрузить сразу несколько файлов
"multiselect": true,
// // Отрабатывать ли добавление файлов через drag&drop
// // Если true, то drag&drop должен отрабатываться для контейнера с классом, указанным в атрибуте add_file_block_class
// "add_files_via_drag_and_drop": true,
// // Можно ли сортировать файлы через drag&drop. Этот функционал должен быть реализован как на avito.ru, ознакомься внимательно там есть фишка,
// // что когда ты тащишь блок, то он в уменьшенном виде подставляется в потенциально новое место до тех пор, пока ты его не отпустил
// "sort_files_via_drag_and_drop": true,
// // Добавлять файлы в начало списка (true) или в конец (false)
// "add_files_at_beginning": false,
// // Типы файлов, которые можно выбрать для загрузки
// "filetypes": [ "jpg", "jpeg" ],
// // Код общего контейнера загрузки файлов
// "container_code": null,
// // Класс контейнера, в котором будут выводиться информационные сообщения. Если не указан, то информационные сообщения не выводятся.
// "error_block_class": null,
// // =========== Контенеры, которые помещяются в контейр, указанный в атрибуте error_block_class ===========
// // Шаблон контейнера для вывода одного информационного сообщения
// "invalid_file_type_message": "Неверный формат изображения, допустим только jpg, bmp и т.д.<br>",
// "invalid_min_size_message": "Размер файла не может быть меньше 20Kb, неприемлемое качество для изображения<br>",
// "invalid_max_size_message": "Размер файла не должен превышать 3Mb<br>",
// "file_upload_error_message": "Изображение не было загружено, попробуйте еще раз<br>",
// // Класс контейнера, клик по которому позволяет выбрать файл на клиенте и drag&drop
// "add_file_block_class": null,
// "add_file_block_at_end": false,
// // Класс, который подставляется к вышеуказанному блоку в том случае, если мы достигли предела, указанного в limit_files
// "add_file_block_disable_class": null,
// "add_file_via_drag_and_drop_class": null,
// // Контейнер, куда будут выводится контейнеры самих файлов
// "files_block_class": null,
// "dummy_single_file_container": null,
// // Коллбэк начала загрузки одиночного файла
// "file_load_start_callback": null,
// // Коллбэк завершения загрузки одиночного файла
// "file_loaded_callback": null,
// // Коллбэк завершения загрузки всех файлов
// "all_files_loaded_callback": null,
// // =================================================================================================
// // Классы, которые подставляются и снимаются к single_file_container_code в зависимости от их текущего состояния. Может быть не указан любой из них.
// // Нормальное состояние
// // Файл выбран, но не загружен
// "single_file_container_not_loaded_state": "not_loaded",
// // Файл выбран и загружен
// "single_file_container_uploaded_state": "uploaded",
// // Файл загружается прямо сейчас
// "single_file_container_uploading_state": "still_upload",
// // Была ошибка загрузки файла
// "single_file_container_error_state": "error",
// "single_file_container":
// {
// // Код контейнера представления одного файла
// "single_file_container_code": null,
// // Класс контейнера, куда будет выводится превью. Если не указан, то превью не выводится. Если это не картинка, то выводится
// // код, указанный в "nonimage_preview"
// "preview_container_class": null,
// "preview_img": null, //"<img src=\"/custom/photosessions/medium/\">",
// // Код превью для файлов, у которых невозможно отобразить превью
// "nonimage_preview": null, //"<img src=\"/pdf.jpg\" />",
// // Класс элемента, клик по которому отрабатывает событие удаление картинки. Если не указано, то функционала удаления у нас нет.
// "remove_class": null,
// // Класс элемента, клик по которому отрабатывает событие поворота картинки на 90 градусов. Каждый клик добавляет 90 градусов. Если не указано, то функционала поворота у нас нет.
// "rotate_class": null,
// // Класс контейнера, куда будет выводится имя файла. Если картинка новая, то выводится имя как на клиенте, если старая, то как на сервера (поле "filename" атрибута current_files). Если не указан, то имя не выводится.
// "name_class": null,
// // Класс контейнера, куда будет выводится размер файла. Выводится только для новых файлов. Если не указан, то размер не выводится.
// "size_class": null,
// // Класс контейнера, куда будет выводится описание файла. Если это textarea, то стандартным способом, если это input, то пишем в val
// "title_class": null,
// // Класс элемента прогресс-бара, у которого надо менять ширину от 0% до 100% согласно прогрессу загрузки файла. Может быть не указано.
// "progress_bar_class": null
// },
// // Загруженные ранее файлы
// "current_files": null
// // Пример содержимого этой переменной
// // [
// // {
// // "filename": "abc.jpg",
// // "order": 1,
// // "title": "Блондинка"
// // },
// // {
// // "filename": "def.jpg",
// // "order": 2,
// // "title": "Брюнетка"
// // }
// // ]
// Дополнительные свойства, которые прокидываются в неизменном виде
// во все кастомизируемые компоненты в пропсе __additionalProps
additionalProps: {}
};
// const props =
// {
// file: "abc.jpg",
// __uploadId: "jfdLJKF4hjenof38NFOfdss",
// __fileupload:
// {
// order: 0,
// id: 1,
// isUploaded: true,
// isError: false
// }
// };
export type SingleFileContainerProps =
{
data: {},
file: string,
size: number,
progress: number,
removeButton: () => React.Node
};
export type FileUploadProps =
{
files?: Array<{}>,
actionURL: string,
autoupload?: boolean,
defaultFileProps: {},
filenameField: string,
positionField?: string,
orderProp?: number, //( props: {} ) => number,
componentContainer: ( props: { childs: Array<{}> } ) => React.Node,
singleFileContainer: ( singleFileContainerData: SingleFileContainerData ) => React.Node,
addButton: React.Node,
removeButton: React.Node,
additionalProps?: {},
onChange: ( {} ) => void
};
// type Data =
// {
// [FileUploadProps.filenameField]: string
// };
type SingleFileState =
{
id: number,
file: File | null,
isUploaded: boolean,
isError: boolean,
data: {}
};
type State =
{
files: Array<SingleFileState>
// value: string,
// items: Array<ItemObject>
};
export class FileUpload extends React.Component <FileUploadProps, State>
{
nextId: number;
addButton: React.Node;
FileInput: React.Node;
fileInputRef: any; // TODO: Сделать нормальный тип
componentContainer: ( props: { childs: Array<{}> } ) => React.Node;
//******************************************************************************************************************************************************************************
//
constructor( props: FileUploadProps )
{
super( props );
this.nextId = 0;
// Adding onClick handler on addButton and removeButton elements
this.addButton = React.cloneElement( props.addButton, { onClick: (): void => this.fileInputRef.click() } );
this.FileInput = React.createElement( "input",
{
type: "file",
name: "file",
// accept: this.acceptTypes,
multiple: props.multiselect || false,
style: { display: "none" },
ref: ( input ) => this.fileInputRef = input,
onChange: this.addFiles
} );
let files = props.files || [];
// prepare files array
// At first we have to sort array by position field
if( files.length > 0 && props.positionField )
files = sortBy( files, props.positionField );
// At second we add part of neccessary information
files = files.map( ( data ) => (
{
...this.getServicePart(),
data: data
} ) );
this.state =
{
files: files
};
}
//******************************************************************************************************************************************************************************
//
getServicePart = (): SingleFileState => (
{
id: this.nextId++, // iterate nextId
file: null,
isUploaded: false,
isError: false,
data: this.props.defaultFileProps
} );
//******************************************************************************************************************************************************************************
// Handler for add files button event
addFiles = ( event: SyntheticInputEvent<HTMLInputElement> ) =>
{
let files = this.state.files;
// TODO: Реализовать момент добавления файла куда угодно
// newFilePosition:
// 0 - add to start
// -1 - add to end
// number - add to fixed position. If number > number of files, then add to end
const newFilePosition = -1;
for( let i = 0; i < event.target.files.length; i++ )
{
const fileProps =
{
...this.getServicePart(),
file: event.target.files[ i ]
};
// add to end by default
if( !newFilePosition || newFilePosition <= -1 || newFilePosition > this.state.files.length )
files = [ ...files, fileProps ];
else // add to start
if( newFilePosition === 0 )
files = [ fileProps, ...files ];
else // add to position
files = files.splice( newFilePosition, 0, fileProps );
}
this.setState( { files: files } );
}
//******************************************************************************************************************************************************************************
//
onChange = ( id: number, data: {} ) =>
{
const files = this.state.files.map( ( file ) =>
{
if( file.id === id )
return (
{
...file,
data: data
} );
return file;
} );
this.setState( { files: files }, this.updateFormValue );
};
//******************************************************************************************************************************************************************************
// Т.к. этот аплоад всего лишь компонент-поле вышестоящей формы, то обновим значение формы
updateFormValue = () => this.props.onChange( this.state.files.map( ( file ) => file.data ) );
//******************************************************************************************************************************************************************************
//
onUploadSuccess = ( id: number ) =>
{
console.log( "onUploadSuccess" );
};
//******************************************************************************************************************************************************************************
//
onUploadError = ( id: number, errorMessage: string ) =>
{
console.log( "onUploadError" );
};
//******************************************************************************************************************************************************************************
//
// Remove file at position
// TODO: Тут еще надо в отдельный массив складывать удаленные элементы
removeFile = ( id: number ) =>
{
this.setState( { files: this.state.files.filter( ( element ) => element.id !== id ) }, this.updateFormValue );
}
//******************************************************************************************************************************************************************************
//
render(): React.Node
{
const size = 0;
const progress = 0;
let childs = this.state.files.map( ( element: SingleFileState ): React.Node =>
{
const props =
{
id: element.id,
data: element.data,
file: element.file,
filenameField: this.props.filenameField,
singleFileContainer: this.props.singleFileContainer,
filesLocationPrefix: this.props.filesLocationPrefix,
actionURL: this.props.actionURL,
autoupload: this.props.autoupload, // TODO: merge default config and props
removeButton: this.props.removeButton,
__additionalProps: this.props.additionalProps,
onChange: this.onChange,
onRemove: this.removeFile,
onUploadSuccess: this.onUploadSuccess,
onUploadError: this.onUploadError
};
return <SingleFileContainer key={ props.id } { ...props } />;
} );
const options =
{
...defaultOptions,
...this.props
};
const componentContainerProps =
{
addButton: childs.length < options.limitFiles ? this.addButton : null,
childs: childs,
__additionalProps: options.additionalProps,
fileInput: this.FileInput // TODO: Убрать этот бред, инпут должен подставляться автоматом
};
const ComponentContainer = this.props.componentContainer;
return <ComponentContainer { ...componentContainerProps } />;
}
} |
import React, {Component} from 'react';
import { Link } from 'react-router-dom';
export default class List extends Component {
constructor(){
super();
this.state = {
users: []
}
}
componentWillMount() {
let userStr = localStorage.getItem('users');
let users = userStr? JSON.parse(userStr): [];
this.setState({
users
})
}
render () {
return (
<ul className="list-group">
{
this.state.users.map((user, index) =>
<li className="list-group-item" key={index}>
<Link to={`/user/detail/${user.id}`}>{user.name}</Link>
</li>
)
}
</ul>
)
}
} |
const express = require("express");
const router = express.Router();
const Ticket = require("../models/ticket");
const User = require("../models/user");
const re = /(\d{4})-([0-1]\d{1})-([0-3]\d{1})/;
const today = () => {
const d = new Date();
const dtf = new Intl.DateTimeFormat('en', { year: 'numeric', month: '2-digit', day: '2-digit' });
const [{ value: mm },,{ value: dd },,{ value: yy }] = dtf.formatToParts(d);
return `${yy}-${mm}-${dd}`;
}
router.post("/give", async (req, res) => {
let {owner, type, date} = req.body;
if(!owner || !type || !date) {
res.status(400).send("Missing field");
return;
}
if(!req.isLogin || (owner !== req.user.id && req.user.group !== "root")) {
res.status(401).send("Not authorized");
return;
}
let handler = (err, user) => {
if(user) return user._id;
else if(err) {
errHandler(err, res);
return null;
}
return null;
}
if(owner.indexOf("@") !== -1) {
owner = await User.findOne({email: owner}, handler);
}
else {
owner = await User.findById(owner, handler);
}
if(owner === null) {
res.status(400).send("Owner does not exist");
return;
}
if(date.length !== 10 || !re.test(date)) {
res.status(400).send("Invalid Date");
return;
}
// Check the request ticket time is one day after
let day = parseInt(date.split('-').pop());
let d = new Date();
let nowday = d.getDate();
let nowhour = d.getHours();
/*
Buggy!
These conditions will fail when the date is at the end of the month.
For example, 30 (or 31) > 1 but it is yesterday.
*/
if(day < nowday){
res.status(400).send("Expired date!");
return;
}
else if(
req.user.group !== "root" && day === nowday && type === 'lunch'
){
res.status(400).send("Too late to request a lunch ticket");
return;
}
else if(
req.user.group !== "root" && day === nowday && type === 'dinner' && nowhour > 12
){
res.status(400).send("Too late to request a dinner ticket");
return;
}
// Check if ticket already exists
let tickets = await Ticket.find({owner, type, date})
.then(ticket => ticket)
.catch(err => errHandler(err));
if(tickets.length !== 0){
res.status(400).send("Ticket already exists!");
return;
}
const newTicket = new Ticket({owner, type, date, usedTime: 0});
const done = await newTicket.save()
.then(_ => true)
.catch(err => errHandler(err, res))
if(done) {
let d = new Date();
console.log(`[${d.toLocaleDateString()}, ${d.toLocaleTimeString()}] Create Ticket success by ${req.user.name}`);
res.status(200).send("Create ticket success");
}
else return;
})
router.post("/use", async (req, res) => {
if(!req.isLogin || req.user.group !== "foodStaff") {
res.status(401).send("Not authorized");
return;
}
const {owner, type} = req.body;
if(!owner || !type) {
res.status(400).send("Missing field");
return;
}
const date = today();
let tickets = await Ticket.find({owner, type, date})
.populate('owner', '_id name email group')
.then(ticket => ticket)
.catch(err => errHandler(err));
if(!tickets || tickets.length === 0) {
res.status(401).send("No Ticket!");
return;
}
let ticket = tickets.find(ticket => ticket.usedTime === 0);
if(!ticket) {
res.status(401).send("Ticket is used!");
return;
}
ticket.usedTime = Date.now();
await ticket.save();
res.status(200).send(ticket.owner);
return;
})
router.post("/delete", async (req, res) => {
let {owner, type, date} = req.body;
if(!owner || !type || !date) {
res.status(400).send("Missing field");
return;
}
if(!req.isLogin || (owner !== req.user.id && req.user.group !== "root")) {
res.status(401).send("Not authorized");
return;
}
let tickets = await Ticket.find({owner, type, date})
.then(ticket => ticket)
.catch(err => errHandler(err));
if(!tickets || tickets.length === 0) {
res.status(401).send("No Ticket!");
return;
}
let ticket = tickets.find(ticket => ticket.usedTime === 0);
if(!ticket) {
res.status(401).send("Ticket is used!");
return;
}
ticket.deleteOne();
res.status(200).send("OK");
return;
})
router.get("/", async (req, res) => {
if(!(req.isLogin)) {
res.status(401).send("Not authorized");
}
let query = {...req.query};
let populate = req.query.populate;
delete query['populate'];
if(!(["root", "foodStaff"].includes(req.user.group))) {
query = {owner: req.user.id};
populate = false
}
let thenable = Ticket.find(query);
if(populate) thenable = thenable.populate('owner', '_id name email group');
/*
thenable.length() will cause an error. (thenable.length is not a function)
Note that thenable is an unresolved Promise, and not an array.
---
Update tickets on query is OK, but I would prefer filtering out outdated tickets in the frontend.
This will reduce some computational effort for both the backend and the DB.
*/
// Check if available tickets are overdued
// for(var i = 0; i < thenable.length(); ++i){
// const nowday = Date.getDate();
// console.log(nowday);
// console.log(thenable[i].date.split('-').pop());
// if(thenable[i].date.split('-').pop() <= nowday && thenable[i].usedTime==0){
// thenable[i].usedTime = 1;
// }
// }
// await thenable.save();
const tickets = await thenable
.then(tickets => tickets)
.catch(err => errHandler(err));
if(tickets) res.status(200).send(tickets);
else res.status(400).send("No Ticket Found");
return;
})
const errHandler = (err, res) => {
console.error(err);
res.status(500).send("Server error");
}
module.exports = router;
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import CircularProgress from '@material-ui/core/CircularProgress';
import Card from '@material-ui/core/Card';
import RandomCatFact from 'routes/Home/components/RandomCatFact';
const styles = theme => ({
root: {
height: '100vh',
background: `url(http://thepatternlibrary.com/img/am.jpg)`,
},
container: {
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
error: {
padding: theme.spacing.unit,
},
});
class Home extends Component {
componentDidMount() {
const { fetchCatFacts } = this.props;
fetchCatFacts();
}
renderRandomCatFact = () => {
const { classes, catFactsLoading, catFacts, catFactsError } = this.props;
if (catFactsLoading) {
return <CircularProgress />;
}
if (catFactsError) {
return (
<Card className={classes.error}>{`Oops. Failed to fetch random cat facts due to: ${
catFactsError.message
}`}</Card>
);
}
return <RandomCatFact facts={catFacts} />;
};
render() {
const { classes } = this.props;
return (
<Grid container className={classes.root}>
<Grid item md={4} />
<Grid item md={4} className={classes.container}>
{this.renderRandomCatFact()}
</Grid>
<Grid item md={4} />
</Grid>
);
}
}
Home.propTypes = {
classes: PropTypes.object.isRequired,
catFactsLoading: PropTypes.bool,
catFacts: PropTypes.array.isRequired,
catFactsError: PropTypes.object,
fetchCatFacts: PropTypes.func.isRequired,
};
Home.defaultProps = {
catFactsLoading: false,
catFactsError: undefined,
};
export default withStyles(styles)(Home);
|
let checkAge = (age) => {
if (age >= 18) {
// Дополни эту строку
return "Вы совершеннолетний человек";
}
return "Вы не совершеннолетний человек";
};
console.log(checkAge(20));
console.log(checkAge(8));
console.log(checkAge(14));
console.log(checkAge(38));
|
import React from "react";
import { Link } from "react-router-dom";
/* import bootstrap */
import Container from "react-bootstrap/Container";
import Navbar from "react-bootstrap/Navbar";
import Button from "react-bootstrap/Button";
import ButtonGroup from "react-bootstrap/ButtonGroup";
import "../index.css";
const FooterComponent = ({ authors }) => {
return (
<Navbar className="footer" bg="black">
<Container id="madeWithLove">
<p id="madeWithLove">Made with Love by</p>
<ButtonGroup>
{authors.length >= 1 &&
authors.map((author, index) => (
<Link
key={index}
to={`/authors/${author.slug}`}
>
<Button
variant="secondary"
key={index}
authors={authors}
color="white"
>
{author.name}
</Button>
</Link>
))}
</ButtonGroup>
</Container>
</Navbar>
);
};
export default FooterComponent;
|
// when there's one argument, no need for parenthesis
const doubleIt = num => num * 2
// createPet() // cannot call arrow function before defining it
foo() // OK
// need parenthesis for multiple arguments. if implicitly returning an object, wrap it in parenthesis
const createPet = (nameStr, ageNum) => ({ name: nameStr, age: ageNum })
function foo() {
console.log('hi!!!')
}
/********************** MAP **********************/
// Transforms an array
// Returns a new array containing the transformed values
// (Does not mutate the original array)
// Callback should return the transformation
const transformedArr = nums.map(num => num * 3)
/********************** FILTER **********************/
// Returns a subarray satisfying a condition
// Does not mutate the original array
// Callback should return a boolean
const filteredArr = bookTitles.filter(bookTitle => bookTitle.length > 5)
/********************** SORT **********************/
// mutates the original array
// callback should return a number
// nums.sort((numA, numB) => numA - numB)
// nums.sort(function (numA, numB) {
// return numB - numA
// })
// nums.sort((numA, numB) => numB - numA)
// bookTitles.sort((bookTitleA, bookTitleB) => bookTitleA.localeCompare(bookTitleB))
// bookTitles.sort((bookTitleA, bookTitleB) => bookTitleB.localeCompare(bookTitleA))
// books.sort((bookA, bookB) => {
// return bookA.author.localeCompare(bookB.author)
// })
// books.sort((bookA, bookB) => bookB.author.localeCompare(bookA.author)) |
export default function personnalInformationCtrl($scope, $state) {
$scope.clickHandler = function() {
$state.go('app.bank');
}
} |
import React from "react";
import JobListing from "./jobListing";
const AvailableJobList = (props) => {
if (props.jobs.length === 0) {
return null;
}
return (
<div className="available-job-list">
<div className="job-listing">
<h2>Job Title</h2>
<h2>Score</h2>
</div>
{props.jobs.data.map((job) => {
return (
<JobListing
selectJobs={props.selectJobs}
selectedJobs={props.selectedJobs}
key={job.id}
id={job.id}
jobName={job.name}
score={job.score}
skillList={props.skillList}
setSkills={props.setSkills}
setDisplay={props.setDisplay}
displaySkills={props.displaySkills}
setColor={props.setColor}
/>
);
})}
</div>
);
};
export default AvailableJobList;
|
function ready() {
function responsiveBgImg(){
var imgs = document.getElementsByClassName("img");
Array.prototype.forEach.call(imgs,function(value,key){
console.log(arguments);
var img = value;
var srcStr = img.getAttribute('data-img-src');
var srcAr = srcStr.match(/[0-9]+ [a-z :\/0-9.]+/g);
console.log(srcAr);
Array.prototype.forEach.call(srcAr,function(v,k){
srcAr[k] = v.split(/ /);
});
for (var i = 0; i < srcAr.length; i++) {
if ((srcAr[i][0]*1) >= window.innerWidth ) {
var imgTmp = new Image();
imgTmp.src = srcAr[i][1];
imgTmp.onload = function() {
img.style['backgroundImage'] = "url(" + srcAr[i][1]+")";
}
break;
}
}
});
}
responsiveBgImg();
window.onresize = function(event) {
responsiveBgImg();
};
}
document.addEventListener("DOMContentLoaded", ready);
|
console.log(x + 2); |
game.resources = [
/* Graphics.
* @example */
{name: "floor", type:"image", src: "assets/floor.png"},
{name: "splash", type:"image", src: "assets/Downtown_New_York_City_from_the_Empire_State_Building_June_2004.JPG"},
{name: "ledder", type:"image", src: "assets/ledder.png"},
{name: "ledder-wall", type: "image", src: "assets/ledder-wall.png"},
{name: "friend1", type:"image", src: "assets/friends.png"},
{name: "helicopter", type:"image", src: "assets/helicopter.png"},
{name: "door", type: "image", src: "assets/door.png"},
{name: "zombie", type: "image", src: "assets/zombies-right.png"},
{name: "hog", type: "image", src: "assets/hand-of-god.png"},
{name: "32x32_font", type:"image", src: "assets/32x32_font.png"},
/* Atlases
* @example
* {name: "example_tps", type: "tps", src: "data/img/example_tps.json"},
*/
/* Maps.
* @example
*/
{name: "level01", type: "tmx", src: "assets/level01.tmx"},
//Background music.
{name: "music", type: "audio", src: "assets/", channel : 1}
/* Sound effects.
* @example
* {name: "example_sfx", type: "audio", src: "data/sfx/", channel : 2}
*/
];
|
const expres=require('express');
const router=expres.Router();
const mongoose=require('mongoose');
const Govs=require('../models/gov');
router.post('/',(req,res,next)=>{
const gov=new Govs({
_id:new mongoose.Types.ObjectId(),
nic:req.body.nic
});
gov
.save()
.then(result=>{
console.log(result);
})
.catch(err=>console.log(err));
res.status(200).json({
message:'Created government user successfully',
createdGov:gov
});
});
router.get('/nic/:nic',(req,res,next)=>{
const nic=req.params.nic;
Govs.findOne({'nic': req.params.nic})
.select('nic')
.exec()
.then(result=>{
res.status(200).json({result});
})
.catch(err=>{
console.log(err);
res.status(500).json({
error:err
});
});
});
router.get('/nic',(req,res,next)=>{
const nic=req.params.nic;
Govs.find()
.select('nic')
.exec()
.then(result=>{
res.status(200).json({result});
})
.catch(err=>{
console.log(err);
res.status(500).json({
error:err
});
});
});
module.exports=router; |
import * as reducerType from '../utils/reducerType';
import avatar_url from '../asserts/img/data/me.jpg';
//0代表联系人对话
const defaultValue = [
{
id: "id_0",
name: "张三",
data: [
["0", "你好,我是张三", "2018-11-7 18:30:22"] ,
["1", "你好,我知道你是张三", "2018-11-7 18:31:23"]
]
},
{
id: "id_1",
name: "张三1",
data: [
["0", "你好,我是张三1", "2018-11-6 18:30:21"] ,
["1", "你好,我知道你是张三1", "2018-11-6 18:31"]
]
},
{
id: "id_2",
name: "张三2",
data: [
["0", "你好,我是我是张三2", "2018-11-5 18:30"]
]
},
{
id: "id_3",
name: "张三3",
data: [
["0", "你好,我是张三3", "2018-11-3 18:30"]
]
},
{
id: "id_4",
name: "张三4",
data: [
["0", "你好,我是张三4", "2018-11-4 18:30"]
]
},
{
id: "id_5",
name: "张三5",
data: [
["0", "你好,我是张三5", "2018-11-5 18:30"]
]
},
{
id: "id_6",
name: "李四1",
data: [
["0", "你好,我是李四1", "2018-11-1 18:30"] ,
["1", "你好,我知道你是李四1", "2018-11-1 18:31:31"]
]
},
{
id: "id_7",
name: "李四2",
data: [
["0", "你好,我是我是李四2", "2018-1-2 18:30:23"]
]
},
{
id: "id_8",
name: "李四3",
data: [
["0", "你好,我是李四3", "2018-1-3 18:30"]
]
},
{
id: "id_9",
name: "李四4",
data: [
["0", "你好,我是李四4", "2018-1-4 18:30"]
]
},
{
id: "id_10",
name: "李四5",
data: [
["0", "你好,我是李四5", "2018-1-5 18:30"]
]
}
];
const dialogs = (state = defaultValue, action) => {
switch(action.type) {
case reducerType.GET_DIALOGS:
return action.payload;
case reducerType.UPDATE_DIALOGS:
let result = [];
state.forEach(({id, name, data}) => {
if(action.payload.id === id ) {
data.push(["1", action.payload.message, action.payload.time]);
result.unshift({id, name, data});
} else {
result.push({id, name, data});
}
return result;
});
case reducerType.SEARCH_CONTACTS:
if(action.payload) {
let contacts = [];
state.map(({id, name, data}) => {
if(name.indexOf(action.payload) !== -1) { //name.includes(action.payload)
contacts.push({id, name, data});
}
});
return contacts;
} else {
return defaultValue;
}
case reducerType.SEND_MESSAGE:
let messages = [];
state.forEach(({id, name, data}) => {
if(id == action.payload.id) {
data.push(["1", action.payload.message, action.payload.time]);
messages.unshift({id, name, data})
} else {
messages.push({id, name, data});
}
});
return messages;
default: return state;
}
}
export default dialogs; |
import React from "react";
import "./App.css";
import Fullname from "./Profile/Profile component/Fullname";
import Ahmed from "./Assets/ahmed.jpg";
function App() {
let profile = {
name: "Ahmed Elloumi",
bio: "27 year old ",
profession: "Ingénieur en génie Mécanique ",
};
const handelChange = (name) => {
alert(name);
};
return (
<div className="App">
<Fullname
name={profile.name}
bio={profile.bio}
profession={profile.profession}
handelChanggit
inite={handelChange}
>
<img src={Ahmed} alt="Ahmed" style={{ width: "200px" }} />
</Fullname>
<br></br>
</div>
);
}
export default App;
|
import bookshelf from "../config/bookshelf.js";
const TABLE_NAME = "user";
class User extends bookshelf.Model {
get tableName() {
return TABLE_NAME;
}
}
export default User;
|
class Level {
constructor(player, defaultMap, otherMap, globalMap, damage) {
this.player = player;
this.damage = 1/damage;
this.defaultMap = defaultMap;
this.otherMap = otherMap;
this.globalMap = globalMap;
this.currentMap = defaultMap;
this.flipper = new Flipper(defaultMap.g, otherMap.g);
}
update() {
this.player.update(this);
this.globalMap.update(this);
this.currentMap.update(this);
if(this.player.y > mapHeight + 5){
kill();
}
}
draw() {
this.currentMap.render();
if (this.currentMap === this.defaultMap) {
this.flipper.unflip(width / 2, height / 2);
} else {
this.flipper.flip(width / 2, height / 2);
}
this.flipper.draw();
this.globalMap.render();
imageMode(CORNER);
image(this.globalMap.g, 0, 0);
this.player.draw();
this.drawHealthBar(this.player.health);
}
drawHealthBar(health) {
noStroke();
rectMode(CENTER);
fill(0);
rect(tp(15),tp(1),tp(8.2),tp(0.7),45);
fill(255, 0, 0);
rect(tp(15),tp(1),tp(max(0, 8*health)),tp(0.5),45)
rectMode(CORNERS);
// rect(tp(15 - (5 * health)), tp(1), tp(15), tp(2));
// rect(tp(15), tp(1), tp(15 + (5 * health)), tp(2));
}
}
|
import React, { Component } from 'react'
import axios from 'axios'
import Pagination from '../Pagination/Pagination';
import { connect } from 'react-redux'
import { addVideoCard } from '../../../Ducks/Reducer'
import { withRouter } from 'react-router-dom'
class VideoCardTable extends Component {
constructor(){
super()
this.state = {
videoCard:[],
currentVideoCards:[],
currentPage:null,
totalPages:null,
asc: 'desc',
}
}
componentDidMount(){
axios.get('/api/video-card').then(res=>{
this.setState({videoCard:res.data})
})
}
onPageChanged = data => {
const { videoCard } = this.state
const { currentPage, totalPages, pageLimit} = data
const offSet = (currentPage - 1) * pageLimit
const currentVideoCards = videoCard.slice(offSet, offSet + pageLimit)
this.setState({currentPage, currentVideoCards, totalPages})
}
compareValues(key, order='asc') {
return function(a, b) {
if(!a.hasOwnProperty(key) || !b.hasOwnProperty(key)) {
// property doesn't exist on either object
return 0;
}
const varA = (typeof a[key] === 'string') ?
a[key].toUpperCase() : a[key];
const varB = (typeof b[key] === 'string') ?
b[key].toUpperCase() : b[key];
let comparison = 0;
if (varA > varB) {
comparison = 1;
} else if (varA < varB) {
comparison = -1;
}
return (
(order === 'desc') ? (comparison * -1) : comparison
);
};
}
compareNums(key,order = 'asc'){
return function(a,b){
let comparison = 0;
let varA = parseInt(a[key]) ? parseInt(a[key]) : 0
let varB = parseInt(b[key]) ? parseInt(b[key]) : 0
if(varA > varB){
comparison = 1;
}else if(varA < varB){
comparison = -1
}
return (
(order === 'desc') ? (comparison * -1) : comparison
)
}
}
sortBy(key, type) {
let arrayCopy = [...this.state.currentCpus];
arrayCopy.sort(this.compareValues(key, type));
this.state.asc === 'asc' ? this.setState({asc:'desc'}) : this.setState({asc:'asc'})
this.setState({currentCpus: arrayCopy});
}
sortByNum(key, type){
let arrayCopy = [...this.state.currentCpus]
arrayCopy.sort(this.compareNums(key, type))
this.state.asc === 'asc' ? this.setState({asc:'desc'}) : this.setState({asc:'asc'})
this.setState({currentCpus: arrayCopy})
}
addVideoCard(id){
this.props.addVideoCard(id)
this.props.history.push('/list')
}
render() {
const {
videoCard,
} = this.state;
const totalVideoCards = videoCard.length;
if (totalVideoCards === 0) return null;
return (
<div>
<table>
<thead>
<tr>
<th> </th>
<th onClick={()=>this.sortBy('cpuname', this.state.asc)}>
Video Card {this.state.asc === 'asc' ? (<i className="fa fa-arrow-down"></i>) : (<i className="fa fa-arrow-up"></i>)}
</th>
<th onClick={()=>this.sortBy('operatingfrequency', this.state.asc)}>
ChipSet {this.state.asc === 'asc' ? (<i className="fa fa-arrow-down"></i>) : (<i className="fa fa-arrow-up"></i>)}
</th>
<th onClick={()=>this.sortByNum('cores', this.state.asc)}>
Memory {this.state.asc === 'asc' ? (<i className="fa fa-arrow-down"></i>) : (<i className="fa fa-arrow-up"></i>)}
</th>
<th onClick={()=>this.sortByNum('thermaldesignpower', this.state.asc)}>
Core Clock{this.state.asc === 'asc' ? (<i className="fa fa-arrow-down"></i>) : (<i className="fa fa-arrow-up"></i>)}
</th>
<td>Rating</td>
<td>Price</td>
<td> </td>
</tr>
</thead>
<tbody>
{
this.state.currentVideoCards.map(e=>{
return (
<tr key={e.video_card_id}>
<td><input type="checkbox"/></td>
<td>{e.video_card_name}</td>
<td>{e.chipset}</td>
<td>{e.memorysize}</td>
<td>{e.coreclock}</td>
<td> </td>
<td> </td>
<td> <button onClick={()=> this.addVideoCard(e.video_card_id)}>Add</button> </td>
</tr>
)
})
}
</tbody>
</table>
<div>
<Pagination
totalRecords={totalVideoCards}
pageLimit={50}
pageNeighbours={1}
onPageChanged={this.onPageChanged}
/>
</div>
</div>
)
}
}
function mapState(state){
let { list } = state
return {
list
}
}
export default withRouter(connect(mapState, {addVideoCard})(VideoCardTable)) |
(function() {
// 这些变量和函数的说明,请参考 rdk/app/example/web/scripts/main.js 的注释
var imports = [
'rd.controls.Graph'
];
var extraModules = [ ];
var controllerDefination = ['$scope', main];
function main(scope ) {
scope.graphData = {
rowDescriptor: [],
header: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
data: [10, 52, 200, 334, 390, 330, 220]
};
}
var controllerName = 'DemoController';
//==========================================================================
// 从这里开始的代码、注释请不要随意修改
//==========================================================================
define(/*fix-from*/application.import(imports)/*fix-to*/, start);
function start() {
application.initImports(imports, arguments);
rdk.$injectDependency(application.getComponents(extraModules, imports));
rdk.$ngModule.controller(controllerName, controllerDefination);
}
})(); |
const Koa = require("koa");
const r = require("koa-route");
const app = new Koa();
app.use(async function (ctx, next) {
// errors from the middleware stack get routed to ctx.onerror, which has some
// default behavior for sending an error response. However, we are going to
// rethrow the error so it can be caught and routed back to the enclosing
// application
ctx.onerror = err => { if (err) throw err }
// koa sets res.statusCode to 404 automatically, so first, undo that
// (you need to bypass ctx because its setter does a validity check)
ctx.res.statusCode = null;
await next()
// now, if at the end of the middleware chain status is still null, tell koa
// not to respond to this request
if (ctx.status == null) {
ctx.respond = false;
// reset the status to its initial value, otherwise downstream handlers will
// fail unless they explicitly set status
ctx.status = 200;
}
});
app.use(r.get("/koa/hello", async ctx => {
ctx.status = 200;
ctx.body = { hello: "koa" };
}));
app.use(r.get("/koa/not_found", async ctx => {
ctx.status = 404;
ctx.body = { error: "not found" };
}));
app.use(r.get("/koa/throw_error", async ctx => {
throw new Error("Kaboom!");
}));
const handle = app.callback();
// export a function compatible with express's middleware signature
module.exports = async function middleware (req, res, next) {
try {
await handle(req, res);
// if koa has not sent the response already, give control back to express
if (!res.headersSent) next();
} catch (err) { next(err) }
}
|
import React from "react";
import { Link } from "react-router-dom";
import "./home.css";
function Home() {
return (
<div className="home">
<h1>Game Site</h1>
<div>
<Link to="/game/roots">Underground Roots Game</Link>
</div>
<div>
<Link to="/game/collide">Collide Game</Link>
</div>
<div>
<Link to="/game/quest">Quest Game</Link>
</div>
</div>
);
}
export default Home;
|
export default {
path: 'settings',
component: resolve => require(['@/modules/Settings'], resolve),
children: [
{
path: 'index',
component: resolve => require(['@/modules/Settings/Form'], resolve)
}
]
}
|
helpers = {
bytesToSize: function(bytes, precision) {
var kilobyte = 1024;
var megabyte = kilobyte * 1024;
var gigabyte = megabyte * 1024;
var terabyte = gigabyte * 1024;
if ((bytes >= 0) && (bytes < kilobyte)) {
return bytes + ' B';
} else if ((bytes >= kilobyte) && (bytes < megabyte)) {
return (bytes / kilobyte).toFixed(precision) + ' KB';
} else if ((bytes >= megabyte) && (bytes < gigabyte)) {
return (bytes / megabyte).toFixed(precision) + ' MB';
} else if ((bytes >= gigabyte) && (bytes < terabyte)) {
return (bytes / gigabyte).toFixed(precision) + ' GB';
} else if (bytes >= terabyte) {
return (bytes / terabyte).toFixed(precision) + ' TB';
} else {
return bytes + ' B';
}
},
buildFilters: function(data) {
var parameters = {};
var filters = Object.keys(data[0]);
for (var i=0; i<filters.length; i++) {
parameters[filters[i]] = [];
}
for (var i=0; i<data.length; i++) {
for (var j=0; j<filters.length; j++) {
var filter = filters[j];
var category = data[i][filter];
if (parameters[filter].indexOf(category) < 0) {
parameters[filter].push(category);
}
}
}
for (i in filters) {
parameters[filters[i]].sort(function(a, b){return a-b});
}
return parameters;
},
defaultSettings: function(filters) {
var labels = Object.keys(filters);
var settings = {
labels: {},
priorities: labels,
sizes: {
pref: 'people',
people: '1',
groups: '1'
}
};
for (var i=0; i<labels.length; i++) {
settings.labels[labels[i]] = labels[i]; // sets the header to itself to start
}
return settings;
},
groupify: function(group) {
var groups;
if (group.settings.sizes.pref == 'groups') {
groups = group.settings.sizes['groups'];
for (var i=0; i<group.data.length; i++) {
group.data[i]['group'] = i%groups; // 0 indexed
}
} else {
var people = group.settings.sizes['people'];
var count = 1;
groups = 1;
for (var i=0; i<group.data.length; i++) {
group.data[i]['group'] = groups-1;
count ++;
if (count > people) {
count = 1;
groups ++;
}
}
}
group.filters['group'] = [];
for (var i=0; i<groups; i++) {
group.filters['group'][i] = i;
}
return group;
}
};
|
/* eslint-env browser */
/* eslint-env jquery */
// devMode created to allow devs experiment with the bookshelf before making real changes in code.
const launcher = document.getElementById('dev-launch');
let counter = 0;
// devMode is launched when element launcher is clicked more than 5 times
launcher.addEventListener('mousedown', () => {
if (counter < 5) {
counter += 1;
} else { // All devMode structure is displayed using document fragment
launcher.classList.add('dev-hide');
// Defining elements to append to the wrapper
const wrapper = document.createDocumentFragment();
const bookSearch = document.createElement('input');
const bookAdd = document.createElement('button');
const addText = document.createTextNode('Add book');
const bookRemove = document.createElement('button');
const removeText = document.createTextNode('Remove book');
const devBar = document.createElement('div');
const container = document.getElementById('dev-container');
// Giving some attributes
$(bookSearch).attr({
type: 'text',
placeholder: 'Input book ISBN...',
id: 'searcher',
});
$(devBar).attr('class', 'dev-display');
$(bookAdd).attr('id', 'add-btn');
$(bookRemove).attr('id', 'remove-btn');
// Assembling the structure
bookAdd.appendChild(addText);
bookRemove.appendChild(removeText);
devBar.appendChild(bookSearch);
devBar.appendChild(bookAdd);
devBar.appendChild(bookRemove);
wrapper.appendChild(devBar);
container.appendChild(wrapper);
}
// Defining functionality of the 'Remove book' button
const remBtn = document.getElementById('remove-btn');
remBtn.addEventListener('mousedown', () => Array.from(document.querySelectorAll('article'))[Array.from(document.querySelectorAll('article')).length - 1].remove());
// buildBook is declared to build the wanted book with the info related to the given ISBN
function buildBook(data) {
// Calling the information from the API
const {
volumeInfo: {
title,
authors: author,
imageLinks: {
thumbnail: cover,
},
},
} = data.items[0];
// Defining elements to append to the wrapper
const wrapper = document.createDocumentFragment();
const article = document.createElement('article');
const figure = document.createElement('figure');
const img = document.createElement('img');
const h3 = document.createElement('h3');
const span = document.createElement('span');
const rate = document.createElement('div');
const star1 = document.createElement('i');
const star2 = document.createElement('i');
const star3 = document.createElement('i');
const star4 = document.createElement('i');
const star5 = document.createElement('i');
const container = document.getElementById('books-container');
// Giving some attributes
$(img).attr({
class: 'book-cover',
src: cover,
alt: `${title} book cover`,
});
$(rate).attr('class', 'rating');
$(star1).attr('class', 'fas fa-star');
$(star2).attr('class', 'fas fa-star');
$(star3).attr('class', 'fas fa-star');
$(star4).attr('class', 'fas fa-star');
$(star5).attr('class', 'fas fa-star');
$(article).attr('class', 'book');
$(h3).attr('class', 'article-title');
$(span).attr('class', 'article-author');
// Assembling the structure
h3.innerHTML = title;
span.innerHTML = author;
article.appendChild(figure);
article.appendChild(h3);
article.appendChild(span);
article.appendChild(rate);
figure.appendChild(img);
rate.appendChild(star1);
rate.appendChild(star2);
rate.appendChild(star3);
rate.appendChild(star4);
rate.appendChild(star5);
wrapper.appendChild(article);
container.appendChild(wrapper);
}
// Defining functionality of the 'Add book' button
const addBtn = document.getElementById('add-btn');
addBtn.addEventListener('mousedown', () => { // Ajax is used to get the info from the API
const apiURL = `https://www.googleapis.com/books/v1/volumes?q=isbn:${document.getElementById('searcher').value}`;
$.ajax({
type: 'GET',
url: apiURL,
success: buildBook,
error(e) {
console.log(e);
},
});
});
});
|
// Import dependencies
import React, { useEffect, useState } from "react";
import useTimer from "../hooks/useTimer";
import MinutesPicker from "./MinutesPicker";
export default function Timer() {
const [
seconds,
isBreak,
isGoing,
{ startTimer, stopTimer, setBreak, changeMinutes },
] = useTimer(25);
const [minutes, setMinutes] = useState(25);
function addZero(number) {
if (new String(number).length === 1) {
return `0${number}`;
}
return number;
}
function sendNotification() {
if (Notification.permission === "granted") {
new Notification("Time is gone!", {
vibrate: true,
body: isBreak
? "Break time is gone. Go working"
: "Working time is gone. Take a Break",
});
}
}
useEffect(() => {
if (seconds === 0) {
stopTimer();
sendNotification();
if (isBreak) return;
// Change timer's type to break
setBreak();
setTimeout(() => {
changeMinutes(5);
// Restart the timer
startTimer();
}, 2000);
}
}, [seconds]);
return (
<div className="timer-block">
<div
className="timer"
onClick={isGoing ? stopTimer : startTimer}
style={{
animation: isGoing ? "timer-animation 5s ease-in infinite" : "",
}}
>
<h1>
{addZero(Math.floor(seconds / 60))}:
{addZero(Math.floor(seconds % 60))}
</h1>
</div>
<MinutesPicker
minutes={minutes}
onSave={(mins) => {
changeMinutes(mins);
setMinutes(mins);
}}
isGoing={isGoing}
/>
</div>
);
}
|
import { instance } from "utils/axios";
export const JobDetailsServices = async jobInfo => {
return await instance.post('/GetJobOpeningDetails', jobInfo)
};
export const loginAuthServices = async loginInfo => {
return await instance.post('/ValidateApplicant', loginInfo)
};
export const registerAuthServices = async registerInfo => {
return await instance.post('/AddApplicant', registerInfo)
};
export const forgetPassAuthServices = async forgetPassInfo => {
return await instance.post('/ForgotPassword', forgetPassInfo)
};
|
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
const StyledFooter = styled.footer`
padding: 1rem;
position: absolute;
bottom: 0;
`
const Button = styled.button`
border: none;
padding: 0;
overflow: visible;
margin: 0 0 1rem;
width: 1rem;
height: 1rem;
display: block;
border-radius: 100%;
cursor: pointer;
background: ${({ theme }) => theme.text};
&:focus {
outline: 0;
}
`
const Footer = ({ handleTheme }) => {
return (
<StyledFooter>
<Button onClick={handleTheme} />
{`© ${new Date().getFullYear()}, Built with `}
<a href="https://www.gatsbyjs.org">Gatsby</a>
</StyledFooter>
)
}
Footer.propTypes = {
handleTheme: PropTypes.func.isRequired,
}
export default Footer
|
function getElementLocation(e) {
var rect = e.getBoundingClientRect();
return Math.round(rect.left + (window.scrollX || document.documentElement.scrollLeft || 0)) + ":" +
Math.round(rect.top + (window.scrollY || document.documentElement.scrollTop || 0)) + ":" +
Math.round(rect.width) + ":" +
Math.round(rect.height);
}
// noinspection JSAnnotator
return getElementLocation(document.querySelector(arguments[0]));
|
// Written by Irena Shaffer
$(document).ready(function() {
"use strict";
var av_name = "DFTpropCON";
var av = new JSAV(av_name);
// Slide 1
av.umsg("We can speed up the matrix-vector multiplication using some nice" +
" properties of the DFT matrix.");
var mat = av.ds.matrix({rows: 8, columns: 8, left: 250, top: -15});
var i;
var j;
var power = 0;
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
power = i * j;
mat.value(i, j, "$z^{" + power + "}$");
}
}
av.displayInit();
// Slide 2
var color1 = "#ffffb3";
var color2 = "#cecdca";
av.umsg("We have: $z^0=1$. (Please note: For each matrix value that gets changed, the math won't display quite right until the following slide.)");
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
if (i === 0 || j === 0) {
mat.value(i, j, "$1$");
mat.css(i, j, {"background-color": color1});
}
}
}
av.step();
// Slide 3
av.umsg("Since N = 8 (degree of the polynomial), then for any integer k, we have $z^{8+k}=z^k$. So $z^0=z^8=z^{16}=z^{24}=1$.");
for (i = 0; i < 8; i++) {
for (j = 0; j < 8; j++) {
if (i === 0 || j === 0) {
mat.css(i, j, {"background-color": color2});
}
}
}
mat.value(4, 2, "$1$");
mat.value(2, 4, "$1$");
mat.value(4, 4, "$1$");
mat.value(4, 6, "$1$");
mat.value(6, 4, "$1$");
mat.css(4, 2, {"background-color": color1});
mat.css(2, 4, {"background-color": color1});
mat.css(4, 4, {"background-color": color1});
mat.css(4, 6, {"background-color": color1});
mat.css(6, 4, {"background-color": color1});
av.step();
// Slide 4
av.umsg("We can compute $z^4=-1$. So, we also have $z^4=z^{12}=z^{20}=z^{28}=z^{36}=-1$.");
mat.css(4, 2, {"background-color": color2});
mat.css(2, 4, {"background-color": color2});
mat.css(4, 4, {"background-color": color2});
mat.css(4, 6, {"background-color": color2});
mat.css(6, 4, {"background-color": color2});
mat.value(1, 4, "$-1$");
mat.value(2, 2, "$-1$");
mat.value(4, 1, "$-1$");
mat.value(2, 6, "$-1$");
mat.value(3, 4, "$-1$");
mat.value(4, 3, "$-1$");
mat.value(4, 5, "$-1$");
mat.value(4, 7, "$-1$");
mat.value(5, 4, "$-1$");
mat.value(6, 2, "$-1$");
mat.value(6, 6, "$-1$");
mat.value(7, 4, "$-1$");
mat.css(1, 4, {"background-color": color1});
mat.css(2, 2, {"background-color": color1});
mat.css(4, 1, {"background-color": color1});
mat.css(2, 6, {"background-color": color1});
mat.css(3, 4, {"background-color": color1});
mat.css(4, 3, {"background-color": color1});
mat.css(4, 5, {"background-color": color1});
mat.css(4, 7, {"background-color": color1});
mat.css(5, 4, {"background-color": color1});
mat.css(6, 2, {"background-color": color1});
mat.css(6, 6, {"background-color": color1});
mat.css(7, 4, {"background-color": color1});
av.step();
// Slide 6
mat.css(1, 4, {"background-color": color2});
mat.css(2, 2, {"background-color": color2});
mat.css(4, 1, {"background-color": color2});
mat.css(2, 6, {"background-color": color2});
mat.css(3, 4, {"background-color": color2});
mat.css(4, 3, {"background-color": color2});
mat.css(4, 5, {"background-color": color2});
mat.css(4, 7, {"background-color": color2});
mat.css(5, 4, {"background-color": color2});
mat.css(6, 2, {"background-color": color2});
mat.css(6, 6, {"background-color": color2});
mat.css(7, 4, {"background-color": color2});
av.umsg("Another property is $z^{4+k}=-z^k$ which can be confirmed" +
" from the elements already placed in the matrix.");
av.step();
// Slide 7
av.umsg("We can compute: $z^1=\\sqrt i$. Thus, we have: $z^9=z^{25}=z^{49}=\\sqrt i$ and $z^5=z^{21}=-\\sqrt i$");
mat.value(1, 1, "$\\sqrt i$");
mat.value(3, 3, "$\\sqrt i$");
mat.value(5, 5, "$\\sqrt i$");
mat.value(7, 7, "$\\sqrt i$");
mat.value(1, 5, "$-\\sqrt i$");
mat.value(3, 7, "$-\\sqrt i$");
mat.value(5, 1, "$-\\sqrt i$");
mat.value(7, 3, "$-\\sqrt i$");
mat.css(1, 1, {"background-color": color1});
mat.css(3, 3, {"background-color": color1});
mat.css(5, 5, {"background-color": color1});
mat.css(7, 7, {"background-color": color1});
mat.css(1, 5, {"background-color": color1});
mat.css(3, 7, {"background-color": color1});
mat.css(5, 1, {"background-color": color1});
mat.css(7, 3, {"background-color": color1});
av.step();
// Slide 9
av.umsg("When we compute $z^2=i$, we also get: $z^{10}=z^{18}=z^{42}=i$ and $z^6=z^{14}=z^{30}=-i$");
mat.css(1, 1, {"background-color": color2});
mat.css(3, 3, {"background-color": color2});
mat.css(5, 5, {"background-color": color2});
mat.css(7, 7, {"background-color": color2});
mat.css(1, 5, {"background-color": color2});
mat.css(3, 7, {"background-color": color2});
mat.css(5, 1, {"background-color": color2});
mat.css(7, 3, {"background-color": color2});
mat.value(1, 2, "$i$");
mat.value(2, 1, "$i$");
mat.value(2, 5, "$i$");
mat.value(3, 6, "$i$");
mat.value(5, 2, "$i$");
mat.value(6, 3, "$i$");
mat.value(6, 7, "$i$");
mat.value(7, 6, "$i$");
mat.value(1, 6, "$-i$");
mat.value(2, 3, "$-i$");
mat.value(2, 7, "$-i$");
mat.value(3, 2, "$-i$");
mat.value(5, 6, "$-i$");
mat.value(6, 1, "$-i$");
mat.value(6, 5, "$-i$");
mat.value(7, 2, "$-i$");
mat.css(1, 2, {"background-color": color1});
mat.css(2, 1, {"background-color": color1});
mat.css(2, 5, {"background-color": color1});
mat.css(3, 6, {"background-color": color1});
mat.css(5, 2, {"background-color": color1});
mat.css(6, 3, {"background-color": color1});
mat.css(6, 7, {"background-color": color1});
mat.css(7, 6, {"background-color": color1});
mat.css(1, 6, {"background-color": color1});
mat.css(2, 3, {"background-color": color1});
mat.css(2, 7, {"background-color": color1});
mat.css(3, 2, {"background-color": color1});
mat.css(5, 6, {"background-color": color1});
mat.css(6, 1, {"background-color": color1});
mat.css(6, 5, {"background-color": color1});
mat.css(7, 2, {"background-color": color1});
av.step();
// Slide 11
av.umsg("Finally, we have: $z^3=z^{35}=i\\sqrt i$" +
" and $z^7=z^{15}=-i\\sqrt i$");
mat.css(1, 2, {"background-color": color2});
mat.css(2, 1, {"background-color": color2});
mat.css(2, 5, {"background-color": color2});
mat.css(3, 6, {"background-color": color2});
mat.css(5, 2, {"background-color": color2});
mat.css(6, 3, {"background-color": color2});
mat.css(6, 7, {"background-color": color2});
mat.css(7, 6, {"background-color": color2});
mat.css(1, 6, {"background-color": color2});
mat.css(2, 3, {"background-color": color2});
mat.css(2, 7, {"background-color": color2});
mat.css(3, 2, {"background-color": color2});
mat.css(5, 6, {"background-color": color2});
mat.css(6, 1, {"background-color": color2});
mat.css(6, 5, {"background-color": color2});
mat.css(7, 2, {"background-color": color2});
mat.value(1, 3, "$i\\sqrt i$");
mat.value(3, 1, "$i\\sqrt i$");
mat.value(5, 7, "$i\\sqrt i$");
mat.value(7, 5, "$i\\sqrt i$");
mat.value(1, 7, "$-i\\sqrt i$");
mat.value(3, 5, "$-i\\sqrt i$");
mat.value(5, 3, "$-i\\sqrt i$");
mat.value(7, 1, "$-i\\sqrt i$");
mat.css(1, 3, {"background-color": color1});
mat.css(3, 1, {"background-color": color1});
mat.css(5, 7, {"background-color": color1});
mat.css(7, 5, {"background-color": color1});
mat.css(1, 7, {"background-color": color1});
mat.css(3, 5, {"background-color": color1});
mat.css(5, 3, {"background-color": color1});
mat.css(7, 1, {"background-color": color1});
av.step();
// Slide 12
av.umsg("Using these properties, we only need to compute 4 values: $z^0$, $z^1$, $z^2$, and $z^3$, to completely fill the matrix.");
mat.css(1, 3, {"background-color": color2});
mat.css(3, 1, {"background-color": color2});
mat.css(5, 7, {"background-color": color2});
mat.css(7, 5, {"background-color": color2});
mat.css(1, 7, {"background-color": color2});
mat.css(3, 5, {"background-color": color2});
mat.css(5, 3, {"background-color": color2});
mat.css(7, 1, {"background-color": color2});
av.recorded();
});
|
define(function(require, exports, module) {
var request = require('../../lib/http/request.js');
var arg = require('../../fnc/arg.js');
var inputTip = require('../../fnc/inputTip.js');
var oArguments;
var oInputTip;
/*
foc foc_num foc_name
*/
function GlobalFnDo(options)
{
this.oWrap = options.oWrap;
this.listName = options.listName || 'content_list_jia178';
this.favUrl = options.favUrl || '/index.php/posts/content/like';
this.focUrl = options.focUrl || '/index.php/posts/userset/follow';
this.useUrl = options.useUrl || '';
}
GlobalFnDo.prototype = {
init: function()
{
this.addEvent();
},
addEvent: function()
{
var _this = this;
this.oWrap.on('click', function(e){
_this.judge(e);
});
},
judge: function(e)
{
var _this = this;
var clickType,
target,
data,
key,
value,
thisParent,
role;
target = $(e.target);
role = target.attr('script-role');
if(!role)return;
var re = /(fav)|(foc)|(use)|(add)|(arg)|(diy)|(carry)|(collect)/gi;
if(re.test(role))
{
clickType = target.attr('script-role').match(re)[0];
}
if (target.attr('dis') == 'true')
{
return;
}
if(!clickType)return;
target.parents().each(function(i){
if (target.parents().eq(i).attr('script-role') == _this.listName)
{
thisParent = target.parents().eq(i);
}
});
data = thisParent.data('info');
switch(clickType)
{
case 'fav':
_this.fav(thisParent, data);
break;
case 'foc':
_this.foc(thisParent, data);
break;
case 'use':
_this.use(thisParent, data);
break;
case 'add':
_this.add(thisParent, data);
break;
case 'arg':
_this.arg(thisParent, data);
break;
case 'book':
_this.book();
break;
case 'diy':
_this.diy(thisParent, data);
break;
case 'carry':
_this.carry(thisParent, data);
break;
case 'collect':
_this.collect(thisParent, data);
break;
}
},
link: function(url, data, suc, fail)
{
request({
url: url,
data: data,
sucDo: function(data)
{
suc && suc(data);
}
});
},//喜欢
fav: function(oThis, data)
{
// 如需增加参数在data对象上添加即可;
var param = {};
param.cid = data.cid;
var oName = oThis.find('[script-role=fav_name]');
var oNum = oThis.find('[script-role=fav_num]');
var cancelStr = '取消喜欢';
var addStr = '喜欢';
var nNewNum = 0;
this.link(this.favUrl, param, function(){
var isLike = data.is_like;
if(isLike == "0")
{
// 喜欢成功do
oName.html(cancelStr);
if(oNum.length)nNewNum = parseInt(oNum.html()) + 1;
data.is_like = "1";
}
else if(isLike == "1")
{
//取消喜欢do
oName.html(addStr);
if(oNum.length)nNewNum = parseInt(oNum.html()) - 1;
data.is_like = "0";
}
if(oNum.length) oNum.html(nNewNum);
});
},//关注
foc: function(oThis, data)
{
var param = {};
param.uid = data.uid ? data.uid : data.user_id;
var oTher = $('[script-role='+this.listName+']');
var cancelStr = '已关注';
var addStr = '关注TA';
var nNewNum = 0;
this.link(this.focUrl, param, function(){
var isFollow = data.is_follow;
oTher.each(function(i){
if(oTher.eq(i).data('info')['uid'] == data.uid)
{
var oName = oTher.eq(i).find('[script-role=foc_name]');
var oNum = oTher.eq(i).find('[script-role=foc_num]');
if(isFollow == "0")
{
// 关注成功do
oName.html(cancelStr);
oName.attr('dis','true');
oName.addClass('default');
if(oNum.length)nNewNum = parseInt(oNum.html()) + 1;
oTher.eq(i).data('info')['is_follow'] = "1";
}
else if(isFollow == "1")
{
//取消关注do
oName.html(addStr);
if(oNum.length)nNewNum = oNum.html() - 1;
oTher.eq(i).data('info')['is_follow'] = "0";
}
if(oNum.length) oNum.html(nNewNum);
}
});
});
},//有用
use: function(oThis, data)
{
var param = {};
param.cid = data.cid;
var oName = oThis.find('[script-role=use_name]');
var oNum = oThis.find('[script-role=use_num]');
var cancelStr = '取消有用';
var addStr = '有用';
var nNewNum = 0;
this.link(this.useUrl, param, function(){
var isRecommend = data.is_recommend;
if(isRecommend == "0")
{
// 喜欢成功do
oName.html(cancelStr);
if(oNum.length)nNewNum = oNum.html() + 1;
data.is_recommend = "1";
}
else if(isRecommend == "1")
{
//取消喜欢do
oName.html(addStr);
if(oNum.length)nNewNum = oNum.html() - 1;
data.is_recommend = "0";
}
if(oNum.length) oNum.html(nNewNum);
});
},
add: function(oThis, data)
{
var addUrl = '/index.php/view/album/albumlist';
var subUrl = '/index.php/posts/album/addtocontent';
var oSelect = oThis.find('[script-role = select_project_area]');
var oAddInput = oThis.find('[script-role = add_new_project]');
var oSelectRaido = oThis.find('[script-role = select_project_type]');
var oAddNewRadio = oThis.find('[script-role = select_add_type]');
var oAddBtn = oThis.find('[script-role = add_project_btn]');
var oNum = oThis.find('[script-role=add_num]');
var nNewNum = 0;
if(!oThis.get(0).FIRSTADDPROJECT)
{
oThis.get(0).FIRSTADDPROJECT = true;
request({
url: addUrl,
sucDo: function(data)
{
var i,
num,
realData;
realData = data.data;
num = realData.length;
for(i=0; i<num; i++)
{
var oOption = $('<option id='+ realData[i].album_id +'>'+ realData[i].album_name +'</option>');
oSelect.append(oOption);
}
}
})
init();
}
oSelectRaido.unbind('click');
oSelectRaido.click(function(){
disbale(oAddInput);
able(oSelect);
clearData(oAddInput);
});
oAddNewRadio.unbind('click');
oAddNewRadio.click(function(){
disbale(oSelect);
able(oAddInput);
clearData(oSelect);
});
submit(oAddBtn, oSelect, oAddInput);
function init()
{
oSelectRaido.get(0).checked = true;
oAddInput.attr('disabled','disabled');
}
function able(obj)
{
obj.removeAttr('disabled');
}
function disbale(obj)
{
obj.attr('disabled','disabled');
}
function clearData(obj)
{
var domObj = obj.get(0);
if(domObj.selectedIndex)
{
domObj.selectedIndex = 0;
}
else
{
domObj.value = '';
}
}
function submit(oBtn,oSelect,oInput)
{
oBtn.unbind('click');
oBtn.click(function(){
var select_name = oSelect.get(0).options[oSelect.get(0).selectedIndex].text;
var cid = oBtn.attr('cid');
var name = oInput.val();
if(!oSelect.val() && !oInput.val())
{
alert('请至少选择或创建一项');
return;
}
else
{
if(oSelect.val())
{
request({
url: subUrl,
data: {name: select_name, cid:cid},
sucDo: function()
{
alert('加入成功');
oSelect.get(0).selectedIndex = 0;
if(oNum.length)nNewNum = parseInt(oNum.html()) + 1;
oNum.html(nNewNum);
},
noDataDo: function(msg)
{
alert(msg);
}
});
}
else
{
request({
url: subUrl,
data: {name:name , cid:cid},
sucDo: function(data)
{
alert('创建成功');
var oOption = $('<option id='+ data.data +'>'+ name +'</option>');
oSelect.append(oOption);
if(oNum.length)nNewNum = parseInt(oNum.html()) + 1;
oNum.html(nNewNum);
oInput.val('');
},
noDataDo: function(msg)
{
alert(msg);
}
});
}
}
});
}
},
arg: function(oThis, data)
{
var oSendBtn = oThis.find('[script-role = pinlun_btn]');
var oArea = oThis.find('[script-role = pinlun_textarea]');
var oListWrap = oThis.find('[script-role = pinlun_wrap]');
var oLoadMore = oThis.find('[script-role = pinlun_more]');
var oNum = oThis.find('[script-role = pinlun_num]');
var oTip = oThis.find('[script-role = pinlun_tip]');
if(!oThis.get(0).FIRSTARGUMENT)
{
oThis.get(0).FIRSTARGUMENT = true;
oInputTip = new inputTip({
oArea : oArea,
oTip : oTip
});
oArguments = new arg({
oSendBtn : oSendBtn,
oLoadMore : oLoadMore,
oListWrap : oListWrap,
oArea : oArea,
articalId : data.cid,
oNum: oNum,
down: function()
{
oInputTip.clear();
}
});
oArguments.init();
oInputTip.init();
}
},
book: function(oThis)
{
var tagId = oThis.attr('tagId');
},
diy: function(oThis, data)
{
var getDataUrl = '/index.php/view/scheme/getDiyList';
var addUrl = '/index.php/posts/room/tomyscheme';
var oBox = $('#carry_step_box_confirm').get(0);
var aRadio = $('[script-role = diy_select_type]');
var oCreate = $('[script-role = diy_create]');
var oSelect = $('[script-role = diy_select]');
var oConfirm = $('[script-role = diy_confirm]');
var param = {};
var sType = 'select';
if(!oBox.firstLoad)
{
request({
url: getDataUrl,
sucDo: function(data)
{
oSelect.html('');
var i,
num,
aList;
aList = data.data;
num = aList.length;
for (i=0; i<num; i++)
{
var oOption = $('<option id='+ aList[i].scheme_id +'>'+ aList[i].scheme_name +'</option>');
oSelect.append(oOption);
}
}
});
}
aRadio.unbind('click');
aRadio.on('click', function(){
sType = $(this).attr('script-type');
if(sType == 'create')
{
oCreate.removeAttr('disabled');
oSelect.attr('disabled', 'disabled');
init();
}
else if(sType == 'select')
{
oSelect.removeAttr('disabled');
oCreate.attr('disabled', 'disabled');
init();
}
});
oConfirm.unbind('click');
oConfirm.on('click', function(){
if(sType == 'select')
{
if(!oSelect.val())
{
alert('请选择');
return;
}else
{
param.sid = oSelect.get(0).options[oSelect.get(0).selectedIndex].id;
param.rid = data.rid;
request({
url: addUrl,
data: param,
sucDo: function(data)
{
alert(data.msg);
init();
$.fancybox.close();
},
noDataDo: function(msg)
{
alert(msg);
init();
$.fancybox.close();
}
});
}
}
else
{
if(!oCreate.val())
{
alert('方案名称不能为空');
return;
}else
{
param.scheme_name = oCreate.val();
param.rid = data.rid;
request({
url: addUrl,
data: param,
sucDo: function(data)
{
alert(data.msg);
init();
$.fancybox.close();
},
noDataDo: function(msg)
{
alert(msg);
init();
$.fancybox.close();
}
});
}
}
});
function init()
{
oSelect.get(0).selectedIndex = 0;
oCreate.val('');
}
$.fancybox({href: '#carry_step_box_confirm'});
},
carry: function(oThis, data)
{
var sNeed = data.need_store;
var sNow = data.user_score;
var oNeed = $('[script-role = need]');
var oNow = $('[script-role = now]');
var oConfirm = $('[script-role = carry_confirm_btn]');
var oRightTip = $('[script-role = right_tip]');
var oWrongTip= $('[script-role = wrongtip]');
var oView = $('[script-role = view_home]');
oNeed.html(sNeed);
oNow.html(sNow);
oView.attr('href', data.userspace);
oConfirm.unbind('click');
oConfirm.on('click', function(){
request({
url: '/index.php/posts/scheme/tomyhome',
data: {sid: data.rid},
sucDo: function(data)
{
oRightTip.html(data.msg.info);
$.fancybox({href:"#carry_step_box_suc"});
oView.attr('href', data.msg.scheme_url);
},
noDataDo: function(msg)
{
oWrongTip.html(msg);
$.fancybox({href:"#carry_step_box_fail"});
}
});
});
$.fancybox({href:"#carry_step_box_confirm"});
},
collect: function(oThis, data)
{
var oName = oThis.find('[script-role = collect_name]');
var oBtn = oName.parents('[script-role = collect]').attr('dis', 'true');
var url = data.type == 'scheme' ? '/index.php/posts/scheme/like' : '/index.php/posts/room/like';
var param = data.type == 'scheme' ? {sid: data.rid} : {rid: data.rid}
request({
url: url,
data: param,
sucDo: function(data)
{
oName.html('已收藏');
oName.attr('dis', 'true');
oBtn.attr('dis', 'true');
oBtn.css('cursor', 'default');
},
noDataDo: function(msg)
{
alert(msg);
}
})
}
};
return GlobalFnDo;
}); |
/*
平台接口基础类
*/
cc.Class({
properties: {
// 无需做适配的手机品牌
_noNeedAdaptBrandList: [],
// 需要适配的品牌中为全面屏但是无刘海的手机型号(无需适配)
// 型号统一用小写
_noDangerAreaModelList: [],
// 需要额外适配的机型 Key:model Value:height
// 型号统一用小写
_needAdaptModelMap: {
default: {},
},
},
ctor() {
this.registerOnGlobalError();
this.loc_login_data = {};
this.loclaunch_options = {};
this.launch_options = null;
this.onshow_options = {};
this.initIPhoneXConfig();
},
onHide() {},
onShow() {},
getOnShowData() {},
clearOnShowData() {},
clearOnShowOptions() {},
onLaunch() {},
report() {},
authorize() {},
showTips(){},
login() {},
getLaunchData() {},
clearLocLaunchData() {},
getLocLaunchData() {},
getRegInfo() {},
allPay() {},
requestPayBill() {},
paySuccessReq() {},
share() {},
shareMessage() {},
keepScreenOn() {},
hideKeyboard() {},
exit() {},
forceUpdate() {},
uploadError() {},
uploadEventStat() {},
uploadHortorStat() {},
initWallSDK() {},
loginWallSDK() {},
setClipboardData() {},
getSystemInfoSync() { return {}; },
reportEndGameData() {},
setUserCloudStorage() {},
getOpenDataContext() {},
createRewardedVideoAd() {},
showRewardedVideoAd() {},
getSetting() {},
previewImage() {},
isSupportNavigate() {},
navigateToMiniProgram() {},
setLocLoginData() {},
removeFile() {},
makeDir() {},
writeFile() {},
saveImageToPhotosAlbum() {},
toTempFilePath() {},
getQRCode() {},
access() {},
//web可用
checkSession(cb) {
if (cb) cb(0);
},
openSetting(cb) {
if (cb) cb(0);
},
clearLocLaunchAndShowData() {
this.clearLocLaunchData();
this.clearOnShowData();
this.clearOnShowOptions();
},
getLocLoginData() {
return this.loc_login_data;
},
setLocLoginAsscessToken(token) {
this.loc_login_data = this.loc_login_data || {};
this.loc_login_data.body = this.loc_login_data.body || {};
this.loc_login_data.body.access_token = token;
},
testWXLogin(successCb) {
let body = {uin: qf.cfg.UIN};
if (successCb) successCb(qf.cmd.TEST_LOGIN, body);
},
garbageCollect() {
cc.sys.garbageCollect();
},
getBatteryLevel() {
return "0";
},
getPlatformName() {
return "web"
},
registerOnGlobalError() {
window.onerror = () => {};
},
getUserInfoWithOutButton() {
return true;
},
createUserInfoButton() {
return true;
},
getUserIsAuthorization() {
return true;
},
getLocalResPath() {
return "";
},
initIPhoneXConfig() {
// 无需做适配的手机品牌
this._noNeedAdaptBrandList = [
// "HUAWEI",
"Xiaomi",
"samsung",
"OnePlus",
"meizu",
"HONOR"
];
// 需要适配的品牌中为全面屏但是无刘海的手机型号(无需适配)
// 型号统一用小写
this._noDangerAreaModelList = [
"vivo nex",
"oppo r17",
"oppo find",
"vivo x23",
];
},
getIPhoneXOffsetHeight () {
let t = cc.view.getFrameSize(), height = 0;
if (t.width === 1125 && t.height === 2436) { //iPhoneX
height = 189;
}
else if (t.width === 375 && t.height === 812) { //iPhoneX
height = 63;
}
else if (t.width === 1080 && t.height === 2208) { //vivo Y85A
height = 171;
}
else if (t.width === 360 && t.height === 736) { //vivo Y85A
height = 57;
}
else {
let systemInfo = this.getSystemInfoSync();
let statusBarHeight = systemInfo.statusBarHeight || 0;
if (statusBarHeight < 28) {
height = 0;
}
else {
let model = systemInfo.model;
let brand = systemInfo.brand;
let value = this.getNeedAdaptValue(model);
if (this.isNoNeedAdapt(brand) || this.isNoDangerArea(model)) {
// 无需做适配
}
else if (value !== null) {
height = value;
}
else if (t.width < t.height) { // 未知分辨率机型统一按iphoneX适配
height = 63;
}
else if (t.width > t.height) {
height = 63;
}
}
}
return height;
},
isNoNeedAdapt (brand) {
if (!brand) return false;
let list = this._noNeedAdaptBrandList;
for (let i in list) {
if (brand.toLowerCase() === list[i].toLowerCase()) {
return true;
}
}
return false;
},
isNoDangerArea (model) {
if (!model) return false;
let list = this._noDangerAreaModelList;
for (let i in list) {
if (model.toLowerCase().indexOf(list[i].toLowerCase()) !== -1) {
return true;
}
}
return false;
},
getNeedAdaptValue (model) {
if (!model) return null;
let list = this._needAdaptModelMap;
for (let key in list) {
if (model.toLowerCase().indexOf(key.toLowerCase()) !== -1) {
return list[key];
}
}
return null;
},
}); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.