text
stringlengths 7
3.69M
|
|---|
import "./PageFilter.css";
import React from "react";
function template() {
return (
<div className="page-filter">
<h1>List with Filter</h1>
<div>
<span>
Enter Name :
<input onChange={this.fieldChange}/>
</span>
<span>
<select onChange={this.fieldChange}>
<option>Select</option>
<option>John</option>
<option>Peter</option>
<option>Paul</option>
<option>Kim</option>
</select>
</span>
</div>
<div>
Grid Items
<div>
{
this.state.data && this.state.data.length>0 &&
<table>
<tbody style={{margin:"20px"}}>
<tr>
<th>ID</th><th>Name</th><th>Price</th>
</tr>
{
this.state.data.map((obj,index) => {
return <tr key={index}>{
this.state.keys.map((keyid,i)=>{
return <td key={i} style={{width:"50px"}}>{obj[keyid]}</td>
})
}</tr>
})
}
</tbody>
</table>
}
</div>
</div>
</div>
);
};
export default template;
|
import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';
import arrow from './arrow.svg';
import classes from './index.module.css';
import {getAsync} from '../../../../tool/api-helper';
import bag from './bag.svg';
import employee from './employee.svg';
import {IfCollect} from '../if-collect';
import location from './location.svg';
import { languageHelper } from '../../../../tool/language-helper';
import {Location} from '../location';
class CompanyCardBarIdReact extends React.Component {
constructor(props) {
super(props);
// state
this.state = {
isLiked : false,
};
// i18n
this.text = CompanyCardBarIdReact.i18n[languageHelper()];
}
async componentDidMount() {
if (this.props.id) {
this.setState({
backend: await getAsync(`/companies/${this.props.id}`)
});
} else {
this.setState({
backend: await getAsync('/companies/1')
});
}
}
clickOnCard = () => {};
clickPositions = () => {};
render() {
return (this.state.backend && this.state.backend.status && this.state.backend.status.code.toString().startsWith('2')) ? (
<div
className={classes.Card}
style={{cursor:'pointer'}}
>
<div className={classes.Clickable} onClick={()=>{
this.props.history.push(`/company/${this.state.backend.content.id}`);
}} />
<div className={classes.UnClickable}>
<div className={classes.Icon}>
<img src={(this.state.backend.content.avatarUrl)?(this.state.backend.content.avatarUrl):('https://frontendpic.oss-us-east-1.aliyuncs.com/%E5%85%AC%E5%8F%B8.png')} alt="no img" />
</div>
<div className={classes.Info}>
<div className={classes.Name}>
<p>{this.state.backend.content.name}</p>
</div>
<div className={classes.Des1}>
<img src={location} alt="no img" />
<Location
code={this.state.backend.content.location[0]}
edit={false}
locate={()=>{}}
/>
</div>
<div className={classes.Des2}>
<img src={employee} alt="no img" />
<p>
<a href={this.state.backend.content.website}>{this.state.backend.content.website}</a>
</p>
</div>
</div>
<div className={classes.Actions}>
<div className={classes.Positions} onClick={this.clickPositions}>
<button>
<img src={bag} alt="no img" />
<p>
{this.text.currently} {this.state.backend.content.jobCount}{this.text.openPos}
</p>
<img src={arrow} alt="no img" />
</button>
</div>
<div className={classes.Like}>
<IfCollect
ifcollect={this.state.backend.content.collected}
type={2}
id={this.state.backend.content.id}
/>
</div>
</div>
</div>
</div>
):null;
}
}
CompanyCardBarIdReact.i18n = [
{
unLike: '取消收藏',
like: '收藏',
currently: '目前',
openPos: '个空缺职位',
employee: '个员工',
},
{
unLike: 'UnLike',
like: 'Like',
currently: 'Currently',
openPos: 'Open Position',
employee: 'employees',
},
];
CompanyCardBarIdReact.propTypes = {
// self
id: PropTypes.string.isRequired,
// React Router
match: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
location: PropTypes.object.isRequired
};
export const CompanyCardBarId = withRouter(CompanyCardBarIdReact);
|
import React from 'react'
import { render } from 'react-dom'
import ExchangeApp from './components/exchange-app'
import './index.css'
const reactRendersHere = document.querySelector("#react-renders-here")
render(<ExchangeApp/>, reactRendersHere )
|
import React from 'react'
import Facility from '../utils/Facility'
import Footer from '../utils/Footer'
import ProductComponents from '../utils/ProductComponents'
import Multi from '../utils/Multi';
import ItemPop from '../utils/ItemPop';
import LastNav from '../utils/LastNav';
const ProductsArea = () => {
return (
<div>
<LastNav />
<ProductComponents />
<Multi />
<Facility />
<Footer />
<ItemPop />
</div>
)
}
export default ProductsArea
|
const MessengerBuddy = require('../../game/players/messengerbuddy');
class PlayerController {
static getFriends(id) {
const connection = Pixel.getDatabase().connection;
return new Promise((resolve, reject) => {
connection.query({
sql: 'SELECT u1.id AS u1_id, u2.id AS u2_id, u1.nickname AS u1_nickname, u2.nickname AS u2_nickname, u1.motto AS u1_motto, u2.motto AS u2_motto, u1.figure AS u1_figure, u2.figure AS u2_figure, u1.gender AS u1_gender, u2.gender AS u2_gender FROM `user_relationships` JOIN users u1 ON user_relationships.userid_0 = u1.id JOIN users u2 ON user_relationships.userid_1 = u2.id',
values: [id, id],
}, (error, results) => {
if (error) {
reject(error);
return;
}
const out = [];
for (const result of results) {
if (result.u1_id === id) {
out.push(new MessengerBuddy(
result.u2_id,
result.u2_nickname,
result.u2_motto,
result.u2_figure,
result.u2_gender
));
} else {
out.push(new MessengerBuddy(
result.u1_id,
result.u1_nickname,
result.u1_motto,
result.u1_figure,
result.u1_gender
));
}
}
resolve(out);
});
});
}
static getFriendCount(id) {
const connection = Pixel.getDatabase().connection;
return new Promise((resolve, reject) => {
connection.query({
sql: 'SELECT (SELECT COUNT(*) FROM user_relationships WHERE userid_0 = ?) + (SELECT COUNT(*) FROM user_relationships WHERE userid_1 = ?) AS count',
values: [id, id],
}, (error, results) => {
if (error) {
reject(error);
return;
}
resolve(results[0].count);
});
});
}
static updateLook(id, newGender, newLook) {
const connection = Pixel.getDatabase().connection;
return new Promise((resolve, reject) => {
connection.query({
sql: 'UPDATE users SET `gender` = ?, `figure` = ? WHERE id = ?',
values: [newGender, newLook, id],
}, (error) => {
if (error) {
reject(error);
return;
}
resolve();
});
});
}
}
module.exports = PlayerController;
|
import { StyleSheet } from "react-native";
export default StyleSheet.create({
filterModalContainer: {
flex: 1,
backgroundColor: "#fff"
},
fitlerModal: {
marginTop: 10,
marginHorizontal: 10,
paddingHorizontal: 10
},
rangesContainer: {
flexDirection: "row",
marginHorizontal: 15,
marginVertical: 10,
flexWrap: "wrap"
},
rangeSelect: {
margin: 5,
borderColor: "#ddd",
borderWidth: 2,
padding: 10
},
selected: {
backgroundColor: "#fff",
borderWidth: 1,
borderColor: "#FF0074"
},
textBold: {
fontSize: 24, fontWeight: "700"
}
});
|
$(document).ready(function () {
$('.select2').select2({
theme: "bootstrap"
});
var open_event;
var $dialog = $('#view-dialog').dialog({
autoOpen: false,
buttons: {
'Duplicar': function () {
duplicate_event(open_event);
$(this).dialog("close");
},
'Apagar': function () {
destroy_event(open_event);
$(this).dialog("close");
}
}
});
$('.js-tree').each(function () {
var $container = $(this);
var $tree_content = $container.find('.tree-content');
var $input = $container.find('.tree-filter');
var tree;
$tree_content.fancytree({
extensions: ["dnd", "persist", "filter"],
quicksearch: true,
clickFolderMode: 2,
focusOnSelect: false,
selectMode: 1,
create: function(){
$container.find(".fancytree-container").addClass("fancytree-connectors");
},
source: {
url: $container.data('tree-source'),
cache: false
},
persist: {
overrideSource: true,
cookiePrefix: 'fancytree-' + $container.data('tree-name') + '-',
store: "cookie", // 'cookie': use cookie, 'local': use localStore, 'session': use sessionStore
types: "active expanded focus selected" // which status types to store
},
dnd: {
smartRevert: false,
draggable: {
zIndex: 999,
appendTo: "body",
helper: draggable_helper
},
dragStart: function () {
return true;
}
}
});
tree = $tree_content.fancytree("getTree");
if($input.length > 0) {
$input.keyup(function (e) {
var match = $(this).val();
if(e && e.which === $.ui.keyCode.ESCAPE || $.trim(match) === ""){
tree.clearFilter();
$input.val('');
return;
}
tree.filterBranches.call(tree, match, {
autoApply: true,
autoExpand: true,
counter: false,
fuzzy: true,
hideExpanders: true,
highlight: true,
nodata: true,
mode: 'hide'
});
// $("button#btnResetSearch").attr("disabled", false);
// $("span#matches").text("(" + n + " matches)");
});
}
});
function draggable_helper(event) {
var sourceNode = $.ui.fancytree.getNode(event.target);
// Copy description to title because Fancytree already use title and Fullcalendar needs it
sourceNode.data.title = sourceNode.data.description;
// Set event data to container because drop source is the container instead of node
$(event.currentTarget).data('event', sourceNode.data);
var $helper =
$('<div class="drag-helper">' +
' <div class="fc-time-grid-event fc-v-event fc-event">' +
' <div class="fc-content">' +
' <div class="fc-title">' + sourceNode.data.description + '</div>' +
' </div>' +
' <div class="fc-bg"></div>' +
' </div>' +
'</div>');
if (sourceNode.data.cor) {
$helper.find('.fc-event').css({
backgroundColor: sourceNode.data.color
});
}
// Attach node reference to helper object
$helper.data("ftSourceNode", sourceNode);
// we return an unconnected element, so `draggable` will add this
// to the parent specified as `appendTo` option
return $helper;
}
var $calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'agendaWeek,month'
},
height: $(window).height() - $('.navbar').outerHeight(true),
defaultView: 'agendaWeek',
nowIndicator: true,
allDaySlot: false,
locale: 'en',
timeFormat: 'H:mm',
slotLabelFormat: 'H:mm',
slotLabelInterval: '01:00:00',
slotDuration: '00:15:00',
snapDuration: '00:15:00',
defaultTimedEventDuration: '01:00:00',
editable: true,
droppable: true,
forceEventDuration: true,
events: {
url: '/api/tasks',
data: {
user_id: app.user_id
}
},
eventResize: function (_event) {
var event = _event;
setTimeout(function(){
$('.fc-event').each(function(){
if($(this).data('fcSeg').event.id == event.id) {
$(this).css('opacity', 0.5);
}
});
}, 10);
$calendar.trigger('busycal.event_update', [event]);
},
eventDrop: function (_event) {
var event = _event;
setTimeout(function(){
$('.fc-event').each(function(){
if($(this).data('fcSeg').event.id == event.id) {
$(this).css('opacity', 0.5);
}
});
}, 10);
$calendar.trigger('busycal.event_update', [event]);
},
eventReceive: function (event) {
event.stored = false;
$('.fc-event').each(function(){
if($(this).data('fcSeg').event.id == event.id) {
$(this).css('opacity', 0.5);
}
});
$calendar.trigger('busycal.event_create', [event]);
},
eventClick: function (event) {
open_event = event;
$dialog.find('.view-dialog-project span').text(event.project);
$dialog.find('.view-dialog-subproject span').text(event.subproject);
$dialog.find('.view-dialog-phase span').text(event.phase);
$dialog.find('.view-dialog-client span').text(event.client);
$dialog.dialog('open');
}
});
$(window).resize(function(){
$calendar.fullCalendar('option', 'height', $(window).height() - $('.navbar').outerHeight(true));
});
$calendar.on('busycal.event_create', function (e, event) {
create_task_api(event);
});
$calendar.on('busycal.event_created', function (e, event) {
$('.fc-event').each(function(){
if($(this).data('fcSeg').event.id == event.id) {
$(this).css('opacity', 1);
}
});
});
$calendar.on('busycal.event_updated', function (e, event) {
$('.fc-event').each(function(){
if($(this).data('fcSeg').event.id == event.id) {
$(this).css('opacity', 1);
}
});
});
$calendar.on('busycal.event_update', function (_e, _event) {
var event = _event;
if (event.stored) {
update_task_api(event);
} else {
if (typeof event.timeout !== 'undefined') {
clearTimeout(event.timeout);
}
event.timeout = setTimeout(function () {
$calendar.trigger('busycal.event_update', [event]);
}, 1000);
}
});
$calendar.on('busycal.event_destroy', function (_e, _event) {
var event = _event;
if (event.stored) {
destroy_task_api(event);
} else {
if (typeof event.timeout !== 'undefined') {
clearTimeout(event.timeout);
}
event.timeout = setTimeout(function () {
$calendar.trigger('busycal.event_destroy', [event]);
}, 1000);
}
});
function create_task_api(_event) {
var event = _event;
$.ajax({
url: '/api/tasks',
type: 'post',
data: {
subproject_phase_id: event.subproject_phase_id,
start: event.start.format(),
end: event.end.format(),
user_id: app.user_id
},
success: function (data) {
event.id = data.task.id;
event.stored = true;
$calendar.trigger('busycal.event_created', [event])
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status == 403) {
location.reload();
} else {
alert('Erro ao salvar!!!');
location.reload();
}
}
});
}
function update_task_api(_event) {
var event = _event;
$.ajax({
url: '/api/tasks/' + event.id,
type: 'patch',
data: {
start: event.start.format(),
end: event.end.format(),
request_control: new Date().getTime(),
user_id: app.user_id
},
success: function (data) {
$calendar.trigger('busycal.event_updated', [event, data])
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status == 403) {
location.reload();
} else {
alert('Erro ao salvar!!!');
location.reload();
}
}
});
}
function destroy_task_api(_event) {
var event = _event;
$.ajax({
url: '/api/tasks/' + event.id,
type: 'delete',
data: {
user_id: app.user_id
},
success: function (data) {
$calendar.trigger('busycal.event_destroyed', [event, data])
},
error: function(jqXHR, textStatus, errorThrown) {
if(jqXHR.status == 403) {
location.reload();
}
}
});
}
function destroy_event(event) {
$calendar.fullCalendar('removeEvents', event._id);
$calendar.trigger('busycal.event_destroy', [event])
}
function duplicate_event(event) {
var clone = {
title: event.title,
client: event.client,
phase: event.phase,
subproject: event.subproject,
project: event.project,
subproject_phase_id: event.subproject_phase_id,
stored: false,
color: event.color,
start: event.start,
end: event.end,
allDay: false
};
var created_event = $calendar.fullCalendar('renderEvent', clone, false);
$calendar.trigger('busycal.event_create', [created_event[0]]);
}
});
|
'use strict';
const Service = require('egg').Service,
MD5 = require('md5.js');
class GetSignInResultService extends Service {
async post(params) {
try {
let SignInResult;
const {
tel,
password
} = params,
selectUserResult = await this.app.mysql.get('users', {
tel,
enabled: 1
});
if (selectUserResult) {
const selectSaleResult = await this.app.mysql.get('verification', {
userid: selectUserResult.userid
}),
salt = selectSaleResult.salt,
oriPasswordMD5 = new MD5().update(password).digest('hex'),
frontOriPasswordMD5 = oriPasswordMD5.substring(0, 16),
afterOriPasswordMD5 = oriPasswordMD5.substring(16, 32),
frontSalt = salt.substring(16, 32),
afterSalt = salt.substring(16, 32),
saltPassword = new MD5().update(afterOriPasswordMD5 + frontSalt + frontOriPasswordMD5 + afterSalt).digest('hex');
if (selectUserResult.password == saltPassword) {
const updateUserLoadStatusResult = await this.app.mysql.update('users', {
loaded: 1
}, {
where: {
userid: selectUserResult.userid
}
}),
updateUserLoadStatusSuccess = updateUserLoadStatusResult.affectedRows === 1;
if (updateUserLoadStatusSuccess) {
this.ctx.session.USERSESSION = {
userid: selectUserResult.userid
};
SignInResult = {
message: '登陆成功了哟~',
success: true
}
} else {
SignInResult = {
message: '登陆失败请重试~',
success: false
}
}
} else {
SignInResult = {
message: '密码错误了哎~',
success: false
}
}
} else {
SignInResult = {
message: '该账号不存在哦~',
success: false
}
}
return SignInResult;
} catch (e) {
return Object.assign(e, {
success: false
});
}
}
}
module.exports = GetSignInResultService;
|
'use strict'
const property = require('@northscaler/property-decorator')
const { IllegalArgumentError, MissingRequiredArgumentError, MethodNotImplementedError } = require('@northscaler/error-support')
const CardinalDirection = require('../enums/CardinalDirection')
class Parallel {
@property()
_degrees
@property()
_max
constructor (degrees, max = 180) {
this.degrees = degrees
this.max = max
}
get minutes () {
return Math.abs((this.degrees - parseInt(this.degrees)) * 60)
}
get seconds () {
const minutes = this.minutes
return Math.abs((minutes - parseInt(minutes)) * 60)
}
get direction () {
throw new MethodNotImplementedError({ info: 'get direction' })
}
_testSetDegrees (degrees) {
degrees = parseFloat(degrees)
if (isNaN(degrees) || degrees < -this.max || degrees > this.max) {
throw new IllegalArgumentError({
info: 'degrees',
message: `only between -${this.max} and ${this.max} inclusive allowed`
})
}
return degrees
}
toString (format) {
switch ((format || '').toString().trim().toLowerCase()) {
case 'dd': // unsigned degrees plus direction
return `${Math.abs(this.degrees)}\xB0${this.direction.name}`
case 'd': // signed decimal degrees
return `${this.degrees}\xB0`
case 'dms': // signed degrees, minute, seconds
return `${this.degrees}\xB0${parseInt(this.minutes)}'${this.seconds}"`
default:
// unsigned degrees, minutes, seconds plus direction
return `${Math.abs(this.degrees)}\xB0${parseInt(this.minutes)}'${this.seconds}"${this.direction.name}`
}
}
clone () {
return new Parallel(this._degrees, this._max)
}
}
class Longitude extends Parallel {
get direction () {
return this.degrees >= 0 ? CardinalDirection.E : CardinalDirection.W
}
}
class Latitude extends Parallel {
get direction () {
return this.degrees >= 0 ? CardinalDirection.N : CardinalDirection.S
}
}
class Gps {
@property()
_lat
@property()
_lon
constructor ({ lat, lon }) {
this.lat = typeof lat === 'number' ? new Latitude(lat) : lat
this.lon = typeof lon === 'number' ? new Longitude(lon) : lon
}
_testSetLat (lat) {
lat = typeof lat === 'number' ? new Latitude(lat) : lat
return lat
}
_testSetLon (lon) {
lon = typeof lon === 'number' ? new Longitude(lon) : lon
return lon
}
toString (format) {
return `${this.lat.toString(format)} ${this.lon.toString(format)}`
}
clone () {
return new Gps({ lat: this._lat.clone(), lon: this._lon.clone() })
}
}
class StreetAddress {
// inspired by https://stackoverflow.com/questions/1159756/how-should-international-geographical-addresses-be-stored-in-a-relational-databa
@property()
_streetNumber // 123, ...
@property()
_buildingName // some addresses have building names instead of street numbers
@property()
_streetNumberSuffix // A, ½, ...
@property()
_streetNameDirectionPrefix // N, SW, ...
@property()
_streetName // Mulberry, ...
@property()
_streetNameDirectionSuffix // N, SW, ...
@property()
_streetType // boulevard, street, place, lane, ...
@property()
_streetTypeDirectionSuffix // N, SW, ...
@property()
_compartmentType // po box, apartment, floor, suite, ...
@property()
_compartmentId // 123, 1A, ...
@property()
_localMunicipality // if it appears in address before the city
@property()
_city // Metroville, ...
@property()
_governingDistrict // state in US, province in CA, distrito federal in MX, ...
@property()
_postalCode // 34213 in US, ...
@property()
_postalCodeSuffixSeparator
@property()
_postalCodeSuffix // US plus-four, ...
@property()
_country // US, CA, MX, ...
clone () {
return Object.keys(this).reduce((it, key) => {
it[key] = this[key]
return it
}, Object.create({}, Object.getPrototypeOf(this)))
}
}
class UsStreetAddress extends StreetAddress {
constructor ({
streetNumber, // 123
streetNumberSuffix, // A, ½, ...
streetNameDirectionPrefix, // N, SW, ...
streetName, // Mulberry
streetNameDirectionSuffix, // N, SW, ...
streetType, // St, Ave, Blvd, ...
streetTypeDirectionSuffix, // N, SW, ...
compartmentType, // Suite, Apartment, ...
compartmentId, // 1A, 200, ...
city, // Austin
state, // TX
zip, // 12345
zipPlus4 // 4321
}) {
super()
this.streetNumber = streetNumber
this.streetNameDirectionPrefix = streetNameDirectionPrefix
this.streetNumberSuffix = streetNumberSuffix
this.streetName = streetName
this.streetNameDirectionSuffix = streetNameDirectionSuffix
this.streetType = streetType
this.streetTypeDirectionSuffix = streetTypeDirectionSuffix
this.compartmentType = compartmentType
this.compartmentId = compartmentId
this.city = city
this.governingDistrict = state
this.postalCode = zip
this.postalCodeSuffix = zipPlus4
this.country = 'US'
this.postalCodeSuffixSeparator = '-'
}
_testSetStreetNumber (it) {
if (!it) throw new MissingRequiredArgumentError({ info: 'streetNumber' })
return it
}
_testSetStreetName (it) {
if (!it) throw new MissingRequiredArgumentError({ info: 'streetName' })
return it
}
_testSetCity (it) {
if (!it) throw new MissingRequiredArgumentError({ info: 'city' })
return it
}
_testSetGoverningDistrict (it) {
const rx = /^[A-Z]{2}$/
if (!it) throw new MissingRequiredArgumentError({ info: 'state' })
if (!rx.test('' + it)) {
throw new IllegalArgumentError({ info: 'state', message: `must be ${rx}` })
}
return it
}
_testSetPostalCode (it) {
const rx = /^[0-9]{5}$/
if (!it) throw new MissingRequiredArgumentError({ info: 'zip' })
if (!rx.test(it)) {
throw new IllegalArgumentError({ info: 'zip', message: `must be ${rx}` })
}
return it
}
_testSetPostalCodeSuffix (it) {
const rx = /^[0-9]{4}$/
if (it && !rx.test(it)) {
throw new IllegalArgumentError({ info: 'zipPlus4', message: `must be ${rx}` })
}
return it
}
_testDirection (it, property) {
const rx = /^(N|S|E|W|NW|NE|SW|SE)$/
if (!it) return it
if (!rx.test(it)) { throw new IllegalArgumentError({ info: property, message: `must be ${rx}` }) }
}
_testSetStreetNameDirectionPrefix (it) {
this._testDirection(it, 'streetNameDirectionPrefix')
return it
}
_testSetStreetNameDirectionSuffix (it) {
this._testDirection(it, 'streetNameDirectionSuffix')
return it
}
_testSetStreetTypeDirectionSuffix (it) {
this._testDirection(it, 'streetTypeDirectionSuffix')
return it
}
toString ({
lineSeparator = '\n',
compartmentSeparator = ', ',
cityStateSeparator = ', ',
stateZipSeparator = ' '
} = {}) {
let it = `${this.streetNumber}`
if (this.streetNumberSuffix) it += this.streetNumberSuffix
if (this.streetNameDirectionPrefix) it += ` ${this.streetNameDirectionPrefix}`
it += ` ${this.streetName}`
if (this.streetNameDirectionSuffix) it += ` ${this.streetNameDirectionSuffix}`
if (this.streetType) it += ` ${this.streetType}`
if (this.streetTypeDirectionSuffix) { it += ` ${this.streetTypeDirectionSuffix}` }
if (this.compartmentType) { it += `${compartmentSeparator}${this.compartmentType} ${this.compartmentId}` }
it += lineSeparator
it += `${this.city}${cityStateSeparator}${this.governingDistrict}${stateZipSeparator}${this.postalCode}`
if (this.postalCodeSuffix) { it += `${this.postalCodeSuffixSeparator}${this.postalCodeSuffix}` }
return it
}
}
module.exports = {
Longitude,
Latitude,
Gps,
StreetAddress,
UsStreetAddress,
Parallel
}
|
// @flow
import * as React from "react";
import { NavigationGroup } from "./NavigationGroup.js";
import { NavigationElement } from "./NavigationElement";
import type { NavigationElementPropsType } from "./NavigationElement.js";
import type { NavigationGroupPropsType } from "./NavigationGroup.js";
export function NavigationGroupOrElement( props: NavigationGroupPropsType | NavigationElementPropsType )
{
// is elements group
if( props.hasOwnProperty( "items" ) )
return <NavigationGroup { ...props } />;
return <NavigationElement key={ props.title } onClick={ props.onClick } { ...props } />;
}
|
import React from 'react'
import { Link } from 'react-router-dom'
export default class Header extends React.Component {
constructor(props){
super(props)
this.state = {
token: null
}
this.handleSignOut = this.handleSignOut.bind(this)
}
async componentWillMount(){
const token = await window.localStorage.getItem('token')
this.setState({ token })
}
async handleSignOut(e){
e.preventDefault()
await window.localStorage.clear()
}
render(){
return (
<div classNameName="App">
<nav className="navbar navbar-expand-lg navbar-custom">
<Link to='/' className="navbar-brand">
<img src={require('../img/logo.png')} className="navbar-logo-img mr-2" />
</Link>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
</ul>
<ul className="navbar-nav ml-auto">
{
this.state.token ? (
<div>
<li className="nav-item">
<Link to='/dashboard' className="nav-link btn-primary text-white">
<i className="fa fa-sign-in" aria-hidden="true"></i> Dashboard
</Link>
</li>
<li className="nav-item">
<button to='/' className="nav-link btn-primary text-white">
<i className="fa fa-sign-in" aria-hidden="true"></i> Sign Out
</button>
</li>
</div>
) : (
<li className="nav-item">
<Link to='/signin' className="nav-link btn-primary text-white">
<i className="fa fa-sign-in" aria-hidden="true"></i> Sign In
</Link>
</li>
)
}
</ul>
</div>
</nav>
</div>
)
}
}
|
const _ = require('underscore');
const paging = require('../');
const dbUtils = require('./support/db');
const driver = process.env.DRIVER;
describe('findWithReq', () => {
let mongod;
const t = {};
beforeAll(async () => {
mongod = dbUtils.start();
t.db = await dbUtils.db(mongod, driver);
await Promise.all([
t.db.collection('test_paging').insert([
{
counter: 1,
myfield1: 'a',
myfield2: 'b',
},
{
counter: 2,
myfield1: 'a',
myfield2: 'b',
},
{
counter: 3,
myfield1: 'a',
myfield2: 'b',
},
{
counter: 4,
myfield1: 'a',
myfield2: 'b',
},
]),
t.db.collection('test_paging_fields').insert({
obj: {
one: 1,
two: {
three: 3,
},
four: {
five: {
six: 6,
},
seven: 7,
},
},
obj2: 1,
}),
]);
});
afterAll(() => mongod.stop());
describe('basic usage', () => {
it('queries first few pages', async () => {
const collection = t.db.collection('test_paging');
const fields = {
counter: 1,
myfield1: 1,
myfield2: 1,
};
// First page of 2
let res = await paging.findWithReq(
{
query: {
limit: '2',
fields: 'counter,myfield1',
},
},
collection,
{
fields,
}
);
expect(res.results.length).toEqual(2);
expect(res.results[0]).toEqual({
counter: 4,
myfield1: 'a',
});
expect(res.results[1]).toEqual({
counter: 3,
myfield1: 'a',
});
expect(res.hasPrevious).toEqual(false);
expect(res.hasNext).toEqual(true);
// Go forward 1
res = await paging.findWithReq(
{
query: {
limit: '1',
next: res.next,
fields: 'counter,myfield1',
},
},
collection,
{
fields,
}
);
expect(res.results.length).toEqual(1);
expect(res.results[0]).toEqual({
counter: 2,
myfield1: 'a',
});
expect(res.hasPrevious).toEqual(true);
expect(res.hasNext).toEqual(true);
// Now back up 1
res = await paging.findWithReq(
{
query: {
previous: res.previous,
limit: '1',
fields: 'counter,myfield1',
},
},
collection,
{
fields,
}
);
expect(res.results.length).toEqual(1);
expect(res.results[0]).toEqual({
counter: 3,
myfield1: 'a',
});
expect(res.hasPrevious).toEqual(true);
expect(res.hasNext).toEqual(true);
});
it('does not query more fields than allowed', async () => {
const collection = t.db.collection('test_paging');
const res = await paging.findWithReq(
{
query: {
limit: '1',
// myfield1 will be ignored because it doesn't exist in fields below
fields: 'counter,myfield1',
},
},
collection,
{
fields: {
counter: 1,
},
}
);
expect(res.results.length).toEqual(1);
expect(res.results[0]).toEqual({
counter: 4,
});
});
it('allows a request to specify fields if not otherwise specified', async () => {
const collection = t.db.collection('test_paging');
const res = await paging.findWithReq(
{
query: {
limit: '1',
fields: 'counter,myfield1',
},
},
collection,
{}
);
expect(res.results.length).toEqual(1);
expect(res.results[0]).toEqual({
counter: 4,
myfield1: 'a',
});
});
it('does not allow a limit to be specified that is higher than params.limit', async () => {
const collection = t.db.collection('test_paging');
const res = await paging.findWithReq(
{
query: {
limit: '2',
},
},
collection,
{
limit: 1,
}
);
expect(res.results.length).toEqual(1);
});
it('handles empty values', async () => {
const collection = t.db.collection('test_paging');
const res = await paging.findWithReq(
{
query: {
limit: '',
next: '',
previous: '',
fields: '',
},
},
collection,
{}
);
expect(res.results.length).toEqual(4);
expect(res.results[0]._id).toBeTruthy();
expect(_.omit(res.results[0], '_id')).toEqual({
counter: 4,
myfield1: 'a',
myfield2: 'b',
});
});
it('handles bad value for limit', async () => {
const collection = t.db.collection('test_paging');
const res = await paging.findWithReq(
{
query: {
limit: 'aaa',
},
},
collection,
{
fields: {
counter: 1,
},
}
);
expect(res.results.length).toEqual(4);
expect(res.results[0]).toEqual({
counter: 4,
});
});
});
describe('fields', () => {
it('picks fields', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj.one,obj.four.five',
},
},
collection,
{
fields: {
obj: 1,
obj2: 1,
},
}
);
expect(res.results[0]).toEqual({
obj: {
one: 1,
four: {
five: {
six: 6,
},
},
},
});
});
it('works without fields', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj.one,obj.four.five',
},
},
collection,
{}
);
expect(res.results[0]).toEqual({
obj: {
one: 1,
four: {
five: {
six: 6,
},
},
},
});
});
it('picks fields when nested', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj.four.five',
},
},
collection,
{
fields: {
'obj.four': 1,
obj2: 1,
},
}
);
expect(res.results[0]).toEqual({
obj: {
four: {
five: {
six: 6,
},
},
},
});
});
it('disallows properties that are not defined', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj.four.five,obj2',
},
},
collection,
{
fields: {
obj: 1,
},
}
);
expect(res.results[0]).toEqual({
obj: {
four: {
five: {
six: 6,
},
},
},
});
});
it('picks exact fields', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj',
},
},
collection,
{
fields: {
obj: 1,
},
}
);
expect(res.results[0]).toEqual({
obj: {
one: 1,
two: {
three: 3,
},
four: {
five: {
six: 6,
},
seven: 7,
},
},
});
});
it('picks exact subfields', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj.one,obj.four.five',
},
},
collection,
{
fields: {
'obj.one': 1,
'obj.four.five': 1,
},
}
);
expect(res.results[0]).toEqual({
obj: {
one: 1,
four: {
five: {
six: 6,
},
},
},
});
});
it('does not allow a broader scoping of fields', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj',
},
},
collection,
{
fields: {
'obj.one': 1,
},
}
);
expect(res.results[0]).toEqual({
obj: {
one: 1,
},
});
});
it('does not allow a broader scoping of subfields', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj.two,obj.four,obj2',
},
},
collection,
{
fields: {
'obj.two.three': 1,
'obj.four.five': 1,
obj2: 1,
},
}
);
expect(res.results[0]).toEqual({
obj: {
two: {
three: 3,
},
four: {
five: {
six: 6,
},
},
},
obj2: 1,
});
});
it('picks exact subfields', async () => {
const collection = t.db.collection('test_paging_fields');
const res = await paging.findWithReq(
{
query: {
fields: 'obj.one',
},
},
collection,
{
fields: {
'obj.one': 1,
},
}
);
expect(res.results[0]).toEqual({
obj: {
one: 1,
},
});
});
});
});
|
// Dummy Ajax methode om de gegevens in de backend te controleren.
function doAjaxRequest() {
var length = $("#ordernummer").val();
var email = $("#email").val();
if (length.length === 12 && email != "") {
var response;
// 50% kans in dit geval
if (Math.random() >= 0.5) {
response = {
status: 200,
message: 'Er is een nieuwe ticketmail naar je verzonden.'
};
} else {
response = {
status: 500,
message: 'Er is geen bestelling gevonden met deze combinatie van gegevens. Neem contact met ons op.'
}
}
alert(response.message);
return response;
} else {
alert("Ordernummer of e-mail is onjuist!");
}
}
|
function isLeapYear(yr) {
}
module.exports = isLeapYear;
|
import express from "express";
import routes from "../routes"
import { getWrite, board, postWrite, getBoardView, boardPageNumber, postCommentDelete, deleteBoard, getEditBoard, postEditBoard, postBoard } from "../controllers/boardController";
import { uploadWriteSingle, onlyPrivate } from "../middlewares";
const boardRouter = express.Router();
boardRouter.get("/", board);
boardRouter.post("/", postBoard);
boardRouter.get(routes.boardPaging(), boardPageNumber)
// boardRouter.get(routes.board(), pagingBoard);
boardRouter.get(routes.write, onlyPrivate, getWrite);
boardRouter.post(routes.write, onlyPrivate, uploadWriteSingle, postWrite);
boardRouter.get("/:id/edit", getEditBoard);
boardRouter.post("/:id/edit",uploadWriteSingle ,postEditBoard);
boardRouter.post("/:id/delete", deleteBoard);
boardRouter.get(routes.boardView(), getBoardView);
boardRouter.get("/comment/delete/:id", postCommentDelete);
export default boardRouter;
|
import instance from '../../helpers/axios';
export default {
state: {
riders: [],
},
mutations: {
setRiders(state, payload) {
state.riders = payload;
},
addRiders(state, payload) {
state.riders = [...state.riders, ...payload];
},
},
actions: {
// eslint-disable-next-line no-unused-vars
async RIDERS_BY_HUB({ commit }, hub = '') {
try {
const { data } = await instance.get(`rider/${hub}`);
return data.data;
} catch (err) {
return Promise.reject(err);
}
},
async RIDERS({ commit }, payload = {}) {
try {
const { lastId } = payload;
const { data } = await instance.get(`rider?lastId=${lastId}`);
if (!lastId) {
commit('setRiders', data.data);
} else commit('addRiders', data.data);
return data.data;
} catch (err) {
return Promise.reject(err);
}
},
},
getters: {
Riders: (state) => state.riders,
},
};
|
import React from 'react';
import {
Alert,
StyleSheet,
View,
Animated,
Easing,
} from 'react-native';
import { Button, Headline, Caption } from 'react-native-paper';
import { connect } from 'react-redux';
import * as AuthSession from 'expo-auth-session';
import axios from 'axios';
import AppIntro from 'rn-falcon-app-intro';
import LottieView from 'lottie-react-native';
import oauth from '../../secrets/oauth';
import api from '../../secrets/api_token';
import { ItScreenContainer } from '../components/common';
import { colors } from '../styles';
import {
SIGNED_IN,
} from '../actions/types';
const { primaryColor, transparentPrimaryColor } = colors;
const INATURALIST_OAUTH_API = 'https://www.inaturalist.org/oauth';
class IiAuthScreen extends React.Component {
INITIAL_STATE = {
isAuthenticating: false,
swiperAnimationProgress: new Animated.Value(0),
progress: 0,
};
constructor(props) {
super(props);
this.state = this.INITIAL_STATE;
}
componentDidMount() {
this.startSwiperAnimation();
this.state.swiperAnimationProgress.addListener((progress) => {
this.setState({ progress: progress.value });
});
}
startSwiperAnimation = () => {
Animated.loop(
Animated.sequence([
Animated.timing(this.state.swiperAnimationProgress, {
toValue: 1,
duration: 10000,
easing: Easing.linear,
useNativeDriver: false,
})
])
).start();
}
loginAsync = async () => {
const { signIn } = this.props;
this.setState({ isAuthenticating: true });
// AuthFlow is handled by Expo.AuthSession
const redirectUrl = AuthSession.getRedirectUrl();
const result = await AuthSession.startAsync({
authUrl:
`${INATURALIST_OAUTH_API}/authorize?response_type=code`
+ `&client_id=${oauth.INATURALIST_APP_ID}`
+ `&redirect_uri=${encodeURIComponent(redirectUrl)}`,
});
console.log('result', result);
// The code was successfully retrieved
if (result.type && result.type === 'success') {
const tokenUrl = `${INATURALIST_OAUTH_API}/token`;
const params = {
client_id: oauth.INATURALIST_APP_ID,
client_secret: oauth.INATURALIST_APP_SECRET,
code: result.params.code,
redirect_uri: AuthSession.getRedirectUrl(),
grant_type: 'authorization_code',
};
// POST request to the iNaturalist OAuth API
const response = await axios
.post(tokenUrl, params)
.catch((error) => {
console.log(
'Error in fetching access token from iNaturalist',
error,
);
return { error };
});
console.log('response', response);
// Response OK
if (response.status === 200) {
// Get the API token required to make API calls for the user
const apiTokenUrl = 'https://www.inaturalist.org/users/api_token.json';
const config = {
headers: {
Authorization: `Bearer ${response.data.access_token}`,
},
};
const apiTokenResponse = await axios.get(apiTokenUrl, config)
.then(r => r)
.catch((e) => {
console.log('Error in fetching API token from iNaturalist', e);
return { error: e };
});
console.log('apiTokenResponse', apiTokenResponse);
if (apiTokenResponse.data && apiTokenResponse.data.api_token) {
// Navigate to next screen with api_token
signIn(apiTokenResponse.data.api_token);
} else {
// Show alert for failure of getting api token
Alert.alert(
'The login was giving an error',
'Unfortunately, you can not proceed',
);
}
} else {
// Show alert for failure of getting oauth token
Alert.alert(
'The login was giving an error',
'Unfortunately, you can not proceed',
);
}
} else {
// The auth session was unsuccessful
if (result.type === 'cancel') {
Alert.alert(
'The login was canceled',
'You need to login to iNaturalist to proceed',
);
}
if (result.type === 'dismissed') {
Alert.alert(
'The login was dismissed',
'Unfortunately, you can not proceed',
);
}
if (result.type === 'error') {
Alert.alert(
'The login was giving an error',
'Unfortunately, you can not proceed',
);
}
}
this.setState({ isAuthenticating: false });
};
render() {
const { signIn } = this.props;
const { isAuthenticating, swiperAnimationProgress, progress } = this.state;
const { paragraph, slide, headline, caption } = styles;
return (
<ItScreenContainer barStyle="dark-content" testID="auth_screen">
<AppIntro
dotColor={transparentPrimaryColor}
activeDotColor={primaryColor}
doneBtnLabel="Login"
rightTextColor={primaryColor}
onDoneBtnClick={() => this.loginAsync()}
skipBtnLabel="Login"
leftTextColor={primaryColor}
onSkipBtnClick={() => this.loginAsync()}
>
<View style={slide}>
{__DEV__ ? (
<Button
testID="dev_skip_login"
onPress={() => signIn(api.api_token)}
>
!!DEV Skip
</Button>
) : <View></View>}
<LottieView
ref={animation => {
this.animation = animation;
}}
style={{
width: null,
backgroundColor: '#ffffff',
}}
source={require('../../assets/animations/swiper.json')}
progress={swiperAnimationProgress}
/>
<View level={10} style={[paragraph, {position: 'absolute', left: 0, right: 0, top: 40}]}>
<Headline level={10} style={headline} >Identify observations by swiping</Headline>
</View>
{progress < 0.25 ? <View level={10} style={[paragraph, {position: 'absolute', left: 0, right: 0, bottom: 70}]}>
<Headline level={10} style={headline}>Plant</Headline>
<Caption level={5} style={caption}>Swipe right</Caption>
</View> : <View></View> }
{progress > 0.25 && progress < 0.5 ? <View level={10} style={[paragraph, {position: 'absolute', left: 0, right: 0, bottom: 70}]}>
<Headline level={10} style={headline}>Animal</Headline>
<Caption level={5} style={caption}>Swipe left</Caption>
</View> : <View></View> }
{progress > 0.5 && progress < 0.75 ? <View level={10} style={[paragraph, {position: 'absolute', left: 0, right: 0, bottom: 70}]}>
<Headline level={10} style={headline}>Fungi</Headline>
<Caption level={5} style={caption}>Swipe up</Caption>
</View> : <View></View> }
{progress > 0.75 ? <View level={10} style={[paragraph, {position: 'absolute', left: 0, right: 0, bottom: 70}]}>
<Headline level={10} style={headline}>Don't know?</Headline>
<Caption level={5} style={caption}>Swipe down to skip</Caption>
</View> : <View></View> }
</View>
<View style={slide}>
<View level={10} style={[paragraph, {position: 'absolute', left: 0, right: 0, top: 40}]}>
<Headline style={headline} >Log in to your iNaturalist account to start</Headline>
</View>
<Button
testID="login_button"
onPress={() => this.loginAsync()}
loading={isAuthenticating}
>
Login with iNaturalist
</Button>
{__DEV__ ? (
<Button
testID="dev_skip_login"
onPress={() => signIn(api.api_token)}
>
!!DEV Skip
</Button>
) : <View></View>}
</View>
</AppIntro>
</ItScreenContainer>
);
}
}
const styles = StyleSheet.create({
paragraph: {
alignItems: 'center',
justifyContent: 'center',
},
slide: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF',
padding: 15,
},
headline: {
alignItems: 'center',
justifyContent: 'center',
color: primaryColor,
fontSize: 32,
textAlign: 'center'
},
caption: {
alignItems: 'center',
justifyContent: 'center',
fontSize: 18,
},
});
const mapStateToProps = state => ({
auth: state.auth,
});
const mapDispatchToProps = dispatch => ({
signIn: (payload) => {
dispatch({ type: SIGNED_IN, payload });
},
});
export default connect(mapStateToProps, mapDispatchToProps)(IiAuthScreen);
|
function counter() {
var date = new Date();
var matchdate = Date(d,h,m,s);
var presenttime = date.getTime();
var matchtime = matchdate.getTime();
var rtime = matchtime - presenttime ;
var s1 = Math.floor(rtime/1000);
var m1 = Math.floor(s1/60);
var h1 = Math.floor(h1/60);
var d1 = Math.floor(h1/24);
h1 %= 24;
m1 %= 60;
s1 %= 60;
h1 = (h1<10)? "0"+h1 : h1;
m1 = (m1<10)? "0"+m1 : m1;
s1 = (s1<10)? "0"+s1 : s1;
document.getElementById("days").innerHTML = d1 + "d:";
document.getElementById("hours").innerHTML = h1 + "h:";
document.getElementById("minutes").innerHTML = m1 + "m:";
document.getElementById("seconds").innerHTML = s1 + "s:";
setTimeout(counter,1000);
}
|
import React from 'react';
import Product from './Product';
const CartItem = ({
price, quantity, title, onRemove,
}) => (
<Product
price={price}
quantity={quantity}
title={title}
action={
<button onClick={onRemove}>{' X '}</button>
}
/>
);
export default CartItem;
|
import { Node } from '../helpers/Node'
const BoardItem = props => {
const { completed, hover, text, key } = props
return (
Node('li', { class: `item ${completed && 'completed'}`, id: key },
hover && (
Node('span', { class: 'checkbox' },
Node('input', { type: 'checkbox' })
)
),
text,
hover && Node('span', { class: 'trash' }, '🗑')
)
)
}
export default BoardItem
|
import React from "react";
import { Component } from "react";
import "../index.css";
class Footer extends Component {
render(){
return(
<div id="footer_main_container">
<ul className="footer_box">
<li><a href="#" className="link_style">Home
</a></li>
<li><a href="#" className="link_style">About
</a></li>
<li><a href="#" className="link_style">Help
</a></li>
<li><a href="#" className="link_style">FAQs
</a></li>
</ul>
<ul className="footer_box">
<li><a href="#" className="link_style">Discover Plants
</a></li>
<li><a href="#" className="link_style">Discover Botany
</a></li>
<li><a href="#" className="link_style">Privacy Policy
</a></li>
<li><a href="#" className="link_style">Terms
</a></li>
</ul>
<ul className="footer_box">
<li><a href="#" className="link_style">Sign In
</a></li>
<li><a href="#" className="link_style">Resources
</a></li>
<li><a href="#" className="link_style">Contact Us
</a></li>
<li><a href="#" className="link_style">Donate
</a></li>
</ul>
<div id="logo">
<img id="ewma_logo" src=""/>
<p className="center_it" id="copyright_statement">Web design and content
2017 EWMAFP
jefalteague@gmail.com>
</p>
</div>
</div>
);
}
}
export default Footer;
|
import blogCollection from '../models/blogMod.js';
// add a blog to the db
export const createBlog = async (req,res,next)=>{
try {
const { bTitle, bContent} = req.body;
const { firstName, lastName } = req.user;
const blog = await blogCollection.findOne({bTitle});
if (blog) return res.status(400).json({msg: 'Blog published before'})
const newBlog = await blogCollection({
bTitle,
bPublisher: { firstName, lastName },
bContent
})
const savedBlog = await newBlog.save();
return res.status(201).json({msg: 'blog created', savedBlog})
} catch (error) {
res.status(400).json(`Error: ${error}`);
// return res.status(500).json({msg: err.message})
}
};
// get a single blog from db
export const singleBlog = async (req, res) => {
try {
let {id} = req.params;
await blogCollection.findById(id).then((blogs) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'Application/json');
res.json(blogs);
})
} catch (error) {
// throw new Error(error);
res.status(400).json(`Error: ${error}`);
}
};
// get list of all blogs from db
export const allBlogs = (req, res, next) => {
blogCollection.find({})
.then((blogs) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(blogs);
}, (err) => next(err))
.catch((err) => next(err));
};
// update a blog in the db
export const updateBlog = async (req, res, next) => {
try {
const blog = await blogCollection.findByIdAndUpdate({_id: req.params.id }, req.body);
const updatedBlog = await blogCollection.findOne({_id: req.params.id });
res.status(200).send(updatedBlog);
}
catch (error) {
res.status(400).json(`Error: ${error}`);
}
};
// delete a blog from the db
export const deleteBlog = async (req, res, next) => {
let { id } = req.params;
try {
const existBlog = await blogCollection.find({_id: id});
if (existBlog.length) {
try {
const delete_blog = await blogCollection.deleteOne({_id: id});
res.status(200).json({message: `blog deleted ${existBlog}`, delete_blog})
} catch (error) {
throw new Error(error);
};
}
else {
res.status(404).json({ status: 403, error: 'blog Id does not exist'});
};
}
catch (error) {
// console.log(error);
res.status(500).json({ status: 403, error: 'invalid blog Id '});
};
};
|
var searchData=
[
['executing_0',['executing',['../classAIStatefulTask.html#a855cb8523b22595dc5ef69361633e7bb',1,'AIStatefulTask']]]
];
|
const fs = require('fs');
const path = require('path');
const autoprefixer = require('autoprefixer');
const cssnano = require('cssnano');
const less = require('less');
const NpmImportPlugin = require('less-plugin-npm-import');
const postcss = require('postcss');
const sass = require('node-sass');
const Core = require('css-modules-loader-core');
const camelCaser = require('./camelCaser').default;
const core = new Core([
Core.localByDefault,
Core.extractImports,
camelCaser,
Core.scope
]);
/**
* replace the tilde-based url with the path to the node module
*
* @param {string} url
* @returns {string}
*/
const resolveUrlPath = (url) => {
if (url[0] !== '~') {
return url;
}
return path.resolve(path.dirname(require.main.filename), 'node_modules', url.slice(1));
};
/**
* save the transformed file to target
*
* @param {string} hash
* @param {string} target
* @returns {function({exportTokens: object, injectableSource: string}): Object}
*/
const saveFile = (hash, target) => {
return ({exportTokens, injectableSource}) => {
// provide the compiled CSS, the id to use in the style tag, and the selector map
const fileValue = {
css: injectableSource,
id: `${hash}_Scoped_Styles`,
selectors: exportTokens
};
// clean the string to mean the rapid7 ESLint config rules
const bufferString = JSON.stringify(fileValue)
.replace(/'/g, '\\\'')
.replace(/"/g, '\'')
.replace(/,/g, ', ');
// make a Buffer of an exportable file
const buffer = new Buffer(`module.exports = ${bufferString};\n`);
// write the file to the target
fs.writeFileSync(target, buffer);
return fileValue;
};
};
/**
* load the prefixed CSS and convert via CSS Modules, then create a file with all metadata provided
*
* @param {string} hash
* @param {string} target
* @returns {function({css: string}): Promise}
*/
const applyCssModules = (hash, target) => {
return ({css}) => {
return core.load(css, hash)
.catch((error) => {
/* eslint-disable no-console */
console.error('There was an error converting your file via CSS Modules.');
/* eslint-enable */
throw new Error(error);
})
.then(saveFile(hash, target));
};
};
/**
* get the CSS buffer from rendering the file
*
* @param {string} source
* @param {Object} renderOptions
* @returns {function(resolve: function): void}
*/
const getRenderedCss = (source, renderOptions) => {
return (resolve) => {
switch (path.extname(source).slice(1)) {
case 'scss':
const scssOptions = Object.assign({}, renderOptions, {
file: source,
importer(url) {
return {
file: resolveUrlPath(url)
};
}
});
// if the file is SCSS, use node-sass to compile into a Buffer
const renderedFile = sass.renderSync(scssOptions);
resolve(renderedFile.css);
break;
case 'less':
// if the file is LESS, convert to string and render
const fileString = fs.readFileSync(source, 'utf8');
const lessOptions = Object.assign({}, renderOptions, {
filename: source,
plugins: [
...(renderOptions.plugins || []),
new NpmImportPlugin({
prefix: '~'
})
]
});
less
.render(fileString, lessOptions)
.then(({css}) => {
resolve(css);
});
break;
default:
// otherwise, assume the file is plain CSS and read the file as a Buffer
resolve(fs.readFileSync(source, 'utf8'));
break;
}
};
};
/**
* get the prefixed css and apply the CSS modules
*
* @param {string} hash
* @param {string} target
* @param {boolean} minify
* @returns {function(cssBuffer: Buffer): Promise}
*/
const getPrefixedCss = (hash, target, minify) => {
return (cssBuffer) => {
// convert the Buffer to a string and prefix via postcss
const string = cssBuffer.toString('utf8');
let prefixerPlugins = [
autoprefixer({
remove: false
})
];
if (minify) {
prefixerPlugins = [
...prefixerPlugins,
cssnano({
safe: true
})
];
}
return postcss(prefixerPlugins).process(string)
.catch((error) => {
/* eslint-disable no-console */
console.error('There was an error prefixing your css.');
/* eslint-enable */
throw new Error(error);
})
.then(applyCssModules(hash, target));
};
};
/**
* generate the JS file with the appropriate prefixed
* styles rendered and modularized
*
* @param {string} hash
* @param {boolean} minify
* @param {Object} renderOptions
* @param {string} source
* @param {string} target
* @returns {Promise}
*/
const generateTransformedStylesFile = (hash, minify, renderOptions, source, target) => {
return new Promise(getRenderedCss(source, renderOptions))
.catch((error) => {
/* eslint-disable no-console */
console.error('There was a problem generating the CSS from your source file.');
/* eslint-enable */
throw new Error(error);
})
.then(getPrefixedCss(hash, target, minify));
};
module.exports = {
applyCssModules,
generateTransformedStylesFile,
getPrefixedCss,
getRenderedCss,
resolveUrlPath,
saveFile
};
|
import React,{Component} from 'react'
import './index.css'
import UploadBtn from '../../shareComponent/UploadBtn'
import {textCountRange} from '../../../funStore/CommonFun'
import {Nickname,Groupname,MemberCount,Welcome,PicText,Admin,GroupInform,Keyword,GroupLabel,CommonRadio} from '../../giSystemPortal/EditModule/unit'
import ButtonBox from '../../shareComponent/ButtonBox'
export default class Step3 extends Component {
render(){
const {params,setGroupEditInfo,setWelcomeMsgResp,addTag,delTag,submiting,updateInfo} = this.props
return (
<div className="gi-manual-step3">
<div className="inner">
<div className="public-edit content clearfix">
<div className="left">
<Nickname
value = {params.groupEditInfo.serviceRobotName}
length = {textCountRange(params.groupEditInfo.serviceRobotName)}
paramName = {'serviceRobotName'}
setparamsHandle = {setGroupEditInfo}
/>
<MemberCount
value = {params.groupEditInfo.memThreshold}
paramName = {'memThreshold'}
setparamsHandle = {setGroupEditInfo}
/>
<CommonRadio
options={{
label:'群邀请确认:'
}}
sourceData={[{name:'启用',value:1},{name:'禁止',value:0}]}
paramName={'protectFlag'}
value={params.groupEditInfo.protectFlag}
setparamsHandle={setGroupEditInfo}
/>
<Welcome
value={params.groupEditInfo.welcomeMsgFlag}
defaultValue = {params.groupEditInfo.welcomeMsgFlag}
setparamsHandle={setGroupEditInfo}
welcomeMsgInterval={params.groupEditInfo.welcomeMsgInterval}
setWelcomeMsgResp={setGroupEditInfo}
/>
{
params.groupEditInfo.welcomeMsgFlag==1
?<PicText
welcomeMsgResp={{welcomeMsgReq:params.groupEditInfo.welcomeMsgReq}}
length={textCountRange(params.groupEditInfo.welcomeMsgReq.items[0].content)}
setparamsHandle={setWelcomeMsgResp}
/>
:''
}
</div>
<div className="right">
<Admin
monitors={params.groupEditInfo.monitorSimpInfos}
paramName = {'monitorSimpInfos'}
setparamsHandle={setGroupEditInfo}
/>
<GroupInform
value={params.groupEditInfo.introduce}
paramName={'introduce'}
length={textCountRange(params.groupEditInfo.introduce)}
setparamsHandle={setGroupEditInfo}
/>
<Keyword
keywordSimpleItems={params.groupEditInfo.keywordNames}
paramName={'keywordNames'}
addTag={addTag}
delTag={delTag}
/>
<GroupLabel
groupLabelProfiles={params.groupEditInfo.groupLabelNames}
paramName={'groupLabelNames'}
addTag={addTag}
delTag={delTag}
/>
<div className="buttonArea">
<UploadBtn
loading={submiting}
text={"保存"}
loadingText={"保存中"}
clickHandle={updateInfo}
propsStyle={{
width:'108px',
height:'36px',
float:'right',
fontWeight:400,
marginRight:'50px'
}}
/>
<ButtonBox
btnTxt={'上一步'}
isCancel={true}
btnStyle={{
float:'right'
}}
btnFunc={this.props.prevStep}
/>
</div>
</div>
</div>
</div>
</div>
)
}
}
|
import React from "react";
import { makeStyles } from "@material-ui/core/styles";
import InvoiceTable from "pages/InvoiceTable";
import Typography from "@material-ui/core/Typography";
import { Button} from "@material-ui/core";
import { useHistory } from "react-router-dom";
const useStyles = makeStyles((theme) => ({
mainGrid: {
marginTop: theme.spacing(3),
},
button: {
marginTop: theme.spacing(3),
marginLeft: theme.spacing(1),
},
}));
const sections = [
{ title: "Home", url: "#" },
{ title: "Invoices", url: "#" },
{ title: "New Invoice", url: "#" },
];
export default function Searchinvoice() {
const classes = useStyles();
const history = useHistory();
const createNewInvoice = () => {
history.push("/newInvoice");
};
return (
<React.Fragment>
<Typography variant="h1">Search your invoice</Typography>
<InvoiceTable />
<Button
variant="contained"
color="primary"
className={classes.button}
onClick={createNewInvoice}
>
Add Invoice
</Button>
</React.Fragment>
);
}
|
'use strict';
const express = require('express');
const router = express.Router();
const bodyParser = require("body-parser");
const config = require('config');
const cors = require('cors');
const app = express();
var log4js = require("log4js");
const { nanoid } = require("nanoid");
const log4jsConfig = {
"appenders" : {
"server" : {
"type": "console", "layout": {
"type": "pattern", "pattern": "%[%d{ISO8601_WITH_TZ_OFFSET} %p %c -%] %m", "tokens": {}
}
},
},
"categories": {"default": { "appenders": ["server"], "level": "info" }}
};
log4js.configure(log4jsConfig, {});
var logger = log4js.getLogger("server");
var connectionManager;
(
async () => {
connectionManager = await require("./lib/connectionManager").getInstance();
})().then( () => {
logger.info("starting server");
const port = config.server.port;
app.listen(port, () => {
logger.info("Started on PORT " + port);
});
app.use(sigPath, router);
}).catch((error) => {logger.error("Server init Error --- exit"); process.exit(1);});
var jsonParser = bodyParser.json();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json({ type: 'application/*+json' }));
app.use(cors());
app.use((req, res, next) => {
req.FCID = nanoid();
logger.info(`${req.FCID} ${req.method} ${req.originalUrl} [REQ]`);
res.on('finish', () => {
logger.info(`${req.FCID} ${req.method} ${req.originalUrl} ${res.statusCode} ${res.statusMessage} [RES]`);
});
next()
})
const apiVersion = '1.0';
const sigPath = '/signaling/' + apiVersion;
//
// Handle offer
//
router.post('/:connectionType/connections', jsonParser, async function(req, res) {
const connectionType = req.params.connectionType;
const appConnectionId = req.query.connectionId;
try {
const connectionId = await connectionManager.addConnection(req.body, connectionType, appConnectionId);
logger.info("Connection %s created", connectionId);
res.status(201).json({connectionId:connectionId});
} catch (error){
res.status(error.errorCode? error.errorCode : 503).json(error);
if(error.errorCode >= 500) {
logger.error(req.FCID + " : " + JSON.stringify(error));
}
}
});
//
// Handle client polling for offer response
//
router.get('/connections/:connectionId/answer', async function(req, res) {
const connectionId = req.params.connectionId;
try{
const offerResp = await connectionManager.getOfferResponse(connectionId);
logger.info("Connection %s answer has given, signaling part completed!", connectionId);
res.status(200).json(offerResp);
} catch (error) {
res.status(error.errorCode? error.errorCode : 503).json(error);
if(error.errorCode >= 500) {
logger.error(req.FCID + " : " + JSON.stringify(error));
}
}
});
router.post('/connections/:connectionId/answer', jsonParser, async function(req, res) {
const connectionId = req.params.connectionId;
const offerResp = req.body;
try{
await connectionManager.saveOfferResponse(connectionId, offerResp);
logger.info("Connection %s got answer from peer ", connectionId);
res.status(201).json(offerResp);
} catch (error) {
res.status(error.errorCode? error.errorCode : 503).json(error);
if(error.errorCode >= 500) {
logger.error(req.FCID + " : " + JSON.stringify(error));
}
}
});
router.get('/connections/:connectionId/offer', async function(req, res) {
const connectionId = req.params.connectionId;
try{
const offer = await connectionManager.getOffer(connectionId);
logger.info("Connection %s TC started webrtc connections establishment", connectionId);
res.status(200).json(offer);
} catch (error) {
res.status(error.errorCode? error.errorCode : 503).json(error);
if(error.errorCode >= 500) {
logger.error(req.FCID + " : " + JSON.stringify(error));
}
}
});
//
// Handle trans container trquest to get unserved offer
//
router.get('/:connectionType/queue', async function(req, res) {
const connectionType = req.params.connectionType;
try{
const connectionId = await connectionManager.getWaitingOffer(connectionType);
logger.info("Connection %s allocated to TC", connectionId);
res.status(200).json({connectionId:connectionId});
} catch (error) {
res.status(error.errorCode? error.errorCode : 503).json(error);
if(error.errorCode >= 500) {
logger.error(req.FCID + " : " + JSON.stringify(error));
}
}
});
/*
router.post('/connections/:connectionId/ice', jsonParser, function(req, res) {
logger.info( "post ice request Received .. " );
const connectionId = req.params.connectionId;
const ice = req.body;
if(!connectionManager.addCandidate(connectionId, ice)) {
res.status(404).json({err:"offer not exist"});
} else {
res.sendStatus(201);
}
});
router.get('/connections/:connectionId/ice', function(req, res) {
logger.info( "get ice request Received .. " )
const connectionId = req.params.connectionId;
const candidate = connectionManager.getCandidate(connectionId);
if(!candidate) {
res.status(404).json({err:"offer not exist"});
} else {
res.status(200).json(candidate);
}
});
*/
/* Handle debug offers and answers */
// 1. debug client gets connectionId by deviceId
router.get('/connections', async function(req, res) {
let deviceId = req.query.deviceId;
try{
let connectionId = await connectionManager.getConnectionIdByDeviceId(deviceId);
res.status(200).json({connectionId: connectionId});
}
catch (error) {
res.status(error.errorCode? error.errorCode : 503).json(error);
}
});
// 2. debug clients puts it's offer
router.put('/connections/:connectionId/debug-offer', jsonParser, async function(req, res) {
const appConnectionId = req.params.connectionId;
try {
await connectionManager.putDebugOffer(appConnectionId, req.body);
res.status(201).send();
} catch (error){
res.status(error.errorCode? error.errorCode : 500).json(error);
}
});
// 3. tc gets debug offer
router.get('/connections/:connectionId/debug-offer', async function(req, res) {
const connectionId = req.params.connectionId;
try{
const offer = await connectionManager.getDebugOffer(connectionId);
res.status(200).json(offer);
} catch (error) {
res.status(error.errorCode? error.errorCode : 503).json(error);
}
});
// 4. tc puts it's answer
router.put('/connections/:connectionId/debug-answer', jsonParser, async function(req, res) {
const appConnectionId = req.params.connectionId;
try {
await connectionManager.putDebugOfferAnswer(appConnectionId, req.body);
res.status(201).send();
} catch (error){
res.status(error.errorCode? error.errorCode : 503).json(error);
}
});
// 5. debug client gets tc answer
router.get('/connections/:connectionId/debug-answer', async function(req, res) {
const connectionId = req.params.connectionId;
try{
const offerResp = await connectionManager.getDebugOfferResponse(connectionId);
res.status(200).json(offerResp);
} catch (error) {
res.status(error.errorCode? error.errorCode : 503).json(error);
}
});
// 6. when debug client disconnects tc deletes the offer to allow a new debug connection
router.delete('/connections/:connectionId/debug-offer', jsonParser, async function(req, res) {
const appConnectionId = req.params.connectionId;
try {
await connectionManager.deleteDebugOffer(appConnectionId);
res.status(200).send();
} catch (error){
res.status(error.errorCode? error.errorCode : 503).json(error);
}
});
|
import Ember from 'ember';
export default Ember.Controller.extend({
projects: Ember.inject.service(),
actions: {
openDashboard() {
window.open(this.get('model.dashboardUrl'),'_blank');
}
}
});
|
import * as types from './actionTypes'
export const loadPages = (pages) => {
return { type: types.EXPORT_PAGES_LOAD_PAGES, payload: pages }
}
export const updatePage = (page) => {
return { type: types.EXPORT_PAGES_UPDATE_EXPORT_PAGE, payload: page }
}
export const resetExportPages = () => {
return { type: types.EXPORT_PAGES_RESET }
}
|
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'starter.services'])
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$ionicConfigProvider.tabs.position('bottom');
// Ionic uses AngularUI Router which uses the concept of states
// Learn more here: https://github.com/angular-ui/ui-router
// Set up the various states which the app can be in.
// Each state's controller can be found in controllers.js
$stateProvider
.state('begin', {
url: '/begin',
templateUrl: 'templates/begin.html'
})
.state('login', {
url: '/login',
templateUrl: 'templates/login.html'
})
.state('select-perfil', {
url: '/select-perfil',
templateUrl: 'templates/select-perfil.html'
})
.state('perfil-pf', {
url: '/perfil-pf',
templateUrl: 'templates/perfil-pf.html'
})
.state('perfil-pj', {
url: '/perfil-pj',
templateUrl: 'templates/perfil-pj.html'
})
.state('forgot-password', {
url: '/forgot-password',
templateUrl: 'templates/forgot-password.html'
})
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tab',
abstract: true,
templateUrl: 'templates/tabs.html'
})
// Each tab has its own nav history stack:
// tab home
.state('tab.home', {
url: '/home',
views: {
'tab-home': {
templateUrl: 'templates/tab-home.html',
controller: 'HomeCtrl'
}
}
})
.state('tab.home-product-detail', {
url: '/home/product-detail',
views: {
'tab-home': {
templateUrl: 'templates/product-detail.html',
controller: 'ProductDetailCtrl'
}
}
})
// tab category
.state('tab.category', {
url: '/category',
views: {
'tab-category': {
templateUrl: 'templates/tab-category.html',
controller: 'CategoryCtrl'
}
}
})
.state('tab.result-category', {
url: '/category/result-category',
views: {
'tab-category': {
templateUrl: 'templates/result-category.html',
controller: 'CategoryCtrl'
}
}
})
// tab search
.state('tab.search', {
url: '/search',
views: {
'tab-search': {
templateUrl: 'templates/tab-search.html',
controller: 'SearchCtrl'
}
}
})
.state('tab.result-search', {
url: '/search/result-search',
views: {
'tab-search': {
templateUrl: 'templates/result-search.html',
controller: 'SearchCtrl'
}
}
})
.state('tab.search-product-detail', {
url: '/search/product-detail',
views: {
'tab-search': {
templateUrl: 'templates/product-detail.html',
controller: 'ProductDetailCtrl'
}
}
})
// tab cart
.state('tab.cart', {
url: '/cart',
views: {
'tab-cart': {
templateUrl: 'templates/tab-cart.html',
controller: 'CartCtrl'
}
}
})
.state('tab.cart-address', {
url: '/cart/cart-address',
views: {
'tab-cart': {
templateUrl: 'templates/cart-address.html',
controller: 'CartCtrl'
}
}
})
.state('tab.cart-newaddress', {
url: '/cart/cart-newaddress',
views: {
'tab-cart': {
templateUrl: 'templates/cart-newaddress.html',
controller: 'CartCtrl'
}
}
})
.state('tab.cart-payment', {
url: '/cart/cart-payment',
views: {
'tab-cart': {
templateUrl: 'templates/cart-payment.html',
controller: 'CartCtrl'
}
}
})
.state('tab.cart-newcard', {
url: '/cart/cart-newcard',
views: {
'tab-cart': {
templateUrl: 'templates/cart-newcard.html',
controller: 'CartCtrl'
}
}
})
.state('tab.cart-confirm', {
url: '/cart/cart-confirm',
views: {
'tab-cart': {
templateUrl: 'templates/cart-confirm.html',
controller: 'CartCtrl'
}
}
})
// tab perfil
.state('tab.perfil', {
url: '/perfil',
views: {
'tab-perfil': {
templateUrl: 'templates/tab-perfil.html',
controller: 'PerfilCtrl'
}
}
});
// if none of the above states are matched, use this as the fallback
// $urlRouterProvider.otherwise('/tab/home');
$urlRouterProvider.otherwise('/begin');
});
|
export * from './grid';
|
'use strict'
import {
StyleSheet,
View,
Text,
} from 'react-native';
import React , {Component} from 'react';
import * as Progress from 'react-native-progress';
import TEAMS from '../../../utils/teams';
export default class PtsBar extends Component {
constructor (props) {
super(props)
this.state = {
progress: 0,
indeterminate: true,
}
}
componentDidMount () {
this.animate();
}
animate() {
const num = 1;
let progress = 0;
this.setState({ progress });
setTimeout(() => {
this.setState({ indeterminate: false });
setInterval(() => {
progress += Math.random() / 5;
if (progress > num) {
progress = num;
}
this.setState({ progress });
}, 500);
}, 1500);
}
render () {
const {points , team , width } = this.props;
const teamName = TEAMS[team].team;
const teamColor = TEAMS[team].color;
return (
<View style={styles.item}>
<Text style={styles.teamName}>{teamName}</Text>
<View style={styles.data}>
<Progress.Bar
progress={this.state.progress}
width={width}
color = {teamColor}
borderColor = {'transparent'}
borderRadius = {5}
height = {8}
/>
<Text style={styles.ptsText}>{points+" pts"}</Text>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
// Item
item: {
marginBottom: 5,
paddingHorizontal: 10
},
teamName: {
color: '#CBCBCB',
flex: 1,
fontSize: 12,
position: 'relative',
top: 2
},
data: {
flex: 2,
flexDirection: 'row'
},
ptsText: {
color: '#CBCBCB',
fontSize: 11
},
})
|
import dotenv from 'dotenv'
import express from 'express';
import Mongoose from 'mongoose';
import TodoModel from './schemas/todo_schema.js';
import cors from 'cors';
dotenv.config()
const app = express();
//getting values in json format
app.use(express.json());
app.use(cors());
const port = 3000 || process.env.PORT;
const db = process.env.DB_URL;
Mongoose.connect(db, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(() => {
console.log('Connected to MongoDB');
}).catch((err) => {
console.log(err);
})
//get all todos
//get one todo
//create todo
//delete todo
//patch one todo
app.get('/', (req, res) => {
return res.status(200).json({
message: "Welcome to the todo API."
})
})
///get all todos
app.get('/todos/:status', async (req, res) => {
const { status } = req.params;
console.log('Fetch todo status', status);
const todoModel = await TodoModel.find({ status: status });
if (todoModel) {
return res.status(200).json({
status: true,
message: "Todos fetched successfully",
data: todoModel
})
} else {
return res.status(400).json({
status: false,
message: "Todos not found",
})
}
})
///get one todo
app.get('/todos/:id', async (req, res) => {
const { id } = req.params;
console.log('Fetch todo status', id);
const todoModel = await TodoModel.findById(id);
if (todoModel) {
return res.status(200).json({
status: true,
message: "Todos fetched successfully",
data: todoModel
})
} else {
return res.status(400).json({
status: false,
message: "Todos not found",
})
}
})
///create one todo
app.post('/todo', async (req, res) => {
const { title, description, date_time } = req.body;
console.log('Fetch todo status', { title, description, date_time });
const todoModel = await TodoModel.create({
title,
description,
date_time
})
if (todoModel) {
return res.status(201).json({
status: true,
message: "Todos created",
data: todoModel
})
} else {
return res.status(400).json({
status: false,
message: "Todos not created",
})
}
})
///update a todo
app.patch('/todos/:id', async (req, res) => {
const { id } = req.params;
const { status } = req.body;
console.log('Fetch todo status', status);
const todoModel = await TodoModel.updateOne(
{ status: status }).where({ _id: id })
if (todoModel) {
return res.status(200).json({
status: true,
message: "Todos updated successfully",
data: todoModel
})
} else {
return res.status(400).json({
status: false,
message: "Todos failed to update",
})
}
})
app.delete('/todos/:id', async (req, res) => {
const todoModel = await TodoModel.findByIdAndDelete(req.params.id);
if (todoModel) {
return res.status(200).json({
status: true,
message: "Todo deleted",
data: todoModel
})
} else {
return res.status(400).json({
status: false,
message: "Failed to delete",
})
}
})
//listening to port
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
|
$(function(){
$(".js-accordion").click(function () {
$(".js-accordion-list").stop().toggle();
});
$(".js-status-item").click(function () {
var value = $(this).children("label").attr("data-value");
var innerValue = $(this).children("label").html();
$(".js-status").val(value);
$(".js-accordion-value").text(innerValue);
});
});
|
var validator = require('yode-validator');
Ext.define('Gvsu.modules.orgs.model.OrgsPubl', {
extend: "Gvsu.modules.orgs.model.OrgsModel"
,regPatterns: {
login: [/^[a-z0-9_а-яА-Я]{3,12}$/i, true]
,email: ['email', true]
,password: ['password', true]
,fname: ['name', true]
,name: ['name', true]
,sname: ['name', true]
,phone: ['phone', true]
,mobile: ['phone', true]
,position: ['string', true]
,company: ['string', true]
}
,constructor: function(cfg) {
this.passwordField = Ext.create('Core.fieldtype.password', {config: cfg.config})
this.callParent(arguments)
}
,registration: function(params, cb) {
var me = this
,res = validator.validateAll(this.regPatterns, params)
res.success = false;
[
function(next) {
if(!res.errors) {
next()
} else
cb(res)
}
,function(next) {
me.src.db.collection('gvsu_users').findOne({$or: [{login: res.values.login}, {email: res.values.email}]}, {_id: 1}, function(e,d) {
if(d && d._id) {
res.errors = {login:'dbl'}
cb(res)
} else {
next()
}
})
}
,function(next) {
res.values.token = Math.random()
me.passwordField.getValueToSave(res.values.password, function(pass) {
next(pass)
})
}
,function(pass) {
var svPass = res.values.password + ''
res.values.password = pass
res.values.activated = false
me.src.db.collection('gvsu_users').insert(res.values, function(e,d) {
if(d && d[0] && d[0]._id) {
res.values._id = d[0]._id
res.values.password = svPass
res.success = true
}
cb(res)
})
}
].runEach()
}
,activate: function(params, cb) {
var me = this;
[
function(next) {
me.src.db.collection('gvsu_users').findOne({_id: params._id}, {token:1, _id:1}, function(e,d) {
if(d) next(d)
else cb({success: false})
})
}
,function(d, next) {
if(params.token == d.token) {
me.src.db.collection('gvsu_users').update({_id: d._id}, {$set:{token: '', activated: 1}}, function(e,d) {
cb({success: true})
})
} else {
cb({success: false})
}
}
].runEach()
}
})
|
const express = require("express");
const cors = require("cors");
const restaurant = require("./restaurant");
const meal = require("./meal");
const order = require("./order");
const router = express.Router();
router.use(cors());
router.use("/restaurant", restaurant);
router.use("/meal", meal);
router.use("/order", order);
module.exports = router;
|
/**
* @module wp.api
*/
angular.module( "wp.api", [
"wp.services",
"ngResource",
"ngSanitize"
] )
.provider("path", function()
{
var provider = {};
var config = { src : "http://" };
provider.set = function( url )
{
config.src = url;
}
provider.$get = function()
{
var service = {};
service.get = function()
{
return config.src;
}
return service;
}
return provider;
})
/**
* @name have-item-wp
*
* @description
*
* The `haveWp` directive is a WordPress loop.
*
* **Attributes**
*
* | Attribute | Type | Details |
* |--------------|--------|----------------------------------------------------------------|
* | wp-type | string | `posts` or `pages` or `media` or custom post type. |
* | wp-per-page | number | The number of posts per page. Default is 10. |
* | wp-offset | number | The number of post to displace or pass over. Default is 0. |
* | wp-id | number | The ID of the post. |
* | wp-filter | object | The object of the filter. |
*
* @example
*
* ```html
* <have-wp wp-type="posts">
* <wp-title></wp-title>
* <wp-content></wp-content>
* </have-wp>
* ```
*
* If you want to get single post, you can use `id`.
*
* ```html
* <have-wp wp-type="posts" wp-id="123">
* <wp-title></wp-title>
* <wp-content></wp-content>
* </have-wp>
* ```
*
* You can pass filters to
* [WP_Query](https://codex.wordpress.org/Class_Reference/WP_Query)
* through via the `filter` argument.
*
* ```html
* <have-wp wp-type="posts" wp-filter="{ order: 'ASC', cat: 123 }">
* <wp-title></wp-title>
* <wp-content></wp-content>
* </have-wp>
* ```
*
*/
.directive( "haveWp", [ "WP", function( WP )
{
return {
restrict: "E",
replace: true,
transclude: true,
scope: {
wpType : '@',
wpId : '@',
wpPerPage : '@',
wpOffset : '@',
wpFilter : '='
},
controller: [ "$scope", function( $scope )
{
$scope.load = function()
{
if ( $scope.query == $scope.last_query ) return;
$scope.last_query = $scope.query;
if ( $scope.wpId )
{
WP.Query( WP.path ).get( $scope.query ).$promise
.then( function( items )
{
$scope.wpitems.push( items );
});
}
else if ( $scope.filter && $scope.filter.name )
{
WP.Query( WP.path ).query( $scope.query ).$promise
.then( function( items )
{
if ( items.length )
{
$scope.is_nextpage = false;
$scope.wpitems = items;
}
});
}
else
{
WP.Query( WP.path ).query( $scope.query ).$promise
.then( function( items )
{
if ( items.length )
{
$scope.is_nextpage = true;
$scope.wpitems = $scope.wpitems.concat( items );
$scope.last_query = {};
$scope.query.offset = parseInt( $scope.query.offset )
+ parseInt( $scope.perPage);
// for ionic framework
$scope.$broadcast( 'scroll.infiniteScrollComplete' );
$scope.$broadcast( 'scroll.refreshComplete');
}
else
{
$scope.is_nextpage = false;
}
});
}
}
}],
compile: function( tElement, tAttrs, transclude )
{
return {
pre: function preLink( scope, element, attrs, controller )
{
scope.wpitems = [];
if ( scope.wpId )
{
scope.query = {
'endpoint': scope.wpType,
'id': scope.wpId,
'_embed': true
}
}
else
{
if ( ! scope.wpPerPage )
scope.wpPerPage = 10;
if ( ! scope.wpOffset )
scope.wpOffset = 0;
var query = {
'endpoint': scope.wpType,
'per_page': scope.wpPerPage,
'offset': scope.wpOffset,
'filter[orderby]': 'date',
'filter[order]': 'DESC',
'_embed': true
}
scope.query = angular.extend(
query,
WP.parseFilters( scope.wpFilter )
);
}
scope.load();
}
}
},
link: function( $scope )
{
$scope.$watch( 'filter', function( newValue )
{
$scope.wpitems = [];
scope.query = angular.extend(
scope.query,
WP.parseFilters( newValue )
);
scope.load();
} );
},
template: function( tElement, tAttrs )
{
return "<div class=\"have-wp\">"
+ "<article class=\"{{ wpType }}"
+ " post-{{ wpitem.id }}\" ng-repeat=\"wpitem in wpitems\">"
+ "<div ng-transclude></div></article>"
+ "</div>";
}
}
} ] )
/**
* @name wp-title
*
* @description
*
* Displays the post title of the current post.
* This tag must be used within The `<have-wp>`.
*
* **Attributes**
*
* | Attribute | Type | Details |
* |-----------|--------|----------------------------------------------------------------|
* | href | string | Specify a link URL like `#/app/posts/:id`. |
*
* @example
*
* ```html
* <wp-title></wp-title>
* ```
* Then:
* ```html
* <div class="wp-title">Hello World</div>
* ```
* If you need a link to the post on your app. Please add `href` as attribute.
* ```html
* <wp-title href="#/posts/:id"></wp-title>
* ```
* Then:
* ```html
* <div class="wp-title"><a href="#/posts/123">Hello World</a></div>
* ```
* `:id` is a placeholder of the post's id. You can use `:slug` as post's slug too.
* ```html
* <wp-title href="#/posts/:slug"></wp-title>
* ```
* Then:
* ```html
* <div class="wp-title"><a href="#/posts/hello-world">Hello World</a></div>
* ```
*/
.directive( "wpTitle", [ "$sce", function( $sce )
{
return{
restrict:'E',
replace: true,
require : '^haveWp',
transclude: true,
compile: function( tElement, tAttrs, transclude )
{
return {
post: function postLink( scope, element, attrs, controller )
{
var wpitem = scope.$parent.wpitem;
scope.title = wpitem.title.rendered;
if ( tAttrs.href )
{
scope.permalink = tAttrs.href;
scope.permalink = scope.permalink.replace( ':id', wpitem.id );
scope.permalink = scope.permalink.replace( ':slug', wpitem.slug );
}
else
{
scope.permalink = '';
}
}
}
},
template: function( tElement, tAttrs )
{
if ( tAttrs.href )
{
return "<div class=\"wp-title\">"
+ "<a ng-href=\"{{ permalink }}\" ng-bind-html=\"title\">"
+ "{{ title }}</a></div>"
}
else
{
return "<div class=\"wp-title\" ng-bind-html=\"title\">"
+ "{{ title }}</div>"
}
}
}
} ] )
/**
* @name wp-content
*
* @description
*
* Displays the post content of the current post.
* This tag must be used within The `<have-wp>`.
*
* @example
*
* ```html
* <wp-content></wp-content>
* ```
* Then:
* ```html
* <div class="wp-content"><p>Hello World</p></div>
* ```
*/
.directive( "wpContent", [ "$sce", function( $sce )
{
return{
restrict:'E',
replace: true,
require : '^haveWp',
compile: function( tElement, tAttrs, transclude )
{
return {
post: function postLink( scope, element, attrs, controller )
{
var wpitem = scope.$parent.wpitem;
scope.content = $sce.trustAsHtml( wpitem.content.rendered );
}
}
},
template: "<div class=\"wp-content\" ng-bind-html=\"content\">"
+ "{{ content }}</div>"
}
} ] )
/**
* @name wp-post-thumbnail
*
* @description
*
* Displays the post thumbnail of the current post.
* This tag must be used within The `<have-wp>`.
*
* **Attributes**
*
* | Attribute | Type | Details |
* |-----------|--------|----------------------------------------------------------------|
* | size | string | Size of the post thumbnail. Default is `full`. |
* | | | full, large, medium, medium_large, post-thumbnail, thumbnail |
* | href | string | Specify a link URL like `#/app/posts/:id`. |
*
* @example
*
* ```html
* <wp-post-thumbnail></wp-post-thumbnail>
* ```
* Then:
* ```
* <div class="wp-post-thumbnail"><img src="http://example.com/image.jpg"></div>
* ```
* Uses `size` attribute.
* ```html
* <wp-post-thumbnail size="full"></wp-post-thumbnail>
* ```
* Then:
* ```
* <div class="wp-post-thumbnail"><img src="http://example.com/image.jpg"></div>
* ```
* If you need a link to the post on your app. Please add `href` as attribute.
* ```html
* <wp-post-thumbnail href="#/posts/:id"></wp-post-thumbnail>
* ```
* Then:
* ```html
* <div class="wp-post-thumbnail">
* <a href="#/posts/123"><img src="http://example.com/image.jpg"></a>
* </div>
* ```
* `:id` is a placeholder of the post's id. You can use `:slug` as post's slug too.
*
* ```html
* <wp-post-thumbnail href="#/posts/:slug"></wp-post-thumbnail>
* ```
* Then:
* ```html
* <div class="wp-post-thumbnail">
* <a href="#/posts/hello-world"><img src="http://example.com/image.jpg"></a>
* </div>
* ```
*/
.directive( "wpPostThumbnail", [ function()
{
return{
restrict:'E',
replace: true,
require : '^haveWp',
compile: function( tElement, tAttrs, transclude )
{
return {
post: function postLink( scope, element, attrs, controller )
{
if ( ! attrs.size )
{
attrs.size = 'post-thumbnail';
}
var scheme = 'wp:featuredmedia',
_embedded = scope.$parent.wpitem._embedded,
img;
if ( _embedded && _embedded[scheme] && _embedded[scheme].length )
{
if ( _embedded[scheme][0].media_details.sizes[attrs.size] )
{
img = _embedded[scheme][0].media_details
.sizes[attrs.size].source_url;
}
else
{
img = _embedded[scheme][0].media_details
.sizes['full'].source_url;
}
}
if ( img )
scope.image_src = img;
var wpitem = scope.$parent.wpitem;
if ( tAttrs.href )
{
scope.permalink = tAttrs.href;
scope.permalink = scope.permalink.replace( ':id', wpitem.id );
scope.permalink = scope.permalink.replace( ':slug', wpitem.slug );
}
else
{
scope.permalink = '';
}
}
}
},
template: function( tElement, tAttrs )
{
if ( tAttrs.href )
{
return "<div class=\"wp-post-thumbnail\">"
+ "<a ng-href=\"{{ permalink }}\">"
+ "<img ng-src=\"{{ image_src }}\"></a></div>"
}
else
{
return "<div class=\"wp-post-thumbnail\">"
+ "<img ng-src=\"{{ image_src }}\"></div>"
}
}
}
} ] )
/**
* @name wp-author
*
* @description
*
* Displays the author of the current post.
* This tag must be used within The `<have-wp>`.
*
* @example
*
* Place the code like following into your HTML.
* ```
* <wp-author></wp-author>
* ```
* Then you will get like following.
* ```
* <div class="wp-author"><p>Jhon Doe</p></div>
* ```
*/
.directive( "wpAuthor", [ '$sce', function( $sce )
{
return {
restrict:'E',
replace: true,
require : '^haveWp',
compile: function( tElement, tAttrs, transclude )
{
return {
post: function postLink( scope, element, attrs, controller )
{
var scheme = 'author',
_embedded = scope.$parent.wpitem._embedded,
author;
if ( _embedded && _embedded[scheme] && _embedded[scheme].length )
{
author = _embedded[scheme][0];
}
if( author )
scope.author = author;
}
}
},
template: "<span class=\"wp-author\" ng-bind-html=\"author.name\">"
+ "{{ author.name }}</span>"
}
} ] )
/**
* @name wp-excerpt
*
* @description
*
* Displays the excerpt of the current post.
* This tag must be used within The `<have-wp>`.
*
* @example
*
* Place the code like following into your HTML.
* ```
* <wp-excerpt></wp-excerpt>
* ```
* Then you will get like following.
* ```
* <div class="wp-excerpt"><p>Hello World.</p></div>
* ```
*/
.directive( "wpExcerpt", [ '$sce', function( $sce )
{
return {
restrict:'E',
replace: true,
require : '^haveWp',
compile: function( tElement, tAttrs, transclude )
{
return {
post: function postLink( scope, element, attrs, controller )
{
var wpitem = scope.$parent.wpitem;
scope.excerpt = $sce.trustAsHtml( wpitem.excerpt.rendered );
}
}
},
template: "<span class=\"wp-excerpt\" ng-bind-html=\"excerpt\">"
+ "{{ excerpt }}</span>"
}
} ] )
/**
* @name wp-date
*
* @description
*
* Displays the date of the current post.
* This tag must be used within The `<have-wp>`.
*
* **Attributes**
*
* | Attribute | Type | Details |
* |-----------|--------|----------------------------------------------------------------|
* | format | string | See https://docs.angularjs.org/api/ng/filter/date |
*
* @example
*
* Place the code like following into your HTML.
* ```
* <wp-date></wp-date>
* ```
* Then you will get like following.
* ```
* <div class="wp-date">2016-02-16 13:54:13</div>
* ```
*
* You can set format string like following.
* See https://docs.angularjs.org/api/ng/filter/date.
* ```
* <wp-date format="yyyy/MM/dd"></wp-date>
* ```
* Then you will get like following.
* ```
* <div class="wp-date">2016-02-16</div>
* ```
*/
.directive( "wpDate", [ function()
{
return{
restrict:'E',
replace: true,
require : '^haveWp',
compile: function( tElement, tAttrs, transclude )
{
return {
post: function postLink( scope, element, attrs, controller )
{
if ( ! attrs.format ) {
scope.format = "yyyy/MM/ddTH:mm:ssZ";
} else {
scope.format = attrs.format;
}
var date = scope.$parent.wpitem.date_gmt + "Z";
scope.date = date;
}
}
},
template: "<span class=\"the-date\">{{ date | date: format }}</span>"
}
} ] )
;
/**
* @module wp.services
*/
angular.module( "wp.services", [ "ngResource" ] )
.service( "WP", [ "$resource", "path", function( $resource, path )
{
this.path = path.get();
/**
* @name WP.Query
*
* @description
* Gets the WordPress objects from wp-api.
*/
this.Query = function( apiRoot )
{
var api = apiRoot + "/:endpoint/:id";
var params = {
endpoint: '@endpoint',
id: '@id'
};
var actions = {};
return $resource( api, params, actions );
}
this.parseFilters = function( filters )
{
var filter_strings = {};
for ( var key in filters ) {
filter_strings[ 'filter[' + key + ']' ] = filters[key];
}
return filter_strings;
}
}])
;
|
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require twitter/bootstrap
//= require turbolinks
//= require_tree .
function build_day_graph(days){
$('#days-container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Followers Tweet Frequency'
},
subtitle: {
text: 'Distributed over weekdays'
},
xAxis: {
categories: [
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Tweet Count'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tweets',
data: days
}]
});
}
function build_time_graph(times){
$('#times-container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Followers Tweet Frequency'
},
subtitle: {
text: 'Distributed over hours in a day'
},
xAxis: {
categories: [
'0:00 - 1:00',
'1:00 - 2:00',
'2:00 - 3:00',
'3:00 - 4:00',
'4:00 - 5:00',
'5:00 - 6:00',
'6:00 - 7:00',
'7:00 - 8:00',
'8:00 - 9:00',
'9:00 - 10:00',
'10:00 - 11:00',
'11:00 - 12:00',
'12:00 - 13:00',
'13:00 - 14:00',
'14:00 - 15:00',
'15:00 - 16:00',
'16:00 - 17:00',
'17:00 - 18:00',
'18:00 - 19:00',
'19:00 - 20:00',
'20:00 - 21:00',
'21:00 - 22:00',
'22:00 - 23:00',
'23:00 - 24:00',
],
crosshair: true
},
yAxis: {
min: 0,
title: {
text: 'Tweet Count'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y}</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: [{
name: 'Tweets',
data: times
}]
});
}
|
const create_link_to_twitter = (username) => {
window.open(`https://twitter.com/${username}`, "_blank");
};
const ministry_menu_button = () => {
if ($(".ministry_list_navbar").css("height") == "0px") {
$(".ministry_list_navbar").css("height", "auto");
//$('.ministry_list_navbar').css('width', '100%');
$(".ministry_list_navbar").css("border-top", "1px solid white");
} else {
$(".ministry_list_navbar").css("height", "0px");
//$('.ministry_list_navbar').css('width', '0%');
$(".ministry_list_navbar").css("border-top", "none");
}
};
$(document).on("click", ".Ministry_twitter_handle_link", function () {
username = $(this).html();
create_link_to_twitter(username);
});
$(document).on("click", ".Minister_twitter_handle_link", function () {
username = $(this).html();
create_link_to_twitter(username);
});
$(document).on("click", "#ministry_list_menu_icon", ministry_menu_button);
let data = [
{
ministry: "Ministry of Petroleum",
ministryHandle: "Abdulaz29562466",
minister: "Alhaji Abdulazeez",
ministerHandle: "Abdulaz29562466",
amount: 10000000,
},
{
ministry: "Ministry of Women Affairs",
ministryHandle: "aisha@buha.ri",
minister: "Aisha Buhari",
ministerHandle: "aisha@buha.ri",
amount: 50000000,
},
{
ministry: "Ministry of Education",
ministryHandle: "simeon979",
minister: "Adegbola Simeon",
ministerHandle: "simeon979",
amount: 30000000,
},
{
ministry: "Ministry of Internal Affairs",
ministryHandle: "tongueblastingcoder",
minister: "TongueBlasting Coder",
ministerHandle: "tongueblastingcoder",
amount: 40000000,
},
];
let displayedData = [];
window.onload = () => {
let table = document.querySelector("table");
for (let item of data) {
let row = document.createElement("tr");
row.appendChild(createCol(item.ministry, []));
row.appendChild(
createCol(item.ministryHandle, ["Ministry_twitter_handle_link"])
);
row.appendChild(createCol(item.minister, []));
row.appendChild(
createCol(item.ministerHandle, ["Minister_twitter_handle_link"])
);
let amountInNaira = new Intl.NumberFormat("en-ng", {
style: "currency",
currency: "NGN",
}).format(item.amount);
row.appendChild(createCol(amountInNaira, []));
table.appendChild(row);
}
document.querySelector("#filter").addEventListener("input", search);
};
const createCol = (content, classes) => {
let contentCol = document.createElement("td");
contentCol.innerText = content;
for (let aClass of classes) {
contentCol.classList.add(aClass);
}
return contentCol;
};
const search = ({ target: value }) => {
let regexp = new RegExp(value.value.toLowerCase());
let allMinistries = document.querySelectorAll("td:first-child");
for (let ministry of allMinistries) {
if (!regexp.test(ministry.textContent.toLowerCase())) {
ministry.parentElement.classList.add("remove");
} else {
ministry.parentElement.classList.remove("remove");
}
}
};
|
import {Entity, PrimaryGeneratedColumn, Column, OneToMany, ManyToOne, ManyToMany, JoinTable} from "typeorm";
import {Content} from "./Content";
import {Session} from "./Session";
import {Region} from "./Region";
import {Country} from "./Country";
@Entity()
export class User {
@PrimaryGeneratedColumn()
id = Number();
@Column ("varchar") firstName;
@Column ("varchar") lastName;
@Column ("varchar") email;
@Column ("varchar") password;
@OneToMany(type => Session, session => session.user)
sessions;
@ManyToOne(type => Country, country => country.users)
country;
@ManyToMany(type => Content, content => content.users )
@JoinTable()
contents ;
}
|
import React, { useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import errorMailbox from 'images/error_mailbox';
import loadMail from 'images/load_mail';
import successMailbox from 'images/success_mailbox';
import {
Dialog,
DialogActions,
DialogContent,
DialogContentText,
Fab,
Typography,
Grid,
} from '@material-ui/core';
import styles from './styles';
function LoadModal({
classes,
open,
status,
handleClick,
handleClose,
errorCount,
}) {
const getText = () => {
let titleText;
let buttonText;
let statusImage;
switch (status) {
case 'loading':
titleText = 'Assigning...';
buttonText = null;
statusImage = loadMail;
break;
case 'complete':
titleText = 'Successfully Assigned!';
buttonText = 'CREATE NEW';
statusImage = successMailbox;
break;
case 'error':
titleText = `Failed to assign ${errorCount} assignments`;
buttonText = 'VIEW FAILED ASSIGNMENTS';
statusImage = errorMailbox;
break;
default:
titleText = null;
buttonText = null;
statusImage = null;
}
return { titleText, buttonText, statusImage };
};
const buttonRef = useRef(null);
const { titleText, buttonText, statusImage } = getText();
useEffect(() => {
if (buttonText && buttonRef.current) {
buttonRef.current.focus();
}
}, [status]);
return (
<Dialog
open={open}
fullWidth
classes={{ paper: classes.modalStyle }}
onClose={handleClose}
onExited={() =>
// Avoid blurring document.body on IE9 since it blurs the entire window
document.activeElement !== document.body
? document.activeElement.blur()
: null
}
>
<Grid item container direction="column" alignItems="center">
<Grid item>
<DialogContent>
<DialogContentText id="alert-dialog-description">
<Typography className={classes.textStyle}>{titleText}</Typography>
</DialogContentText>
</DialogContent>
</Grid>
<Grid item>
<DialogContent>
<img src={statusImage} alt={titleText} />
</DialogContent>
</Grid>
<Grid item>
<DialogActions>
{buttonText ? (
<Fab
className={classes.iconStyle}
ref={buttonRef}
component="span"
variant="extended"
size="medium"
color="primary"
onClick={handleClick}
disableRipple
>
<Typography
className={classes.categoryButtonStyle}
align="center"
>
{buttonText}
</Typography>
</Fab>
) : null}
</DialogActions>
</Grid>
</Grid>
</Dialog>
);
}
LoadModal.propTypes = {
classes: PropTypes.object.isRequired,
status: PropTypes.string,
open: PropTypes.bool.isRequired,
handleClick: PropTypes.func.isRequired,
handleClose: PropTypes.func,
errorCount: PropTypes.number,
};
export default withStyles(styles)(LoadModal);
|
// Dropdown
class Dropdown {
constructor() {
this.dropdownButton = document.querySelector('.dropdown__button');
this.dropdownMenu = document.querySelector('.dropdown__menu');
// console.log(this.dropdownMenu);
this.dropdownButton.addEventListener('click', this.toggleMenu.bind(this));
}
toggleMenu(event) {
this.dropdownMenu.classList.toggle('dropdown__menu--show');
}
}
window.onload = () => new Dropdown();
|
const gulp = require('gulp');
const argv = require('yargs').argv;
const { changelogModule, cleanModule, jsdocModule, versioningModule } = require('meister-js-dev').gulp;
const { createBuildTask, createConfig, createCompiler } = require('meister-gulp-webpack-tasks');
// Build tasks.
const MODULE_NAME = 'HtmlUi';
gulp.task('build', (done) => {
const bundleConfig = createConfig('./index.js', `build/${MODULE_NAME}.js`, false);
const bundleCompiler = createCompiler(bundleConfig);
createBuildTask(bundleCompiler)(done);
});
gulp.task('build:min', (done) => {
const bundleConfig = createConfig('./index.js', `dist/${MODULE_NAME}.min.js`, true);
const bundleCompiler = createCompiler(bundleConfig);
createBuildTask(bundleCompiler)(done);
});
gulp.task('build:dist', (done) => {
const bundleConfig = createConfig('./index.js', `dist/${MODULE_NAME}.js`, false);
const bundleCompiler = createCompiler(bundleConfig);
createBuildTask(bundleCompiler)(done);
});
// Documentation tasks.
gulp.task('docs', jsdocModule.createGenerateDocs('./src/js/**/*.js', './docs/js-docs'));
gulp.task('clean:docs', cleanModule.createClean('./docs/js-docs'));
gulp.task('clean:build', cleanModule.createClean('./build/**'));
gulp.task('clean:dist', cleanModule.createClean('./dist/**'));
// Versioning tasks.
let type = 'patch';
const userType = argv.type ? argv.type.toLowerCase() : null;
if (userType && (userType === 'major' || userType === 'minor')) {
type = userType;
}
gulp.task('bump-version', versioningModule.createBumpVersion('./package.json', type));
gulp.task('changelog', changelogModule.createGenerateLog('./docs/CHANGELOG.md'));
|
let $this = new Object();
$this.alerts = new Object();
$this.alerts.hola = null;
define($this);
|
import { helper } from '@ember/component/helper';
export function medalIcon(params/*, hash*/) {
var rank = params[0] + 1;
switch(rank) {
case 1:
return `<img class="medal-icon" src="https://s3-ap-northeast-1.amazonaws.com/coin24hours-static/gold.svg" height=37 width=37 />`;
break;
case 2:
return '<img class="medal-icon" src="https://s3-ap-northeast-1.amazonaws.com/coin24hours-static/silver.svg" height=37 width=37 />';
break;
case 3:
return '<img class="medal-icon" src="https://s3-ap-northeast-1.amazonaws.com/coin24hours-static/bronze.svg" height=37 width=37 />';
break;
default:
return '';
break;
}
}
export default helper(medalIcon);
|
var quizData = {
name: 'My Badly Named Quiz',
scores: new Object(),
leaderboard: [],
questions: [
{
id: 0,
question: 'What is your name?',
answer: 'Arthur, King of the Britons',
choices: ['Arthur, King of the Britons', 'Brave Sir Robin', 'Sir Launcelot'],
attempts: 0,
timesCorrect: 0
},
{
id: 1,
question: 'What is your quest?',
answer: 'To Seek the Holy Grail',
choices: ['To Seek the Holy Grail'],
attempts: 0,
timesCorrect: 0
},
{
id: 2,
question: 'What is your favorite color?',
answer: 'Blue. No! Yellooooooowwwww!',
choices: ['Chartreuse', 'Mauve', 'Blue. No! Yellooooooowwwww!'],
attempts: 0,
timesCorrect: 0
},
{
id: 3,
question: 'What is the capital of Assyria',
answer: 'I don\'t know that!',
choices: ['Ashur', 'Calah', 'Dur Sharrukin', 'Nineveh', 'I don\'t know that!'],
attempts: 0,
timesCorrect: 0
},
{
id: 4,
question: 'What is the air-speed velocity of an unladen swallow?',
answer: 'African or European swallow?',
choices: ['24 mph', 'African or European swallow?'],
attempts: 0,
timesCorrect: 0
}
]
};
|
"use strict";
function AppState() {
if (AppState._instanceAlreadyCreated) {
if(console && console.warn)
console.warn("Another instance of the AppState has been generated. There should only be 1 instantiated for the lifetime of the application.");
}
AppState._instanceAlreadyCreated = true;
this.urlToPublicJsonStore = "brain/cortex.json";
this.urlToPrivateJsonStore = "body.json";
this._currentStore = null;
this._initialStore = null;
this._eventsObj_StoreChanged;
this._actionHistory = [];
this._storeIsBeingSaved = false;
this._storeSaveBacklogRequestCounter = 0;
this._reducersArr = [];
this._stateCleanerArr = [];
this._isHtml5PushStateAvailable = ('history' in window && 'pushState' in history) ? true : false;
if(this._isHtml5PushStateAvailable){
var scopeThis = this;
// This could take considerable work to replay all of the a action objects on top of the initial state.
// If a performance impact is detected (hitting BACK/FORWARD) on a large database with a large number of actions it seems like a good idea to store "new state bases" every X number of actions.
// The additional "base states" could be stored in local storage and referenced within the Push State objects.
// This way the system will only need to replay the actions on top of closest "base state", meaning that there are less actions to process.
window.addEventListener('popstate', function(e) {
console.log("Pop State: Received a event:", e.state);
var actionHistoryArrFromPopState = [];
if(e.state && e.state.actionHistory){
actionHistoryArrFromPopState = e.state.actionHistory;
if(!Array.isArray(actionHistoryArrFromPopState))
throw new Error("Error in AppState, 'popstate' event handler. The 'actionHistory' key was available on the state object but it is not of type Array:", actionHistoryArrFromPopState);
}
else{
console.log("Pop State: There is not a state object on the HTML5 Push State, resetting the application back to its initial state. ");
}
var newStore = HIPI.framework.Utilities.copyObject(scopeThis._initialStore);
// Replay all of the Actions from the History Array on top of the initial store.
// It would be easier to just put the entire State object onto the HTML5 PushState entry, but this database could grow very large and some vendors put size constraints on the PushState API.
for(var i=0; i<actionHistoryArrFromPopState.length; i++){
// Run any reducers attached to this application (defined outside of the Components themselves).
for(var j=0; j<scopeThis._reducersArr.length; j++){
var loop_StoreObj = scopeThis._reducersArr[j](newStore, actionHistoryArrFromPopState[i]);
newStore = HIPI.framework.Utilities.copyObject(loop_StoreObj);
}
// Run any reducers defined within the Components.
newStore = HIPI.framework.ComponentCollection.runComponentReducers(newStore, actionHistoryArrFromPopState[i]);
}
scopeThis._currentStore = newStore;
if(scopeThis._eventsObj_StoreChanged)
scopeThis._eventsObj_StoreChanged.fire();
HIPI.framework.ComponentCollection.runDigestCycle();
HIPI.framework.AppState.saveStore()
.then(function(){
console.log("Store was saved successfully after navigating to a new position in the browser history.");
});
});
}
};
// This is one of two places where Reducers can be added.
// Any Reducer functions added here will run before the Component Reducers in FIFO.
// Components can also define their own Reducers within the definition files.
AppState.prototype.addReducerFunction = function (reducerFunction) {
HIPI.framework.Utilities.ensureTypeFunction(reducerFunction);
this._reducersArr.push(reducerFunction);
};
// This is one of two places where a State Cleaner function can be added.
// Components can also define their own State Cleaners within the definition files.
// The purpose of the State Cleaners are to remove any data from the Store before persisting the state to disk.
// For example, the "current user's" position(s) might exist in the global State object but that stuff is not something which should be shared with others.
// In other words, it is any type of data that should be lost after restarting the application, such as refreshing the browser.
AppState.prototype.addStateCleanerFunction = function (stateCleanupFunction) {
HIPI.framework.Utilities.ensureTypeFunction(stateCleanupFunction);
this._stateCleanerArr.push(stateCleanupFunction);
};
// The event will fire before the digest cycle runs.
AppState.prototype.subscribeToStoreChangedEvents = function (functionReference, functionArgumentsArr, objectRefForEvent) {
if(!this._eventsObj_StoreChanged)
this._eventsObj_StoreChanged = new HIPI.framework.Events();
this._eventsObj_StoreChanged.addSubscription(functionReference, functionArgumentsArr, objectRefForEvent);
};
AppState.prototype.dispatchAction = function (actionObj) {
HIPI.framework.Utilities.ensureTypeObject(actionObj);
if(typeof actionObj.type !== "string" || !actionObj.type)
throw new TypeError("Error in AppState.dispatchAction. The action object must always contain a non-empty string for the 'type' property.");
console.log("Dispatching Action: ", actionObj);
if(this._isHtml5PushStateAvailable){
var newActionHistoryArr = this._getActionHistoryFromCurrentHistoryState();
newActionHistoryArr.push(actionObj);
this._actionHistory.push(actionObj);
history.pushState({"actionHistory": newActionHistoryArr}, null, (HIPI.framework.Constants.getApplicationFileName() + "?action=" + this._actionHistory.length));
}
var newStore = HIPI.framework.Utilities.copyObject(this._currentStore);
// Reducers take the current state and action, then returns a copy of the new state using "pure functions".
for(var i=0; i<this._reducersArr.length; i++)
newStore = this._reducersArr[i](newStore, actionObj);
// Now let the Component Reducers work on the copy.
newStore = HIPI.framework.ComponentCollection.runComponentReducers(newStore, actionObj);
this._currentStore = newStore;
if(this._eventsObj_StoreChanged)
this._eventsObj_StoreChanged.fire();
HIPI.framework.ComponentCollection.runDigestCycle();
};
AppState.prototype.setStoreObj = function (storeObj) {
HIPI.framework.Utilities.ensureTypeObject(storeObj);
this._currentStore = HIPI.framework.Utilities.copyObject(storeObj);
console.log("Store object overridden", this._currentStore);
if(this._eventsObj_StoreChanged)
this._eventsObj_StoreChanged.fire();
HIPI.framework.AppState.runDigestCycle();
};
AppState.prototype.getStoreObj = function () {
if(!this._currentStore)
throw new Error("Error in AppState.getStoreObj. The Store is being requested before it has been loaded.");
return HIPI.framework.Utilities.copyObject(this._currentStore);
};
// The following 2 methods contain application-specific code for bisecting the global state object into public/private parts.
// It would be better to run this logic through callback methods (maybe attached through boot.js) to keep this AppState class abstract.
AppState.prototype.getPublicStoreObj = function (globalStoreObj) {
HIPI.framework.Utilities.ensureTypeObject(globalStoreObj);
globalStoreObj = HIPI.framework.Utilities.copyObject(globalStoreObj);
delete globalStoreObj.privateState;
return globalStoreObj;
};
AppState.prototype.getPrivateStoreObj = function (globalStoreObj) {
HIPI.framework.Utilities.ensureTypeObject(globalStoreObj);
globalStoreObj = HIPI.framework.Utilities.copyObject(globalStoreObj);
if(globalStoreObj.privateState)
return globalStoreObj.privateState;
else
return {};
};
AppState.prototype.loadStore = function () {
if(this._currentStore)
throw new Error("Error in AppState.loadStore. Cannot load the store after it has already been loaded.");
var scopeThis = this;
// If someone refreshes the browser it doesn't clear the PushState history, it just adds another entry.
// The problem is that the "initial store" is reloaded from disk after a refresh so the Action History events get replayed on top of an unpredictable base.
if(scopeThis._isHtml5PushStateAvailable){
var currentURL = new String(window.location).toString();
if(!currentURL.match(/\?action=start/)){
currentURL = currentURL.replace(/\?.*$/, "");
currentURL = currentURL.replace(HIPI.framework.Constants.getApplicationFileName(), "");
currentURL += HIPI.framework.Constants.getApplicationFileName() + "?action=start";
window.location.replace(currentURL);
return Promise.reject(HIPI.framework.Constants.redirectingToStartPagePromiseRejectionString());
}
}
return HIPI.framework.Utilities.getAjax(this.urlToPublicJsonStore)
.then(function(publicJsonStr){
try{
scopeThis._currentStore = JSON.parse(publicJsonStr);
console.log("The Public Store object has been fetched from the server.", scopeThis._currentStore);
}
catch(e){
return Promise.reject("Unable to parse the public JSON store '"+scopeThis.urlToPublicJsonStore+"'. It's possible that the file has been corrupted. Consider rolling back the state of this file using your version control software.");
}
// Add another Promise to the chain.
return HIPI.framework.Utilities.getAjax(scopeThis.urlToPrivateJsonStore);
})
.then(function(privateJsonStr){
try{
var privateStoreObj = JSON.parse(privateJsonStr);
// Merge the private store object into the global state within its own key.
scopeThis._currentStore.privateState = privateStoreObj;
// The initial store object is only needed so that the HTML5 Push State can replay actions on top of a base (i.e. whenever Back/Forward is used).
scopeThis._initialStore = HIPI.framework.Utilities.copyObject(scopeThis._currentStore);
console.log("The Private Store object has been fetched from the server and merged into the current store.", scopeThis._currentStore);
}
catch(e){
return Promise.reject("Unable to parse the private JSON store '"+scopeThis.urlToPrivateJsonStore+"'. It's possible that the file has been corrupted. Consider rolling back the state of this file using your version control software or erase the contents of the file and restart this application.");
}
})
.catch(function(err){
return Promise.reject("Unable to fetch the store from the server. Error: " + err);
});
};
AppState.prototype.saveStore = function () {
if(!this._currentStore)
throw new Error("Error in AppState.saveStore. Cannot save the store before it has been loaded.");
// If the database grows large it could take some time to "clean the state" and save to disk.
// This conditional will prevent overlapping asynchronous requests while ensuring that the last call is honored.
if(this._storeIsBeingSaved){
this._storeSaveBacklogRequestCounter++;
console.log("In AppState.saveStore. Received another request to save the store while a save process is currently underway. Marking a backlog request, will try re-saving once the current request completes. Total backlog requests: " + this._storeSaveBacklogRequestCounter);
// Let the calling code know that the store wasn't actually saved, but without raising any concerns through a rejected promise.
return Promise.resolve({"delayedSave": true, "backlogRequestCounter":this._storeSaveBacklogRequestCounter});
}
this._storeIsBeingSaved = true;
var globalStoreForPersist = this._getCleanCopyOfStoreForDisk();
var publicStoreForPersist = this.getPublicStoreObj(globalStoreForPersist);
var privateStoreForPersist = this.getPrivateStoreObj(globalStoreForPersist);
var scopeThis = this;
return HIPI.framework.Utilities.postAjax(this.urlToPublicJsonStore, JSON.stringify(publicStoreForPersist, null, '\t'))
.then(function(resultStr){
if(resultStr !== "OK")
return Promise.reject("Received an unexpected response while trying to persist the public data store to URL: " + scopeThis.urlToPublicJsonStore);
// Chain link another promise onto the save routine.
return HIPI.framework.Utilities.postAjax(scopeThis.urlToPrivateJsonStore, JSON.stringify(privateStoreForPersist, null, '\t'))
})
.then(function(resultStr){
if(resultStr !== "OK")
return Promise.reject("Received an unexpected response while trying to persist the private data store to URL: " + scopeThis.urlToPrivateJsonStore);
// Don't acknowledge that the store has been saved until both private & public objects have successful server-side responses.
scopeThis._storeIsBeingSaved = false;
if(scopeThis._storeSaveBacklogRequestCounter){
console.log("In AppState.saveStore. The last save operation completed with "+scopeThis._storeSaveBacklogRequestCounter+" pending backlog request(s). Going to try re-saving the store now.");
scopeThis._storeSaveBacklogRequestCounter = 0;
// This will return a Promise which may lengthen the time it takes for the first request to resolve.
// Any subsequent requests )which incremented this._storeSaveBacklogRequestCounter would have had their promises resolve almost immediately.
return scopeThis.saveStore();
}
})
.catch(function(err){
scopeThis._storeIsBeingSaved = false;
scopeThis._storeSaveBacklogRequestCounter = 0;
return Promise.reject("Unable to save the store to the server. Is it still running? Error: " + err);
});
};
// This method will return a copy of the current store with all session-specific date removed.
// Essentially this returns an application state that is suitable for sharing with everyone else, much like the way that it was found when the application started.
AppState.prototype._getCleanCopyOfStoreForDisk = function () {
// Always work with copies when dealing with "pure functions".
var storeClone = HIPI.framework.Utilities.copyObject(this._currentStore);
// Cleaners take the current state and return a copy without any session-specific data.
for(var i=0; i<this._stateCleanerArr.length; i++){
var loop_StoreObj = this._stateCleanerArr[i](storeClone);
storeClone = HIPI.framework.Utilities.copyObject(loop_StoreObj);
}
// Now let the Components clean up anything they need on the copy.
return HIPI.framework.ComponentCollection.runComponentStateCleaners(storeClone);
};
// This will return an array of Action Objects held within the HTML History API (whatever the current position is).
// If there aren't any history records yet this method will return an empty array.
AppState.prototype._getActionHistoryFromCurrentHistoryState = function () {
if(!this._isHtml5PushStateAvailable)
throw new Error("Error in _getActionHistoryFromCurrentHistoryState. This method cannot be called on browsers which do not support the HTML5 pushState API.");
var actionHistoryArr = [];
if(window.history && window.history.state)
actionHistoryArr = window.history.state.actionHistory;
if(!Array.isArray(actionHistoryArr))
throw new Error("Error in AppState._getActionHistoryFromCurrentHistoryState. The 'actionHistory' key was available on the state object but it is not of type Array:", actionHistoryArr);
return actionHistoryArr;
};
|
const mongoose = require('mongoose');
const user1Id = mongoose.Types.ObjectId();
const user2Id = mongoose.Types.ObjectId();
const user3Id = mongoose.Types.ObjectId();
const data = {
users: [
{
_id: user1Id,
avatar: "https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png",
email: "admin@gmail.com",
name: "admin@gmail.com",
username: "admin@gmail.com",
info: "admin@gmail.com",
password: "admin@gmail.com",
role: "admin"
},
{
_id: user2Id,
avatar: "https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png",
email: "guest@gmail.com",
name: "guest@gmail.com",
username: "guest@gmail.com",
info: "guest@gmail.com",
password: "guest@gmail.com",
role: "guest"
},
{
_id: user3Id,
avatar: "https://cdn1.iconfinder.com/data/icons/ninja-things-1/1772/ninja-simple-512.png",
email: "instructor@gmail.com",
name: "instructor@gmail.com",
username: "instructor@gmail.com",
info: "instructor@gmail.com",
password: "instructor@gmail.com",
role: "instructor"
},
],
portfolios: [
{
title: 'Job in Netcentric',
company: 'Netcentric',
companyWebsite: 'www.google.com',
location: 'Spain, Barcelona',
jobTitle: 'Engineer',
description: 'Doing something, programing....',
startDate: '01/01/2014',
endDate: '01/01/2016',
user: user1Id
},
{
title: 'Job in Siemens',
company: 'Siemens',
companyWebsite: 'www.google.com',
location: 'Slovakia, Kosice',
jobTitle: 'Software Engineer',
description: 'Responsoble for parsing framework for JSON medical data.',
startDate: '01/01/2011',
endDate: '01/01/2013',
user: user2Id
},
{
title: 'Work in USA',
company: 'WhoKnows',
companyWebsite: 'www.google.com',
location: 'USA, Montana',
jobTitle: 'Housekeeping',
description: 'So much responsibility....Overloaaaaaad',
startDate: '01/01/2010',
endDate: '01/01/2011',
user: user3Id
}
],
}
module.exports = data;
|
var util = require('util');
var User = require('./User.class.js');
var Users = require('./Users.class.js');
function PlayingUsers() {
}
util.inherits(PlayingUsers, Users);
PlayingUsers.prototype.setUsers = function(users) {
this.removeListeners();
this.users = users;
this.addListeners();
this.broadcast('start game');
};
//start game, score update, end game
PlayingUsers.prototype.broadcast = function(event, vars) {
if (vars == undefined) {
vars = new Object();
}
if (event == 'score update') {
vars.scores = new Object();
for (var i = 0; i < this.users.length; i++) {
vars.scores[this.users[i].socket.id] = this.users[i].score;
}
}
PlayingUsers.super_.prototype.broadcast.call(this, event, vars);
};
//private
PlayingUsers.prototype.addListeners = function(user) {
for (var i = 0; i < this.users.length; i++) {
this.users[i].addListener(User.SCORE_UPDATE, this.broadcast.bind(this, 'score update'));
this.users[i].addListener(User.DISCONNECT, this.onUserDisconnect.bind(this, this.users[i]));
}
};
PlayingUsers.prototype.removeListeners = function(user) {
for (var i = 0; i < this.users.length; i++) {
this.users[i].removeListener(User.SCORE_UPDATE, this.broadcast.bind(this, 'score update'));
this.users[i].removeListener(User.DISCONNECT, this.onUserDisconnect.bind(this, this.users[i]));
}
};
PlayingUsers.prototype.onUserDisconnect = function(user) {
PlayingUsers.super_.prototype.onUserDisconnect.call(this, user);
this.endGame();
}
PlayingUsers.prototype.endGame = function(user) {
this.broadcast('end game');
this.users = new Array();
};
module.exports = PlayingUsers;
|
var mysql = require('mysql');
var inquirer = require('inquirer');
var connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'root',
database: 'bamazon'
});
connection.connect(function(err) {
if (err) throw err;
displayProducts();
itemsToBuy();
});
function displayProducts() {
console.log('Hi. Database succuessfully connected');
connection.query('SELECT item_id, product_name, price FROM bamazon.products',
function(err, res) {
if (err) throw err;
for(var i = 0; i < res.length; i++) {
console.log('item ID: ' + res[i].item_id + ' | Product name: ' + res[i].product_name + ' | Price: $' + res[i].price);
};
});
};
function itemsToBuy () {
inquirer.prompt([
{
name: 'item_id',
type: 'input',
message: 'Please enter the id of item you would like to purchase?',
validate: function(value) {
if (isNaN(value) === false) {
return true;
}
return false;
}
},
{
name: 'pQuantity',
type: 'input',
message: 'How many items would you like to purchase?',
validate: function(value) {
if (isNaN(value) === false) {
return true;
}
return false;
}
}
])
.then(function(answer) {
var chosenID = parseInt(answer.item_id);
var chosenQuantity = parseInt(answer.pQuantity);
connection.query('SELECT * FROM bamazon.products',
{
item_id: answer.item_id
},
function(err, res) {
if (err) throw err;
console.log('You want to purchase Item-id: ' + chosenID);
console.log('Quantity: ' + chosenQuantity);
console.log('Product Name: ' + res[chosenID-1].product_name);
console.log('Stock Quantity: ' + res[chosenID-1].stock_quantity);
if (chosenQuantity > res[chosenID-1].stock_quantity) {
console.log('Insufficient Quantity!');
}
else {
connection.query(
'UPDATE bamazon.products SET ? WHERE ?',
[
{
stock_quantity: (res[chosenID-1].stock_quantity) - (chosenQuantity)
},
{
item_id: chosenID
}
],
function(error) {
if(error) throw err;
connection.query(
'SELECT * FROM bamazon.products',
function(err, res) {
console.log('Success! There are ' + res[chosenID-1].stock_quantity + ' more left' )
;
});
}
)
}
});
});
};
|
/**
* 该文件专门用于暴露一个 store 对象,整个应用只有一个 store 对象
*/
//引入 createStore ,用于创建 redux 中最为核心的 store对象
import { createStore, applyMiddleware } from 'redux'
//引入redux-thunk,用于支持异步action
import thunk from 'redux-thunk'
//引入为Count组件服务的reducer
import countReducer from './count_reducer'
//暴露 store
export default createStore(countReducer, applyMiddleware(thunk))
|
/**
* jsdoc How does it work in RN?
* @flow
* @format
*/
import React, { PureComponent } from 'react'
import { StyleSheet, Text } from 'react-native'
type Props = { text: string, children: any, style: StyleSheet.NamedStyles<any> }
export default class HelloBlink extends PureComponent<Props> {
static defaultProps = {
text: 'HelloBlink default Text',
}
constructor(...props) {
super(...props)
this.state = { isShowText: true }
// 每1000毫秒对showText状态做一次取反操作
setInterval(() => {
this.setState((previousState) => {
return {
isShowText: !previousState.isShowText,
}
})
}, 1000)
}
render() {
// 根据当前showText的值决定是否显示text内容
const { isShowText } = this.state
const { text, children, style } = this.props
if (!isShowText) return null
return (
<Text style={style}>
{text}
{children}
</Text>
)
}
}
|
//we need to get access to the mongoose, which is gonna help us to define the schema or structure for db
const mongoose = require('mongoose')
//create schema now
const alienSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
tech: {
type: String,
required: true
},
sub: {
type: Boolean,
required: true,
default: false
}
})
//We need to export the schema
module.exports = mongoose.model('Alien', alienSchema)
|
function HelloWorld() {
alert("Hello World");
}
function Addition() {
let number1 = prompt("Input first number", 0);
let number2 = prompt("Input second number", 0);
if (isNaN(number1) || isNaN(number2)) {
alert("Please enter only numbers !");
} else {
const resultContainer = document.querySelector("#additionResult");
resultContainer.innerHTML = "Result : " + number1 + "+" + number2 + " = " + (Number(number1) + Number(number2));
}
}
function displayArray(container, arrayToDisplay) {
const table = document.createElement("table");
const row = document.createElement("tr");
for (let i = 0; i < arrayToDisplay.length; i++) {
const cell = document.createElement("td");
cell.appendChild(document.createTextNode(arrayToDisplay[i]));
row.appendChild(cell);
}
table.appendChild(row);
container.appendChild(table);
}
function ArrayOfNumberExercice(arrayLength) {
if (arrayLength < 0) {
return;
}
const arrayOfNumber = Array(arrayLength);
for (let i = 0; i < arrayLength; i++) {
let correctInput = false;
while (!correctInput) {
let number = prompt("Input number n°" + (i + 1));
if (isNaN(number)) {
alert("Please enter only numbers !");
} else {
correctInput = true;
arrayOfNumber[i] = number;
}
}
}
const resultContainer = document.querySelector("#arrayResult");
resultContainer.innerText = ""; // Cleaning of resultContainer
resultContainer.appendChild(document.createTextNode("Unsorted array"));
displayArray(resultContainer, arrayOfNumber);
arrayOfNumber.sort();
resultContainer.appendChild(document.createTextNode("Sorted array"));
displayArray(resultContainer, arrayOfNumber);
}
|
/*
* Copyright 2014 Jabil
*/
jQuery.sap.require("com.jabil.maestro.mob.util.Helper");
jQuery.sap.require("com.jabil.maestro.mob.util.Global");
jQuery.sap.require("com.jabil.maestro.mob.util.MainViewHelper");
jQuery.sap.require("com.jabil.maestro.mob.util.ShortagesHelper");
sap.ui.controller("com.jabil.maestro.mob.view.Main", {
/**
* Called when a controller is instantiated and its View controls (if available) are already created.
* Can be used to modify the View before it is displayed, to bind event handlers and do other one-time initialization.
*/
onInit : function (evt) {
},
/**
* Similar to onAfterRendering, but this hook is invoked before the controller's View is re-rendered
* (NOT before the first rendering! onInit() is used for that one!).
*/
// onBeforeRendering: function() {
//
// },
/**
* Called when the View has been rendered (so its HTML is part of the document). Post-rendering manipulations of the HTML could be done here.
* This hook is the same one that SAPUI5 controls get after being rendered.
*/
onAfterRendering: function() {
//initialize
loadTabImages();
selectTab(selView,true);
//set this week default and disable this week
sap.ui.getCore().byId("thisWeek").setEnabled(false);
//load sites
loadSites();
},
/**
* Called when the Controller is destroyed. Use this one to free resources and finalize activities.
*/
onExit : function () {
},
/**
* Called when Weekly navigation button is pressed
*/
handleWeekNav: function(evt){
isCurrentWeek = this.getId() == "thisWeek";
if(isCurrentWeek){
sap.ui.getCore().byId("lastWeek").setEnabled(true);
sap.ui.getCore().byId("thisWeek").setEnabled(false);
}else{
sap.ui.getCore().byId("thisWeek").setEnabled(true);
sap.ui.getCore().byId("lastWeek").setEnabled(false);
}
refreshSelectedChart();
//set flag to load next chart on swipe
loadDataAtSwipe = true;
},
//Called when user pulls to refresh
handleRefresh: function(evt){
refreshSelectedChart();
this.hide();
},
/**
* Called when User navigates between different charts
*/
handleOTDPageChange : function(evt){
//get the selected chart
selectedChart = this.getActivePage();
selectedChart = selectedChart.substring(0,selectedChart.length-3)
//set nav buttons for Weekly and Achievable charts
switch(selectedChart){
case "dailyOTDChart" :
sap.ui.getCore().byId("lastWeek").setVisible(false);
sap.ui.getCore().byId("thisWeek").setVisible(false);
break;
case "weeklyOTDChart" :
{
sap.ui.getCore().byId("lastWeek").setVisible(true);
sap.ui.getCore().byId("thisWeek").setVisible(true);
if($("#weeklyOTDChart").highcharts() == null || loadDataAtSwipe){
loadWeeklyOTDChart(getWeekStartDate(isCurrentWeek,true));
}
break;
}
case "achivableOTDChart" :
{
sap.ui.getCore().byId("lastWeek").setVisible(true);
sap.ui.getCore().byId("thisWeek").setVisible(true);
if($("#achivableOTDChart").highcharts() == null || loadDataAtSwipe){
loadAchOTDChart(getWeekStartDate(isCurrentWeek,true));
}
break;
}
}
loadDataAtSwipe = false;
},
/**
* Called when user navigtes back to home page
*/
handleNavHome : function (evt) {
var nav = sap.ui.getCore().byId("Main").getController().nav;
nav.back("Home");
},
//Called when user press the site DD button
handleSiteDDPress: function(evt){
if(siteDialog != null && siteDialog.getButtons().length == 1){
var confirmBtMain = new sap.m.Button("confirmBtMain",{text:"Confirm",press:sap.ui.getCore().byId("Main").getController().handleSiteSelection, width:"100%"});
siteDialog.addButton(confirmBtMain);
sap.ui.getCore().byId("confirmBtHome").setVisible(false);
}
openSiteDialog();
},
/**
* Called when Site is selected.
*/
handleSiteSelection: function(oEvent) {
//get user site and site text and close the dialog
//get user site and site text and close the dialog
$.each(sap.ui.getCore().byId("siteDialog").getContent()[0].getItems(),function(id,obj){
if(obj.getSelected()){
userSite= this.getTooltip();
userSiteTxt=this.getText().split("-")[0].trim();
sap.ui.getCore().byId("siteDDButton").setText(userSiteTxt);
}
});
this.getParent().close();
//update user site
updateSite(userSite,true);
},
/**
* Called when Logoff is pressed.
*/
handleLogoff: function(oEvent) {
logoff("Home");
},
/**
* Called when user search for materials
*/
searchOrder: function(evt){
var query = evt.getParameter("query");
if(query.length>0){
orderLookup(query);
}
},
/**
* Called when Weekly navigation button is pressed
*/
filterMaterials: function(evt){
var like = evt.getParameter("newValue");
var oFilter = new sap.ui.model.Filter("MATERIAL",
sap.ui.model.FilterOperator.StartsWith,
like);
var listBinding = sap.ui.getCore().byId("materialList").getBinding("items");
listBinding.filter([oFilter]);
},
/**
* Called when user search for materials
*/
searchMaterials: function(evt){
var query = evt.getParameter("query");
if(query.length==0){
loadMaterialShortagesList();
}else{
materialLookup(query);
}
},
/*
* called when user select the list item in material shortages list
*/
handleMSListSelect: function(evt){
if (!(navMat== this.getTitle() && navSite == this.getTooltip())){
loadMatShotageDetails(this.getTitle(),this.getTooltip());
}
navMat= this.getTitle();
navSite = this.getTooltip();
sap.ui.getCore().byId("msDetContent").setVisible(true);
sap.ui.getCore().byId("msBtContent").setVisible(false);
},
/*
* called when user clicks on follow
*/
handleFollow: function(evt){
if(this.getText() == "Follow"){
var matText = this.getParent().getParent().getItems()[0].getItems()[0];
followMaterial(matText.getText(),matText.getTooltip(),this);
}else {
var matList = evt.getSource().getParent();
unFollowMaterial(matList.getSwipedItem().getTitle(),matList.getSwipedItem().getTooltip());
matList.swipeOut();
}
},
//Called when user press back button on MSDetail screen
handleMSDetBack: function(evt){
sap.ui.getCore().byId("msDetContent").setVisible(false);
sap.ui.getCore().byId("msBtContent").setVisible(true);
},
/**
* Called when user clicks on filter button
*/
changeSelect: function(evt){
if (buDialog == null) {
buDialog = getBUDialog("Main");
}
buDialog.open();
},
/*
* called when user select the BU drop down
*/
handleBUSelection: function(evt){
selectedBU= evt.getParameter("selectedItem").getTitle();
if (selectedBU.length >0) {
sap.m.MessageToast.show("Filter LTC by BU : " + selectedBU);
}
// selected is All clear selectedBU for all BU data
selectedBU=selectedBU=="All"?"":selectedBU;
loadLTCChart(getWeekStartDate(isCurrentWeek,true),selectedBU);
},
/**
Called when user search BU in the dialog
*/
handleBUSearch : function(evt){
var sValue = evt.getParameter("value");
var oFilter = new sap.ui.model.Filter("BUSINESS_UNIT", sap.ui.model.FilterOperator.Contains, sValue);
var oBinding = evt.getSource().getBinding("items");
oBinding.filter([oFilter]);
}
});
|
var http = require("http");
var fs = require("fs");
var qs = require("querystring");
var util = require("util");
var maxAcceptedLength = 4 * 1024; // 4KB
function sendForm(res) {
fs.readFile("form.html", function(error, data) {
if (error) {
console.log(error.message);
res.writeHead(400);
res.end();
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
}
function receiveData(req, res) {
var data = "";
var length = 0;
req.on("data", function(chunk) {
length += chunk.length;
if (length > maxAcceptedLength) {
this.destroy();
return;
}
data += chunk;
})
.once("end", function() {
if (length > maxAcceptedLength) {
res.writeHead(413);
res.end("Request Entity Too Large");
return;
}
if (!data) {
res.end();
return;
}
var dataObj = qs.parse(data);
console.log(data);
console.dir(dataObj);
res.end(util.inspect(dataObj));
});
}
var server = http.createServer(function(req, res) {
if (req.method === "GET") sendForm(res);
else if (req.method === "POST") receiveData(req, res);
})
.listen(1010, function() {
console.log("Server started, listening on port " + server.address().port);
});
|
<!--
/**
* Codilar_Irp extension
* NOTICE OF LICENSE
*
*
* @category Codilar
* @package Codilar_Afbt
* @copyright Copyright (c) 2019
*/
-->
define(['jquery', 'underscore', 'owlCarousel'], function ($, _, owlCarousel) {
return function (config) {
var Irp = {
fetchUrl: config.irpFetchUrl,
parentProductId: config.product_id,
init: function () {
var self = this;
self.getRelatedProducts();
},
getRelatedProducts: function () {
var self = this;
$.ajax({
url: self.fetchUrl,
method: "POST",
data: {product_id: self.parentProductId},
success: function (response) {
if (response.status) {
require([
"text!"+require.toUrl("Codilar_Irp/template/irp_cards.html")
], function (template) {
template = _.template(template);
$(".irp-container").html(template({
productsData: response.products
}));
var owl = $("#related-carousel-blog");
owl.owlCarousel({
loop: false,
nav: true,
margin: 15,
navText: ['<div class="left-arrow">', '<div class="right-arrow">'],
responsive: {
0: {
items: 2,
margin: 0
},
600: {
items: 2,
margin: 0
},
1000: {
items: 5
}
}
});
checkClasses();
owl.on('translated.owl.carousel', function (event) {
checkClasses();
});
function checkClasses() {
var total = $('.fbt-container .owl-stage .owl-item.active').length;
$('.fbt-container .owl-stage .owl-item').removeClass('lastActiveItem');
$('.fbt-container .owl-stage .owl-item.active').each(function (index) {
if (index === total - 1 && total > 1) {
// this is the last one
$(this).addClass('lastActiveItem');
}
});
}
});
} else {
$(".irp-container").html("");
}
}
});
}
};
/** initialize the irp widget */
Irp.init();
};
});
|
let postfixstr;
let answ= "";
const readline = require('readline');
const rl = readline.createInterface({input: process.stdin,output: process.stdout});
//Function for assigning weights to operators.
function prec(ch){
switch(ch){
case '+' : return 1;
case '-' : return 1;
case '*' : return 2;
case '/' : return 2;
case '%' : return 2;
case 'POW' : return 3;
case '(' : return 0;
default : return -1;
}};
//Function for determining operator precedence.
function hashigherprec(op1,op2){
let op1W = prec(op1);
let op2W = prec(op2);
return (op1W <= op2W) ? true : false;
};
//Function to convert infix to postFix.
function convert(answ){
postfixstr = '';
let operandstack=[];
let postfixQ= [];
let r;
let infixstr = answ;
console.log('Entered Infix Expression is:', answ);
let infixQ = infixstr.split(" ");
while( infixQ.length > 0)
{
r = infixQ[0];
if(r>= 0 && r <= 999999999){
r = parseFloat(infixQ[0]);
}
infixQ.splice(0,1);
if(r>= 0 && r <= 999999999){ // 1
postfixQ.push(r);
} else if (operandstack.length == 0){ //2
operandstack.push(r);
} else if (r== '('){ //3
operandstack.push(r);
} else if (r == ')'){ //4
let s = operandstack.pop();
operandstack.push(s);;
while (s !=='(')
{
postfixQ.push(operandstack.pop());
s = operandstack.pop();
operandstack.push(s);
}
operandstack.pop();
}
else //5
{
let q = operandstack.pop();
operandstack.push(q);
while(operandstack.length > 0 && q !=="(" && hashigherprec(r,q))
{
postfixQ.push(q);
operandstack.pop();
q = operandstack.pop();
operandstack.push(q);
}
operandstack.push(r);
}
}
while(operandstack.length>0)
{
postfixQ.push(operandstack.pop());
}
postfixstr = postfixQ.join(" ");
console.log('postfix expression of entered infix expression is: ', postfixQ.join(" "));
solve(postfixstr);};
//Funcytion to read input
function infix (){
rl.question('Enter quit to end the program or Please input your infix math problem: ', answ => {
if(answ === 'quit' ){
rl.close();
}
else {
convert (answ);
}
});
};
//Function to solve the postfix expression
function solve (postfixstr){
let postfix = postfixstr;
let t =[];
let resultstack = [];
let result
let splitpostfix = postfix.split(" ");
while(splitpostfix.length > 0)
{
t = splitpostfix[0];
if(t>= 0 && t <= 999999999){
t = parseFloat(splitpostfix[0]);
}
splitpostfix.splice(0,1);
if(t>= 0 && t <= 999999999)
{
resultstack.push(t);
}
else
{
let a = resultstack.pop();
let b = resultstack.pop();
switch ( t )
{
case '+': result = parseFloat(b)+parseFloat(a) ; break;
case '-': result = parseFloat(b)-parseFloat(a) ; break;
case '*': result = parseFloat(b)*parseFloat(a) ; break;
case '/': result = parseFloat(b)/parseFloat(a) ; break;
case '%': result = parseFloat(b)%parseFloat(a) ; break;
case 'POW': result = Math.pow(parseFloat(b),parseFloat(a)) ; break;
}
resultstack.push(result);
}
}
let finalresult = resultstack[0];
console.log('solution of entered Infix Expression is: ',finalresult);
evaluate();};
//Start the program
function evaluate(){
infix();
};
evaluate();
|
/**
* Created by jiayi.hu on 5/26/17.
* 废弃代码
*/
import React, { Component } from 'react'
import promiseXHR from '../../funStore/ServerFun'
import AuthProvider from '../../funStore/AuthProvider'
import $ from 'jquery'
import TagList from './TagList'
import TagInput from './TagInput'
import BubbleCheck from './BubbleCheck'
import {API_PATH} from '../../constants/OriginName'
export default class BubbleTag extends Component {
static propTypes = {
}
constructor(props){
super(props)
this.state = {
labelid:'',
inputFlag:'none'
}
}
handleSubmitTag(id,tagName){
const reg = /\ud83c[\udf00-\udfff]|\ud83d[\udc00-\ude4f]|\ud83d[\ude80-\udeff]/g
if(reg.test(tagName)) this.filterEmojiHandle();
tagName = tagName.replace(reg,'')
if(tagName == '') return
const actions = this.props.actions
if(this.props.type=='GROUP'){
const url = API_PATH+'/groupadmin-api/authsec/groupadmin/group/'+id+'/label'
AuthProvider.getAccessToken()
.then((resolve,reject)=>{
promiseXHR(url,{type:'Bearer',value:resolve},{'name':tagName},'POST')
.then((res) =>{
let data = JSON.parse(res)
if(data.resultCode==100){
actions.addGroupTag(id,[data.resultContent])
}
})
})
}else if(this.props.type == 'USER'){
const url = API_PATH+'/groupadmin-api//authsec/groupadmin/group/'+this.props.groupId+'/member/'+id+'/label'
AuthProvider.getAccessToken()
.then((resolve,reject)=>{
promiseXHR(url,{type:'Bearer',value:resolve},{'name':tagName},'POST')
.then((res) =>{
let data = JSON.parse(res)
if(data.resultCode==100){
actions.addMemberTag(id,[data.resultContent])
}
})
})
}
}
handleDeleteTag(labelid) {
this.setState({
labelid:labelid
})
this.props.showFlagHandle('block')
}
handleCancel(){
this.props.showFlagHandle('none')
this.props.featureTypeHandle('')
}
handleSure(){
this.props.showFlagHandle('none')
this.props.featureTypeHandle('')
}
handleAddInput(){
this.setState({
inputFlag:'block'
})
}
handleAddCancel(){
this.setState({
inputFlag: 'none'
})
}
filterEmojiHandle () {
this.props.showFlagHandle('block')
this.props.featureTypeHandle('EMOJI')
}
render(){
let {inputFlag,labelid} = this.state
let {id,type,groupList,memberList,groupId,actions,featureType,showFlag,removeTagBox} = this.props
let labelList
if(type=='GROUP'){
labelList = groupList.listData.find((item)=>item.id==id).labelList
}else if(type=='USER'){
labelList = memberList.listData.find((item)=>item.id==id)?memberList.listData.find((item)=>item.id==id).labelList:[]
}
let tagInput = inputFlag=='block'?
<TagInput
onSubmit={this.handleSubmitTag.bind(this)}
handleAddCancel={this.handleAddCancel.bind(this)}
id={id}
labelList={labelList}
/>:null
return(
<div className='TagWrapper'>
<BubbleCheck
id={id}
labelid={labelid}
groupId={groupId}
style={showFlag}
onCancel={this.handleCancel.bind(this)}
onSure={this.handleSure.bind(this)}
type={type}
deleteGroupTag={actions.deleteGroupTag}
deleteMemberTag={actions.deleteMemberTag}
removeMember={actions.removeMember}
featureType={featureType}
removeTagBox={removeTagBox}
actions={actions}/>
<TagList tagName={labelList}
onDelete={this.handleDeleteTag.bind(this)}
onAdd={this.handleAddInput.bind(this)}
addFlag={inputFlag}
type={type}
/>
{tagInput}
</div>
)
}
}
|
import { MEISTER_DATA_STANDARD_ATTR } from './constants';
import { extractNodesWithSelector, replaceNodeWith, formatValue } from './utilities';
import createStandardElement from '../standard/createStandardElement';
/**
* Returns a list of all child nodes that have meister standard data properties.
* @memberof module:CustomUi
* @param {HTMLElement} rootNode The root node from which to search for relevant nodes.
* @return {HTMLElement[]} Array with nodes that have the meister standard data property.
*/
export function extractStandardNodes(rootNode) {
return extractNodesWithSelector(rootNode, `[${MEISTER_DATA_STANDARD_ATTR}]`);
}
/**
* Create a function that can be used to replace nodes with Standard Ui elements.
* @memberof module:CustomUi
* @param {Meister} meister Meister instance to be used in the event callbacks.
* @param {Object} [config={}] StandardUi config to be used when creating standard components.
* @return {module:CustomUi~loadStandardElement} Function that can be used to replace nodes with Standard Ui elements.
*/
export function createLoadStandardElement(meister, config = {}) {
/**
* Replace nodes with the Standard Ui element specified in MEISTER_DATA_STANDARD_ATTR.
* @function module:CustomUi~loadStandardElement
* @param {HTMLElement} domNode Node with data-mstr-standard that should be replaced with a Standard Ui element.
*/
return function loadStandardElement(domNode) {
const elementName = formatValue(domNode.getAttribute(MEISTER_DATA_STANDARD_ATTR));
if (!elementName) { return; }
const standardElement = createStandardElement(meister, config, elementName);
if (!standardElement) {
console.error(`No standard element with name '${elementName}'`);
}
replaceNodeWith(domNode, standardElement.getNode());
};
}
|
import React from 'react'
import { connect } from 'dva'
import { table } from 'antd'
const columns = [
{
title: 'ss',
dataIndex: 'name',
}, {
title: 'yy',
dataIndex: 'id',
},
]
const data = []
function Demo () {
return (<div>
<table columns={columns} datasource={data} />
</div>
)
}
export default connect()(Demo)
|
(function() {
'use strict';
// TODO refactor this app into two components: an app component and a videoDetail component
// see https://docs.angularjs.org/guide/component for help
// 1. Create an app component that has a controller similar to the VideoListController - put template in app.html
// 2. Create a videoDetail component which is responsible for rendering a single video - put template in videoDetails.html
// 3. Change index.html to use the app component
// 4. For bonus points, extract a search component from the app component and use output parameters on that to have app component orchestrate search and render
angular.module('myApp', []).controller('VideoListController', function($http, $log) {
var ctrl = this;
ctrl.query = 'Rick Astley';
ctrl.search = function() {
return $http.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=20&type=video&q=' + ctrl.query + '&key=AIzaSyD4YJITOWdfQdFbcxHc6TgeCKmVS9yRuQ8')
.then(function(res) {
$log.info(res.data.items);
ctrl.videos = res.data.items.map(function (v) {
var snip = v.snippet;
return {
title: snip.title,
description: snip.description,
thumb: snip.thumbnails.medium.url,
link: 'https://www.youtube.com/watch?v=' + v.id.videoId
};
});
});
};
ctrl.search();
});
})();
|
import React, { PureComponent } from 'react';
import { View, KeyboardAvoidingView, TextInput } from 'react-native';
import PostMeta from './postMeta';
import styles from './styles';
import NavButton from './navButton';
import AddToPost from './addToPost';
class PostCreationScreen extends PureComponent {
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
return {
title: 'Create Post',
headerLeft: <NavButton onPress={() => navigation.goBack(null)}>Cancel</NavButton>,
headerRight: <NavButton onPress={params.handlePressPost}>Post</NavButton>,
};
};
state = {
statusText: '',
};
componentDidMount() {
this.props.navigation.setParams({
handlePressPost: this.handlePressPost,
});
}
handlePressPost = () => {
console.log('cancelled called');
};
render() {
return (
<KeyboardAvoidingView
style={styles.container}
behavior="padding"
keyboardVerticalOffset={100}
>
<View style={styles.statusContainer}>
<PostMeta avatar={require('../../assets/img/default_avatar.png')} author="Bilal" />
<TextInput
multiline
numberOfLines={4}
onChangeText={t => this.setState({ statusText: t })}
value={this.state.statusText}
placeholder="Write something...."
placeholderTextColor="grey"
autoCorrect={false}
autoFocus
returnKeyType="done"
style={styles.textInput}
/>
</View>
<AddToPost />
</KeyboardAvoidingView>
);
}
}
export default PostCreationScreen;
|
/* eslint-disable no-unused-vars */
/**
* Gets the repositories of the user from Github
*/
import { call, put, select, takeLatest } from 'redux-saga/effects';
import { LOAD_REPOS } from 'containers/App/constants';
import { reposLoaded, repoLoadingError } from 'containers/App/actions';
import { post } from 'axios';
import request from 'utils/request';
import {
makeSelectUsername,
makeInputFile,
} from 'containers/HomePage/selectors';
import { SUBMIT_FILE_URL } from './constants';
/**
* Github repos request/response handler
*/
export function* getRepos() {
// Select username from store
const username = yield select(makeSelectUsername());
const requestURL = `https://api.github.com/users/${username}/repos?type=all&sort=updated`;
try {
// Call our request helper (see 'utils/request')
const repos = yield call(request, requestURL);
yield put(reposLoaded(repos, username));
} catch (err) {
yield put(repoLoadingError(err));
}
}
export function* upload() {
const url = 'http://localhost:3000/uploadImageorVideo';
const fileupload = yield select(makeInputFile());
const formdata = new FormData();
formdata.append('file', fileupload, fileupload.name);
const option = {
headers: {
'Content-Type': 'multipart/form-data',
},
filename: fileupload.name,
};
post(url, formdata, option);
}
/**
* Root saga manages watcher lifecycle
*/
export default function* githubData() {
// Watches for LOAD_REPOS actions and calls getRepos when one comes in.
// By using `takeLatest` only the result of the latest API call is applied.
// It returns task descriptor (just like fork) so we can continue execution
// It will be cancelled automatically on component unmount
yield takeLatest(LOAD_REPOS, getRepos);
yield takeLatest(SUBMIT_FILE_URL, upload);
}
|
const Engineer = require('../engineer')
describe('adding a git name',()=>{
it('Should store a github user using the constructor',()=>{
const testVal = 'markogit';
const testGuy = new Engineer('Marko',888,'email@email.com',testVal);
expect(testGuy.github).toBe(testVal);
});
});
describe('getGithub',()=>{
it('Should return github user with function',()=>{
const testVal = 'markogit';
const testGuy = new Engineer('Marko',888,'email@email.com',testVal);
expect(testGuy.getGithub()).toBe(testVal);
});
});
describe('getRole',()=>{
it('Should return the role with function',()=>{
const testVal = 'Engineer';
const testGuy = new Engineer('Marko',888,'email@email.com','markogit');
expect(testGuy.getRole()).toBe(testVal);
});
});
|
const REGEXP = /^[\s]*|[\s]*$/g;
//trim() regex
// const str = " Hello World "
// // "Hello World"
// const str = " We need more space "
// // "We need more space"
|
import React, { useState } from "react";
import { Button, Col, Container, Form } from "react-bootstrap";
import { useStateValue } from "./StateProvider";
import { db } from "../firebaseConfig";
import { ToastContainer, toast } from "react-toastify";
import "../../node_modules/react-toastify/dist/ReactToastify.css";
import { CopyToClipboard } from "react-copy-to-clipboard";
const FormDetail = () => {
const [state, dispatch] = useStateValue();
const [hid, setHid] = useState(true);
const [copied, setCopied] = useState(false);
const [uid, setUid] = useState("");
const [cardInfo, setCardInfo] = useState({ ...state });
// console.log(state);
const senderHandle = (e) => {
// e.preventDefault();
setCardInfo({ ...cardInfo, sender: e.target.value });
// console.log(sender);
};
const receiverHandle = (e) => {
setCardInfo({ ...cardInfo, receiver: e.target.value });
};
const qouteHandle = (e) => {
setCardInfo({ ...cardInfo, qoute: e.target.value });
};
const submit = (e) => {
e.preventDefault();
setHid(false);
dispatch({ type: "ADD_TO_DB", item: cardInfo });
db.collection("Cards")
.add({ ...cardInfo })
.then((docRef) => {
toast.success(`Your Card info is stored with id: ${docRef.id}`, {
position: "bottom-right",
});
setUid(docRef.id);
})
.catch((error) => {
console.error("Error adding document: ", error);
});
// console.log(state);
// add data to fireStore and redirect to path=/uid
};
const handleGen = () => {
setHid(true);
setCopied(false);
};
return (
<>
<Container
style={{
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<Col
style={{ display: !hid ? "block" : "none" }}
className="text-center"
>
<input
type="text"
value={`https://holi-cards.web.app/cards/${uid}`}
disabled
/>
<CopyToClipboard text={`https://holi-cards.web.app/cards/${uid}`}>
<Button onClick={() => setCopied(true)}>Copy</Button>
</CopyToClipboard>
<p style={{ display: copied ? "block" : "none", color: "red" }}>
{" "}
Copied!!
</p>
<br></br>
<br></br>
<Button style={{ padding: 15 }} onClick={handleGen}>
Generate Another
</Button>
</Col>
</Container>
<Form onSubmit={submit} style={{ display: hid ? "block" : "none" }}>
<Form.Group controlId="formBasicSender" onChange={senderHandle}>
<Form.Label>Sender</Form.Label>
<Form.Control type="text" placeholder="Sender's name" />
</Form.Group>
<Form.Group controlId="formBasicReveiver" onChange={receiverHandle}>
<Form.Label>Receiver</Form.Label>
<Form.Control type="text" placeholder="Receiver's name" />
</Form.Group>
<Form.Group controlId="formBasicReveiver" onChange={qouteHandle}>
<Form.Label>Quote</Form.Label>
<Form.Control type="text-area" placeholder="Message" />
</Form.Group>
<Button variant="primary" type="submit">
Generate
</Button>
</Form>
<ToastContainer />
</>
);
};
export default FormDetail;
|
const finalPOsition = function(moves) {
let position = [0, 0];
for (let i = 0; i < moves.length; i++) {
if (moves[i] === "north") {
position[1] += 1;
} else if (moves[i] === "south") {
position[1] -= 1;
} else if (moves[i] === "east") {
position[0] += 1;
} else if (moves[i] === "west") {
position[0] -= 1;
}
}
return position;
}
|
function orders_clear()
{
window.localStorage.clear();
}
function recast()
{
var x = 'Cart is empty!';
$('#ordertable').text(x);
window.localStorage.clear();
button_update();
}
function orders_input()
{
var orders = orders_list();
$('#orders_input').val(orders);
}
function button_update()
{
var text = 'Cart' + ' ' + '(' + items_in_cart() + ')';
$('#cart_btn').val(text);
}
function orders_list()
{
var list = '';
for(var i=0; i < localStorage.length; i++)
{
var key = localStorage.key(i); //localStorage.key = key , localStorage[key] = value
var list = list + localStorage.key(i) + '=' + localStorage[key] + ',';
}
return list;
}
function items_in_cart()
{
var total = 0;
for(var i=0; i < localStorage.length; i++)
{
var key = localStorage.key(i);
var total = total*1 + localStorage[key]*1;
}
return total;
}
function orders_output_database()
{
var orders = orders_list();
$('#orderdata').val(orders);
button_update();
}
function table_orders_insert()
{
var code_insert=document.getElementById("orders_table");
for (var i=0; i < localStorage.length; i++)
{
var key = localStorage.key(i);
code_insert.innerHTML += "<tr><td>" + localStorage.key(i) + "</td><td>" + localStorage[key] + "</td></tr>";
}
}
|
import React, { useEffect, useState } from 'react'
import Title from '../text/Title'
import Button from '../button/ButtonSmall'
import Close from '../icon/Close'
const Modal = ({ title, children, confirm, cancel, width = 600, hub }) => {
const [visible, setVisible] = useState(false)
useEffect(() => {
setVisible(true)
const c = e => {
if (e.keyCode === 13) {
hub.set('device.overlay', false)
if (typeof confirm === 'function') {
confirm(e)
} else if (confirm.onConfirm) {
confirm.onConfirm(e)
}
}
}
if (confirm) {
document.addEventListener('keydown', c)
}
return () => {
if (confirm) {
document.removeEventListener('keydown', c)
}
}
}, [confirm])
const footer =
confirm || cancel ? (
<div
style={{
marginTop: 20,
display: 'flex',
justifyContent: 'flex-end'
}}
>
{cancel ? (
<Button
onClick={e => {
hub.set('device.overlay', false)
if (typeof cancel === 'function') {
cancel(e)
} else if (typeof cancel === 'object' && cancel.onCancel) {
cancel.onCancel(e)
}
}}
>
{(typeof cancel === 'object' && cancel.title) || 'Cancel'}
</Button>
) : null}
{confirm ? (
<Button
style={{ marginLeft: 10 }}
onClick={e => {
hub.set('device.overlay', false)
if (typeof confirm === 'function') {
confirm(e)
} else {
confirm.onConfirm(e)
}
}}
>
{confirm.title || 'Confirm'}
</Button>
) : null}
</div>
) : null
return (
<div
style={{
backgroundColor: 'white',
boxShadow: 'rgba(0,0,0,0.1) 0px 0px 40px',
width,
maxWidth: 'calc(100%-100px)',
height: 'auto',
maxHeight: 'calc(100%-100px)',
borderRadius: 4,
padding: 30,
opacity: visible ? 1 : 0,
transition: 'opacity 0.3s, transform 0.15s',
transform: visible ? 'scale(1)' : 'scale(0.9)'
}}
>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
marginBottom: children ? 10 : 0
}}
>
{title ? (
<Title
style={{
color: 'black'
}}
>
{title}
</Title>
) : (
<div />
)}
<Close large onClick={() => hub.set('device.overlay', false)} />
</div>
<div
style={{
display: 'flex',
flexDirection: 'column',
maxHeight: 'calc(100%-200px)'
}}
>
<div
style={{
overflow: 'auto',
height: 'auto',
maxHeight: 'calc(100vh-200px)'
}}
>
{children}
</div>
{footer}
</div>
</div>
)
}
export default (props, children) => {
props.hub.set('device.overlay', {
fade: true,
position: 'center',
component: <Modal {...props}>{children}</Modal>
})
return (nprops, nchildren) => {
props.hub.set('device.overlay', {
component: (
<Modal {...props} {...nprops}>
{nchildren || children}
</Modal>
)
})
}
}
|
const fish = require('./index');
test('calculate surviving fish', () => {
const a = [4,3,2,1,5];
const b = [0,1,0,0,0];
expect(fish(a,b)).toEqual(2);
});
test('calculate surviving fish', () => {
const a = [0,1];
const b = [1,1];
expect(fish(a,b)).toEqual(2);
});
|
import React, { Component } from "react";
import { Text, View, TextInput, StyleSheet, Image } from "react-native";
import { EMAIL_REGEX } from "../helpers/constants";
import { fonts, metrics, colors } from "../themes";
import Button from "../components/common/Button";
import Logo from "../images/logo.png";
import { scale } from "../helpers/functions";
export default class SignIn extends Component {
constructor() {
super();
this.state = {
email: "nazihatalbi@gmail.com",
password: "123456",
mailvalidation: false,
passwordvalidation: false,
emailInput: "",
passwordInput: ""
};
}
validatEmail = emailInput => {
this.setState({
emailInput,
mailvalidation: EMAIL_REGEX.test(emailInput.trim())
});
};
validatepassword = passwordInput => {
this.setState({
passwordInput,
passwordvalidation: passwordInput.length >= 6
});
};
handleLogin = ({ email = this.state.emailInput, password = this.state.passwordInput }) => {
if (email.trim() === this.state.email && this.state.password === password.trim()) {
this.props.navigation.replace("Home");
}
};
render() {
return (
<View style={ViewStyle.container}>
<Image source={Logo} style={Styles.image} />
<Text style={Styles.Title}>Sign In </Text>
<TextInput
style={[Styles.input, !this.state.mailvalidation ? Styles.error : null]}
placeholder="Mail"
onChangeText={this.validatEmail}
/>
<TextInput
secureTextEntry={true}
style={[Styles.input, !this.state.passwordvalidation ? Styles.error : null]}
placeholder="password"
onChangeText={this.validatepassword}
/>
<Button
full={true}
style={Styles.button}
onPress={this.handleLogin}
disabled={!this.state.mailvalidation || !this.state.passwordvalidation}
>
<Text style={Styles.text}>Se Connecter</Text>
</Button>
</View>
);
}
}
const ViewStyle = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center"
}
});
const Styles = StyleSheet.create({
input: {
borderBottomColor: "#000000",
borderBottomWidth: 1,
width: 300
},
Title: {
...fonts.h1,
justifyContent: "center",
alignItems: "center",
color: colors.black,
marginVertical: metrics.baseMargin
},
text: {
...fonts.h1,
color: colors.white
},
image: {
width: scale(200),
height: scale(200),
justifyContent: "center",
alignItems: "center"
},
button: {
borderRadius: 40,
backgroundColor: colors.bleu,
marginVertical: metrics.baseMargin
},
error: {
borderBottomColor: "red",
borderBottomWidth: 2
}
});
|
$(document).ready(function(){
$('a#ajaxjour').click(function(){
alert('okok');
$.ajax({
type: 'get',
beforeSend: function(){
// $('.listehebergements').parent().append('<div class="loading"> </div>');
},
success: function(data){
alert('okok');
}
})
});
});
|
/**
* @param {*} req
* @param {*} res
* @param {*} next
*/
module.exports = async (req, res, next) => {
try {
req.ApiPack.operation.identifiers = req.params;
req.ApiPack.operation.context.filters = req.query;
req.ApiPack.operation.context.query = req.query;
await req.ApiPack.read();
if (!req.ApiPack.operation.data && req.method !== "POST") {
return res.status(404).send({
message: "Not Found"
});
}
next();
} catch(e) {
return res.status(500).send({
message: e.toString()
});
}
};
|
import React from "react";
import styled from "styled-components/native";
import { Text } from "react-native";
import { WIDTH } from "../../../constants/layout";
const SignUpBtn = ({
navigation,
width,
backgroundColor,
height,
marginTop,
fontColor,
text,
handlePressbtn,
}) => {
return (
<NextBtnView>
<NextBtn
style={{
width: +width,
height: +height,
backgroundColor: backgroundColor,
marginTop: +marginTop,
}}
onPress={handlePressbtn}
>
<NextBtnText style={{ color: fontColor }}>{text}</NextBtnText>
</NextBtn>
</NextBtnView>
);
};
export default SignUpBtn;
const NextBtnView = styled.View`
align-items: center;
`;
const NextBtn = styled.Pressable`
align-items: center;
justify-content: center;
border-radius: 10;
`;
const NextBtnText = styled.Text`
color: white;
font-weight: 600;
`;
|
//import liraries
import React from 'react';
import {FaPhone, FaRegWindowClose, FaVideo} from 'react-icons/fa';
// create a component
const ChatBox = () => {
return (
<div className="chat">
<div className="chat__header">
<div className="chat__header-img">
<img src="/Images/Kasalkar.jpg" alt="user" />
</div>
<div className="chat__header-name">
Akash Kasalkr
</div>
<div className="chat__second">
<FaVideo className="chat__header-icons" />
<FaPhone className="chat__header-icons" />
<FaRegWindowClose className="chat__header-icons" />
</div>
</div>
<div className="chat__body">
<div className="chat__left">
<p className="msg">Hi </p>
</div>
<div className="chat__right">
<p className="msg">Hello </p>
</div>
<div className="chat__left">
<p className="msg">How Are you? </p>
</div>
<div className="chat__right">
<p className="msg">I'm fine</p>
</div>
</div>
<div className="chat__footer">
<input type="text" className="chat__input" placeholder="Aa" />
</div>
</div>
);
};
//make this component available to the app
export default ChatBox;
|
import React, { useState, useEffect } from 'react';
import { withRouter } from 'react-router';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';
import { parse } from 'utils/queryString';
import './pagination.scss';
const Pagination = ({ location, limit, totalResults, className, handlePageFilter }) => {
const [pagination, setPagination] = useState([]);
const [currentPage, setCurrentPage] = useState(1);
useEffect(() => {
if (location.search) {
const searchParam = parse(location.search);
const pageNo = parseInt(searchParam.page, 10) + 1;
renderPagination(pageNo);
} else {
renderPagination(1);
}
}, []);
useEffect(() => {
if (location.search) {
const searchParam = parse(location.search);
if (searchParam.page && parseInt(searchParam.page, 10) !== currentPage) {
const pageNo = parseInt(searchParam.page, 10) + 1;
renderPagination(pageNo);
} else {
renderPagination(1);
}
}
}, [currentPage]);
useEffect(() => {
if (location.search) {
const searchParam = parse(location.search);
if (!searchParam.page) {
setCurrentPage(1);
}
} else {
setCurrentPage(1);
}
}, [location.search]);
const renderPagination = (page) => {
const paginationArray = [];
const moreFive = totalResults > limit * 5;
const totalPages = Math.ceil(totalResults / limit);
page = page ? parseInt(page, 10) : 1;
setCurrentPage(page);
new Array(Math.min(5, totalPages)).fill(null).forEach((item, index) => {
let value = index + 1;
if (page > 3 && moreFive) {
if (value === 1) {
value += '..';
} else {
const offset = page >= totalPages - 1 ? (2 - (totalPages - page)) : 0;
value = page + (index - 2 - offset);
}
}
paginationArray.push(value);
});
if (moreFive && totalPages > paginationArray[4]) {
paginationArray.push(`..${totalPages}`);
}
setPagination(paginationArray);
};
const updatePage = (page) => {
const updatedPage = parseInt(page.toString().replace('..', ''), 10);
setCurrentPage(updatedPage);
handlePageFilter('page', updatedPage);
};
return (
<section className={`pagination ${className}`}>
<p className="pagination-tip">
<span className="tip body-text">Viewing</span>
<span className="current-page body-text">{(currentPage * limit) - (limit - 1)} - {Math.min(currentPage * limit, totalResults)}</span>
<span className="tip body-text">of</span>
<span className="total-count body-text">{totalResults} results</span>
</p>
<div className="pagination-controls">
{currentPage > 1 &&
<LeftOutlined className="controller_icon left" onClick={() => updatePage(currentPage - 1)} />
}
<ul>
{pagination.map((value) => <li key={value} className={value === currentPage ? 'Pagination_active' : 'body-text pagination-number'} onClick={() => updatePage(value)}>{value}</li>)}
</ul>
{currentPage * limit < totalResults &&
<RightOutlined disabled className="controller_icon right" onClick={() => updatePage(currentPage + 1)} />
}
</div>
</section>
);
};
export default withRouter(Pagination);
|
// 1.Arithmetic Operators
// 2.Assignment Operators
// 3.Comparison Operators
// 4.Logical Operators
// 5.Membership Operators
// 6.Bitwise Operators
console.log("Arithmetic Operators")
//-----------------1.Arithmetic Operators---------------
console.log("11 + 2=", 11+2)
console.log("11 - 2=", 11-2)
console.log("11 * 2=", 11*2)
console.log("11 / 2=", 11/2)
console.log("11 % 2=", 11%2)
console.log("11**2=", 11**2)
let incrementNumber1=10
let incrementNumber2=10
console.log(incrementNumber1++) // 10
console.log(++incrementNumber2) //11
console.log("Assignment Operators")
//------------------2.Assignment Operators-----------------
let number=10
number +=5
console.log(number)
console.log("Comparison Operators")
//------------------3.Comparison Operators-----------------
console.log( 5<10) //True
console.log( 5>10) //False
console.log(5>=5) //True
console.log(5<=5) //True
let myNumber='500'
let myNumber2=500
console.log(myNumber==myNumber2) //True
console.log(myNumber===myNumber2) //False
console.log(myNumber !==myNumber2) //True
console.log("Logical Operators")
//------------------4.Logical Operators-----------------
let num1=5
let num2=6
console.log(num1 >10 && num2<10) //False
console.log(num1 >10 || num2<10) //True
console.log("Membership Operators")
//------------------5.Membership Operators---------------
let myArray=[1,2,3,4,5]
console.log(2 in myArray) //True
console.log(8 in myArray) //False
console.log("Bitwise operator")
//----------------------6.Bitwise Operators-----------------
//--------------Complement(~)-------------
/*
12 = 00001100
1's complement = 11110011 (-12)
+1
---------------------------
2's complement = 11110100
13 = 00001101
1's complement = 11110010 (-13)
+1
---------------------------
2's complement = 11110011 which is 1's complement of 12
hence complement of 12 (~12)= -13
*/
console.log(~12) // -13
//---------------Bitwise and (&)-------------
/*
0 & 0 = 0
0 & 1 = 0
1 & 0 = 0
1 & 1 = 1
12 & 13= 12
12 = 00001100
13 = 00001101
---------------
= 00001100 =12
*/
console.log(12 & 13) //12
//--------------Bitwise or (|)----------------
/*
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
12 | 13= 13
12 = 00001100
13 = 00001101
---------------
= 00001101 =13
*/
console.log(12 | 13) //13
//--------------------XOR(^)------------------
/*
XOR(^) as like family home rent where bachelor not allowed
if we think 0=female and 1=male
0 ^ 0 = 0 (female+female= not allowed)
0 ^ 1 = 1 (female+male= allowed)
1 ^ 0 = 1 (male+female= allowed)
1 ^ 1 = 0 (male+male= not allowed)
12 ^ 13 = 1
12 = 00001100
13 = 00001101
---------------
= 00000001 =1
*/
console.log(12^13) // 1
//----------------Left Shift ( << )---------------
/*
12 = 00001100.0000
12<<2= 0000110000.00=48
*/
console.log(12<<2) //48
//----------------Right Shift ( >> )--------------
/*
12 = 00001100.0000
12>>2= 000011.000000=3
*/
console.log(12>>2) //3
|
import request from '@/utils/request'
// 查询课程类型列表
export function listType(query) {
return request({
url: '/course/type/list',
method: 'get',
params: query
})
}
// 查询课程类型详细
export function getType(id) {
return request({
url: '/course/type/' + id,
method: 'get'
})
}
// 新增课程类型
export function addType(data) {
return request({
url: '/course/type',
method: 'post',
data: data
})
}
// 修改课程类型
export function updateType(data) {
return request({
url: '/course/type',
method: 'put',
data: data
})
}
// 删除课程类型
export function delType(id) {
return request({
url: '/course/type/' + id,
method: 'delete'
})
}
// 导出课程类型
export function exportType(query) {
return request({
url: '/course/type/export',
method: 'get',
params: query
})
}
// 查询全部课程类型
export function getTypeList() {
return request({
url: '/course/type/getTypeList',
method: 'get'
})
}
|
const express = require('express');
const router = express.Router();
const {
userRateLimiter,
userSlowDown
} = require('../../../middleware/limitation');
const auth = require('../../../middleware/authentication');
// Models
const User = require('../../../models/User');
const Walk = require('../../../models/Walk');
// @route POST api/dashboard/walks
// @desc Add walk to the family
// @access Private
router.post('/', auth, (req, res) => {
const { dogs, date, time, duration, pee, poop } = req.body;
if (
!dogs ||
!date ||
!time ||
!duration ||
pee === undefined ||
poop === undefined
)
return res
.status(400)
.json({ msg: 'You must enter all mandatory fields!' });
const { user } = req;
User.findOne({ _id: user.id }).then(user => {
if (!user._familyId)
return res.status(400).json({
msg: 'You must have a registered family to be able to add walks'
});
const walk = new Walk({
_familyId: user._familyId,
dogs,
person: user.name,
date,
time,
duration,
pee,
poop
});
walk.save().then(savedWalk =>
res.status(200).json({
newWalk: savedWalk
})
);
});
});
// @route DELETE api/dashboard/walks
// @desc Delete walk from the family
// @access Private
router.delete('/', auth, (req, res) => {
const { user } = req;
const { id } = req.body;
if (!id)
return res.status(400).json({ msg: 'Walk must have an ID for delete' });
User.findOne({ _id: user.id }).then(user => {
if (!user._familyId)
return res.status(400).json({
msg: 'You must have a registered family to be able to delete walks'
});
Walk.findOne({ _id: id }).then(walk => {
if (!walk)
return res.status(200).json({
msg:
'Nothing could be removed since no walk was found with the given ID'
});
if (!walk._familyId.equals(user._familyId)) {
return res
.status(400)
.json({ msg: 'You cannot delete walks from other families' });
}
walk.remove().then(() => {
return res
.status(200)
.json({ msg: `Successfully removed walk`, walkId: walk._id });
});
});
});
});
module.exports = router;
|
/*
* 消息提示模块
* @date:2014-09-05
* @author:kotenei(kotenei@qq.com)
*/
define('km/tooltips', ['jquery'], function ($) {
/**
* 消息提示模块
* @param {JQuery} $element - dom
* @param {Object} options - 参数
*/
function Tooltips($element, options) {
this.$element = $element;
this.options = $.extend(true, {
delay: 0,
content: '',
tipClass: '',
placement: 'right',
trigger: 'hover click',
container: $(document.body),
type: 'tooltips',
scrollContainer: null,
tpl: '<div class="k-tooltips">' +
'<div class="k-tooltips-arrow"></div>' +
'<div class="k-tooltips-inner"></div>' +
'</div>'
}, options);
this.init();
};
/**
* 初始化
* @return {Void}
*/
Tooltips.prototype.init = function () {
var self = this;
this.$tips = $(this.options.tpl);
this.$tips.addClass(this.options.placement).addClass(this.options.tipClass);
this.$container = $(this.options.container);
this.setContent();
this.isShow = false;
var triggers = this.options.trigger.split(' ');
for (var i = 0, trigger; i < triggers.length; i++) {
trigger = triggers[i];
if (trigger === 'click') {
this.$element.on(trigger + "." + this.options.type, $.proxy(this.toggle, this));
} else if (trigger != 'manual') {
var eventIn = trigger === 'hover' ? 'mouseenter' : 'focus';
var eventOut = trigger === 'hover' ? 'mouseleave' : 'blur';
this.$element.on(eventIn + "." + this.options.type, $.proxy(this.show, this));
this.$element.on(eventOut + "." + this.options.type, $.proxy(this.hide, this));
}
}
if (this.$container[0].nodeName !== 'BODY') {
this.$container.css('position', 'relative')
}
this.$container.append(this.$tips);
//if (this.options.scrollContainer) {
// $(this.options.scrollContainer).on('scroll.' + this.options.type, function () {
// });
//}
$(window).on('resize.' + this.options.type, function () {
self.setPosition();
});
this.hide();
};
/**
* 设置内容
* @param {String} content - 内容
*/
Tooltips.prototype.setContent = function (content) {
content = $.trim(content || this.options.content);
if (content.length === 0) {
content = this.$element.attr('data-content') || "";
}
var $tips = this.$tips;
$tips.find('.k-tooltips-inner').html(content);
};
/**
* 定位
*/
Tooltips.prototype.setPosition = function () {
var pos = this.getPosition();
this.$tips.css(pos);
};
/**
* 获取定位偏移值
* @return {Object}
*/
Tooltips.prototype.getPosition = function () {
var placement = this.options.placement;
var container = this.options.container;
var $element = this.$element;
var $parent = $element.parent();
var $tips = this.$tips;
var ew = $element.outerWidth();
var eh = $element.outerHeight();
var tw = $tips.outerWidth();
var th = $tips.outerHeight();
var position = { left: 0, top: 0 };
var parent = $element[0];
var ret;
do {
position.left += parent.offsetLeft - parent.scrollLeft;
position.top += parent.offsetTop - parent.scrollTop;
} while ((parent = parent.offsetParent) && parent != this.$container[0]);
switch (placement) {
case 'left':
ret = { top: position.top + eh / 2 - th / 2, left: position.left - tw };
break;
case 'top':
ret = { top: position.top - th, left: position.left + ew / 2 - tw / 2 };
break;
case 'right':
ret = { top: position.top + eh / 2 - th / 2, left: position.left + ew };
break;
case 'bottom':
ret = { top: position.top + eh, left: position.left + ew / 2 - tw / 2 };
break;
}
return ret;
};
/**
* 显示tips
* @return {Void}
*/
Tooltips.prototype.show = function () {
if ($.trim(this.options.content).length === 0) {
this.hide();
return;
}
this.isShow = true;
this.setPosition();
this.$tips.show().addClass('in');
this.setPosition();
};
/**
* 隐藏tips
* @return {Void}
*/
Tooltips.prototype.hide = function () {
this.isShow = false;
this.$tips.hide().removeClass('in');
};
/**
* 切换
* @return {Void}
*/
Tooltips.prototype.toggle = function () {
if (this.isShow) {
this.hide();
} else {
this.show();
}
};
/**
* 销毁
* @return {Void}
*/
Tooltips.prototype.destroy = function () {
this.$tips.remove();
};
/**
* 全局tooltips
* @param {JQuery} $elements - dom
*/
Tooltips.Global = function ($elements) {
var $elements = $elements || $('[data-module="tooltips"]');
$elements.each(function () {
var $this = $(this);
var tooltips = Tooltips.Get($this);
if (!tooltips) {
var options = $this.attr('data-options');
if (options && options.length > 0) {
options = eval('(0,' + options + ')');
} else {
options = {
title: $this.attr('data-title'),
content: $this.attr('data-content'),
placement: $this.attr('data-placement'),
tipClass: $this.attr('data-tipClass'),
trigger: $this.attr('data-trigger')
};
}
tooltips = new Tooltips($this, options);
Tooltips.Set($this, tooltips);
}
});
};
/**
* 从缓存获取对象
* @param {JQuery} $element - dom
*/
Tooltips.Get = function ($element) {
return $.data($element[0], 'tooltips');
};
/**
* 设置缓存
* @param {JQuery} $element - dom
* @param {Object} tooltips - 缓存对象
*/
Tooltips.Set = function ($element, tooltips) {
$.data($element[0], 'tooltips', tooltips);
}
return Tooltips;
});
|
'use strict';
var knex = require('../../connection.js');
var changesets = [];
describe('changeset create endpoint', function () {
it('returns a numerical changeset id.', function (done) {
server.injectThen({
method: 'PUT',
url: '/changeset/create',
payload: {
uid: 99,
user: 'openroads',
comment: 'test comment'
}
})
.then(function (res) {
res.statusCode.should.eql(200);
var result = JSON.parse(res.payload);
result.id.should.be.within(0, Number.MAX_VALUE);
changesets.push(result.id);
done();
})
.catch(function (err) {
return done(err);
});
});
it('creates a user with the given id if one does not exist', function (done) {
server.injectThen({
method: 'PUT',
url: '/changeset/create',
payload: {
uid: Math.floor(Math.random() * 1000),
user: Math.random().toString(36).substring(7),
comment: 'test comment'
}
})
.then(function (res) {
res.statusCode.should.eql(200);
var result = JSON.parse(res.payload);
result.id.should.be.within(0, Number.MAX_VALUE);
changesets.push(result.id);
done();
})
.catch(function (err) {
return done(err);
});
});
});
|
//@ts-check
const { createMacro } = require("babel-plugin-macros");
module.exports = createConstantMacro;
/**
* @param {Record<string,any>|any[]} data
*/
function createConstantMacro(data) {
return createMacro(function Macro({ references, babel }) {
const t = babel.types;
Object.entries(references).forEach(([key, value]) => {
value.forEach((ref) => {
if (key in data) {
const x = data[key];
/**
* @type {Expression}
*/
let expression;
switch (typeof x) {
case "bigint":
expression = t.bigIntLiteral(x.toString());
break;
case "boolean":
expression = t.booleanLiteral(x);
break;
case "number":
expression = t.numericLiteral(x);
break;
case "string":
expression = t.stringLiteral(x);
break;
default:
expression = t.nullLiteral();
}
ref.replaceWith(expression);
}
});
});
});
}
/**
* @typedef Expression
* @type {babel.types.Expression}
*/
|
import React, { Component } from 'react'
import ReactDOM from 'react-dom'
const Otsikko = (props) => {
return (
<h1>{props.otsikko}</h1>
)
}
const Osa = (props) => {
const { text, number, symbol } = props
return (
<p>{text}: {number} {symbol || null}</p>
)
}
const Sisalto = (props) => {
const { osat } = props
return (
<div>
<Osa text={osat[0].nimi} number={osat[0].tehtavia} />
<Osa text={osat[1].nimi} number={osat[1].tehtavia} />
<Osa text={osat[2].nimi} number={osat[2].tehtavia} />
</div>
)
}
const Yhteensa = (props) => {
const { osat } = props
return (
<p>yhteensä {osat[0].tehtavia + osat[1].tehtavia + osat[2].tehtavia}</p>
)
}
const App = () => {
const kurssi = {
nimi: 'Half Stack -sovelluskehitys',
osat: [
{
nimi: 'Reactin perusteet',
tehtavia: 10
},
{
nimi: 'Tiedonvälitys propseilla',
tehtavia: 7
},
{
nimi: 'Komponenttien tila',
tehtavia: 14
}
]
}
return (
<div>
<Otsikko otsikko={kurssi.nimi} />
<Sisalto osat={kurssi.osat} />
<Yhteensa osat={kurssi.osat} />
</div>
)
}
const Button = (props) => {
const { btnText, onClick } = props
return (
<button onClick={onClick}>{btnText}</button>
)
}
const Statistics = (props) => {
const { hyvä, huono, neutraali, laske, positiivisia } = props
return (
<div>
<Otsikko otsikko={"statistiikka"} />
<Statistic text={"hyvä"} number={hyvä} />
<Statistic text={"neutraali"} number={neutraali} />
<Statistic text={"huono"} number={huono} />
<Statistic text={"keskiarvo"} number={laske} />
<Statistic text={"Positiivista"} number={positiivisia} symbol={"%"} />
</div>
)
}
const Statistic = (props) => {
const { text, number, symbol } = props
return (
<p>{text}: {number} {symbol || null}</p>
)
}
class PalauteAppi extends Component {
static initialState = () => ({
hyväCount: null,
neutraaliCount: null,
huonoCount: null
})
constructor(props) {
super(props)
this.state = PalauteAppi.initialState()
}
addHyvä = () => {
var newState = { ...this.state };
newState.hyväCount += 1;
this.setState(newState);
console.log("tick")
}
addNeutraali = () => {
var newState = { ...this.state };
newState.neutraaliCount += 1;
this.setState(newState);
console.log("tick")
}
addHuono = () => {
var newState = { ...this.state };
newState.huonoCount += 1;
this.setState(newState);
console.log("tick")
}
laske = () => {
const { hyväCount, neutraaliCount, huonoCount } = this.state
const jakaja = hyväCount + neutraaliCount + huonoCount;
const num = ((this.state.hyväCount + (this.state.huonoCount*-1)) / jakaja);
const noRound = parseFloat(num).toFixed(2)
const round = parseFloat(Math.round(num * 100) / 100).toFixed(1);
return round;
}
positiivisia = () => {
const { hyväCount, neutraaliCount, huonoCount } = this.state
const prosentteina = hyväCount / (hyväCount + neutraaliCount + huonoCount) * 100;
return parseFloat(prosentteina).toFixed(2)
}
render() {
const { hyväCount, neutraaliCount, huonoCount } = this.state
return (
<div>
<Otsikko otsikko={"anna palautetta"} />
<Button btnText={"hyvä"} onClick={this.addHyvä} />
<Button btnText={"neutraali"} onClick={this.addNeutraali} />
<Button btnText={"huono"} onClick={this.addHuono} />
{hyväCount || neutraaliCount || huonoCount ?
<Statistics
hyvä={hyväCount}
huono={huonoCount}
neutraali={neutraaliCount}
laske={this.laske()}
positiivisia={this.positiivisia()}
/>
:null }
</div>
)
}
}
ReactDOM.render(
<PalauteAppi />,
document.getElementById('root')
)
|
import React from "react";
export default props => {
const uri = window.location.origin;
return (
<>
<h2>Exam Notes</h2>
<h3>Static Javascript Pages</h3>
<ul>
<li>
<a href={uri + "/javascript-pages/calculator.html"}>Calculator</a>
</li>
<li>
<a href={uri + "/javascript-pages/map.html"}>Map</a>
</li>
<li>
<a href={uri + "/javascript-pages/dataGenerator.html"}>Data Generator</a>
</li>
</ul>
</>
);
};
|
import React, { useRef } from 'react';
import { useSpring, useChain, animated } from 'react-spring';
import AnimatedText from './components/AnimatedText';
function App() {
const backgroundColorChange = useSpring({
from: { backgroundColor: 'white' },
to: { backgroundColor: '#9AE6B4' },
});
const fromTopRef = useRef();
const fromTop = useSpring({
from: { top: '-1000px' },
to: { top: '0px' },
config: { mass: 3, friction: 20, tension: 100 },
ref: fromTopRef,
});
const fromLeftRef = useRef();
const fromLeft = useSpring({
from: { left: '-2000px' },
to: { left: '0px' },
config: { mass: 3, friction: 20, tension: 100 },
ref: fromLeftRef,
});
useChain([fromTopRef, fromLeftRef], [0, 0.2]);
return (
<animated.main
className="min-h-screen relative"
style={backgroundColorChange}
>
<animated.div className="relative pt-16 pb-8 px-16" style={fromTop}>
<h1 className="text-6xl text-white">Hello world</h1>
<animated.hr
className="relative w-24 mr-auto ml-0 border-4 border-white"
style={fromLeft}
/>
</animated.div>
<div className="px-16">
<p>
<AnimatedText />
</p>
</div>
</animated.main>
);
}
export default App;
|
"use strict";
/**
* @class test factory model
*/
DIC.define('DemoApp.test.Factory.CircleTest', new function () {
/**
* @description the manager mock
* @memberOf DemoApp.test.Factory.CircleTest
* @alias {EquivalentJS.Manager}
*/
var manager;
/**
* @description setup the manager
* @memberOf DemoApp.test.Factory.CircleTest
* @param {EquivalentJS.Manager} managerInstance
*/
this.setup = function (managerInstance) {
manager = managerInstance;
};
/**
* @description test has assigned module class type by manager
* @memberOf DemoApp.test.Factory.CircleTest
* @param {EquivalentJS.test.Unit.assert} assert
* @param {DemoApp.Factory.Circle} moduleClass
*/
this.testHasAssignedTypeByManager = function (assert, moduleClass) {
assert.ok(
'DemoApp.Factory.Circle' === moduleClass.type,
'is DemoApp.Factory.Circle'
);
};
/**
* @description test set or get model without create
* @memberOf DemoApp.test.Factory.CircleTest
* @param {EquivalentJS.test.Unit.assert} assert
* @param {DemoApp.Factory.Circle} moduleClass
*/
this.testSetOrGetModelWithoutCreate = function (assert, moduleClass) {
assert.throws(
function() {
moduleClass.setSize('1rem');
},
new Error('Firstly use the create method!'),
'exception was thrown on set model before create'
);
assert.throws(
function() {
moduleClass.get();
},
new Error('Firstly use the create method!'),
'exception was thrown on get model before create'
);
};
/**
* @description test create model without factory class
* @memberOf DemoApp.test.Factory.CircleTest
* @param {EquivalentJS.test.Unit.assert} assert
* @param {DemoApp.Factory.Circle} moduleClass
*/
this.testCreateModelWithoutFactoryClass = function (assert, moduleClass) {
assert.throws(
function() {
moduleClass.create(1);
},
new Error('Only can create from factory class!'),
'exception was thrown on create without factory class'
);
};
/**
* @description test create model with factory class
* @memberOf DemoApp.test.Factory.CircleTest
* @param {EquivalentJS.test.Unit.assert} assert
* @param {DemoApp.Factory.Circle} moduleClass
*/
this.testCreateModelWithFactoryClass = function (assert, moduleClass) {
var assertAsync = assert.async();
manager.add('DemoApp.Factory', {
data: {
"amount": 1,
"size": ["5rem"],
"background": ["red"],
"border": ["black"]
}
}).done(function (module) {
moduleClass.create(1, module);
moduleClass.setBackgroundColor('rgb(255, 165, 0)');
var $circle = moduleClass.get();
assert.ok(1 === $circle.length, 'create and get a model by factory');
assert.ok(
'rgb(255, 165, 0)' === $circle.css('background-color'),
'set a model by factory'
);
assertAsync();
});
};
});
|
var getData=function(){
var tam = document.getElementById("tamano").value;
function burbuja(arreglo,n)
{
var i, k ,aux;
for(k=1; k<n;k++){
for(i=0; i <(n-k);i++){
if(arreglo[i]>arreglo[i +1]){
aux=arreglo[i];
arreglo[i] = arreglo[i + 1];
arreglo[i+1]=aux;
}
}
}
}
function ingresar(arreglo,n)
{
for(var k =0;k<n;k++)
{
var datos = parseInt(prompt("Ingresa los elementos "));
arreglo[k]=datos;
}
}
function Principal()
{
var arreglo123=[];
//var n = parseInt(prompt("Ingrese el tamaño "));
ingresar(arreglo123,tam)
var t=arreglo123.length;
document.getElementsByName("aing")[0].value=arreglo123;
console.log(arreglo123);
burbuja(arreglo123,t);
document.getElementsByName("arresal")[0].value=arreglo123;
console.log(arreglo123);
}
Principal();
}
|
import {inject} from "aurelia-framework";
import {Router, Redirect} from "aurelia-router";
import app, {users} from "../services";
const ERR_PASSWORD_MISMATCH = "Your passwords don't match. Try again.";
const ERR_LOGIN_TAKEN = "That Login Name is already in use. Try again.";
const ERR_EMPTY_FIELDS = "Please fill out all fields";
const ERR_GENERIC = "Something went wrong. Please try again later.";
@inject(Router)
export class Signup
{
loginName = "";
password = "";
passwordConfirm = "";
displayName = "";
error = "";
router;
constructor(router)
{
this.router = router;
}
canActivate()
{
if (app.get("user")) return new Redirect("home");
}
async send()
{
if (!this.loginName || !this.password || !this.passwordConfirm || !this.displayName)
{
this.error = ERR_EMPTY_FIELDS;
return;
}
if (this.password !== this.passwordConfirm)
{
this.error = ERR_PASSWORD_MISMATCH;
return;
}
try
{
await users.create({
loginName: this.loginName,
password: this.password,
displayName: this.displayName
});
}
catch (err)
{
console.error(JSON.stringify(err));
if (err.name === "Conflict")
{
this.error = ERR_LOGIN_TAKEN;
}
else
{
this.error = ERR_GENERIC;
}
return;
}
this.router.navigateToRoute("login", {signupSuccess: true});
}
}
|
import React from 'react'
import './style.scss'
import { PropTypes } from 'prop-types'
import { Link } from 'react-router-dom'
import { Spinner } from 'react-bootstrap'
export default function Widget({
value,
title,
className = '',
loading = false,
uri
}) {
return (
<Link to={uri} className={className + ' widget'}>
{loading ? (
<Spinner animation="border" variant="light" />
) : (
<>
<div className="widget__value">{value}</div>
<div className="widget__title">{title}</div>
</>
)}
</Link>
)
}
Widget.propTypes = {
value: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
uri: PropTypes.string.isRequired,
loading: PropTypes.bool,
className: PropTypes.string
}
|
/**
* Created by Ratnesh on 13/09/2019.
*/
import React from "react";
import BaseComponent from '../baseComponent'
import DashBoardComponent from './dashboardComponent'
import Utils, {dispatchAction} from "../../utility";
import {connect} from "react-redux";
class DashBoard extends BaseComponent {
constructor(props) {
super(props);
this.state = {
}
}
componentDidMount() {
}
onChangeEvent = (event) => {
this.setState({[event.target.id]: event.target.value});
};
render() {
return (
<DashBoardComponent state={this.state}
onChangeEvent={this.onChangeEvent}
togglePassword={this.togglePassword}/>
);
}
}
const mapStateToProps = (state) => {
return {user: state.user}
};
export default connect(mapStateToProps, {dispatchAction})(DashBoard);
|
<!-- color script written entirely in JavaScript -->
<!-- Written by myhyli & 色眯眯的小疯狗, 2003/05/12. -->
var temp_bt_colorSetting;
var tempState=1;
var tempTimeout;
function initializeUI() {
if(GetCookie('blueidea_colorSetting')!=null) {
document.styleSheets[0].disabled=1;
updateColor(GetCookie('blueidea_colorSetting').split(';'),true);
document.styleSheets[0].disabled=0;
}
}
initializeUI();
function settingColor() {
var reValue=window.showModelessDialog('js/color/colorSetting.htm',window,'dialogWidth:450px;dialogHeight:405px;status:no;scroll:no;help:no;');
}
function updateColor(settings,grade) {
if(tempState==0) return false;
clearTimeout(tempTimeout);
////为了增加颜色转换的效果和消除切换的生硬感,使用了滤镜
if(grade!=1) {
tempState=0;
var oldBody=document.body;
if(oldBody!=null) {
var newBody=oldBody.cloneNode();//必须在应用滤镜前进行,以确保body对象是干净的
oldBody.style.filter='blendTrans(duration=1)';
oldBody.filters[0].apply();
}
}
////////////////////////////////////////////////////////
var colors=new Object();
for(var i=0;i<settings.length;i++) {
colors[settings[i].split(':')[0].replace(/^(d_)|(c_)/i,'').toLowerCase()]=settings[i].split(':')[1];
}
for(i=0;i<document.styleSheets[0].rules.length;i++) {
with(document.styleSheets[0].rules[i]) {
var tempText=selectorText.toLowerCase().replace(/[^\.]*\./i,'');
tempText=tempText.replace(/:\w*/i,'');
switch(tempText) {
case 'a':
if(selectorText.match(/:hover/)!=null)style.color=colors['a_hover'];
else style.color=colors[tempText];
break;
case 'navlink':
style.color=colors[tempText];
break;
case 'content':
style.color=colors[tempText];
break;
case 'td':
style.color=colors['content'];
break;
case 'docparameter td':
style.color=colors['docparameter_text'];
break;
default:
if(colors[tempText]) {
if(tempText=='body' && document.readyState=='complete') {
bt_colorSetting.style.backgroundColor=colors[tempText];
}
else if(tempText=='body' && document.readyState!='complete') {
temp_bt_colorSetting=colors[tempText];
}
style.backgroundColor=colors[tempText];
}
break;
}
}
}
////播放滤镜,并且在播放完毕后更新body,以消除应用滤镜后的滞后感,该部分代码作者:色眯眯的小疯狗
if(grade!=1) {
document.body.filters[0].play();
tempTimeout=setTimeout(function() {
if(oldBody!=null) {
oldBody.applyElement(newBody, "inside")
oldBody.swapNode(newBody);
oldBody.removeNode(true);
}
tempState=1;
},1500);
}
/////////////////////////////////////////////////////////////////
}
function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = window.document.cookie.length;
var i = 0;
while (i < clen) {
var j = i + alen;
if (window.document.cookie.substring(i, j) == arg) return getCookieVal (j);
i = window.document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}
function getCookieVal (offset) {
var endstr = window.document.cookie.indexOf (";", offset);
if (endstr == -1) endstr = window.document.cookie.length;
return unescape(window.document.cookie.substring(offset, endstr));
}
function SetCookie (name, value) {
var exp = new Date();
exp.setTime(exp.getTime() + (30*24*60*60*1000));
window.document.cookie = name + "=" + escape (value) + "; expires=" + exp.toGMTString()+";path=/";
}
function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
window.document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString()+";path=/";
}
|
var tomImage = new Image();
tomImage.src = "images/tomas.png";
function Tom(){
this.x = 100;
this.y = 500;
this.width = 50;
this.height = 50;
this.name = "Tom";
this.vx = 6; //15
this.vy = 3; //6
this.tomCounter = 0;
this.tomArray = [];
this.tomRandomArray = [
[Math.floor(Math.random() * canvas1.width), -100], // верх
[Math.floor(Math.random() * canvas1.width), canvas1.height], //низ
[-100 ,Math.floor(Math.random() * canvas1.height)], //лево
[canvas1.width, Math.floor(Math.random() * canvas1.height)] //право
];
}
Tom.prototype.displayRandomTom = function(){
var index = Math.floor(Math.random() * this.tomRandomArray.length);
return this.tomRandomArray[index];
}
Tom.prototype.createTom = function(valX, valY, valW, valH, valVX, valVY){
this.tomArray.push({
x: valX,
y: valY,
w: valW,
h: valH,
vx: valVX,
vy: valVY
});
this.tomCounter +=1;
};
Tom.prototype.drawImage = function(cheese){
ctx.drawImage(tomImage, cheese.x, cheese.y, valW, valH);
}
Tom.prototype.draw = function(){
this.tomArray.forEach(this.drawImage.bind(this));
}
Tom.prototype.move = function(){
this.tomArray.forEach(function(tomTab){
tomTab.x += tomTab.vx;
tomTab.y += tomTab.vy;
if(tomTab.y + tomTab.vy > canvas1.height || tomTab.y + tomTab.vy < -100){
tomTab.vy *= -1;
}
if(tomTab.x + tomTab.vx > canvas1.width || tomTab.x + tomTab.vx < -100){
tomTab.vx *= -1;
}
})
}
|
/*
金币场大厅控制器
*/
let Controller = require("../../frameworks/mvc/Controller");
cc.Class({
extends: Controller,
ctor () {
},
//初始化全局事件监听
initGlobalEvent() {
qf.event.on(qf.ekey.EVT_SHOW_HALL, this.onShowHall, this);
},
//控制器事件,随着主view销毁而销毁
initModuleEvent() {
},
initView(params) {
let prefab = cc.loader.getRes(qf.res.prefab_hall);
let script = cc.instantiate(prefab).getComponent("HallView");
script.init(params);
return script;
},
show(params) {
this._super(params);
this.view.playAction(qf.const.INOUT_TYPE.IN);
},
onShowHall(params) {
qf.rm.checkLoad("hall",()=>{
qf.mm.show("hall", params, true);
})
},
onDestroy () {
}
});
|
const Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
return sequelize.define('SalesInvoiceGrid', {
entity_id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
primaryKey: true,
comment: "Entity ID"
},
increment_id: {
type: DataTypes.STRING(50),
allowNull: true,
comment: "Increment ID"
},
state: {
type: DataTypes.INTEGER,
allowNull: true,
comment: "State"
},
store_id: {
type: DataTypes.SMALLINT.UNSIGNED,
allowNull: true,
comment: "Store ID"
},
store_name: {
type: DataTypes.STRING(255),
allowNull: true,
comment: "Store Name"
},
order_id: {
type: DataTypes.INTEGER.UNSIGNED,
allowNull: false,
comment: "Order ID"
},
order_increment_id: {
type: DataTypes.STRING(50),
allowNull: true,
comment: "Order Increment ID"
},
order_created_at: {
type: DataTypes.DATE,
allowNull: true,
comment: "Order Created At"
},
customer_name: {
type: DataTypes.STRING(255),
allowNull: true,
comment: "Customer Name"
},
customer_email: {
type: DataTypes.STRING(255),
allowNull: true,
comment: "Customer Email"
},
customer_group_id: {
type: DataTypes.INTEGER,
allowNull: true
},
payment_method: {
type: DataTypes.STRING(128),
allowNull: true,
comment: "Payment Method"
},
store_currency_code: {
type: DataTypes.STRING(3),
allowNull: true,
comment: "Store Currency Code"
},
order_currency_code: {
type: DataTypes.STRING(3),
allowNull: true,
comment: "Order Currency Code"
},
base_currency_code: {
type: DataTypes.STRING(3),
allowNull: true,
comment: "Base Currency Code"
},
global_currency_code: {
type: DataTypes.STRING(3),
allowNull: true,
comment: "Global Currency Code"
},
billing_name: {
type: DataTypes.STRING(255),
allowNull: true,
comment: "Billing Name"
},
billing_address: {
type: DataTypes.STRING(255),
allowNull: true,
comment: "Billing Address"
},
shipping_address: {
type: DataTypes.STRING(255),
allowNull: true,
comment: "Shipping Address"
},
shipping_information: {
type: DataTypes.STRING(255),
allowNull: true,
comment: "Shipping Method Name"
},
subtotal: {
type: DataTypes.DECIMAL(20,4),
allowNull: true,
comment: "Subtotal"
},
shipping_and_handling: {
type: DataTypes.DECIMAL(20,4),
allowNull: true,
comment: "Shipping and handling amount"
},
grand_total: {
type: DataTypes.DECIMAL(20,4),
allowNull: true,
comment: "Grand Total"
},
created_at: {
type: DataTypes.DATE,
allowNull: true,
comment: "Created At"
},
updated_at: {
type: DataTypes.DATE,
allowNull: true,
comment: "Updated At"
},
base_grand_total: {
type: DataTypes.DECIMAL(20,4),
allowNull: true,
comment: "Base Grand Total"
}
}, {
sequelize,
tableName: 'sales_invoice_grid',
timestamps: false,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "entity_id" },
]
},
{
name: "SALES_INVOICE_GRID_INCREMENT_ID_STORE_ID",
unique: true,
using: "BTREE",
fields: [
{ name: "increment_id" },
{ name: "store_id" },
]
},
{
name: "SALES_INVOICE_GRID_STORE_ID",
using: "BTREE",
fields: [
{ name: "store_id" },
]
},
{
name: "SALES_INVOICE_GRID_GRAND_TOTAL",
using: "BTREE",
fields: [
{ name: "grand_total" },
]
},
{
name: "SALES_INVOICE_GRID_ORDER_ID",
using: "BTREE",
fields: [
{ name: "order_id" },
]
},
{
name: "SALES_INVOICE_GRID_STATE",
using: "BTREE",
fields: [
{ name: "state" },
]
},
{
name: "SALES_INVOICE_GRID_ORDER_INCREMENT_ID",
using: "BTREE",
fields: [
{ name: "order_increment_id" },
]
},
{
name: "SALES_INVOICE_GRID_CREATED_AT",
using: "BTREE",
fields: [
{ name: "created_at" },
]
},
{
name: "SALES_INVOICE_GRID_UPDATED_AT",
using: "BTREE",
fields: [
{ name: "updated_at" },
]
},
{
name: "SALES_INVOICE_GRID_ORDER_CREATED_AT",
using: "BTREE",
fields: [
{ name: "order_created_at" },
]
},
{
name: "SALES_INVOICE_GRID_BILLING_NAME",
using: "BTREE",
fields: [
{ name: "billing_name" },
]
},
{
name: "SALES_INVOICE_GRID_BASE_GRAND_TOTAL",
using: "BTREE",
fields: [
{ name: "base_grand_total" },
]
},
{
name: "FTI_95D9C924DD6A8734EB8B5D01D60F90DE",
type: "FULLTEXT",
fields: [
{ name: "increment_id" },
{ name: "order_increment_id" },
{ name: "billing_name" },
{ name: "billing_address" },
{ name: "shipping_address" },
{ name: "customer_name" },
{ name: "customer_email" },
]
},
]
});
};
|
export default {
dark: "#000",
medium: "#545454",
light: "#fff",
grey: "#999",
lightgrey: "#eee",
darkGrey: "#777",
blue: "#558ded",
lightBlue: "#7ca7f2",
red: "#e73838",
};
|
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var opencv4nodejs_1 = __importDefault(require("opencv4nodejs"));
var show_image_1 = __importDefault(require("../../dev/show-image"));
var highThreshold = 0;
var lowThreshold = 0;
var sigmaX = 0;
function cannyEdgeDetection(image) {
var grayscale = image.cvtColor(opencv4nodejs_1.default.COLOR_BGR2GRAY);
// const blurred = grayscale.gaussianBlur(new Size(5, 5), sigmaX)
// https://github.com/opencv/opencv/blob/master/modules/imgproc/src/canny.cpp#L939
// convert Mat to cv.CV_16SC1 || cv.CV_16SC3
var converted16SC3 = grayscale.convertTo(opencv4nodejs_1.default.CV_16SC3);
var cannyImage = opencv4nodejs_1.default.canny(converted16SC3, converted16SC3, lowThreshold, highThreshold);
show_image_1.default(cannyImage);
return cannyImage;
}
exports.default = cannyEdgeDetection;
|
import React from "react";
import {
FormControl,
FormLabel,
Input,
Button,
Center,
Text,
} from "@chakra-ui/react";
import { createExpense, updateExpense } from "../../data/api";
import { inputFormattedToday } from "../../helpers/date";
import applicationColors from "../../style/colors";
import PropTypes from "prop-types";
import CurrencyContext from "../../contexts/currencyContext";
const ExpenseForm = ({
action,
onClose,
type,
expense,
projectId,
closePopover,
}) => {
const [name, setName] = React.useState(expense?.name || "");
const [date, setDate] = React.useState(
expense?.date || inputFormattedToday()
);
const [cost, setCost] = React.useState(expense?.cost || "");
const [error, setError] = React.useState(null);
const { currency } = React.useContext(CurrencyContext);
const create = (expense) => {
createExpense(expense)
.then((data) => {
if (data.expenses) {
action(data.expenses);
onClose();
}
if (data.error) {
setError(data.error[0]);
setTimeout(() => setError(null), 5000);
}
})
.catch((e) => {
console.warn(e);
});
};
const update = (expense) => {
updateExpense(expense)
.then((data) => {
if (data.expenses) {
action(data.expenses);
onClose();
closePopover();
}
if (data.error) {
setError(data.error[0]);
setTimeout(() => setError(null), 5000);
}
})
.catch((e) => {
console.warn(e);
});
};
const validate = () => {
if (name.length > 40) {
setError("Expense name must be < 40 characters");
return false;
}
if (cost <= 0) {
setError("Cost must be greater than 0");
return false;
}
if (cost > 10000) {
setError("Cost must be less than 10000.0");
return false;
}
return true;
};
const submitForm = (e) => {
e.preventDefault();
if (!validate()) return;
const expenseDetails = {
name,
date,
cost: Number.parseFloat(cost).toFixed(2), // Ensure to 2 decimal places
};
if (type === "Create") {
create({ ...expenseDetails, project_id: projectId });
} else if (type === "Edit") {
update({
...expenseDetails,
project_id: expense.project_id,
id: expense.id,
});
}
};
return (
<form onSubmit={submitForm}>
<FormControl isRequired>
<FormLabel fontSize="sm" casing="uppercase">
Name of expense
</FormLabel>
<Input
data-cy="expense-name"
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="A new expense"
></Input>
</FormControl>
<FormControl m="15px 0 " isRequired>
<FormLabel fontSize="sm" m="0">
Date
</FormLabel>
<Input
data-cy="expense-date"
type="date"
mt="5px"
value={date}
max={inputFormattedToday()}
onChange={(e) => setDate(e.target.value)}
/>
</FormControl>
<FormControl mt="10px" isRequired>
<FormLabel fontSize="sm" casing="uppercase">
Cost of expense ({currency[currency.length - 1]})
</FormLabel>
<Input
data-cy="cost"
placeholder="20"
value={cost}
onChange={(e) => setCost(e.target.value)}
style={{ width: "50%" }}
type="number"
></Input>
</FormControl>
{error && (
<Text
data-cy="expense-error"
fontSize="sm"
color={applicationColors.ERROR_COLOR}
m="10px 0"
>
{error}
</Text>
)}
<Center mt="15px">
<Button type="submit" data-cy="submit">
{type} Expense
</Button>
</Center>
</form>
);
};
ExpenseForm.propTypes = {
action: PropTypes.func,
onClose: PropTypes.func,
type: PropTypes.string,
expense: PropTypes.object,
projectId: PropTypes.number,
closePopover: PropTypes.func,
};
export default ExpenseForm;
|
import React from "react";
import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";
import Badge from "@material-ui/core/Badge";
import Button from "@material-ui/core/Button";
import ListIcon from "@material-ui/icons/List";
const Header = ({ count, clear }) => {
return (
<AppBar position="static">
<Toolbar>
<Badge badgeContent={count} color="secondary">
<ListIcon />
</Badge>
<Typography
style={{marginLeft: 30, flexGrow: 1}}
variant="h6">Todo List</Typography>
<Button onClick={clear} color="inherit">CLEAR</Button>
</Toolbar>
</AppBar>
)
}
export default Header;
|
// test the website links
var baseUrl = casper.cli.options.baseUrl;
casper.test.begin(baseUrl, 2, function(test)
{
/////////////////////////////////
// first test the navbar links //
/////////////////////////////////
casper.start(baseUrl + 'demos/', function()
{
test.assertTitle('Demos');
});
casper.then(function() {
casper.evaluate(function() {
$('a[href="https://forum.baxon.fr"]').get(0).click();
});
});
casper.waitForPopup(/https:\/\/forum\.baxon\.fr/, function() {
this.echo('popup forum loaded');
test.assertEquals(this.popups.length, 1, "one popup loaded");
});
// casper.waitForPopup(/35\.158\.164\.182/, function() {
// this.echo('popup loaded');
// });
// // casper.withPopup(/35\.158\.164\.182/, function() {
// // test.assertTitle('urls');
// // });
// casper.then(function() {
// this.echo(this.getTitle());
// test.assertEval(function() {
// var select = 'strong[itemprop="name"] > a';
// return document.querySelector(select).innerHTML === "urlPad";
// });
// });
casper.run(function() {
test.done();
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.