text
stringlengths 7
3.69M
|
|---|
import React, { useState } from 'react'
import numeral from 'numeral'
import Button from '../components/Button'
import Link from '../components/Link'
// import VideoContainer from '../components/VideoContainer'
import SearchBox from '../components/SearchBox'
import DatasetCard from '../components/DatasetCard'
import { trackGoal } from '../utils/analytics'
const hardCodedMetrics = {
datasets: 3447,
versions: 5120,
size: 49200000000
}
const IndexPage = () => {
const features = [
{
id: 'version',
title: 'Version',
description: 'All changes to Qri Datasets are versioned. Compare one version to any other. Explore the history of commits to see how datasets evolve over time.',
icon: 'version',
buttonText: 'How Qri Versioning Works',
link: '/docs/concepts/understanding-qri/how-qri-version-control-works',
image: ''
},
{
id: 'automate',
title: 'Automate',
description: 'Write transform code that lives right alongside your dataset. Import from external data sources or other Qri datasets. ',
icon: 'automate',
buttonText: 'How Qri Binds Code to Data',
link: '/docs/concepts/understanding-qri/how-qri-data-transforms-and-automation-work',
image: ''
}
]
const [selectedFeatureId, setSelectedFeatureId] = useState('version')
const selectedFeature = features.find(d => d.id === selectedFeatureId)
const handleSearchSubmit = (query) => {
// general-search-from-homepage event
trackGoal('PM9MTQ4Y', 0)
const newParams = new URLSearchParams(`q=${query}`)
window.open(`https://qri.cloud/search?${newParams.toString()}`)
}
return (
<>
<div className='pt-0 md:pt-16 overflow-x-hidden'>
<div className='px-5 md:px-10 lg:px-20 z-10'>
<div className='flex flex-col sm:flex-row -mx-6'>
<div className='inline-block mx-6 flex-grow'>
<div className='-mx-1.5'>
<img className='relative left-40 transform scale-75 md:transform-none md:-left-10' src='/img/new-docs/homepage/nodes-1.svg'/>
<div className='text-qritile-600 font-extrabold text-5xl md:text-6xl px-1.5 py-0 border-0 md:border-2 border-qrigray-100 bg-none md:bg-white inline-block relative mb-5'>
Data with Friends
</div>
<div className='px-1.5'>
<div className='flex mb-5 md:mb-8'>
<div className='text-lg md:text-xl w-0 flex-grow'>Qri helps you organize, version, automate, and share datasets.</div>
</div>
<Link to='https://qri.cloud'>
<Button type='secondary' size='lg' className='mb-8'>Get Started</Button>
</Link>
</div>
<div className='border-b-2 border-qrigray-200 mb-8 mx-1.5'></div>
</div>
<div className='flex mb-10 md:mb-0'>
<div className='text-center px-3 mr-6'>
<div className='text-qritile-600 font-bold block text-xl mb-1.5'>{numeral(hardCodedMetrics.datasets).format('0,0')}</div>
<div className='text-sm block font-light'>Datasets</div>
</div>
<div className='text-center px-3 mr-6'>
<div className='text-qritile-600 font-bold block text-xl mb-1.5'>{numeral(hardCodedMetrics.versions).format('0,0')}</div>
<div className='text-sm block font-light'>Versions</div>
</div>
<div className='text-center px-3 mr-6'>
<div className='text-qritile-600 font-bold block text-xl mb-1.5'>{numeral(hardCodedMetrics.size).format('0.0b')}</div>
<div className='text-sm block font-light'>Public Data</div>
</div>
</div>
</div>
<div className='text-right mx-6 flex items-center'>
<img className='inline' src='/img/new-docs/homepage/splash-data-snuggle.svg'/>
</div>
</div>
<img className='absolute -left-10 z-0 transform origin-left scale-75 md:transform-none' src='/img/new-docs/homepage/yellow-aura-1.svg'/>
<div className='pt-20 text-center py-10 z-10 relative'>
<div className='text-qritile-600 text-4xl font-extrabold mb-4'>Let's rethink what datasets can do</div>
<div className='text-qrigray-700 text-lg font-light'>Qri is an all new suite of tools for doing more with datasets</div>
</div>
{/* Begin Feature Carousel */}
<div className='text-center z-10 relative'>
<div className='flex mb-6 md:mb-16'>
{
features.map(({ id, title, icon }) => {
const isSelected = id === selectedFeature.id
return (
<Button
key={title}
icon={ icon }
className='mr-3 bg-white'
size = 'lg'
type={isSelected ? 'secondary-outline' : 'light'}
onClick={() => {
setSelectedFeatureId(id)
}}
block
>
{title}
</Button>
)
})
}
</div>
<div className='flex flex-wrap-reverse md:flex-nowrap items-center -mx-8 mb-16 md:mb-0 pb-16'>
<div className='w-full md:w-2/4 lg:w-5/12 text-left mx-8'>
<div className='font-bold text-3xl text-qritile-600 mb-6'>{selectedFeature.title}</div>
<div className='text-lg lg:text-xl font-light mb-7'>{selectedFeature.description}</div>
<Link to={selectedFeature.link}>
<Button type='secondary' size='lg'>{selectedFeature.buttonText}</Button>
</Link>
</div>
<div className='w-full md:w-2/4 lg:w-7/12 flex-grow mb-6 md:mb-0 mx-8'>
<img src={`/img/new-docs/homepage/feature-${selectedFeature.id}.svg`}/>
</div>
</div>
</div>
</div>
{/* End Feature Carousel */}
{/* Begin Featured Datasets */}
<div className='bg-qrigray-100 py-14 relative mb-28' style={{
backgroundImage: 'url(\'/img/new-docs/dot-white.svg\')'
}}>
<div className='absolute z-0 top-20 md:-top-1 transform origin-top-left scale-150 md:transform-none'>
<img src='/img/new-docs/homepage/featured-nodes.svg'/>
</div>
<div className='px-5 md:px-10 lg:px-20 relative z-20'>
<div className='text-right'>
<div className='inline-block mb-6'>
<div className='text-qripink-600 text-4xl lg:text-5xl font-black mb-7'>Featured Datasets</div>
<SearchBox size='lg' onSubmit={handleSearchSubmit} placeholder='Search qri.cloud for datasets'/>
</div>
</div>
<div className='flex flex-wrap md:flex-nowrap -mx-3'>
<div className='flex flex-col md:flex-row'>
<div className='w-full md:w-1/3'>
<DatasetCard
title='NYC Subway Turnstile Counts - 2021'
name='turnstile_daily_counts_2021'
description='NYC Subway Turnstile Counts Data aggregated by day and station complex for the year 2021. Updated weekly.'
updatedAt={new Date('Thu Oct 21 2021 15:59:46 GMT-0400')}
username='nyc-transit-data'
userAvatar='https://qri-user-images.storage.googleapis.com/1570029763701.png'
className='mx-3 mb-6 md:mb-0'
/>
</div>
<div className='w-full md:w-1/3'>
<DatasetCard
title='World Bank Population'
name='world_bank_population'
description='( 1 ) United Nations Population Division. World Population Prospects: 2017 Revision. ( 2 ) Census reports and other statistical publications from national statistical offices, ( 3 ) Eurostat: Demographic Statistics, ( 4 ) United Nations Statistical Division. Population and Vital Statistics Reprot ( various years ), ( 5 ) U.S. Census Bureau: International Database, and ( 6 ) Secretariat of the Pacific Community: Statistics and Demography Programme.'
updatedAt={new Date('Tue Aug 03 2020 20:03:46 GMT-0400')}
username='b5'
userAvatar='https://qri-user-images.storage.googleapis.com/1570029763701.png'
className='mx-3 mb-6 md:mb-0'
/>
</div>
<div className='w-full md:w-1/3'>
<DatasetCard
title='New York City Population by Borough, 1950 - 2040'
name='new-york-city-population-by-borough-1950-2040'
description='Unadjusted decennial census data from 1950-2000 and projected figures from 2010-2040: summary table of New York City population numbers and percentage share by Borough, including school-age (5 to 17), 65 and Over, and total population.'
updatedAt={new Date('Tue Nov 24 2020 16:16:46 GMT-0400')}
username='nyc-open-data-archive'
userAvatar='https://qri-user-images.storage.googleapis.com/1570029763701.png'
className='mx-3 mb-6 md:mb-0'
/>
</div>
</div>
<div className='w-full md:w-24 text-center flex-shrink-0'>
<Link to='https://qri.cloud' className='mx-auto sm:h-full'>
<div className='hidden md:flex bg-qripink-600 hover:bg-qripink-700 text-white text-base font-semibold align-middle rounded-lg items-center px-2 text-center mx-auto md:mx-3 h-full'>
<div>Explore<br/>More</div>
</div>
<Button size='lg' type='secondary' className='visible sm:hidden'>
<div>Explore More</div>
</Button>
</Link>
</div>
</div>
</div>
</div>
{/* End Featured Datasets */}
{/* Begin Videos */}
{/*
<div className='py-48 relative'>
<div className='absolute right-0 -bottom-16 z-0 transform origin-bottom-right scale-75 md:transform none'>
<img src='/img/new-docs/homepage/yellow-aura-2.svg'/>
</div>
<div className='hidden md:block absolute right-40 top-60 z-0'>
<img src='/img/new-docs/homepage/nodes-2.svg'/>
</div>
<div className='px-5 md:px-10 lg:px-20 relative flex flex-wrap'>
<div className='md:w-5/12 text-left pr-16 flex items-center mb-16'>
<div>
<div className='font-bold text-3xl md:text-4xl text-qritile-600 mb-6'>Videos</div>
<div className='text-lg md:text-xl font-light mb-7'>Get up and running quickly with these helpful videos.</div>
<Button type='secondary'>Check out Youtube</Button>
</div>
</div>
<div className='md:w-7/12'>
<div className='text-center flex flex-col'>
<VideoContainer
id='dhdorFezaEc'
title='Qri Desktop Demo: Exploring the Collection View'
className='mb-7 self-end'
/>
<VideoContainer
id='WKayeh0OAes'
title='Qri Desktop Demo - Pull and Sync With Qri.Cloud'
className='self-start'
/>
</div>
</div>
</div>
</div>
*/}
{/* End Videos */}
{/* Begin Laptop Thing */}
<div className='relative'>
<img src='/img/new-docs/homepage/circle-1.svg' className='absolute z-10 transform origin-bottom-right scale-50 md:transform-none' style={{
top: -214,
right: 0
}}/>
<img src='/img/new-docs/homepage/circle-2.svg' className='absolute z-10 hidden md:block' style={{
top: -72,
right: 98
}}/>
<div className='px-5 md:px-10 lg:px-20 relative w-full'>
<img src='/img/new-docs/homepage/linked-nodes.svg' className='hidden md:block absolute z-5' style={{
top: -300,
left: -10
}}/>
<div className='bg-qritile-600 pt-10 md:pt-24 px-6 md:px-40 pb-20 md:pb-48 w-full text-white text-center relative'>
<img src='/img/new-docs/homepage/donut-pink.svg' className='absolute -left-1.5 -top-1.5'/>
<img src='/img/new-docs/homepage/donut-orange.svg' className='absolute -right-1.5 -top-1.5'/>
<img src='/img/new-docs/homepage/donut-pink.svg' className='absolute -right-1.5 -bottom-1.5'/>
<img src='/img/new-docs/homepage/donut-orange.svg' className='absolute -left-1.5 -bottom-1.5'/>
<div className='text-3xl md:text-4xl font-bold mb-5'>Work Smarter with Data on Qri Cloud</div>
<div className='text-base md:text-lg font-light mb-5'>Use our code editor and CI-style automation to keep your datasets fresh and tidy</div>
<Link to='https://qri.cloud/signup' size='lg'>
<Button type='secondary' size='lg'>Try it Now</Button>
</Link>
</div>
<div className='relative -top-12 md:-top-36'>
<img src='/img/new-docs/homepage/laptop.svg' className='mx-auto'/>
</div>
</div>
</div>
{/* End Laptop Thing */}
</div>
</>
)
}
export default IndexPage
|
function active() {
const menu = document.querySelector("img#menu");
const close = document.querySelector("img#close");
const m1 = document.querySelector("main#m1");
const m4 = document.querySelector("main#m4");
const aside = document.querySelector("aside");
menu.addEventListener("click", (e) => {
menu.classList.toggle("hidden");
close.classList.toggle("hidden");
m1.classList.toggle("hidden");
m4.classList.toggle("hidden");
aside.classList.toggle("hidden");
e.preventDefault();
});
close.addEventListener("click", (e) => {
menu.classList.toggle("hidden");
close.classList.toggle("hidden");
m1.classList.toggle("hidden");
m4.classList.toggle("hidden");
aside.classList.toggle("hidden");
e.preventDefault();
});
const chk = document.getElementById("switch");
chk.addEventListener("change", () => {
document.body.classList.toggle("light");
});
}
active();
function totop() {
if (document.body.scrollTop > 50 || document.documentElement.scrollTop > 50) {
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
} else {
}
}
let c = document.querySelector(".clock");
let d = document.querySelector(".date");
setInterval(() => {
let today = new Date();
let hh = today.getHours();
let mm = today.getMinutes();
let ss = today.getSeconds();
let date = today.toDateString();
c.innerText = `${mktwodigits(hh)} : ${mktwodigits(mm)} : ${mktwodigits(ss)}`;
d.innerText = date;
}, 10);
function mktwodigits(m) {
return m.toString().padStart(2, "0");
}
window.onload = function () {
CoronaStats();
};
function CoronaStats() {
fetch("https://disease.sh/v2/countries/qatar")
.then(function (resp) {
return resp.json();
})
.then(function (data) {
let active = data.active;
let todaycases = data.todayCases;
let todaydeaths = data.todayDeaths;
let deaths = data.deaths;
let recovered = data.recovered;
let tests = data.tests;
let critical1 = data.critical;
let total = data.cases;
//let update = data.location.updated;
document.getElementById("dead").innerHTML = deaths.toLocaleString("en");
document.getElementById("dead24").innerHTML = todaydeaths.toLocaleString(
"en"
);
document.getElementById("active").innerHTML = active.toLocaleString("en");
document.getElementById("active24").innerHTML = todaycases.toLocaleString(
"en"
);
document.getElementById("recovered").innerHTML = recovered.toLocaleString(
"en"
);
document.getElementById("tested").innerHTML = tests.toLocaleString("en");
document.getElementById("critical1").innerHTML = critical1.toLocaleString(
"en"
);
document.getElementById("total").innerHTML = total.toLocaleString("en");
//document.getElementById('lastupdate').innerHTML = update.substr(0, 10);
})
.catch(function () {
console.log("error");
});
setTimeout(CoronaStats, 1800000); // update every .5 hours
}
|
module.exports = {
up: (queryInterface, Sequelize) =>
queryInterface.createTable('compounds', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.BIGINT
},
name: {
allowNull: false,
type: Sequelize.STRING
},
elementsObject: {
allowNull: false,
type: Sequelize.JSONB
},
description: {
type: Sequelize.TEXT
},
}),
down: queryInterface => queryInterface.dropTable('compounds')
};
|
/**
* 通用公共方法
* Created by lvls on 2018/1/30.
*/
$(document).ready(function() {
});
// 恢复提示框显示
function resetTip(){
top.$.jBox.tip.mess = null;
}
// 关闭提示框
function closeTip(){
top.$.jBox.closeTip();
}
//显示提示框
function showTip(mess, type, timeout, lazytime){
//resetTip();
setTimeout(function(){
$.jBox.tip(mess, (type == undefined || type == '' ? 'info' : type), {opacity:0,
timeout: timeout == undefined ? 2000 : timeout});
}, lazytime == undefined ? 500 : lazytime);
}
|
'use strict'
const passport = require('passport');
const error_types = require('../controllers/error_types');
let middlewares = {
ensureAuthenticated: (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user, info) => {
if (info) { return next(new error_types.Error401(info.message)); }
if (err) { return next(err); }
if (!user) { return next(new error_types.Error403("You are not allowed to access.")); }
req.user = user;
next();
})(req, res, next);
},
ensureManager: (req, res, next) => {
passport.authenticate("jwt", { session: false }, (err, user, info) => {
if (info) { return next(new error_types.Error401(info.message)); }
if (err) { return next(err); }
if (user.rol != "ADMIN" && user.rol != "MANAGER") { return next(new error_types.Error403("You are not allowed to access.")); }
req.user = user;
next();
})(req, res, next);
},
ensureAdmin: (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user, info) => {
if (info) { return next(new error_types.Error401(info.message)); }
if (err) { return next(err); }
if (user.rol != "ADMIN") { return next(new error_types.Error403("You are not allowed to access.")); }
req.user = user;
next();
})(req, res, next);
},
errorHandler: (error, req, res, next) => {
if (error instanceof error_types.InfoError)
res.status(200).json({ error: error.message });
else if (error instanceof error_types.Error404)
res.status(404).json({ error: error.message });
else if (error instanceof error_types.Error403)
res.status(403).json({ error: error.message });
else if (error instanceof error_types.Error401)
res.status(401).json({ error: error.message });
else if (error instanceof error_types.Error400)
res.status(400).json({ error: error.message });
else if (error.name == "ValidationError") //de mongoose
res.status(200).json({ error: error.message });
else if (error.message)
res.status(500).json({ error: error.message });
else
next();
},
notFoundHandler: (req, res, next) => {
res.status(404).json({ error: "endpoint not found" });
}
}
module.exports = middlewares
|
//localHandler({"result":"我是远程js带来的数据"});
var localHandler = {"result":"我是远程js带来的数据"};
|
a = new Array();
a[4546625535] = 1;
console.log(a[4546625535]);
|
import React from 'react'
import Listfile from '../Components/Sunday/Listfile'
const Sundaylist = () => {
return (
<Listfile/>
)
}
export default Sundaylist
|
class MoodboardHelper {
setTestHelper(ui)
{
this.ui = ui;
return this;
}
setWrapper(wrapper)
{
this.wrapper = wrapper;
return this;
}
getImages()
{
return [
{id: 1, src: 'abc.jpg', url: 'https://loremflickr.com/549/280/?71087', width: 549, height: 280},
{id: 2, src: 'def.jpg', url: 'https://loremflickr.com/247/424/?62311', width: 247, height: 424},
{id: 3, src: 'ghi.jpg', url: 'https://loremflickr.com/227/251/?44689', width: 227, height: 251},
];
}
}
export default MoodboardHelper;
|
var vumigo = require('vumigo_v02');
var libxml = require('libxmljs');
var crypto = require('crypto');
var App = vumigo.App;
var Choice = vumigo.states.Choice;
var ChoiceState = vumigo.states.ChoiceState;
var FreeText = vumigo.states.FreeText;
var EndState = vumigo.states.EndState;
var HttpApi = vumigo.http.api.HttpApi;
var utils = vumigo.utils;
var InteractionMachine = vumigo.InteractionMachine;
// Thanks SO!
// http://stackoverflow.com/q/1353684
function isValidDate(d) {
if (Object.prototype.toString.call(d) !== "[object Date]") {
return false;
}
return !isNaN(d.getTime());
}
// Thanks SO!
// http://stackoverflow.com/a/1685917
function toFixed(x) {
if (Math.abs(x) < 1.0) {
var e = parseInt(x.toString().split('e-')[1]);
if (e) {
x *= Math.pow(10,e-1);
x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);
}
} else {
var e = parseInt(x.toString().split('+')[1]);
if (e > 20) {
e -= 20;
x /= Math.pow(10,e);
x += (new Array(e+1)).join('0');
}
}
return x;
}
var zero_pad = function(v) {
return v < 10 ? '0' + v : v;
};
var CDA_Template = [
'<?xml version="1.0"?>',
'<ClinicalDocument xmlns="urn:hl7-org:v3" xmlns:cda="urn:hl7-org:v3" xmlns:voc="urn:hl7-org:v3/voc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:pcc="urn:ihe:pcc:hl7v3" xmlns:lab="urn:oid:1.3.6.1.4.1.19376.1.3.2" xmlns:sdtc="urn:hl7-org:sdtc" xsi:schemaLocation="urn:hl7-org:v3 CDA.xsd">',
'<typeId root="2.16.840.1.113883.1.3" extension="POCD_HD000040"/>',
'<templateId root="2.16.840.1.113883.10" extension="IMPL_CDAR2_LEVEL1"/>',
'<id root="${uniqueId}"/>',
'<code code="51855-5" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>',
'<title>SA National Pregnancy Register - Patient Note</title>',
'<!-- Creation time of document, e.g. 20140217121212 -->',
'<effectiveTime value="${createdTime}"/>',
'<confidentialityCode code="N" displayName="Normal" codeSystem="2.16.840.1.113883.5.25" codeSystemName="Confidentiality"/>',
'<languageCode code="en-UK"/>',
'<!-- Client details -->',
'<recordTarget>',
' <patientRole>',
' <!-- Patient Identifier -->',
' <!-- The value for extension must be specified in HL7 CX format: -->',
' <!-- id^^^assigningAuthority^typeCode -->',
' <!-- The typeCode specified the type of identifier, e.g. NI for National Identifier or PPN for Passport Number -->',
' <!-- The assigningAuthority specifies the issuer of the id, e.g. ZAR for South Africa -->',
' <!-- An example for a South African National ID is: -->',
' <!-- <id extension="7612241234567^^^ZAF^NI" root="526ef9c3-6f18-420a-bc53-9b733920bc67" /> -->',
' <id extension="${pidCX}" root="526ef9c3-6f18-420a-bc53-9b733920bc67"/>',
' <addr/>',
' <!-- Telephone number in RFC3966 format, e.g. tel:+27731234567 -->',
' <telecom value="tel:${cellNumber}"/>',
' <patient>',
' <name>',
' <given>${givenName}</given>',
' <family>${familyName}</family>',
' </name>',
' <administrativeGenderCode code="F" codeSystem="2.16.840.1.113883.5.1"/>',
' <!-- e.g. 19700123 -->',
' <birthTime value="${birthDate}"/>',
' <languageCommunication>',
' <languageCode code="${languageCode}"/>',
' <preferenceInd value="true"/>',
' </languageCommunication>',
' </patient>',
' </patientRole>',
'</recordTarget>',
'<!-- HCW Details -->',
'<author>',
' <time value="${time}"/>',
' <assignedAuthor>',
' <id extension="${hcwCode}" root="833f2856-b9e1-4f54-8694-c74c4283755f" assigningAuthorityName="HCW Code"/>',
' <addr/>',
' <telecom value="tel:${hcwCellNumber}"/>',
' <assignedPerson>',
' <name>',
' <given>${hcwGivenName}</given>',
' <family>${hcwFamilyName}</family>',
' </name>',
' </assignedPerson>',
' <representedOrganization>',
' <id extension="${facilityId}" root="ab8c9bd1-26e9-47bf-8bbe-3524fccb9f2c" assigningAuthorityName="Facility Code"/>',
' <name>${facilityName}</name>',
' </representedOrganization>',
' </assignedAuthor>',
'</author>',
'<custodian>',
' <assignedCustodian>',
' <representedCustodianOrganization>',
' <id root="a5881e6c-b42e-4559-a1fd-d1dc52379658"/>',
' <name>SA National Department of Health</name>',
' </representedCustodianOrganization>',
' </assignedCustodian>',
'</custodian>',
'<documentationOf>',
' <serviceEvent classCode="PCPR">',
' <effectiveTime value="${encounterDateTime}"/>',
' </serviceEvent>',
'</documentationOf>',
'<component>',
' <structuredBody>',
' <component>',
' <section>',
' <code code="57060-6" displayName="Estimated date of delivery Narrative" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>',
' <text>',
' <table>',
' <thead>',
' <tr>',
' <td>Pregnancy status</td>',
' <td>Note Date</td>',
' <td>Delivery Date (Estimated)</td>',
' </tr>',
' </thead>',
' <tbody>',
' <!-- e.g. -->',
' <tr>',
' <td>Pregnancy confirmed</td>',
' <td>2014-02-17</td>',
' <td>2014-10-17</td>',
' </tr>',
' </tbody>',
' </table>',
' </text>',
' <entry>',
' <!-- Pregnancy Status -->',
' <observation classCode="OBS" moodCode="EVN">',
' <code code="11449-6" displayName="Pregnancy status" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>',
' <text/>',
' <statusCode code="completed"/>',
' <!-- e.g. 20140217 -->',
' <effectiveTime value="${effectiveTime}"/>',
' <!-- one of \'value\' -->',
' <value xsi:type="CE" code="77386006" displayName="Pregnancy confirmed" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>',
' <!--<value xsi:type="CE" code="102874004" displayName="Unconfirmed pregnancy" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>-->',
' <!--<value xsi:type="CE" code="60001007" displayName="Not pregnant" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>-->',
' <!--<value xsi:type="CE" code="289256000" displayName="Mother delivered" codeSystem="2.16.840.1.113883.6.96" codeSystemName="SNOMED CT"/>-->',
' <!-- Remove entryRelationship if \'Not pregnant\' -->',
' <entryRelationship typeCode="SPRT" inversionInd="true">',
' <!-- Delivery Date -->',
' <observation classCode="OBS" moodCode="EVN">',
' <!-- one of \'code\' -->',
' <code code="11778-8" displayName="Delivery date Estimated" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/>',
' <!-- <code code="8665-2" displayName="Last menstrual period start date" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/> -->',
' <!-- Delivery Date (if \'Mother Delivered\') -->',
' <!-- <code code="21112-8" displayName="Birth date" codeSystem="2.16.840.1.113883.6.1" codeSystemName="LOINC"/> -->',
' <text/>',
' <statusCode code="completed"/>',
' <!-- e.g. 20141017 -->',
' <value xsi:type="TS" value="${date}"/>',
' </observation>',
' </entryRelationship>',
' </observation>',
' </entry>',
' </section>',
' </component>',
' </structuredBody>',
'</component>',
'</ClinicalDocument>'
].join('\n');
var GoNDOH = App.extend(function(self) {
App.call(self, 'states:name');
self.init = function() {
return self.im.contacts.for_user().then(function(user_contact) {
self.contact = user_contact;
});
};
self.get_nid = function() {
return (
self.im.user.get_answer('states:nid_1') +
self.im.user.get_answer('states:nid_2') +
self.im.user.get_answer('states:nid_3') +
self.im.user.get_answer('states:nid_4'));
};
self.states.add('states:name', function(name) {
return new FreeText(name, {
next: 'states:surname',
question: ('Welcome to the Pregnancy Registration Vumi Demo.\n' +
'What is your name?')
});
});
self.states.add('states:surname', function(name) {
return new FreeText(name, {
next: 'states:dob',
question: 'What is your surname?'
});
});
self.states.add('states:dob', function(name) {
return new FreeText(name, {
next: 'states:nid_1',
question: 'What is your date of birth? (YYYY-MM-DD)',
check: function(content) {
if(!isValidDate(new Date(content))) {
return 'Please provide the date in the YYYY-MM-DD format:';
}
}
});
});
self.states.add('states:nid_1', function(name) {
return new FreeText(name, {
next: 'states:nid_2',
question: 'Please enter the first 4 digits of your National ID:'
});
});
self.states.add('states:nid_2', function(name) {
return new FreeText(name, {
next: 'states:nid_3',
question: 'Please enter the second 4 digits of your National ID:'
});
});
self.states.add('states:nid_3', function(name) {
return new FreeText(name, {
next: 'states:nid_4',
question: 'Please enter the next 4 digits of your National ID:'
});
});
self.states.add('states:nid_4', function(name) {
return new FreeText(name, {
next: 'states:nid_confirm',
question: 'Please enter the last 4 digits of your National ID:'
});
});
self.states.add('states:nid_confirm', function(name) {
return new ChoiceState(name, {
question: 'Please confirm your National ID:\n' + self.get_nid() + '\n',
next: function(choice) {
return (choice.value == 'correct' ?
'states:last_menstruation' : 'states:nid_1');
},
choices: [
new Choice('correct', 'This is correct.'),
new Choice('incorrect', 'This is incorrect.')
]
});
});
self.states.add('states:last_menstruation', function(name) {
return new FreeText(name, {
question: 'When was your last menstruation? (YYYY-MM-DD)',
next: 'states:pregnancy_status',
check: function(content) {
if(!isValidDate(new Date(content))) {
return 'Please provide the date in the YYYY-MM-DD format:';
}
}
});
});
self.states.add('states:pregnancy_status', function(name) {
return new ChoiceState(name, {
question: 'Do you think you are pregnant or has it been confirmed?',
choices: [
new Choice('suspected', 'I suspect I am pregnant.'),
new Choice('confirmed', 'It has been confirmed, I am pregnant.')
],
next: function(choice) {
var contact = self.contact;
var user = self.im.user;
contact.name = user.get_answer('states:name');
contact.surname = user.get_answer('states:surname');
contact.dob = new Date(user.get_answer('states:dob')).toISOString();
contact.extra.last_menstruation = new Date(user.get_answer('states:last_menstruation')).toISOString();
contact.extra.pregnancy_status = user.get_answer('states:pregnancy_status');
contact.extra.nid = self.get_nid();
return self.im.contacts.save(contact)
.then(function() {
return self.jembi_api_call(self.build_cda_doc());
})
.then(function(result) {
return result.code == 200 ? 'states:end' : 'states:error';
});
}
});
});
self.states.add('states:end', function(name) {
return new EndState(name, {
text: 'Thank you! Your details have been captured.',
next: 'states:name'
});
});
self.states.add('states:error', function(name) {
return new EndState(name, {
text: 'Sorry, something went wrong when saving the data. Please try again.',
next: 'states:name'
});
});
self.format_dob = function(dob) {
var d = new Date(dob);
return (d.getFullYear() +
zero_pad(d.getMonth() + 1) +
zero_pad(d.getDate()));
};
self.get_timestamp = function() {
var d = new Date();
return (
d.getFullYear() +
zero_pad(d.getMonth() + 1) +
zero_pad(d.getDate()) +
zero_pad(d.getHours()) +
zero_pad(d.getMinutes()) +
zero_pad(d.getSeconds()));
};
self.get_uuid = function () {
return utils.uuid();
};
self.get_oid = function () {
var uuid = self.get_uuid();
var hex = uuid.replace('-', '');
var number = parseInt(hex, 16);
return '2.25.' + toFixed(number);
};
self.build_metadata = function(cda_docstr) {
var shasum = crypto.createHash('sha1');
shasum.update(cda_docstr);
return {
"documentEntry": {
"patientId": self.get_nid() + "^^^ZAF^NI",
"uniqueId": self.get_oid(),
"entryUUID": "urn:uuid:" + self.get_uuid(),
// NOTE: these need to be these hard coded values according to
// https://jembiprojects.jira.com/wiki/display/NPRE/Save+Registration+Encounter
"classCode": { "code": "51855-5", "codingScheme": "2.16.840.1.113883.6.1", "codeName": "Patient Note" },
"typeCode": { "code": "51855-5", "codingScheme": "2.16.840.1.113883.6.1", "codeName": "Patient Note" },
"formatCode": { "code": "npr-pn-cda", "codingScheme": "4308822c-d4de-49db-9bb8-275394ee971d", "codeName": "NPR Patient Note CDA" },
"mimeType": "text/xml",
"hash": shasum.digest('hex'),
"size": cda_docstr.length
}
};
};
self.replace_element = function (element, content) {
var parent = element.parent();
var replacement = new libxml.Element(
element.doc(), element.name(), content);
parent.addChild(replacement);
element.remove();
return replacement;
};
self.update_attr = function (element, attname, attvalue) {
var attrs = {};
attrs[attname] = attvalue;
return element.attr(attrs);
};
self.build_cda_doc = function() {
/**
HERE BE MODERATE DRAGONS
**/
var user = self.im.user;
var doc = libxml.parseXmlString(CDA_Template);
var map = {
'//*[@root="${uniqueId}"]': function (element) {
return self.update_attr(element, 'root', self.get_uuid());
},
'//*[@value="${createdTime}"]': function (element) {
return self.update_attr(element, 'value', self.get_timestamp());
},
'//*[@extension="${pidCX}"]': function (element) {
return self.update_attr(element, 'extension', self.get_nid() + '^^^ZAF^NI');
},
'//*[@value="tel:${cellNumber}"]': function (element) {
return self.update_attr(element, 'value', 'tel:' + user.addr);
},
'//*[text()="${givenName}"]': function (element) {
return self.replace_element(element, user.get_answer('states:name'));
},
'//*[text()="${familyName}"]': function (element) {
return self.replace_element(element, user.get_answer('states:surname'));
},
'//*[@value="${birthDate}"]': function (element) {
return self.update_attr(
element, 'value', self.format_dob(user.get_answer('states:dob')));
},
'//*[@code="${languageCode}"]': function (element) {
return self.update_attr(
element, 'code', 'en');
},
'//*[@value="${time}"]': function (element) {
return self.update_attr(
element, 'value', self.get_timestamp());
},
'//*[@value="tel:${hcwCellNumber}"]': function (element) {
return self.update_attr(element, 'value', 'tel:' + user.addr);
},
'//*[@extension="${hcwCode}"]': function (element) {
return self.update_attr(element, 'extension', '1234');
},
'//*[text()="${hcwGivenName}"]': function (element) {
return self.replace_element(element, 'Grace');
},
'//*[text()="${hcwFamilyName}"]': function (element) {
return self.replace_element(element, 'Doctor');
},
'//*[@extension="${facilityId}"]': function (element) {
return self.update_attr(element, 'extension', '2345');
},
'//*[text()="${facilityName}"]': function (element) {
return self.replace_element(element, 'Good Health Center');
},
'//*[@value="${encounterDateTime}"]': function (element) {
return self.update_attr(element, 'value', self.get_timestamp().slice(0, 8));
},
'//*[@value="${effectiveTime}"]': function (element) {
return self.update_attr(element, 'value', self.get_timestamp().slice(0, 8));
},
'//*[@value="${date}"]': function (element) {
return self.update_attr(element, 'value', self.get_timestamp().slice(0, 8));
}
};
Object.keys(map).forEach(function (key) {
var elements = doc.find(key);
elements.forEach(function (element) {
handler = map[key];
handler(element);
});
});
return doc;
};
self.build_multipart_data = function(boundary, parts) {
return parts.map(function (part) {
return [
'--' + boundary,
'Content-Disposition: form-data; name="' + part.name + '"; filename="' + part.file_name + '"',
'Content-Type: ' + part.content_type,
'',
part.body,
''
].join('\n');
}).join('\n').trim();
};
self.build_request_data = function (doc, boundary) {
var docstr = doc.toString().trim();
return self.build_multipart_data(boundary, [
{
name: "ihe-mhd-metadata",
file_name: 'MHDMetadata.json',
content_type: 'application/json',
body: JSON.stringify(self.build_metadata(docstr))
},
{
name: 'content',
file_name: 'CDARequest.xml',
content_type: 'text/xml',
body: docstr
}
]);
};
self.jembi_api_call = function (doc) {
var http = new HttpApi(self.im, {
auth: {
username: self.im.config.jembi.username,
password: self.im.config.jembi.password
}
});
return http.post(self.im.config.jembi.url, {
data: self.build_request_data(doc, 'yolo'),
headers: {
'Content-Type': ['multipart/form-data; boundary=yolo']
}
});
};
});
if (typeof api != 'undefined') {
new InteractionMachine(api, new GoNDOH());
}
this.GoNDOH = GoNDOH;
|
/**
* @name 地区枚举
*/
import base from './base'
const {file_host} = base
export default [
{
icon:`${file_host}/1.png`,
text:'每日健康提醒',
url:'#/lists/health'
},
{
icon:`${file_host}/2.png`,
text:'我的治病经验',
url:'#/experience'
},
{
icon:`${file_host}/3.png`,
text:'疑难杂症120',
url:'#/difficult'
},
{
icon:`${file_host}/4.png`,
text:'出生缺陷预防',
url:'#/prevention'
},
{
icon:`${file_host}/5.png`,
text:'专家孕哺讲座',
url:'http://www.669669669.com/Wap/healthuser/exptlect.html'
},
{
icon:`${file_host}/6.png`,
text:'青春婚恋须知',
url:'#/notes'
},
{
icon:`${file_host}/7.png`,
text:'交友大世界',
url:'#/firends'
},
{
icon:`${file_host}/8.png`,
text:'健康送爸妈',
url:'#/health'
},
{
icon:`${file_host}/9.png`,
text:'百行孝居先',
url:'#/fealty'
},
{
icon:'',
text:''
},
{
icon:`${file_host}/10.png`,
text:'我是传播人',
url:'#/spread'
},
{
icon:'',
text:''
},
]
|
function MainMenu() {
this.background = null;
};
MainMenu.prototype = {
preload: function() {
console.log("Main Menu PRELOADING");
},
create: function() {
this.level_change_triggered = false;
this.background = game.add.sprite(0,0, 'mainMenuBackground');
this.adc_logo = new ADCLogo(1100, 775, 'adcLogo');
//----------------------------
title_button_background = game.add.sprite(598, 526, 'AllGameTextures');
this.title_button_background = title_button_background;
//for tweening
this.title_button_background.x = 598;
this.title_button_background.y = 1063;
this.title_button_background.frameName = 'introModule.png';
this.title_button_background.anchor.setTo(0.5, 0.5);
this.title_button_background_tween = game.add.tween(this.title_button_background);
// this.title_button_background_tween.to({ y: 526 }, 1000, Phaser.Easing.Linear.None);
// this.title_button_background_tween.to({ y: 526 }, 1000, Phaser.Easing.Elastic.Out);
this.title_button_background_tween.to({ y: 526 }, 1000, Phaser.Easing.Bounce.Out);
//-------------
title_play_button = game.add.button(598, 648, 'AllGameTextures', this.performPlayButtonPress, this, 'playNowButton.png', 'playNowButton.png', 'playNowButton_down.png', 'playNowButton.png');
this.title_play_button = title_play_button;
this.title_play_button.anchor.setTo(0.5, 0.5);
this.title_play_button.scale.setTo(0, 0);
this.title_play_button_tween = game.add.tween(this.title_play_button.scale);
// this.title_play_button_tween.to({ x: 1, y: 1 }, 500, Phaser.Easing.Linear.Out);
this.title_play_button_tween.to({ x: 1, y: 1 }, 500, Phaser.Easing.Elastic.Out);
// this.title_play_button_tween.to({ x: 1, y: 1 }, 500, Phaser.Easing.Bounce.Out);
this.title_button_background_tween.onComplete.add((function() {
this.title_play_button_tween.start();
}), this);
//-------------
title_image = game.add.sprite(601, 210, 'AllGameTextures');
this.title_image = title_image;
//for tweening
this.title_image.x = 601;
this.title_image.y = -117;
this.title_image.frameName = 'dw_logo_large.png';
this.title_image.anchor.setTo(0.5, 0.5);
this.title_image_tween = game.add.tween(this.title_image);
// this.title_image_tween.to({ y: 210 }, 250, Phaser.Easing.Linear.None);
// this.title_image_tween.to({ y: 210 }, 1000, Phaser.Easing.Elastic.Out);
this.title_image_tween.to({ y: 210 }, 1000, Phaser.Easing.Bounce.Out);
//----------------------------
//creates the lens flare animation and sets the on complete call back to trigger the tweening in of the other elements
lens_flare = new LensFlare(0, 0, 'LensFlare')
this.lens_flare = lens_flare;
this.lens_flare.animations.getAnimation('lensFlare').onComplete.add(this.triggerTweenIns, this);
this.fader = new Fader(600, 400);
this.fader.fadebg.alpha = 1;
this.fader.startFade(1, 0, 1000);
game.input.onDown.add(this.performTouchLogic, this);
this.triggerIntroAnimation();
resizeGame();
},
render: function() {
// game.debug.pointer(game.input.activePointer);
// game.debug.spriteBounds(overlay);
// game.debug.spriteInfo(playerShip, 32, 32);
// game.debug.text('Distance Travelled: ' + this.playerShip.distanceTravelledY, 500, 32);
},
update: function() {
if (game.input.keyboard.isDown(Phaser.Keyboard.F)) {
if(!this.level_change_triggered) {
this.triggerLevelChange();
}
}
},
triggerIntroAnimation: function() {
this.lens_flare.play('lensFlare');
},
triggerTweenIns: function() {
this.title_image_tween.start();
this.title_button_background_tween.start();
},
triggerLevelChange: function() {
if(!this.level_change_triggered) {
this.level_change_triggered = true;
this.fader = new Fader(600, 400);
this.fader.startFade(0, 1, 1000, function() { game.state.start('FlappyDragon'); } );
}
},
performPlayButtonPress: function() {
this.triggerLevelChange();
window.event_tracker.play_button_pressed++;
CNEventer.send_adc_event('DOWNLOAD');
},
performTouchLogic: function() {
}
};
|
import { combineReducers } from 'redux';
import songListReducer from './songListReducer';
import selectedSongReducer from './selectedSongReducer';
export default combineReducers({
songs: songListReducer,
selectedSong: selectedSongReducer
});
|
import React from 'react';
import {View, Text, TouchableOpacity, StyleSheet, Image, Dimensions, Alert} from 'react-native';
import PropTypes from "prop-types";
import Colors from "../constants/Colors";
const {width: SCREEN_WIDTH, height: SCREEN_HEIGHT} = Dimensions.get("window");
const SavedCardListItem = (props) => {
const {
containerStyle,
detailStyle,
cardType,
_handleNavigate,
addressId,
cardTypeTextStyle,
creditCardNumber,
Name,
buy,
navigatePage,
expire_Date,
NameTextStyle,
creditCardNumberTextStyle,
} = props;
return (
<TouchableOpacity
onPress={() => _handleNavigate(navigatePage, {params: {addressId}})}
style={[styles.container, containerStyle]}>
<View
style={[styles.detail, detailStyle]}>
<Text
style={[styles.cardTypeTextStyle, cardTypeTextStyle]}>
{cardType}
</Text>
<Text
style={[styles.creditCardNumberTextStyle,creditCardNumberTextStyle]}>
{creditCardNumber}
</Text>
<View style={{
flexDirection:'row',
justifyContent:'space-between',
}}>
<Text
style={[styles.NameStyleTextStyle,NameTextStyle]}>
{Name}
</Text>
<Text
style={[styles.NameStyleTextStyle,NameTextStyle]}>
{expire_Date}
</Text>
</View>
</View>
</TouchableOpacity>
)
}
const styles = StyleSheet.create({
container : {
height: SCREEN_HEIGHT / 7,
elevation: 2,
backgroundColor: '#FFF',
marginTop: 20,
borderRadius: 15,
marginBottom: 10,
width: (SCREEN_WIDTH - 20) / 2.6,
paddingVertical: 10,
marginHorizontal: 10
},
detail:{
flexDirection: 'column',
paddingTop: 15,
paddingHorizontal: 10,
height: "40%"
},
cardTypeTextStyle: {
color: '#FF8303',
fontWeight: 'bold',
fontSize: 13,
textAlign: 'center',
},
creditCardNumberTextStyle: {
fontWeight: 'bold',
top:6,
fontSize: 10,
textAlign: 'center',
},NameStyleTextStyle: {
top:8,
fontWeight: 'bold',
fontSize: 13,
color: '#FF8303',
textAlign: 'center',
},
})
SavedCardListItem.propTypes = {
containerStyle: PropTypes.object,
detailStyle: PropTypes.object,
cardType: PropTypes.string.isRequired,
cardTypeTextStyle: PropTypes.object,
creditCardNumberTextStyle: PropTypes.object,
creditCardNumber: PropTypes.string.isRequired,
Name: PropTypes.string.isRequired,
navigatePage: PropTypes.string,
}
SavedCardListItem.defaultProps = {
containerStyle: {},
detailStyle: {},
cardTypeTextStyle: {},
creditCardNumberTextStyle: {},
NameTextStyle: {},
navigatePage: "Products",
}
export default SavedCardListItem;
|
module.exports = app => {
const sectionModel = require('../models/sections/section.model.server');
const enrollmentModel = require('../models/enrollments/enrollment.model.server');
// find all enrollments
app.get('/api/enrollment', (req, res) =>
enrollmentModel.findAllEnrollments()
.then(enrollments => res.send(enrollments))
);
// enrolls student into a section
app.post('/api/section/:sectionId/enrollment', (req, res) => {
let sectionId = req.params['sectionId'];
let currentUser = req.session['currentUser'];
var thisSection = {};
if (currentUser !== undefined) {
let enrollment = {
student: currentUser._id,
section: sectionId
};
sectionModel.findSectionById(sectionId)
.then((section) => {
thisSection = section;
if (section.availableSeats <= 0) {
return res.sendStatus(409);
}
})/*
.then(() => {
enrollmentModel.findEnrollmentByStudentAndSection(enrollment.student, enrollment.section)
.then(response => {
if (response !== null) {
return res.sendStatus(403);
}
});
}).then(() => {
sectionModel.findAllSectionsForCourseAndStudent(thisSection.courseId, enrollment.student)
.then(response => {
if (response !== null) {
return res.sendStatus(406);
}
});
})
*/
.then(() => sectionModel.subSectionSeat(sectionId))
.then(() => enrollmentModel.createEnrollment(enrollment))
.then(() => res.send(enrollment)
)
}
}
);
// retrieves all the sections a student is enrolled in
app.get('/api/student/section/', (req, res) => {
let currentUser = req.session.currentUser;
if (currentUser !== undefined) {
let studentId = currentUser._id;
enrollmentModel.findAllSectionsForStudent(studentId)
.then((enrollments) => res.send(enrollments));
}
}
);
// un-enrolls a student from a section
app.delete('/api/section/:sectionId/enrollment', (req, res) => {
let currentUser = req.session.currentUser;
let sectionId = req.params['sectionId'];
if (currentUser !== undefined) {
let studentId = currentUser._id;
sectionModel.addSectionSeat(sectionId)
.then(() => enrollmentModel.deleteEnrollment(studentId, sectionId))
.then(() => res.sendStatus(200));
}
}
);
};
|
import React from 'react';
import {Field, reduxForm} from 'redux-form';
import {Textarea} from '../../common/FormsControls/FormsControls';
import {required, maxLengthCreator} from '../../../utils/validators/validators';
import {Button, Form} from 'react-bootstrap';
import {nameAddMessageForm} from '../../common/FormsControls/paramsForms';
const maxLength50 = maxLengthCreator(50);
const AddMessageForm = (props) => {
return(
<Form onSubmit={props.handleSubmit} className="mt-3 mb-3">
<Field component={Textarea}
validate = {[required, maxLength50]}
name={"newMessageBody"} placeholder='Enter your message'/>
<Button variant="outline-success" type="submit">Send</Button>
</Form>
)
}
export default reduxForm({form: nameAddMessageForm})(AddMessageForm);
|
import React from 'react'
import Link from 'gatsby-link'
const IndexPageEn = () => (
<div>
<div className="Hero">
<div className="HeroGroup">
<h1>HK Promising Academy</h1>
<h2>We free our students from the restriction of locations by <strong>teaching online</strong>.</h2>
<p>we group graduates in multiple universities all around the world. All our teachers are your seniors in different fields from <strong>world Top-30</strong> universities.</p>
{/* <div className="Contact">
<Link to="/page-contact/">Contact Us</Link>
</div> */}
<div className="Logos">
<img src={require("../images/AP.png")} height="50" />
<img src={require("../images/ALEVEL.png")} height="50" />
<img src={require("../images/IGCSE.png")} height="50" />
</div>
</div>
</div>
</div>
)
export default IndexPageEn
|
const Sequelize = require('sequelize');
const DatabaseNormalizer = require("../util/DatabaseNormalizer");
const JalaliDate = require("../util/JalaliDate");
const {firstWithValue} = DatabaseNormalizer;
module.exports = (sequelize, DataTypes) => {
return VisitAppointment.init(sequelize, DataTypes);
}
class VisitAppointment extends Sequelize.Model {
static init(sequelize, DataTypes) {
super.init({
id: {
autoIncrement: true,
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
field: 'IDVisit',
},
patientUserId: {
type: DataTypes.INTEGER,
allowNull: false,
field: 'UserIDPatient',
},
expired: {
type: DataTypes.VIRTUAL,
get() {
const jalali = JalaliDate.create(this.scheduledVisitDate.jalali.asString);
return !this.hasVisitHappened && jalali.isValidDate() && jalali.compareWithToday() < 0;
},
set() {
return null;
}
},
isScheduled: {
type: DataTypes.VIRTUAL,
get() {
return this.scheduledVisitDate.iso != null;
},
set() {
return null;
}
},
approximateVisitDate: {
type: DataTypes.VIRTUAL,
get() {
const jalali = JalaliDate.create({
year: this.approximateVisitYear,
month: this.approximateVisitMonth,
day: this.approximateVisitDay,
});
return jalali.toJson();
},
set(value) {
const jalali = JalaliDate.create(value).toJson().jalali.asObject;
this.approximateVisitYear= jalali.year;
this.approximateVisitMonth= jalali.month;
this.approximateVisitDay= jalali.day;
}
},
scheduledVisitDate: {
type: DataTypes.VIRTUAL,
get() {
const jalali = JalaliDate.create({
year: this.visitYear,
month: this.visitMonth,
day: this.visitDay,
});
return jalali.toJson();
},
set(value) {
const jalali = JalaliDate.create(value).toJson().jalali.asObject;
this.visitYear = jalali.year || null;
this.visitMonth = jalali.month || null;
this.visitDay = jalali.day || null;
}
},
scheduledVisitTime: {
type: DataTypes.VIRTUAL,
get() {
const [hour, minute] = [Number(this.visitHour || 0), Number(this.visitMinute || 0)];
const hourStr = hour.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false});
const minuteStr = minute.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false});
const time = {
asString: `${hourStr}:${minuteStr}`,
asObject: {
hour,
minute,
},
asArray: [hour, minute],
};
return time;
},
set(value) {
if (!value) return;
const [hour, minute] = [Number(value.hour || 0), Number(value.minute || 0)];
const hourStr = hour.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false});
const minuteStr = minute.toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false});
this.visitHour = hourStr;
this.visitMinute = minuteStr;
}
},
hasVisitHappened: {
type: DataTypes.STRING(1),
allowNull: true,
field: 'FlagVisit',
defaultValue: "0",
get() {
return DatabaseNormalizer.booleanValue(this.getDataValue('hasVisitHappened'));
},
set(value) {
this.setDataValue('hasVisitHappened', DatabaseNormalizer.booleanToNumberedString(value));
}
},
approximateVisitYear: {
type: DataTypes.STRING(4),
allowNull: false,
field: 'AYearVisit',
},
approximateVisitMonth: {
type: DataTypes.STRING(2),
allowNull: false,
field: 'AMonthVisit',
},
approximateVisitDay: {
type: DataTypes.STRING(2),
allowNull: false,
field: 'ADayVisit',
},
visitYear: {
type: DataTypes.STRING(4),
allowNull: true,
field: 'YearVisit',
},
visitMonth: {
type: DataTypes.STRING(2),
allowNull: true,
field: 'MonthVisit',
},
visitDay: {
type: DataTypes.STRING(2),
allowNull: true,
field: 'DayVisit',
},
visitHour: {
type: DataTypes.STRING(2),
allowNull: true,
field: 'HourVisit',
},
visitMinute: {
type: DataTypes.STRING(2),
allowNull: true,
field: 'MinuteVisit',
},
}, {
sequelize,
tableName: 'AppointmentTbl',
schema: 'myinrir_test',
timestamps: false,
indexes: [
{
name: "PK_appointmentTbl",
unique: true,
fields: [
{ name: "IDVisit" },
]
},
],
scopes: {
expired: {
where: {
}
},
attended: {
where: {
hasVisitHappened: true,
}
},
},
});
return VisitAppointment;
}
}
VisitAppointment.prototype.getApiObject = function () {
const plainObject = this.get({plain: true});
return {
id: plainObject.id,
patientUserId: plainObject.patientUserId,
hasVisitHappened: plainObject.hasVisitHappened,
expired: plainObject.expired,
isScheduled: plainObject.isScheduled,
approximateVisitDate: plainObject.approximateVisitDate,
scheduledVisitDate: plainObject.scheduledVisitDate,
scheduledVisitTime: plainObject.scheduledVisitTime,
}
}
|
// TODO: upload empty texture if null ? maybe not
// TODO: upload identity matrix if null ?
// TODO: sampler Cube
let ID = 1;
// cache of typed arrays used to flatten uniform arrays
const arrayCacheF32 = {};
export class Program {
constructor(renderer, { vertex = undefined, fragment = undefined, uniforms = {}, transparent = false, depthTest = true, depthWrite = true, depthFunc = WebGLRenderingContext.LESS, } = {}) {
this.renderer = renderer;
this.gl = this.renderer.gl;
this.id = ID++;
this.uniforms = uniforms;
if (!vertex)
console.warn("vertex shader not supplied");
if (!fragment)
console.warn("fragment shader not supplied");
// Store program state
this.transparent = transparent;
this.depthTest = depthTest;
this.depthWrite = depthWrite;
this.depthFunc = depthFunc;
this.blendFunc = {};
this.blendEquation = {};
// set default blendFunc if transparent flagged
if (this.transparent && !this.blendFunc.src) {
if (this.renderer.premultipliedAlpha)
this.setBlendFunc(this.gl.ONE, this.gl.ONE_MINUS_SRC_ALPHA);
else
this.setBlendFunc(this.gl.SRC_ALPHA, this.gl.ONE_MINUS_SRC_ALPHA);
}
// compile vertex shader and log errors
const vertexShader = this.gl.createShader(this.gl.VERTEX_SHADER);
this.gl.shaderSource(vertexShader, vertex);
this.gl.compileShader(vertexShader);
if (this.gl.getShaderInfoLog(vertexShader) !== "") {
console.warn(`${this.gl.getShaderInfoLog(vertexShader)}\nVertex Shader\n${addLineNumbers(vertex)}`);
}
// compile fragment shader and log errors
const fragmentShader = this.gl.createShader(this.gl.FRAGMENT_SHADER);
this.gl.shaderSource(fragmentShader, fragment);
this.gl.compileShader(fragmentShader);
if (this.gl.getShaderInfoLog(fragmentShader) !== "") {
console.warn(`${this.gl.getShaderInfoLog(fragmentShader)}\nFragment Shader\n${addLineNumbers(fragment)}`);
}
// compile program and log errors
this.program = this.gl.createProgram();
this.gl.attachShader(this.program, vertexShader);
this.gl.attachShader(this.program, fragmentShader);
this.gl.linkProgram(this.program);
if (!this.gl.getProgramParameter(this.program, this.gl.LINK_STATUS)) {
console.warn(this.gl.getProgramInfoLog(this.program));
return;
}
// Remove shader once linked
this.gl.deleteShader(vertexShader);
this.gl.deleteShader(fragmentShader);
// Get active uniform locations
this.uniformLocations = new Map();
let numUniforms = this.gl.getProgramParameter(this.program, this.gl.ACTIVE_UNIFORMS);
for (let uIndex = 0; uIndex < numUniforms; uIndex++) {
let uniform = this.gl.getActiveUniform(this.program, uIndex);
const split = uniform.name.match(/(\w+)/g);
let uniformData = {
location: this.gl.getUniformLocation(this.program, uniform.name),
uniformName: split[0],
isStruct: false,
};
if (split.length === 3) {
uniformData.isStructArray = true;
uniformData.structIndex = Number(split[1]);
uniformData.structProperty = split[2];
}
else if (split.length === 2 && isNaN(Number(split[1]))) {
uniformData.isStruct = true;
uniformData.structProperty = split[1];
}
this.uniformLocations.set(uniform, uniformData);
}
// Get active attribute locations
this.attributeLocations = new Map();
const locations = [];
const numAttribs = this.gl.getProgramParameter(this.program, this.gl.ACTIVE_ATTRIBUTES);
for (let aIndex = 0; aIndex < numAttribs; aIndex++) {
const attribute = this.gl.getActiveAttrib(this.program, aIndex);
const location = this.gl.getAttribLocation(this.program, attribute.name);
locations[location] = attribute.name;
this.attributeLocations.set(attribute, location);
}
this.attributeOrder = locations.join("");
}
setBlendFunc(src, dst, srcAlpha = undefined, dstAlpha = undefined) {
this.blendFunc.src = src;
this.blendFunc.dst = dst;
this.blendFunc.srcAlpha = srcAlpha;
this.blendFunc.dstAlpha = dstAlpha;
if (src)
this.transparent = true;
}
setBlendEquation(modeRGB, modeAlpha) {
this.blendEquation.modeRGB = modeRGB;
this.blendEquation.modeAlpha = modeAlpha;
}
use() {
let textureUnit = -1;
const programActive = this.renderer.currentProgram === this.id;
// Avoid gl call if program already in use
if (!programActive) {
this.gl.useProgram(this.program);
this.renderer.currentProgram = this.id;
}
// Set only the active uniforms found in the shader
this.uniformLocations.forEach((location, activeUniform) => {
let name = location.uniformName;
// get supplied uniform
let uniform = this.uniforms[name];
// For structs, get the specific property instead of the entire object
if (location.isStruct) {
uniform = uniform[location.structProperty];
//name += `.${location.structProperty}`;
}
if (location.isStructArray) {
uniform = uniform[location.structIndex][location.structProperty];
//name += `[${location.structIndex}].${location.structProperty}`;
}
// if (!uniform) {
// return warn(`Active uniform ${name} has not been supplied`);
// }
// if (uniform && uniform.value === undefined) {
// return warn(`${name} uniform is missing a value parameter`);
// }
if (uniform.value.texture) {
textureUnit = textureUnit + 1;
// Check if texture needs to be updated
uniform.value.update(textureUnit);
return setUniform(this.gl, activeUniform.type, location.location, textureUnit);
}
// For texture arrays, set uniform as an array of texture units instead of just one
if (uniform.value.length && uniform.value[0].texture) {
const textureUnits = [];
uniform.value.forEach((value) => {
textureUnit = textureUnit + 1;
value.update(textureUnit);
textureUnits.push(textureUnit);
});
return setUniform(this.gl, activeUniform.type, location.location, textureUnits);
}
setUniform(this.gl, activeUniform.type, location.location, uniform.value);
});
this.applyState();
}
applyState() {
if (this.depthTest) {
this.renderer.enable(this.gl.DEPTH_TEST);
}
else {
this.renderer.disable(this.gl.DEPTH_TEST);
}
if (this.blendFunc.src) {
this.renderer.enable(this.gl.BLEND);
}
else {
this.renderer.disable(this.gl.BLEND);
}
this.renderer.setDepthMask(this.depthWrite);
this.renderer.setDepthFunc(this.depthFunc);
if (this.blendFunc.src)
this.renderer.setBlendFunc(this.blendFunc.src, this.blendFunc.dst, this.blendFunc.srcAlpha, this.blendFunc.dstAlpha);
this.renderer.setBlendEquation(this.blendEquation.modeRGB, this.blendEquation.modeAlpha);
}
remove() {
this.gl.deleteProgram(this.program);
}
}
function setUniform(gl, type, location, value) {
const isArray = value.length;
switch (type) {
case WebGLRenderingContext.FLOAT: // 5126
return isArray ? gl.uniform1fv(location, value) : gl.uniform1f(location, value); // FLOAT
case WebGLRenderingContext.FLOAT_VEC2: // 35664
return gl.uniform2fv(location, value); // FLOAT_VEC2
case WebGLRenderingContext.FLOAT_VEC3: // 35665
return gl.uniform3fv(location, value); // FLOAT_VEC3
case WebGLRenderingContext.FLOAT_VEC4:
return gl.uniform4fv(location, value); // FLOAT_VEC4
case 35670: // BOOL
case 5124: // INT
case 35678: // SAMPLER_2D
case 35680:
return isArray ? gl.uniform1iv(location, value) : gl.uniform1i(location, value); // SAMPLER_CUBE
case 35671: // BOOL_VEC2
case 35667:
return gl.uniform2iv(location, value); // INT_VEC2
case 35672: // BOOL_VEC3
case 35668:
return gl.uniform3iv(location, value); // INT_VEC3
case 35673: // BOOL_VEC4
case 35669:
return gl.uniform4iv(location, value); // INT_VEC4
case 35674:
return gl.uniformMatrix2fv(location, false, value); // FLOAT_MAT2
case 35675:
return gl.uniformMatrix3fv(location, false, value); // FLOAT_MAT3
case 35676:
return gl.uniformMatrix4fv(location, false, value); // FLOAT_MAT4
}
}
function addLineNumbers(string) {
let lines = string.split("\n");
for (let i = 0; i < lines.length; i++) {
lines[i] = i + 1 + ": " + lines[i];
}
return lines.join("\n");
}
let warnCount = 0;
function warn(message) {
if (warnCount > 100)
return;
console.warn(message);
warnCount++;
if (warnCount > 100)
console.warn("More than 100 program warnings - stopping logs.");
}
|
export const robots=[{
name:"Farhan",
id:"1",
email:"fk912254@gmail.com"
},{
name:"Falak",
id:"2",
email:"MereBaigan@gmail.com"
},{
name:"Saif",
id:"3",
email:"OverProtectiveActor@gmail.com"
},{
name:"Daniyal",
id:"4",
email:"DannuPaaji@gmail.com"
},{
name:"Fareha",
id:"5",
email:"AmmaJi@gmail.com"
},{
name:"RaziaParween",
id:"6",
email:"ParweenAunty@gmail.com"
},{
name:"Nashat Ahmad",
id:"7",
email:"Pops@gmail.com"
},{
name:"Azra",
id:"8",
email:"HappuBirthday@gmail.com"
}]
|
const Command = require("../base/Command");
const { ErrorMsg } = require("../functions");
module.exports = class Template extends Command {
constructor(bot) {
super(bot, {
name:"clear",
aliases:["purge"],
category:"Moderation",
usage:"!clear <amount> (reason) or !clear <user> [this will clear the most recent messages of that user]",
description:"Deletes a certain amount of messages or the most recent messages of a certain user",
cooldown: 5000,
example: "!clear 50 spam",
});
}
async run(message, args, guild) {
if(!message.member.hasPermission("MANAGE_MESSAGES", false, true, true)) return ErrorMsg(this.bot, message, "You do not have the required permissions!");
const [toClear, ...reason] = args;
if(isNaN(toClear) || toClear.includes("-") || !toClear || toClear == 0) return ErrorMsg(this.bot, message, "Please provide a valid amount of messages to delete!");
const messages = await message.channel.fetchMessages({ limit: toClear });
await message.delete();
await message.channel.bulkDelete(messages);
const clearEmbed = this.bot.botEmbed(message, this.bot)
.setColor("#000000")
.setAuthor(`Clear | Case: ${guild.case}`, message.author.displayAvatarURL)
.setDescription(`**Cleared Messages:** ${messages.size}\n**Cleared in :**${message.channel}\n **Cleared by:** ${message.author}\n**Reason:** ${reason.length > 0 ? reason.join(" ") : "No Reason"}`);
const logChannel = message.guild.channels.get(guild.logChannel) || message.channel;
logChannel.send(clearEmbed);
guild.case++;
guild.save().catch(console.error);
}
};
|
module.exports = {
mongoURL : 'mongodb://admin:admin123@ds251223.mlab.com:51223/lcocourse',
secret : "mystrongsecret"
};
|
exports.seed = function(knex) {
return knex("products").insert([
{
productName: "Test Product - Store One",
color: "white",
size: "med",
type: "dtg",
designId: "1",
product_id: "canvas-unisex-t-shirt",
fullSizeURL:
"https://res.cloudinary.com/dze74ofbf/image/upload/v1581453585/wsjikfpellbybgzbymy2.jpg",
thumbnailURL:
"https://res.cloudinary.com/dze74ofbf/image/upload/v1581454280/eiz7lg8c8mtosndddelk.jpg",
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ornare arcu vulputate arcu suscipit venenatis. Donec sit amet ipsum ac urna dignissim euismod a euismod nisi. Nullam pulvinar odio semper.",
price: 10.3,
storeID: 1
},
{
productName: "Test Product - Store 2",
color: "black",
size: "med",
type: "dtg",
designId: "1",
product_id: "canvas-unisex-t-shirt",
fullSizeURL:
"https://res.cloudinary.com/dze74ofbf/image/upload/v1581453585/wsjikfpellbybgzbymy2.jpg",
thumbnailURL:
"https://res.cloudinary.com/dze74ofbf/image/upload/v1581454280/eiz7lg8c8mtosndddelk.jpg",
description:
"Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ornare arcu vulputate arcu suscipit venenatis. Donec sit amet ipsum ac urna dignissim euismod a euismod nisi. Nullam pulvinar odio semper.",
price: 22.3,
storeID: 2
}
]);
};
|
var map = new L.Map('introMap', { zoomControl: false }).setView([55.745, 37.606], 17);
/*
* Init layers
*/
var
lt_cmade = L.tileLayer('http://{s}.tile.cloudmade.com/324b77d6f6774461a4ba74d61caba29b/997/256/{z}/{x}/{y}.png',
{
attribution: 'Данные карты © участники <a href="http://openstreetmap.org">OpenStreetMap</a>, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, рендер © <a href="http://cloudmade.com">CloudMade</a>',
maxZoom: 18,
alias: 'CM'
}
),
lt_mbox = new L.TileLayer(
'http://{s}.tiles.mapbox.com/v3/putnik.map-86mogcj7/{z}/{x}/{y}.png',
{
attribution: 'Данные карты © участники <a href="http://openstreetmap.org">OpenStreetMap</a>, рендер © <a href="http://mapbox.com/">MapBox</a>',
maxZoom: 17,
alias: 'MB'
}
),
lt_mquest = new L.TileLayer(
'http://otile{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png',
{
attribution: 'Данные карты © участники <a href="http://openstreetmap.org">OpenStreetMap</a>, рендер © <a href="http://www.mapquest.com/">MapQuest <img src="http://developer.mapquest.com/content/osm/mq_logo.png"></a>',
maxZoom: 18,
subdomains: '1234',
alias: 'MQ'
}
),
lt_mapnik = L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
{
attribution: 'Данные карты © участники <a href="http://openstreetmap.org">OpenStreetMap</a>, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>',
maxZoom: 18,
alias: 'M'
}
),
l_3d = new L.BuildingsLayer({ url: 'http://data.osmbuildings.ru/?w={w}&n={n}&e={e}&s={s}&z={z}', alias: '3D' }),
l_3d_test = new L.BuildingsLayer({ url: 'http://test.osmbuildings.ru/?w={w}&n={n}&e={e}&s={s}&z={z}', alias: '3T' });
/*
* Add layers
*/
l_3d
.addTo(map)
.setStyle({ strokeRoofs: true });
lt_cmade.addTo(map);
/*
* Add controls
*/
var c_layers = L.control.layers(
{
'CloudMade': lt_cmade,
'MapBox': lt_mbox,
'MapQuest': lt_mquest,
'Mapnik': lt_mapnik
},
{
'3D-здания': l_3d,
'3D-здания (test)': l_3d_test
}
).addTo(map);
new L.Control.Permalink(c_layers).addTo(map).setPosition('bottomleft');
new L.Control.ZoomFS().addTo(map);
new L.Control.Locate().addTo(map);
|
import DS from 'ember-data';
import config from '../config/environment'
export default DS.RESTAdapter.extend({
host: config.APP.host,
header: function() {
return {
'sec-user-toke': 'dadasdasd'
}
}
});
|
var React = require('react'),
Link = require('react-router').Link;
module.exports = React.createClass({
render: function () {
var descr = this.props.category.description;
var style = {};
if (this.props.category.img_url_big){
style = ({
backgroundImage: 'url('+this.props.category.img_url_big+')'
});
}
var content = <div className="category-tile shadow">
<div className="category-img" style={style}/>
<div className="title-bar">
<h4 className="category-title">{this.props.category.name}</h4>
<text className="category-subtitle">{descr}</text>
</div>
</div>;
if (!this.props.static) {
return <li className="category-index-item">
<Link to={"/category/" + this.props.category.id}>
{content}
</Link>
</li>;
} else {
return <li className="category-index-item">
<a href="session/new">
{content}
</a>
</li>;
}
}
});
|
$(function() {
$.localScroll();
});
|
import { put, post, get } from "./baseApi";
const getProject = async () => {
return await get(`/projects`);
};
const submitProject = async (data) => {
return await post("/projects", data);
};
const editProject = async (id, data, user) => {
return await put(`/projects/${id}`, data);
};
export { getProject, submitProject, editProject };
|
require('./deviceRouteTest');
require('./extRouteTest');
require('./configurationRouteTest');
require('./checkNestedFetching');
|
//we don't need to redefine the player and the board classes because raos.html will include both board.js and controller.js
//this is initilized by main.js
// var io = io.connect();
//controller vars
var playerID;
function join_game(game_id){
//send 'controller_connect' message to server so it can keep track of us.
}
io.on('display_roll', function() {
//display the users roll, and wait for them to say okay. When they do send a ready_to_proceed message to the server.
});
io.on('notify_controller', function(action, role) {
if (action == "review_character"){
//display our player role.
}else if (action == "cupid"){ //the board should only send the cupid player this message.
//display 2 player picker.
}else if (action == "nomination"){
//show the picker for nomination
}
});
function did_pick_players(player){
//notify game board of whom was picked.
}
|
export const UNSELECT_CHARACTER_TWO = "unselectCharacterTwo";
export default function unselectCharacterTwo() {
return {
type: UNSELECT_CHARACTER_TWO
};
}
|
import React from "react"
import styled from "styled-components"
import Headline1 from "../Headlines/Headline1"
import useMatchMedia from "../../hooks/useMatchMedia"
import { above } from "../../styles/Theme"
const BelowHeaderHeadlineSection = () => {
const showHeadline = useMatchMedia({ width: 600 })
return (
<>
{showHeadline ? (
<HeadlineContainer>
<Headline1>
Ready to get back into exercise... burn fat... and feel great about
your body?
</Headline1>
<Headline1>
Try our studio for 14 days of unlimited classes for only $14
</Headline1>
</HeadlineContainer>
) : null}
</>
)
}
export default BelowHeaderHeadlineSection
const HeadlineContainer = styled.div`
margin: 70px 0 0 0;
padding: 0 12px;
display: grid;
grid-template-columns: 1fr;
gap: 40px;
width: 100%;
max-width: 800px;
${above.mobile`
padding: 0 12px;
`}
${above.tablet`
margin: 80px 0 0 0;
padding: 0;
`}
`
|
import React from 'react';
export const TimerHeader = ((props) => {
return <h3>Działam od: {props.time} sekund</h3>
})
|
const assert = require('assert');
function inc(x) { return x + 1; }
function add(x, y) {
return inc(x + y);
}
assert.equal(add.apply({}, [1, 2]), 4)
|
const express = require('express');
const page = require('../controller/page');
const template = require('../lib/template');
const router = express.Router();
router.get('/', page.index);
module.exports = router;
|
var pyconKr = (function ($) {
var $body = $('body'),
$window = $(window),
doc = document,
$link = $('#nav a, #main a'),
$mMenu = $('#m-menu'),
scrollAnchor,
scrollPoint,
map,
eventLocationMarker;
function init() {
$link.on('click', function () {
scrollAnchor = $(this).attr('data-scroll');
scrollPoint = $('section[data-anchor="' + scrollAnchor + '"]').offset().top - 28;
$('body,html').animate({
scrollTop: scrollPoint
}, 500);
return false;
});
$mMenu.on('click', function () {
$body.toggleClass('active');
return false;
});
// google maps
google.maps.event.addDomListener(window, 'load', function () {
eventLocationMarker = new google.maps.Marker({
// 숙명여대
position: new google.maps.LatLng(37.546171, 126.964662)
});
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 15,
center: eventLocationMarker.getPosition()
});
eventLocationMarker.setMap(map);
});
// showdown markdown
var mdown = $('.markdown-content').html();
var converter = new Showdown.converter();
var html = converter.makeHtml(mdown);
$('.markdown-content').html(html);
}
return {
init: init
};
})(jQuery);
$(document).ready(function () {
pyconKr.init();
});
|
import React, { useContext } from 'react'
import { Context } from '../../../context/Context'
export const AddProduct = (props) => {
const {values, handleInputChange, uploadImage} = useContext(Context)
const { id, marca, nombre, descripcion, precio } = values
const handleFileChange = (e) => {
const file = URL.createObjectURL(e.target.files[0]);
if (file) {
uploadImage(file)
}
}
const handlePictureClick = () => {
document.querySelector('#fileSelector').click();
}
const handleSave = (e) => {
e.preventDefault();
props.nuevoproduct()
props.setNuevoProduct(false)
}
return (
<div>
<form>
<div className="mb-3">
<input
name='id'
type="text"
placeholder="id"
className="form-control"
autoComplete="off"
required
value={id}
onChange={handleInputChange}
/>
</div>
<div className="mb-3">
<input
name='marca'
type="text"
placeholder="Marca"
className="form-control"
autoComplete="off"
required
value={marca}
onChange={handleInputChange}
/>
</div>
<div className="mb-3">
<input
name='nombre'
type="text"
placeholder="Nombre"
className="form-control"
autoComplete="off"
required
value={nombre}
onChange={handleInputChange}
/>
</div>
<div className="mb-3">
<textarea
name='descripcion'
type="text"
placeholder="Descripción"
className="form-control"
autoComplete="off"
required
value={descripcion}
onChange={handleInputChange}
/>
</div>
<div className="mb-3">
<input
name='precio'
type="text"
placeholder="Precio"
className="form-control"
autoComplete="off"
required
value={precio}
onChange={handleInputChange}
/>
</div>
<div style={{display: 'flex', justifyContent: 'flex-start'}}>
<button
type="submit"
className="btn btn-primary"
onClick={handleSave}
>
<i className="far fa-save"></i>
<span> Guardar</span>
</button>
<button
type="button"
className="btn btn-primary ms-1"
onClick={handlePictureClick}
>
<i className="fas fa-file-upload"></i>
<span> Subir imagen</span>
</button>
<input
id="fileSelector"
name="imagen"
type="file"
style={{display:"none"}}
onChange={handleFileChange}
/>
</div>
</form>
</div>
)
}
|
import React from 'react';
import FeatureTidbit from '../FeatureTidbit'
import Wrapper from './Wrapper'
import { withGoogleMap, GoogleMap, Marker } from "react-google-maps";
import _ from 'lodash'
import withScriptjs from 'react-google-maps/lib/async/withScriptjs';
import InfoBox from "react-google-maps/lib/addons/InfoBox";
const renderInfoWindow = (marker, index) => {
// Normal version: Pass string as content
const featureLocation = {
lat: marker.position.lat,
lng: marker.position.lng
};
return (
<InfoBox
key={`${index}_info_window`}
defaultPosition={featureLocation}
options={{closeBoxURL: "", enableEventPropagation: true, disableAutoPan: true, boxStyle: { opacity: 1,width: "225px" }}}>
<FeatureTidbit feature={marker} />
</InfoBox>
)
}
const GettingStartedGoogleMap = withScriptjs(withGoogleMap(props => (
<GoogleMap
ref={props.onMapLoad}
defaultZoom={3}
defaultCenter={{ lat: 44.8781, lng: -87.6298 }}
onClick={props.onMapClick}
>
{ props.markers.map((marker, index) => (
<Marker
{...marker}
onRightClick={() => props.onMarkerRightClick(index)}
>
{renderInfoWindow(marker, index)}
</Marker>
))}
</GoogleMap>
)));
export default class GMap extends React.Component {
render() {
let featuresToShow;
if(this.props.filteredFeatures) {
featuresToShow = this.props.filteredFeatures;
} else {
featuresToShow = this.props.features;
}
return (
<Wrapper>
<GettingStartedGoogleMap
googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp"
loadingElement={
<div style={{ height: `100%` }}>
<p>Loading Map...</p>
</div>
}
containerElement={
<div style={{ height: `100%` }} />
}
mapElement={
<div style={{ height: `100%` }} />
}
onMapLoad={_.noop}
onMapClick={_.noop}
markers={featuresToShow}
onMarkerRightClick={_.noop}
/>
</Wrapper>
);
}
}
|
import {plainProvedGet as g} from 'src/App/helpers'
import {getFilteredVideoList} from 'ssr/lib/helpers/mapFns'
export default x => ({
videoList: getFilteredVideoList(
g(x, 'page', 'GALS_INFO', 'ids'),
g(x, 'page', 'GALS_INFO', 'items')
),
})
|
(function () {
'use strict';
angular
.module('app.outbox')
.controller('OutboxController', OutboxController)
OutboxController.$inject = ['mailservice', 'logger'];
function OutboxController(mailservice, logger) {
/* jshint validthis:true */
var vm = this;
vm.title = 'Outbox';
vm.messages = [];
activate();
function activate() {
return getOutboxMail().then(function() {
logger.info('Retrieved Outbox');
});
}
function getOutboxMail() {
return mailservice.getOutbox().then(function (data) {
vm.messages = data;
return vm.messages;
});
}
}
})();
|
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
const resultRouter = router.namespace('/results');
resultRouter.post('/list', controller.result.list);
};
|
import Sequelize from 'sequelize';
import Admin from './Admin.model';
import db from '../config/database';
const Employee = db.define('employee', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
firstname: {
type: Sequelize.STRING,
allowNull: false,
},
lastname: {
type: Sequelize.STRING,
allowNull: false,
},
email: {
type: Sequelize.STRING,
allowNull: false,
unique: true,
},
password: {
type: Sequelize.STRING,
allowNull: false,
},
gender: {
type: Sequelize.STRING,
allowNull: false,
},
jobRole: {
type: Sequelize.STRING,
allowNull: false,
},
department: {
type: Sequelize.STRING,
allowNull: false,
},
address: {
type: Sequelize.STRING,
allowNull: false,
},
role: {
type: Sequelize.STRING,
defaultValue: 'Employee',
},
createdAt: Sequelize.DATEONLY,
updatedAt: Sequelize.DATEONLY,
});
Admin.hasMany(Employee, { constraints: true, onDelete: 'CASCADE' });
export default Employee;
|
import { getNotificationsUser, getPages, sendMail, followFanfic, disFollowFanfic, followAuthor, disFollowAuthor, preventAbuse, favorite, unfavorite, getFollowAuthor, getFollowFanfic } from "@/api/other"
export const namespaced = true;
export const state = {
news: [],
notifications: [],
pages: [],
contact: null,
feedback: null,
favorited: null,
followedStory: [],
followedAuthor: [],
followStory: null,
followAuthor: null,
followUserId: null,
followStoryId: null
};
export const mutations = {
setFollowUserId (state, data) {
state.followUserId = data
},
setFollowStoryId (state, data) {
state.followStoryId = data
},
postFollowAuthor (state, data) {
state.followAuthor = data
},
postFollowStory (state, data) {
state.followStory = data
},
setFollowAuthor (state, data) {
state.followedAuthor = data
},
setFollowStory (state, data) {
state.followedStory = data
},
postFavoritedByUser (state, data) {
state.favorited = data
},
postUnFavoritedByUser (state, data) {
state.favorited = data
},
postContactForm (state, data) {
state.contact = data
},
postFeedbackForm (state, data) {
state.feedback = data
},
setNotifications(state, data) {
state.notifications = data;
},
setNews(state, data) {
state.news = data;
},
setPages(state, data) {
state.pages = data;
}
};
export const actions = {
async addFollowStory({commit}, data) {
commit('postFollowStory')
await followFanfic(data.from_user, data.to_fanfic)
.then(res => {
commit('setFollowStoryId', res.id)
})
.catch(err => console.log(err));
},
async removeFollowStory({commit}, data) {
return commit('postFollowStory', await disFollowFanfic(data.id));
},
async addFollowAuthor({commit}, data) {
commit('postFollowAuthor')
await followAuthor(data.user_from, data.user_to)
.then(res => {
commit('setFollowUserId', res.id)
})
.catch(err => console.log(err));
},
async removeFollowAuthor({commit}, data) {
return commit('postFollowAuthor', await disFollowAuthor(data.id));
},
async fetchFollowStory({commit}) {
return commit('setFollowStory', await getFollowFanfic());
},
async fetchFollowAuthor({commit}) {
return commit('setFollowAuthor', await getFollowAuthor());
},
clearFollowAuthor({commit}) {
return commit('setFollowAuthor', [])
},
clearFollowStory({commit}) {
return commit('setFollowStory', [])
},
async postUnfavorited({commit}, data) {
return commit('postUnFavoritedByUser', await unfavorite(data.id, data.user));
},
async postFavorited({commit}, data) {
return commit('postFavoritedByUser', await favorite(data.id, data.user));
},
clearNews({commit}) {
return commit('setNews', []);
},
clearNotifications({commit}) {
return commit('setNotifications', []);
},
async getNotifications({commit}) {
return commit('setNotifications', await getNotificationsUser());
},
async fetchPages({commit}, data) {
return commit('setPages', await getPages(data));
},
clearPages({commit}) {
return commit('setPages', []);
},
async sendFormContactEmail({ commit }, data) {
return commit('postContactForm', await sendMail(data.from_email, data.subject, data.message));
},
async sendFormPreventAbuse({commit}, data) {
return commit('postFeedbackForm', await preventAbuse(data.id));
}
}
export const getters = {};
|
function scroll_to(div){
$('html, body').animate({
scrollTop: $(div).offset().top
},1000);
}
$(window).resize(function(){
if ($(window).width()>=845){
$("#mobile-menu").hide();
}
});
scroll_to("#container");
$('html').css('overflow', 'hidden');
$("#mobile-menu-img").click(function(event){
event.stopPropagation();
$("#mobile-menu").slideDown("slow");
});
$('body').click(function(event){
event.stopPropagation();
$("#mobile-menu").slideUp("slow");
});
$("#welcome-button").click(function(){
$("#welcome").fadeOut("slow");
$('html').css('overflow', 'scroll');
})
|
const api = require("./api");
const http = require("http");
const url = require("url");
const https = require("https");
const fs = require("fs");
const MIME = {
html: "text/html",
css: "text/css",
js: "application/x-javascript",
png: "image/png",
jpg: "image/jpeg",
gif: "image/gif",
mp3: "audio/mp3",
json: "application/json",
ttf: "application/x-font-ttf"
};
const options = {
key: fs.readFileSync("./s2l/Nginx/2_s2l.xyz.key"),
cert: fs.readFileSync("./s2l/Nginx/1_s2l.xyz_bundle.crt")
};
function handleStatic(pathName) {
let reg = /\.([a-zA-Z0-9]*)$/;
if (reg.test(pathName)) {
let type = RegExp.$1;
return MIME[type];
}
}
function Server() {
http
.createServer((req, res) => {
let pathName = url.parse(req.url).pathname;
console.log(pathName)
// 判断静态资源
var fileType = handleStatic(pathName);
console.log(fileType)
if (fileType) {
api["/"](req, res, pathName, fileType);
} else {
res.writeHead(404, {
"content-type": `application/json`
});
res.end("404 Not Found");
}
})
.listen(50011, "0.0.0.0", () => {
console.log("server running at port 50011");
});
}
function HttpsServer () {
https
.createServer(options, (req, res) => {
let pathName = url.parse(req.url).pathname;
console.log(pathName)
// 判断静态资源
var fileType = handleStatic(pathName);
console.log(fileType)
if (fileType) {
api["/"](req, res, pathName, fileType);
} else {
res.writeHead(404, {
"content-type": `application/json`
});
res.end("404 Not Found");
}
})
.listen(50012, "0.0.0.0", () => {
console.log("htpps server running at port 50012");
});
}
Server();
HttpsServer();
|
(function () {
"use strict";
function doubler(number) {
console.log(number);
if (number <= 70000) {
doubler(number * 2);
}
}
doubler(2);
// This is how you get a random number between 50 and 100
var allCones = Math.floor(Math.random() * 50) + 50;
// This expression will generate a random number between 1 and 5
Math.floor(Math.random() * 5) + 1;
}
)()
|
'use strict';
angular.module('miwurster.model')
.factory('UserService', ['Restangular', 'User', function (Restangular, User) {
var resource = Restangular.all('users');
Restangular.extendModel('users', function (object) {
return User.mixInto(object);
});
return {
findAll: function () {
return resource.getList();
},
findById: function (id) {
return resource.get(id.toString());
}
// ...
}
}])
.factory('User', ['BaseModel', 'Company', function (BaseModel, Company) {
return BaseModel.extend({
beforeMixingInto: function (object) {
Company.mixInto(object['company'])
},
formattedAddress: function () {
var street = this['address']['street'];
var city = this['address']['city'];
var zipCode = this['address']['zipcode'];
return street + ', ' + zipCode + ' ' + city;
},
formattedCompany: function () {
return this['company'].what();
}
//...
});
}]);
|
import Happens from 'happens';
export default new class Screen{
constructor(){
Happens( this );
this.width = window.innerWidth;
this.height = window.innerHeight;
window.addEventListener('resize', this.onResize.bind(this), false);
this.onResize();
}
onResize(){
this.width = window.innerWidth;
this.height = window.innerHeight;
this.emit( 'resize' );
}
};
|
const blocks = document.getElementsByClassName("block");
const turn = document.getElementById("turn");
const result = document.getElementById("result");
let tMatrix = [
[-1, -1, -1],
[-1, -1, -1],
[-1, -1, -1],
];
const winCombinations = ["00,01,02","00,10,20","00,11,22","10,11,12","20,21,22","02,12,22","01,11,21","02,12,22","20,11,02"]
// 3 -> X; 4 -> O;
let currentPlayer = 3;
turn.innerHTML = "X";
let winnerDeclared = false;
let sum =0;
function detectWinner(){
let won = winCombinations.some((combination) =>{
sum = 0;
// ["10","11","12"]
combination.split(',').forEach((item)=>{
sum = sum + tMatrix[item[0]][item[1]]
});
return (sum === 9 || sum ===12)
});
if(won){
result.innerHTML = "Player "+ (sum === 9?'X':'O') + " wins"
winnerDeclared = true;
}
}
function updatePlayer(){
currentPlayer = currentPlayer===3 ? 4 : 3;
turn.innerHTML = currentPlayer===3 ? "X" : "O";
// if(currentPlayer===0){
// currentPlayer = 1
// }else{
// currentPlayer = 0
// }
}
function updateBlocks(){
[...blocks].forEach((block, index)=>{
if(tMatrix[parseInt(index/3)][index%3]===3){
block.innerHTML = "X"
}else if(tMatrix[parseInt(index/3)][index%3]===4){
block.innerHTML = "O"
}
})
}
function onBlockClick(id){
if(tMatrix[parseInt(id/3)][id%3]>=0 || winnerDeclared)
return;
tMatrix[parseInt(id/3)][id%3] = currentPlayer;
// id = 0 0 0
// id = 1 0 1
// id = 2 0 2
// id = 3 1 0
// id = 4 1 1
// id = 5 1 2
// id = 6 2 0
// id = 7 2 1
// id = 8 2 2
updatePlayer();
updateBlocks();
detectWinner();
}
function reset() {
location.reload();
}
|
const formidable = require("formidable");
const dao = require("../dao/dao.js");
exports.Get_login = (request, response, next) => { //获取登陆界面,ok
var tip = "";
var tips = request.query.tip;
if(tips == 1) tip = "用户名或密码错误";
else if(tips == 2) tip = "请先登陆";
response.render("login", {
"tip": tip
});
}
exports.Post_login = (request, response, next) => { //提交登陆信息,ok
var form = new formidable.IncomingForm();
form.parse(request, (err, fields, files) => {
if(err != null) {
console.log("表单解析错误");
next();
return;
}
var userName = fields.userName;
var userPass = fields.userPass;
var sql = "select * from login where user='" + userName + "' and pass='" + userPass + "'";
dao.query(sql, (err, results) => {
if(err) {
console.log(err);
next();
return;
}
if(results.length == 0) {
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=1"
});
response.end();
} else {
request.session.userName = userName;
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/index?list=2"
});
response.end();
}
});
});
}
exports.Get_index = (request, response, next) => { //获取主页,及其所有数据,ok
if(request.session.userName == null) {
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=2"
});
response.end();
return;
}
var id = 2;
if(request.query.list != null) id = parseInt(request.query.list);
var sql = "select * from lists where type = 'child'";
dao.query(sql, (err, left_result) => {
if(err) {
console.log(err);
next();
return;
}
if(id == 1) {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth() + 1;
var day = now.getDate();
if(month < 10) month = "0" + month;
if(day < 10) day = "0" + day;
var now_date = year + "-" + month + "-" + day;
sql = "select * from to_do where time='" + now_date + "' and isdelete=0 order by urgent desc,time asc";
} else if(id == 2) sql = "select * from to_do where isdelete=0 order by urgent desc,time asc";
else if(id == 3) sql = "select * from to_do where isdelete=1 order by urgent desc,time asc";
else sql = "select * from to_do where list_id=" + id + " and isdelete=0 order by urgent desc,time asc";
dao.query(sql, (err, right_result) => {
if(err) {
console.log(err);
next();
return;
}
response.render("index", {
"lists": left_result,
"contents": right_result,
"list_flag": id
});
});
});
}
exports.Post_addThing = (request, response, next) => { //添加计划,ok
if(request.session.userName == null) {
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=2"
});
response.end();
return;
}
var form = new formidable.IncomingForm();
var list_id = 2;
if(request.query.list != null) list_id = parseInt(request.query.list);
form.parse(request, (err, fields, files) => {
if(err != null) {
console.log("表单解析错误");
next();
return;
}
var title = fields.title;
var urgent = parseInt(fields.urgent);
var year = fields.year;
var month = fields.month;
var day = fields.day;
if(month < 10) month = "0" + parseInt(month);
if(day < 10) day = "0" + parseInt(day);
var time = year + "-" + month + "-" + day;
var sql = "insert into to_do values(null,?,?,?,?,?)";
var params = [title, urgent, time, list_id, 0];
dao.add(sql, params, (err, result) => {
if(err) {
console.log(err);
next();
return;
}
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/index?list=" + list_id
});
response.end();
});
});
}
exports.Get_delete = (request, response, next) => { //删除计划,软删除方式,ok
if(request.session.userName == null) {
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=2"
});
response.end();
return;
}
var id = request.query.id;
var list = request.query.list;
var sql = "update to_do set isdelete=1 where id=?";
dao.update(sql, [id], (err, result) => {
if(err) {
console.log(err);
next();
return;
}
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/index?list=" + list
});
response.end();
});
}
exports.Get_remove = (request, response, next) => { //删除计划,硬删除方法,ok
if(request.session.userName == null) {
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=2"
});
response.end();
return;
}
var id = request.query.id;
var sql = "delete from to_do where id=" + id;
dao.remove(sql, (err, result) => {
if(err) {
console.log(err);
next();
return;
}
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/index?list=3"
});
response.end();
});
}
exports.Post_addList = (request, response, next) => { //新建列表,ok
if(request.session.userName == null) {
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=2"
});
response.end();
return;
}
var form = new formidable.IncomingForm();
form.parse(request, (err, fields, files) => {
if(err != null) {
console.log("表单解析错误");
next();
return;
}
var listName = fields.listName;
var sql = "insert into lists values(null,?,'child')";
dao.add(sql, [listName], (err, result) => {
if(err) {
console.log(err);
next();
return;
}
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/index?list=2"
});
response.end();
});
});
}
exports.Post_search = (request, response, next) => { //搜索,ok
if(request.session.userName == null) {
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=2"
});
response.end();
return;
}
var form = new formidable.IncomingForm();
form.parse(request, (err, fields, files) => {
if(err != null) {
console.log("表单解析错误");
next();
return;
}
var search = fields.search;
var sql = "select * from to_do where title like '%" + search + "%' and isdelete=0 order by urgent desc,time asc";
dao.query(sql, (err, result) => {
if(err) {
console.log(err);
next();
return;
}
sql = "select * from lists where type='child'";
dao.query(sql, (err, resl) => {
if(err) {
console.log(err);
next();
return;
}
response.render("index", {
"lists": resl,
"contents": result,
"list_flag": -1
});
});
});
});
}
exports.Get_deleteList = (request, response, next) => {
if(request.session.userName == null) {
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=2"
});
response.end();
return;
}
var id = parseInt(request.query.id);
var sql = "delete from lists where id=" + id;
dao.remove(sql, (err, result) => {
if(err) {
console.log(err);
next();
return;
}
sql = "delete from to_do where list_id=" + id;
dao.remove(sql, (err, result) => {
if(err) {
console.log(err);
next();
return;
}
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/index?list=2"
});
response.end();
});
});
}
exports.Get_logout = (request, response, next) => { //退出登陆,ok
request.session.userName = null;
response.writeHead(302, {
"Location": "http://127.0.0.1:3000/login?tip=2"
});
response.end();
}
|
alert('Welcome to the Top Anime Website');
var question1 = 'Who is your favourite character in one piece, luffy or zoro?';
alert(question1);
var answer1 = prompt("your answer");
// Making a loop to get the answer for the question either zoro or luffy and adding the loop to a function
var photo1 = ''
var finalAnswer1 = function() {
while ( answer1 !== 'luffy' && answer1 !== 'zoro'){
answer1 = prompt('your answer must be either luffy or zoro' )
}
if (answer1 === 'luffy') {
photo1 ='<img src="https://i.pinimg.com/474x/47/e2/3e/47e23ef9f58145646746b7e911b79c00.jpg"/> <br>'
} else if (answer1 === 'zoro') {
photo1 = '<img src="https://mangathrill.com/wp-content/uploads/2020/12/daaaqweasdasdaqweasdasd.jpg"/ , width= 350> <br>'
}
return photo1
}
document.write(finalAnswer1());
var question2 = 'Who is your favourite character in Naruto, naruto or sasuke?';
alert(question2);
var answer2 = prompt("your answer");
// Making a loop to get the answer for the question either naruto or sasuke and adding the loop to a function
var photo2 = ''
var finalAnswer2 = function(){
while ( answer2 !== 'naruto' && answer2!== 'sasuke') {
answer2 = prompt("your answer must be either naruto or sasuke")
}
if (answer2 === 'naruto'){
photo2= '<img src="https://64.media.tumblr.com/cb22e5c2e2cdd57bc1c66012aa0db077/tumblr_pjznxwjt3w1wnec3vo1_250.gifv"/>'
} else if (answer2 === 'sasuke') {
photo2 = '<img src="https://animesouls.com/wp-content/uploads/2017/03/14.jpg"/ , width = 300px> '
}
return photo2
}
document.write(finalAnswer2());
var question3 = 'Who you wish to be his/her name written in the Death Note?';
alert(question3);
var answer3 = prompt("your answer");
document.write('<h3> you can say: May he/she rest in peace </h3>');
// Asking for Death Note posters
var dnPoster = '';
var numberOfdn = prompt("How many posters you want to buy for Death Note?");
for (var i = 1;i<=numberOfdn;i++){
dnPoster = dnPoster + '<img src= "https://cdn.europosters.eu/image/750/posters/death-note-duo-i28405.jpg"/> ' + i+ '<br>' ;
}
document.write(dnPoster);
var txt;
var r = confirm("Do you wish to know what will happen in the next episode of One Piece!");
if (r == true) {
txt = "You need to go and read the manga!";
} else {
txt = "Then you shall wait!";
}
document.write('<br> <p> ' + txt + ' </p> </br> ');
|
const services = require('../utils/services')
async function list(filters = {}) {
const commentsServiceClient = services.getCommentsServiceClient();
const result = await new Promise((reslove, reject) => {
commentsServiceClient.list(filters, (err, res) => {
if (err) reject(err)
reslove(res);
});
})
return result.comments ? result.comments : [];
}
async function get({ id }) {
const commentsServiceClient = services.getCommentsServiceClient();
const result = await new Promise((reslove, reject) => {
commentsServiceClient.get({ id }, (err, res) => {
if (err) reject(err)
reslove(res);
});
})
return result;
}
async function create(request) {
const commentsServiceClient = services.getCommentsServiceClient();
const result = await new Promise((reslove, reject) => {
commentsServiceClient.create(request, (err, res) => {
if (err) reject(err)
reslove(res);
});
})
return result;
}
module.exports = {
list,
get,
create,
}
|
// import * as types from '../api'
// state初始化
const state = {
all: [],
isFetching: false
}
const getters = {
isFetching: state => state.isFetching
}
export default {
state,
getters
}
|
import React from 'react';
import { Grid } from 'react-bootstrap';
import Categories from './categoriesComponent';
import Posts from './postsComponent';
//component which holds the title of the app and creates posts and comments section
const Homepage = () => (
<div>
<Grid>
<h1 className="appTitle">
<center>
Readable App
</center>
</h1>
</Grid>
<Categories />
<Posts />
</div>
);
export default Homepage;
|
import { findOverlap, MinMax } from '../math/minmax';
import Shape from '../math/shape';
import Vec2 from '../math/vec2';
import { defaultBodyColor } from '../util/colorpalette';
const MAX_AXES = 15;
/**
* @typedef BodyAsObject
* @property {import('../math/shape').ShapeAsObject} shape The shape of the body
* @property {number} k Coefficient of restitution
* @property {number} fc Coefficient of friction
* @property {number} m The mass of the body
* @property {import('../math/vec2').Vec2AsObject} pos The center of mass of the body
* @property {number} am The angular mass of the body
* @property {number} rotation The rotation of the body
* @property {number} ang The angular velocity of the body
* @property {import('../math/vec2').Vec2AsObject} vel The velocity of the body
* @property {string | number} [layer] The layer of the body
* @property {import('../math/vec2').Vec2AsObject[]} defaultAxes The axes of the body when
* it's rotation is 0
* @property {import('../math/vec2').Vec2AsObject[]} axes The axes of the body
* @property {{x:import('../math/minmax').MinMaxAsObject,y:import('../math/minmax').MinMaxAsObject}}
* boundingBox The bounding box of the body
* @property {string} style The style of the body
*/
/** @typedef {"repeat" | "no-repeat" | "repeat-x" | "repeat-y"} RepeatMode */
/**
* A class representing a body
*/
class Body {
/**
* Creates and initalises a body.
*
* @param {Shape} shape The frame of the body
* @param {number} density The density of the body. If set to 0, the body is fixed.
* @param {number} k The coefficient of restitution of the body
* @param {number} fc The friction coefficient of the body
*/
constructor(shape, density = 1, k = 0.2, fc = 0.5) {
this.shape = shape;
this.k = k;
this.fc = fc;
const geometryDat = this.shape.getGeometricalData();
this.m = geometryDat.area * density;
this.pos = geometryDat.center;
this.am = geometryDat.secondArea * density;
this.rotation = 0;
this.ang = 0;
this.vel = new Vec2(0, 0);
/** @type {number | undefined} */
this.layer = undefined;
/** @type {Vec2[]} */
this.defaultAxes = [];
/** @type {Vec2[]} */
this.axes = [];
this.calculateAxes();
this.boundingBox = {
x: this.shape.getMinMaxX(),
y: this.shape.getMinMaxY(),
};
/** @type {MinMax[]} */
this.minMaxes = [];
this.calculateMinMaxes();
/** The style of the body. Has to be a hex color or a texture pointer. */
this.style = defaultBodyColor;
/** The texture of the body */
/** @type {ImageBitmap | 'none'} */
this.texture = 'none';
this.textureTransform = {
offset: new Vec2(0, 0),
scale: 1,
rotation: 0,
};
/** @type {RepeatMode} */
this.textureRepeat = 'repeat';
}
/**
* Calculates the axes of the body and stores them.
*/
calculateAxes() {
const maxCos = Math.cos(Math.PI / MAX_AXES);
this.defaultAxes = this.normals.map((n) => new Vec2(n.x, Math.abs(n.y)));
for (let i = this.defaultAxes.length - 2; i >= 0; i -= 1) {
for (let j = this.defaultAxes.length - 1; j > i; j -= 1) {
const v1 = this.defaultAxes[j];
const v2 = this.defaultAxes[i];
if (Math.abs(Vec2.dot(v1, v2)) > maxCos) {
this.defaultAxes.splice(j, 1);
this.defaultAxes[i] = v1;
}
}
}
this.axes = this.defaultAxes.map((a) => a.copy);
}
/**
* Calculates the MinMax intervals in the body's axes' directions.
*/
calculateMinMaxes() {
this.minMaxes = this.axes.map((axe) => this.shape.getMinMaxInDirection(axe));
}
/**
* Returns the normals of all the sides of the body's polygon.
*
* @returns {Vec2[]} The normals
*/
get normals() {
if (this.shape.r !== 0) {
return [new Vec2(0, 1)];
}
const normals = this.shape.points.map(
(p, i) => Vec2.sub(this.shape.points[(i + 1) % this.shape.points.length], p),
);
normals.forEach((n) => {
n.rotate270();
n.normalize();
});
return normals;
}
/**
* Moves the body by a given vector
*
* @param {Vec2} v The offset to move by
*/
move(v) {
this.shape.move(v);
this.pos.add(v);
this.boundingBox.x.max += v.x;
this.boundingBox.x.min += v.x;
this.boundingBox.y.max += v.y;
this.boundingBox.y.min += v.y;
}
/**
* Rotates the body.
*
* @param {number} angle The angle to rotate by
*/
rotate(angle) {
this.rotation += angle;
if (this.shape.r === 0) this.shape.rotateAround(this.pos, angle);
Vec2.rotateArr(this.axes, angle);
this.boundingBox = {
x: this.shape.getMinMaxX(),
y: this.shape.getMinMaxY(),
};
}
/**
* Rotates the body around a given point.
*
* @param {Vec2} center The center to rotate around
* @param {number} angle The angle to rotate by
*/
rotateAround(center, angle) {
this.rotation += angle;
this.shape.rotateAround(center, angle);
this.pos.rotateAround(center, angle);
Vec2.rotateArr(this.axes, angle);
this.boundingBox = {
x: this.shape.getMinMaxX(),
y: this.shape.getMinMaxY(),
};
}
/**
* Calculates the effective velocity of the ball in a
* given point from it's velocity and angular velocity.
*
* @param {Vec2 | import('../math/vec2').Vec2AsObject} point The point to be taken a look at
* @returns {Vec2} The velocity of the Body in the given point
*/
velInPlace(point) {
const vp = Vec2.sub(point, this.pos);
vp.rotate90();
vp.mult(this.ang);
vp.add(this.vel);
return vp;
}
/**
* Check if a point is inside a point or not.
*
* @param {Vec2} p The point to take a look at
* @returns {boolean} Tells if the body contains a point or not
*/
containsPoint(p) {
return this.shape.containsPoint(p);
}
/**
* Calculates the density of the body.
*
* @returns {number} The density
*/
get density() {
return this.m / this.shape.getGeometricalData().area;
}
/**
* Sets the new density of the shape
*/
set density(newDensity) {
if (newDensity < 0 || !Number.isFinite(newDensity)) return;
const geomDat = this.shape.getGeometricalData();
this.m = geomDat.area * newDensity;
this.am = geomDat.secondArea * newDensity;
}
/**
* Fixes the body making it into a wall.
*/
fixDown() {
this.m = 0;
}
/**
* Scales the body around a given point.
*
* @param {Vec2} center The center of the transformation
* @param {number} scalingFactor The factor of the scaling
*/
scaleAround(center, scalingFactor) {
if (scalingFactor === 0) return;
this.pos.scaleAround(center, scalingFactor);
this.shape.points.forEach((p) => p.scaleAround(center, scalingFactor));
this.shape.r = Math.abs(this.shape.r * scalingFactor);
this.m *= (scalingFactor ** 2);
this.am *= (scalingFactor ** 4);
}
/**
* Scales the body around a given point only on the X axis.
*
* @param {Vec2} center The center of the transformation
* @param {number} scalingFactor The factor of the scaling
*/
scaleAroundX(center, scalingFactor) {
if (scalingFactor === 0) return;
const { density } = this;
this.shape.points.forEach((p) => p.scaleAroundX(center, scalingFactor));
this.shape.r = Math.abs(this.shape.r * scalingFactor);
const geometryDat = this.shape.getGeometricalData();
this.m = geometryDat.area * density;
this.pos = geometryDat.center;
this.am = geometryDat.secondArea * density;
this.calculateAxes();
this.calculateMinMaxes();
}
/**
* Scales the body around a given point only on the Y axis.
*
* @param {Vec2} center The center of the transformation
* @param {number} scalingFactor The factor of the scaling
*/
scaleAroundY(center, scalingFactor) {
if (scalingFactor === 0) return;
const { density } = this;
this.shape.points.forEach((p) => p.scaleAroundY(center, scalingFactor));
this.shape.r = Math.abs(this.shape.r * scalingFactor);
const geometryDat = this.shape.getGeometricalData();
this.m = geometryDat.area * density;
this.pos = geometryDat.center;
this.am = geometryDat.secondArea * density;
this.calculateAxes();
this.calculateMinMaxes();
}
/**
* Applies and impulse on the body.
*
* @param {Vec2} contactPoint The point where the impulse applies
* @param {Vec2} impulse The vector of the impulse
*/
applyImpulse(contactPoint, impulse) {
if (this.m === 0) return;
const r = Vec2.sub(contactPoint, this.pos);
this.vel.add(Vec2.div(impulse, this.m));
this.ang += Vec2.cross(r, impulse) / this.am;
}
/**
* Detects collsion between two bodies and returns the collision data.
* The algorithm expects a precalculated minMaxes array in each of the bodies.
*
* @param {Body} body1 The first body
* @param {Body} body2 The second body
* @returns {{normal:Vec2, overlap:number, contactPoint:Vec2} | boolean} Collsion data
*/
static detectCollision(body1, body2) {
const b1 = body1;
const b2 = body2;
// Check if their bounding boxes overlap and return if they do not
{
const xOverlap = findOverlap(b1.boundingBox.x, b2.boundingBox.x);
if (xOverlap.max < xOverlap.min) return false;
const yOverlap = findOverlap(b1.boundingBox.y, b2.boundingBox.y);
if (yOverlap.max < yOverlap.min) return false;
}
let axes1 = body1.axes;
let axes2 = body2.axes;
if (b1.shape.r !== 0) {
const closest = b2.shape.getClosestPoint(b1.pos);
const axe = Vec2.sub(closest, b1.pos);
axe.normalize();
axes1 = [axe];
b1.minMaxes = [b1.shape.getMinMaxInDirection(axe)];
}
if (b2.shape.r !== 0) {
const closest = b1.shape.getClosestPoint(b2.pos);
const axe = Vec2.sub(closest, b2.pos);
axe.normalize();
axes2 = [axe];
b2.minMaxes = [b2.shape.getMinMaxInDirection(axe)];
}
const coordinateSystems = [...axes1, ...axes2];
/**
* Return the max and min coordinates of the points in the given space.
*
* @param {Vec2} normal The vector to project with
* @returns {import('../math/minmax').MinMax} The max and min values
*/
const getMinMaxes1 = (normal) => b1.shape.getMinMaxInDirection(normal);
/**
* Return the max and min coordinates of the points in the given space.
*
* @param {Vec2} normal The vector to project with
* @returns {import('../math/minmax').MinMax} The max and min values
*/
const getMinMaxes2 = (normal) => b2.shape.getMinMaxInDirection(normal);
/** @type {import('../math/minmax').MinMax[]} */
const overlaps = [];
if (coordinateSystems.some((s, i) => {
// Retrieve the MinMax from the precalculated ones if it is in there
let currMinMax1;
if (i < axes1.length) {
currMinMax1 = body1.minMaxes[i];
} else {
currMinMax1 = getMinMaxes1(s);
}
let currMinMax2;
if (i >= axes1.length) {
currMinMax2 = body2.minMaxes[i - axes1.length];
} else {
currMinMax2 = getMinMaxes2(s);
}
const overlap = findOverlap(currMinMax1, currMinMax2);
if (overlap.max < overlap.min) return true;
overlaps.push(overlap);
return false;
})) return false;
const overlapSizes = overlaps.map((overlap) => overlap.size());
let smallestOverlap = overlapSizes[0];
let index = 0;
for (let i = 1; i < overlapSizes.length; i += 1) {
if (smallestOverlap > overlapSizes[i]) {
smallestOverlap = overlapSizes[i];
index = i;
}
}
const n = coordinateSystems[index].copy;
// Make n point towards the second body
if (Vec2.dot(n, Vec2.sub(b1.pos, b2.pos)) > 0)n.mult(-1);
let cp;
if (index < axes1.length) {
const projected = b2.shape.points.map((p) => Vec2.dot(p, n));
cp = b2.shape.points[projected.indexOf(Math.min(...projected))].copy;
if (b2.shape.r !== 0)cp.sub(Vec2.mult(n, b2.shape.r));
} else {
const projected = b1.shape.points.map((p) => Vec2.dot(p, n));
cp = b1.shape.points[projected.indexOf(Math.max(...projected))].copy;
if (b1.shape.r !== 0)cp.add(Vec2.mult(n, b1.shape.r));
}
return {
normal: n,
overlap: smallestOverlap,
contactPoint: cp,
};
}
/**
* Converts an object to a Body.
*
* @param {BodyAsObject} obj The body represented as a JS object.
* @returns {Body} The created body.
*/
static fromObject(obj) {
/** @type {Body} */
const ret = Object.create(Body.prototype);
ret.am = obj.am;
ret.ang = obj.ang;
ret.axes = obj.axes.map((a) => Vec2.fromObject(a));
ret.boundingBox = {
x: new MinMax(obj.boundingBox.x.min, obj.boundingBox.x.max),
y: new MinMax(obj.boundingBox.y.min, obj.boundingBox.y.max),
};
ret.defaultAxes = obj.defaultAxes.map((da) => Vec2.fromObject(da));
ret.fc = obj.fc;
ret.k = obj.k;
ret.layer = obj.layer;
ret.m = obj.m;
ret.pos = Vec2.fromObject(obj.pos);
ret.rotation = obj.rotation;
ret.shape = Shape.fromObject(obj.shape);
ret.style = obj.style;
ret.vel = Vec2.fromObject(obj.vel);
ret.minMaxes = [];
ret.calculateMinMaxes();
return ret;
}
/**
* Returns a copy of the body.
*
* @returns {Body} The clone.
*/
get copy() {
/** @type {Body} */
const ret = Object.create(Body.prototype);
ret.am = this.am;
ret.ang = this.ang;
ret.axes = this.axes.map((a) => a.copy);
ret.boundingBox = {
x: this.boundingBox.x.copy,
y: this.boundingBox.y.copy,
};
ret.defaultAxes = this.defaultAxes.map((da) => da.copy);
ret.fc = this.fc;
ret.k = this.k;
ret.layer = this.layer;
ret.m = this.m;
ret.pos = this.pos.copy;
ret.rotation = this.rotation;
ret.shape = this.shape.copy;
ret.style = this.style;
ret.vel = this.vel.copy;
ret.minMaxes = this.minMaxes.map((mm) => mm.copy);
ret.texture = this.texture;
ret.textureRepeat = this.textureRepeat;
ret.textureTransform = {
offset: this.textureTransform.offset.copy,
rotation: this.textureTransform.rotation,
scale: this.textureTransform.scale,
};
return ret;
}
}
export default Body;
|
app.get("/api/getTickets", passport.authenticate("userPrivate"), (req, res) => {
const { status, page, perPage, sort, order, dateFrom, dateTo } = req.query;
const query = {
user: req.user._id,
...(status && { status }),
...(dateFrom &&
dateTo && {
createdAt: {
$gte: new Date(`${dateFrom} 0:0`),
$lt: new Date(`${dateTo} 0:0`),
},
}),
};
const sortOrder = {
[sort || "createdAt"]: order === "asc" ? 1 : -1,
};
Ticket.aggregate([
{ $match: query },
{
$lookup: {
from: "milestones",
as: "milestone",
localField: "milestone",
foreignField: "_id",
},
},
{
$lookup: {
from: "transactions",
as: "transaction",
localField: "transaction",
foreignField: "_id",
},
},
{ $sort: sortOrder },
{ $set: { milestone: { $first: "$milestone" } } },
{ $set: { transaction: { $first: "$transaction" } } },
{
$facet: {
tickets: [
{ $skip: +perPage * (+(page || 1) - 1) },
{ $limit: +(perPage || 20) },
],
pageInfo: [{ $group: { _id: null, count: { $sum: 1 } } }],
},
},
])
.then((dbRes) => {
res.json({ code: "ok", tickets: dbRes[0] });
})
.catch((err) => {
console.log(err);
res.status(500).josn({ code: 500, message: "database error" });
});
});
app.get(
"/api/singleTicket",
passport.authenticate("userPrivate"),
(req, res) => {
if (req.query._id && ObjectId.isValid(req.query._id)) {
Ticket.aggregate([
{
$match: {
_id: new ObjectId(req.query._id),
user: req.user._id,
},
},
{
$lookup: {
from: "transactions",
localField: "transaction",
foreignField: "_id",
as: "transaction",
},
},
{
$lookup: {
from: "milestones",
localField: "milestone",
foreignField: "_id",
as: "milestone",
},
},
{
$set: {
transaction: {
$first: "$transaction",
},
milestone: {
$first: "$milestone",
},
},
},
]).then((ticket) => {
if (ticket.length) {
res.json({ code: "ok", ticket: ticket[0] });
} else {
res
.status(404)
.json({ code: 404, message: "ticket could not be found" });
}
});
} else {
res.status(400).json({ code: 400, message: "valid _id is required" });
}
}
);
app.post(
"/api/openTicket",
passport.authenticate("userPrivate"),
(req, res) => {
const { issue, milestone, transaction, message } = req.body;
if (milestone && !ObjectId.isValid(milestone)) {
res.status(400).json({ code: 400, message: "milestone ID is invalid" });
return;
}
if (issue && message) {
new Ticket({
issue,
...(milestone && { milestone }),
...(transaction && { transaction }),
user: req.user._id,
messages: [
{
user: {
name: req.user.firstName + " " + req.user.lastName,
role: "client",
},
message,
},
],
})
.save()
.then((ticket) => {
res.json({ code: "ok", ticket });
})
.catch((err) => {
console.log(err);
res.status(500).json({ code: 500, message: "database error" });
});
} else {
res.status(400).json({
code: 400,
message: "issue, milestone, message is required",
fieldsFound: req.body,
});
}
}
);
app.patch(
"/api/closeTicket",
passport.authenticate("userPrivate"),
(req, res) => {
if (req.body._id && ObjectId.isValid(req.body._id)) {
Ticket.findOneAndUpdate(
{ _id: req.body._id, user: req.user._id },
{ status: "closed" },
{ new: true }
).then((ticket) => {
if (ticket) {
res.json({ code: "ok", ticket });
} else {
res
.status(404)
.json({ code: 404, message: "ticket could not be found" });
}
});
} else {
res.status(400).json({ code: 400, message: "valid _id is required" });
}
}
);
app.patch(
"/api/addTicketReply",
passport.authenticate("userPrivate"),
(req, res) => {
if (ObjectId.isValid(req.body._id) && req.body.message) {
Ticket.findOneAndUpdate(
{ _id: req.body._id },
{
$push: {
messages: {
user: {
name: req.user.firstName + " " + req.user.lastName,
role: "client",
},
message: req.body.message,
},
},
},
{ new: true }
).then((dbRes) => {
if (dbRes) {
res.json({ code: "ok", ticket: dbRes });
} else {
res
.status(404)
.json({ code: 404, message: "Ticket does not exist." });
}
});
} else {
res
.status(400)
.json({ code: 400, message: "valid _id and message is required" });
}
}
);
app.get("/api/faq", (req, res) => {
const { q, audience } = req.query;
Faq.find({
...(audience && { audience }),
...(q && {
$or: [{ ques: new RegExp(q, "gi") }, { ans: new RegExp(q, "gi") }],
}),
})
.then((faqs) => {
res.json({ code: "ok", faqs });
})
.catch((err) => {
console.log(err);
res.status(500).json({ code: 500, message: "database erro" });
});
});
app.post(
"/api/reportUser",
passport.authenticate("userPrivate"),
(req, res) => {
const { user, message } = req.body;
if (user && message) {
new Report({
from: req.user._id,
against: user,
message,
})
.save()
.then((dbRes) => {
res.json({ code: "ok", report: dbRes });
})
.catch((err) => {
console.log(err);
res.status(500).json({ code: 500, message: "database error" });
});
} else {
res.status(400).json({
code: 400,
message: "user & message is required.",
fieldsFound: req.body,
});
}
}
);
app.get("/api/siteConfig", (req, res) => {
Config.findOne()
.then((config) => {
res.json({ code: "ok", config });
})
.catch((err) => {
console.log(err);
res.status(500).json({ code: 500, message: "something went wrong" });
});
});
app.post("/api/bugReport", (req, res) => {
new Bug({
user: req.body.user || null,
issue: req.body.issue,
dscr: req.body.dscr,
url: req.headers.referer,
files: req.body.files || null,
})
.save()
.then((bug) => {
res.json({ code: "ok", message: "bug has been reported" });
})
.catch((err) => {
console.log(err, req.body);
res.status(500).json({ code: 500, message: "Database error" });
});
});
|
/* eslint-disable */
import { getModule } from 'nuxt-property-decorator'
import Filters from '~/store/filters'
import Object_ from '~/store/object'
import Objects from '~/store/objects'
import Pagination from '~/store/pagination'
import LightCurveStore from '~/store/lightcurve'
import FeaturesStore from '~/store/features'
import ProbabilitiesStore from '~/store/probabilities'
import StatsStore from '~/store/stats'
import TnsStore from '~/store/tns'
import XmatchesStore from '~/store/xmatches'
import AvroStore from '~/store/avro'
import DataReleaseStore from '~/store/datarelease'
import UserStore from '~/store/user'
let filtersStore = null
let objectStore = null
let objectsStore = null
let paginationStore = null
let lightCurveStore = null
let featuresStore = null
let probabilitiesStore = null
let statsStore = null
let tnsStore = null
let xmatchesStore = null
let avroStore = null
let datareleaseStore = null
let userStore = null
function initialiseStores(store) {
filtersStore = getModule(Filters, store)
objectStore = getModule(Object_, store)
objectsStore = getModule(Objects, store)
paginationStore = getModule(Pagination, store)
lightCurveStore = getModule(LightCurveStore, store)
featuresStore = getModule(FeaturesStore, store)
probabilitiesStore = getModule(ProbabilitiesStore, store)
statsStore = getModule(StatsStore, store)
tnsStore = getModule(TnsStore, store)
xmatchesStore = getModule(XmatchesStore, store)
avroStore = getModule(AvroStore, store)
datareleaseStore = getModule(DataReleaseStore, store)
userStore = getModule(UserStore, store)
}
export {
initialiseStores,
filtersStore,
objectStore,
objectsStore,
paginationStore,
lightCurveStore,
featuresStore,
probabilitiesStore,
statsStore,
tnsStore,
xmatchesStore,
avroStore,
datareleaseStore,
userStore
}
|
function controlBorrado($path){
swal({
title: "¿Estas seguro/a?",
text: "Si eliges continuar no podras recuperar tu post!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location.replace($path);
}
});
}
function controlPublicar($path){
swal({
title: "¿Estas seguro/a?",
text: "Si publicas tu posts todos podran verlo!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
window.location.replace($path);
}
});
}
|
import { useColor } from '../functions/providers/ColorContext';
import { mountReactHook } from './mockHook';
import { waitFor, act } from '@testing-library/react-native';
const green = {
primary: "#ffffff",
primaryText: "#465448",
highlight: "#004509",
inactive: "#687c6b",
background: "#9fd984",
shadow: "#444"
};
const colorSchemes = [
'green',
'blue',
'yellow',
'pink',
'lavender',
'periwinkle',
'original',
'dark2',
'dark3',
'dark1'
];
describe('Color Tests', () => {
let setupComponent;
let hook;
beforeEach(() => {
setupComponent = mountReactHook(useColor);
hook = setupComponent.componentHook;
});
it('Has initial color', async () => {
expect(hook.color).toEqual(green);
});
it('Has color schemes', async () => {
expect(Object.keys(hook.colorSchemes)).toEqual(colorSchemes);
});
// it('Changes color', async () => {
// await act(async () => {
// hook.setName('dark3');
// await waitFor(() => {});
// });
// expect(hook.color).toEqual(hook.colorSchemes['dark3']);
// });
});
|
var reservation = angular.module('reservation', ['ngRoute']);
reservation.config(function ($routeProvider, $locationProvider) {
//роутинг и прочие настройки
});
|
import authReducer from '../../reducers/auth';
test('should set uid for login', ()=>{
const testObject={
type: 'LOGIN',
uid: '123456789abcdef'
};
const result = authReducer({}, testObject);
expect(result.uid).toEqual(testObject.uid);
});
test('should clear the uid when logout', ()=>{
const testObject={
type: 'LOGIN'
};
const result = authReducer({}, testObject);
expect(result).toEqual({});
});
test('should test the default value', ()=>{
const testObject={
type: 'TEST',
uid: '123456789abcdef'
};
const result = authReducer({}, testObject);
expect(result).toEqual({});
});
|
//Programmer: Chris Tralie
/** A canvas for drawing a self-similarity matrix synchronized with audio */
/**
* Create a self-similarity canvas
* @param {object} audio_obj - A dictionary of audio parameters, including
* a handle to the audio widget and a time interval between adjacent rows
* of the SSM, and the dimension "dim" of the SSM
*/
function SimilarityCanvas(audio_obj) {
this.ssmcontainer = d3.select("#SSMContainer");
this.ssmcanvas = d3.select("#SimilarityCanvas");
this.eigcanvas = d3.select("#EigCanvas");
this.CSImage = this.ssmcanvas.append('image');
this.ssmlinehoriz = this.ssmcanvas.append('line')
.attr('x1', 0).attr('x2', 0)
.attr('y1', 0).attr('y2', 0)
.attr('stroke-width', 2)
.attr('stroke', 'cyan');
this.ssmlinevert = this.ssmcanvas.append('line')
.attr('x1', 0).attr('x2', 0)
.attr('y1', 0).attr('y2', 0)
.style('fill', 'cyan')
.attr('stroke-width', 2)
.attr('stroke', 'cyan');
this.EigImage = this.eigcanvas.append('image');
this.eiglinevert = this.eigcanvas.append('line')
.attr('x1', 0).attr('x2', 0)
.attr('y1', 0).attr('y2', 0)
.attr('stroke-width', 2)
.attr('stroke', 'cyan');
this.audio_obj = audio_obj;
/**
* A function use to update the images on the canvas and to
* resize things accordingly
* @param {object} params : A dictionary of parameters returned
* from the Python program as a JSON file
*/
this.updateParams = function(params) {
this.CSImage.attr('href', params.W)
.attr('width', params.dim)
.attr('height', params.dim);
this.audio_obj.audio_widget.style.width = params.dim;
this.ssmlinehoriz.attr('x2', params.dim);
this.ssmlinevert.attr('y2', params.dim);
if ('v' in params) {
this.EigImage.attr('href', params.v)
.attr('width', params.dim)
.attr('height', params.v_height);
this.eigcanvas.attr('width', params.dim)
.attr('height', params.v_height);
this.eiglinevert.attr('y2', params.dim);
}
this.ssmcanvas.attr('width', params.dim)
.attr('height', params.dim);
};
/**
* A function which toggles all of the visible elements to show
*/
this.show = function() {
this.ssmcontainer.style("display", "block");
};
/**
* A function which toggles all of the visible elements to hide
*/
this.hide = function() {
this.ssmcontainer.style("display", "none");
};
/**
* A click release handler that is used to seek through the self-similarity
* canvas and to seek to the corresponding position in audio.
* Left click seeks to the row and right click seeks to the column
* @param {*} evt: Event handler
*/
this.releaseClickSSM = function(evt) {
evt.preventDefault();
var offset1idx = evt.offsetY;
var offset2idx = evt.offsetX;
var offsetidx = 0;
clickType = "LEFT";
evt.preventDefault();
if (evt.which) {
if (evt.which == 3) clickType = "RIGHT";
if (evt.which == 2) clickType = "MIDDLE";
}
else if (evt.button) {
if (evt.button == 2) clickType = "RIGHT";
if (evt.button == 4) clickType = "MIDDLE";
}
if (clickType == "LEFT") {
offsetidx = offset1idx;
}
else {
offsetidx = offset2idx;
}
this.audio_obj.audio_widget.currentTime = this.audio_obj.times[offsetidx];
this.repaint();
return false;
};
/**
* A click release handler that is used to seek through the Laplacian eigenvector
* canvas and to seek to the corresponding position in audio
* @param {*} evt: Event handler
*/
this.releaseClickEig = function(evt) {
evt.preventDefault();
this.audio_obj.audio_widget.currentTime = this.audio_obj.times[evt.offsetX];
this.repaint();
return false;
};
/**
* An event handler that does nothing
* @param {*} evt
*/
this.dummyHandler = function(evt) {
evt.preventDefault();
return false;
};
/**
* A fuction which renders the SSM and laplacian eigenvectors
* with lines superimposed to show where the audio is
*/
this.updateCanvas = function() {
var t = this.audio_obj.getClosestIdx();
this.ssmlinehoriz.attr('y1', t).attr('y2', t);
this.ssmlinevert.attr('x1', t).attr('x2', t);
this.eiglinevert.attr('x1', t).attr('x2', t);
};
/**
* A function that should be called in conjunction with requestionAnimationFrame
* to refresh this canvas so that it is properly synchronized with the audio as it plays.
* It continually generates callbacks as long as the audio is playing, but stops generating
* callbacks when it is paused, to save computation.
*/
this.repaint = function() {
this.updateCanvas();
if (!this.audio_obj.audio_widget.paused) {
requestAnimationFrame(this.repaint.bind(this));
}
};
this.initDummyListeners = function(canvas) {
canvas.addEventListener("contextmenu", function(e){ e.stopPropagation(); e.preventDefault(); return false; }); //Need this to disable the menu that pops up on right clicking
canvas.addEventListener('mousedown', this.dummyHandler.bind(this));
canvas.addEventListener('mousemove', this.dummyHandler.bind(this));
canvas.addEventListener('touchstart', this.dummyHandler.bind(this));
canvas.addEventListener('touchmove', this.dummyHandler.bind(this));
canvas.addEventListener('contextmenu', function dummy(e) { return false });
};
this.initCanvasHandlers = function() {
var canvas = document.getElementById('SimilarityCanvas');
this.initDummyListeners(canvas);
canvas.addEventListener('mouseup', this.releaseClickSSM.bind(this));
canvas.addEventListener('touchend', this.releaseClickSSM.bind(this));
canvas = document.getElementById('EigCanvas');
this.initDummyListeners(canvas);
canvas.addEventListener('mouseup', this.releaseClickEig.bind(this));
canvas.addEventListener('touchend', this.releaseClickEig.bind(this));
};
this.initCanvasHandlers();
}
|
import React from 'react';
export default class FilterOptions extends React.Component {
handleChange(e) {
const val = e.target.value;
this.props.changeOption(val);
}
render() {
return (
<div className="styled-select">
<select className="userLive" id="selectValue" onChange={this.handleChange.bind(this)}>
{this.props.options.map((option) => {
return <option key={option} value={option}>{option}</option>;
})}
</select>
</div>
);
}
}
|
var oTitle = document.getElementsByClassName("fix-title")[0];
var oRight = document.getElementsByClassName("pull-right")[0];
var oContainer = document.getElementsByClassName("container")[0];
var iContainer = parseInt(getStyle(oContainer, 'width'));
var iContainer2 = parseInt(getStyle(oContainer, 'paddingLeft'));
oTitle.style.width = parseInt(iContainer) - parseInt(iContainer2)*2 - oRight.offsetWidth - 10 +'px';
//收藏按钮AJAX
var oBtn = document.getElementsByClassName("img")[0];
//收藏的数量
var iNum = parseInt(document.getElementsByClassName("num")[0].innerHTML);
oBtn.onclick = function(){
if(oBtn.className == 'img'){
oBtn.className = 'img click-img';
iNum++;
document.getElementsByClassName("num")[0].innerHTML = iNum;
}else{
oBtn.className = 'img';
iNum--;
document.getElementsByClassName("num")[0].innerHTML = iNum;
}
}
|
import { connect } from 'react-redux';
import OrderPage from '../../../components/OrderPage';
import { Action } from '../../../action-reducer/action';
import { getPathValue } from '../../../action-reducer/helper';
import helper, { getObject, fetchJson, showError, showSuccessMsg} from '../../../common/common';
import {search2} from '../../../common/search';
import {showImportDialog} from '../../../common/modeImport';
import { exportExcelFunc, commonExport } from '../../../common/exportExcelSetting';
import { showColsSetting } from '../../../common/tableColsSetting';
import {toFormValue} from "../../../common/check";
import showFinanceDialog from "./financeDialog";
import showFilterSortDialog from "../../../common/filtersSort";
import showTemplateManagerDialog from "../../../standard-business/template/TemplateContainer";
import {dealExportButtons} from "../customersArchives/RootContainer";
const STATE_PATH = ['config', 'suppliersArchives'];
const URL_LIST = '/api/config/suppliersArchives/list';
const URL_ABLE = '/api/config/suppliersArchives/able';
const URL_BUYERS = '/api/config/suppliersArchives/buyers';
const URL_DETAIL = '/api/config/suppliersArchives/detail';
const URL_DELETE = '/api/config/suppliersArchives/delete';
const URL_FINANANCIAL = '/api/basic/user/name';
const action = new Action(STATE_PATH);
const getSelfState = (rootState) => {
return getPathValue(rootState, STATE_PATH);
};
// 为EditDialog组件构建状态
const buildEditDialogState = (config={}, data, edit) => {
const EDIT_DIALOG = ['config', 'size'];
const backConfig = helper.deepCopy(config);
const newData = backConfig.controls[1].data.map(item => {
if (item.key === 'tax') item.type = 'readonly';
return item;
});
backConfig.controls[1].data = newData;
return {
edit,
...getObject(config, EDIT_DIALOG),
title: edit ? config.edit : config.add,
value: helper.getObjectExclude(data, ['checked']),
options: {},
controls: data['taxType'] === 'tax_rate_way_not_calculate' ? backConfig.controls : config.controls
};
};
const updateTable = async (dispatch, getState) => {
const {currentPage, pageSize, searchDataBak={}} = getSelfState(getState());
return search2(dispatch, action, URL_LIST, currentPage, pageSize, toFormValue(searchDataBak))
};
const resetActionCreator = (dispatch) => {
dispatch(action.assign({searchData: {}}));
};
const searchActionCreator = async (dispatch, getState) => {
const {pageSize, searchData} = getSelfState(getState());
const newState = {searchDataBak: searchData, currentPage: 1};
return search2(dispatch, action, URL_LIST, 1, pageSize, searchData, newState);
};
const changeActionCreator = (key, value) => action.assign({[key]: value}, 'searchData');
const formSearchActionCreator = (key, value) => async (dispatch, getState) => {
const {filters} = getSelfState(getState());
let data, options;
switch (key) {
case 'purchasePersonId': {
const option = helper.postOption({maxNumber: 20, filter: value});
data = await fetchJson(URL_BUYERS, option);
options = data.result.data;
break;
}
case 'settlementPersonnel': {
const option = helper.postOption({filter: value});
data = await fetchJson(URL_FINANANCIAL, option);
options = data.result.data;
break;
}
default: return;
}
if(data.returnCode !== 0) return showError(data.returnMsg);
const index = filters.findIndex(item => item.key === key);
dispatch(action.update({options}, 'filters', index));
};
// 新增
const addActionCreator = (dispatch, getState) => {
const {editConfig} = getSelfState(getState());
const payload = buildEditDialogState(editConfig, {}, false);
dispatch(action.assign(payload, 'edit'));
};
//需求变更 放开可编辑的权限
const editAction = async (isDbClick, dispatch, getState, rowIndex=0) => {
const {tableItems, editConfig, customConfig} = getSelfState(getState());
const index = isDbClick ? rowIndex : helper.findOnlyCheckedIndex(tableItems);
if (index === -1) return showError('请勾选一条数据!');
// if(tableItems[index]['enabledType'] !== 'enabled_type_unenabled'){
// return showError('只能编辑未启用状态记录');
// }
const id = tableItems[index].id;
const {returnCode, returnMsg, result} = await fetchJson(`${URL_DETAIL}/${id}`);
if (returnCode !== 0) return showError(returnMsg);
if (customConfig.controls && customConfig.controls.length > 0) {
editConfig.controls.push({
key: 'otherInfo', title: '其他信息', data: customConfig.controls
});
}
const payload = buildEditDialogState(editConfig, result, true);
dispatch(action.assign(payload, 'edit'));
};
// 编辑
const editActionCreator = async (dispatch, getState) => {
editAction(false, dispatch, getState);
};
const doubleClickActionCreator = (rowIndex) => async (dispatch, getState) => {
editAction(true, dispatch, getState, rowIndex);
};
const ableActionCreator = async (type='enabled_type_enabled', dispatch, getState) => {
const {tableItems} = getSelfState(getState());
const checkItems = tableItems.filter(o=>o.checked);
if(checkItems.length < 1) return showError('请勾选一条数据!');
if(type === 'enabled_type_enabled') {
if (checkItems.some(o=> o.enabledType === 'enabled_type_enabled')) return showError('请选择未启用或禁用状态的数据!');
} else if(type === 'enabled_type_disabled') {
if (checkItems.some(o=> o.enabledType !== 'enabled_type_enabled')) return showError('请选择已启用状态的数据!');
}
const params = {
ids: checkItems.map(o=>o.id),
type
};
const {returnCode, returnMsg} = await fetchJson(`${URL_ABLE}`, helper.postOption(params));
if (returnCode !== 0) return showError(returnMsg);
showSuccessMsg(returnMsg);
searchActionCreator(dispatch, getState);
};
// 启用
const enableActionCreator = (dispatch, getState) => ableActionCreator('enabled_type_enabled', dispatch, getState);
// 禁用
const disableActionCreator = (dispatch, getState) => ableActionCreator('enabled_type_disabled', dispatch, getState);
// 删除
const deleteActionCreator = async (dispatch, getState) => {
const {tableItems} = getSelfState(getState());
const checkItems = tableItems.filter(o=>o.checked);
if (!checkItems.length) return showError('勾选一条记录!') ;
if (checkItems.some(o => o.enabledType !== 'enabled_type_unenabled')) return showError('请选择未启用状态的数据!');
const {returnCode, returnMsg} = await fetchJson(URL_DELETE, helper.postOption(checkItems.map(o=>o.id)));
if (returnCode !== 0) return showError(returnMsg);
showSuccessMsg(returnMsg);
searchActionCreator(dispatch, getState);
};
// 导入
const importActionCreator = () => showImportDialog('supplier_import');
// 配置字段
const configActionCreator = async (dispatch, getState) => {
const {tableCols} = getSelfState(getState());
const okFunc = (newCols) => {
dispatch(action.assign({tableCols: newCols}));
};
showColsSetting(tableCols, okFunc, 'suppliersArchives');
};
//设置财务人员
const financeActionCreator = async (dispatch, getState) => {
const {finance, tableItems} = getSelfState(getState());
const idList = tableItems.reduce((result, item) => {
item.checked && result.push(item.id);
return result
}, []);
return !idList.length ? showError('请勾选一条数据') :
await showFinanceDialog(finance, idList);
};
const sortActionCreator = async (dispatch, getState) => {
const {filters} = getSelfState(getState());
const newFilters = await showFilterSortDialog(filters, helper.getRouteKey());
newFilters && dispatch(action.assign({filters: newFilters}));
};
//页面导出
const exportPageActionCreator = (subKey) => (dispatch, getState) => {
const {tableCols=[]} = JSON.parse(subKey);
const {tableItems} = getSelfState(getState());
//税率保存时虽然是字典但是只保存title, 所以在前端导出时先去掉options
const exportTableCols = helper.deepCopy(tableCols).map(_item => {
if (_item.key === 'tax') delete _item.options;
return _item;
});
return exportExcelFunc(exportTableCols, tableItems);
};
// 查询导出
const exportSearchActionCreator = (subKey) => (dispatch, getState) =>{
const {tableCols=[]} = JSON.parse(subKey);
const {searchData} = getSelfState(getState());
//税率保存时虽然是字典但是只保存title, 所以要去掉字典属性
const exportTableCols = helper.deepCopy(tableCols).map(_item => {
if (_item.key === 'tax') delete _item.dictionary;
return _item;
});
return commonExport(exportTableCols, '/archiver-service/supplier/list/search', searchData);
};
//模板管理
const templateManagerActionCreator = async (dispatch, getState) => {
const {tableCols, buttons} = getSelfState(getState());
if(true === await showTemplateManagerDialog(tableCols, helper.getRouteKey())) {
dispatch(action.assign({buttons: dealExportButtons(buttons, tableCols)}));
}
};
const toolbarActions = {
reset: resetActionCreator,
search: searchActionCreator,
add: addActionCreator,
edit: editActionCreator,
enable: enableActionCreator,
disable: disableActionCreator,
sort: sortActionCreator,
delete: deleteActionCreator,
import: importActionCreator,
exportSearch: exportSearchActionCreator,
exportPage :exportPageActionCreator,
templateManager: templateManagerActionCreator,
finance: financeActionCreator,
config: configActionCreator
};
const clickActionCreator = (key) => {
const k = key.split('_')[1] || key;
if (toolbarActions.hasOwnProperty(k)) {
return toolbarActions[k];
} else {
return {type: 'unknown'};
}
};
const subClickActionCreator = (key, subKey) => {
const k = key.split('_')[1] || key;
if (toolbarActions.hasOwnProperty((k))) {
return toolbarActions[k](subKey);
} else {
return {type: 'key unknown'};
}
};
const checkActionCreator = (isAll, checked, rowIndex) => {
isAll && (rowIndex = -1);
return action.update({checked}, 'tableItems', rowIndex);
};
const pageNumberActionCreator = (currentPage) => (dispatch, getState) => {
const {pageSize, searchData={}} = getSelfState(getState());
const newState = {currentPage};
return search2(dispatch, action, URL_LIST, currentPage, pageSize, searchData, newState);
};
const pageSizeActionCreator = (pageSize, currentPage) => async (dispatch, getState) => {
const {searchData={}} = getSelfState(getState());
const newState = {pageSize, currentPage};
return search2(dispatch, action, URL_LIST, currentPage, pageSize, searchData, newState);
};
const mapStateToProps = (state) => {
return getObject(getSelfState(state), OrderPage.PROPS);
};
const actionCreators = {
onClick: clickActionCreator,
onChange: changeActionCreator,
onSubClick: subClickActionCreator,
onSearch: formSearchActionCreator,
onCheck: checkActionCreator,
onDoubleClick: doubleClickActionCreator,
onPageNumberChange: pageNumberActionCreator,
onPageSizeChange: pageSizeActionCreator,
};
// 编辑完成后的动作
const afterEditActionCreator = (isOk=false ,dispatch, getState) => {
dispatch(action.assign({edit: undefined}));
isOk && updateTable(dispatch, getState);
};
const Container = connect(mapStateToProps, actionCreators)(OrderPage);
export default Container;
export {afterEditActionCreator, updateTable};
|
import React, {useState} from 'react';
import {StackActions} from '@react-navigation/native';
import {
StyleSheet,
Text,
View,
ScrollView,
TextInput,
TouchableOpacity,
} from 'react-native';
import normalize from 'react-native-normalize';
import {connect} from 'react-redux';
import {editUser, signOut, clearStore} from '../redux/actions';
// import {updateUser} from '../services/HttpService';
import get from 'lodash/get';
import UserCard from '../components/common/UserCard';
import {Overlay} from 'react-native-elements';
import ButtonMedium from '../components/common/ButtonMedium';
//import CustomButton from '../components/common/CustomButton';
function UserProfileScreen(props) {
const [signOut, setSignOut] = useState(false);
const [visible, setVisible] = useState(false);
const [userName, setUsername] = useState(props.user.first_name);
const [userEmail, setUserEmail] = useState(props.user.email);
const user = props.user;
const handleEditProfile = () => {
toggleOverlay();
};
const toggleOverlay = () => {
setVisible(!visible);
};
const handleUsernameChange = name => {
setUsername(name);
};
const handleUserEmailChange = email => {
setUserEmail(email);
};
const handleUpdateProfile = () => {
// const updateObject = {
// _id: props.user._id,
// user: {first_name: userName, email: userEmail},
// };
// updateUser(updateObject, props.user.jwtToken).then(users => {
// if (!users) console.log('Error Updating the name');
// else
// props.editUser({first_name: userName, email: userEmail}),
// toggleOverlay();
// });
};
if (!user.userId) {
props.navigation.dispatch(StackActions.replace('Login'));
return null;
} else
return (
<View
style={styles.container}
contentContainerStyle={styles.contentContainer}>
<View style={styles.StoreHeadingContainer}></View>
<Overlay
isVisible={visible}
onBackdropPress={toggleOverlay}
overlayStyle={
Platform.OS === 'ios' ? styles.ModalStylesIOS : styles.ModalStyles
}>
<View style={styles.ModalContainer}>
<View style={styles.ModalSubtitle}>
<Text style={styles.ModalSubtitleText}>Edit your Profile</Text>
</View>
<View style={styles.ModalFormGroup}>
<View style={styles.InputContainer}>
<TextInput
style={styles.InputStyle}
onChangeText={handleUsernameChange}
placeholder="Your Name"
placeholderTextColor="#6e6e6e"
keyboardAppearance="dark"
value={userName}
autoFocus={true}
/>
</View>
</View>
<View style={styles.ModalFormGroup}>
<View style={styles.InputContainer}>
<TextInput
style={styles.InputStyle}
onChangeText={handleUserEmailChange}
placeholder="Your Email"
placeholderTextColor="#6e6e6e"
keyboardAppearance="dark"
value={userEmail}
autoFocus={true}
/>
</View>
</View>
<View style={styles.ModalVerificationCodeContainer}>
<TouchableOpacity
style={styles.VerifyButton}
activeOpacity={0.5}
onPress={handleUpdateProfile}>
<Text style={styles.VerifyButtonText}>Save</Text>
</TouchableOpacity>
</View>
</View>
</Overlay>
<ScrollView style={{flex: 1}}>
<UserCard
name={props.user.first_name}
phone={props.user.phone}
email={props.user.email}
handleEditProfile={handleEditProfile}
/>
<View style={{marginTop: 15}}>
<ButtonMedium
buttonText="Sign Out"
color="#EF7D21"
textColor="#ffffff"
onPressAction={() => {
props.signOut();
// props.clearStore();
// props.setOrders([]);
setSignOut(true);
}}
// buttonIcon="md-log-out"
/>
</View>
</ScrollView>
<View style={{flex: 0.2}}></View>
</View>
);
}
const mapStateToProps = state => {
return {
user: get(state, 'userState'),
};
};
const mapDispatchToProps = dispatch => {
return {
// editUser: value => dispatch(editUser(value)),
signOut: () => dispatch(signOut()),
// setOrders: value => dispatch(setOrders(value)),
// clearStore: () => dispatch(clearStore()),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(UserProfileScreen);
const styles = StyleSheet.create({
container: {
backgroundColor: '#ffffff',
flex: 10,
},
StoreHeadingContainer: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
height: normalize(135, 'width'),
backgroundColor: '#EF7D21',
marginBottom: normalize(20, 'width'),
},
PageHeadingText: {
color: '#EF7D21',
fontSize: normalize(32, 'width'),
fontWeight: 'bold',
},
contentContainer: {
flexDirection: 'column',
justifyContent: 'center',
alignItems: 'center',
marginTop: normalize(20, 'width'),
},
heading: {
marginBottom: '10%',
fontSize: 24,
color: 'white',
},
EmptyMessage: {
marginTop: normalize(5, 'width'),
marginLeft: 7,
color: 'rgb(98,99,100)',
fontSize: normalize(16, 'width'),
textAlign: 'center',
},
ModalStylesIOS: {
backgroundColor: '#018bff',
width: '95%',
height: normalize(260, 'width'),
borderRadius: 15,
marginBottom: normalize(120, 'width'),
},
ModalStyles: {
backgroundColor: '#018bff',
width: '95%',
height: normalize(260, 'width'),
borderRadius: 15,
},
ModalSubtitle: {
flexDirection: 'row',
justifyContent: 'center',
},
ModalSubtitleText: {
color: '#ffffff',
fontSize: normalize(18, 'width'),
fontWeight: '600',
textAlign: 'center',
paddingLeft: normalize(50, 'width'),
paddingRight: normalize(50, 'width'),
paddingTop: normalize(15, 'width'),
paddingBottom: normalize(10, 'width'),
},
ModalVerificationCodeContainer: {
flexDirection: 'row',
justifyContent: 'center',
marginTop: normalize(20, 'width'),
},
VerifyButton: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
height: normalize(32, 'width'),
width: normalize(120, 'width'),
borderRadius: 50,
margin: 5,
},
VerifyButtonText: {
color: '#747474',
fontSize: normalize(14, 'width'),
},
ModalFormGroup: {
justifyContent: 'center',
alignSelf: 'center',
width: '80%',
marginTop: normalize(15, 'width'),
},
InputContainer: {
flexDirection: 'row',
height: normalize(45, 'width'),
borderColor: '#353735',
borderWidth: 3,
borderRadius: 25,
backgroundColor: '#292929',
paddingLeft: normalize(25, 'width'),
justifyContent: 'center',
alignItems: 'center',
},
InputStyle: {
flex: 1,
color: '#ffffff',
fontSize: normalize(14, 'width'),
},
});
|
/**
* Created by Ziv on 2017/1/29.
*/
/**
* 在某一个位置左右两边的和是一样的,求出这个位置的下标
* @param arr
* @returns {number}
*/
function findEvenIndex(arr) {
let sum = 0, leftsum = 0;
sum = arr.reduce((a, b) => a + b);
for (let i = 0; i < arr.length; i++) {
sum -= arr[i];
if (sum === leftsum) {
console.log(i);
return i;
}
leftsum += arr[i];
}
return -1;
}
findEvenIndex([1, 2, 3, 4, 3, 2, 1]); //3
//another solution
// function findEvenIndex(arr)
// {
// for(var i=1; i<arr.length-1; i++) {
// if(arr.slice(0, i).reduce((a, b) => a+b) === arr.slice(i+1).reduce((a, b) => a+b)) {
// return i;
// }
// }
// return -1;
// }
|
var ReactsNearYou = {
init: function (dx, dy, excheight) {
this.reactx = dx || 80
this.reacty = dy || 50
this.excheight = excheight || 20
},
nearyou: function () {
return Math.abs(this.x - You.x) < this.reactx && Math.abs(this.y - You.y) < this.reacty
},
think: function (dt) {
if (this.nearyou() && You.state === LandState) {
this.exctime = 0.6
} else {
this.exctime = Math.max(this.exctime - dt, 0)
}
},
draw: function () {
if (this.nearyou()) {
UFX.draw("[ t 0", this.excheight, "fs white textalign center textbaseline middle vflip")
context.font = settings.fonts.exc
context.fillText("!", 0, 0)
UFX.draw("]")
}
},
}
var Discharges = {
activate: function () {
effects.push(new Discharge(this.x, this.y + 10))
this.alive = false
},
}
var FlySplats = {
activate: function () {
effects.push(new BirdSplat(this.x, this.y, this.x - You.x, this.y - You.y))
this.alive = false
},
}
var LaunchesYou = {
activate: function () {
effects.push(new ShockWave(this.x, this.y + 16))
this.alive = false
if (this.nearyou()) {
var dx = You.x - this.x, dy = You.y - this.y + 40
if (Math.abs(dy) < 0.1) dy = 1
var f = mechanics.launchspeed / Math.sqrt(dx*dx + dy*dy)
You.vx = f * dx
You.vy = f * dy
}
},
}
var WhipsItGood = {
activate: function () {
effects.push(new Windmill(this.x, this.y + 16))
this.alive = false
},
}
var CarriesYou = {
activate: function () {
You.carrier = this
You.nextstate = CarriedState
this.carrybounced = false
},
bounce: function () {
if (You.carrier === this) {
if (this.carrybounced && getheight(this.x) > 0) {
this.alive = false
You.nextstate = LandState
effects.push(new Splat(this.x, this.y))
You.vy = 50
You.y = getheight(You.x)
}
this.carrybounced = true
}
},
}
var RandomlyDiesOnBounce = {
init: function (dieprob) {
this.dieprob = dieprob || 0.05
},
bounce: function () {
if (You.carrier !== this && getheight(this.x) < 0) {
if (UFX.random() < this.dieprob) {
this.alive = false
}
}
},
}
var FollowsYou = {
init: function (vxmax) {
this.vxmax = vxmax
},
think: function (dt) {
if (this.nearyou()) {
var d = You.x - this.x
this.vx += dt * 50 * (d > 0 ? 1 : -1)
this.vx = Math.min(Math.max(this.vx, -this.vxmax), this.vxmax)
} else {
this.vx *= Math.exp(-2 * dt)
}
this.x += this.vx * dt
},
}
var DisappearsUnderwater = {
draw: function () {
if (this.y < 40) {
UFX.draw("( m -1000", -this.y, "l 1000", -this.y, "l 0 1000 ) clip")
}
},
}
var Bounces = {
bounce: function () {
this.y = getheight(this.x)
this.vy = UFX.random(200, 300)
if (this.exctime) playsound("boing")
},
think: function (dt) {
this.vy -= dt * mechanics.gravity
this.y += this.vy * dt
if (this.y < getheight(this.x)) {
this.bounce()
}
},
draw: function () {
var s = 1 + this.vy / 1000
UFX.draw("z", 1/s, s)
},
}
var SwimsAbout = {
bounce: function () {
this.y = Math.max(getheight(this.x), -10)
this.vy = UFX.random(200, 300)
},
think: function (dt) {
this.vy -= dt * mechanics.gravity
this.y += this.vy * dt
this.x += this.vx * dt
if (this.y < getheight(this.x) || this.y < -10) {
this.bounce()
}
},
}
var FliesAbout = {
init: function (fxmax, fymax) {
this.fxmax = fxmax || 200
this.fymax = fymax || 200
},
think: function (dt) {
this.vx = Math.min(Math.max(this.vx + dt * 50 * (this.x > this.x0 ? -1 : 1), -this.fxmax), this.fxmax)
if (this.ascending) {
this.vy = Math.min(this.vy + dt * 15, 50)
if (this.y - getheight(this.x) > 400) {
this.ascending = false
if (UFX.random() < 0.2) this.alive = false
}
} else {
this.vy = Math.min(this.vy - dt * 5, -20)
if (this.y - Math.max(0, getheight(this.x)) < 160) this.ascending = true
}
this.y += this.vy * dt
this.x += this.vx * dt
},
}
var WindsUpRandomly = {
init: function (vxmax) {
this.vxmax = vxmax || 160
},
think: function (dt) {
if (this.resting) {
this.vx *= Math.exp(-2 * dt)
if (Math.abs(this.vx) < 1) this.vx = 0
if (this.vx == 0 && UFX.random() * 0.1 < dt) {
if (this.nearyou()) {
this.vx = You.x > this.x ? 1 : -1
} else {
this.vx = UFX.random.choice([-1, 1])
}
this.resting = false
}
} else {
this.vx += (this.vx > 0 ? 1 : -1) * 320 * dt
this.vx = Math.min(Math.max(this.vx, -this.vxmax), this.vxmax)
if (UFX.random() * 0.6 < dt && !(this.nearyou() && (You.x - this.x) * this.vx > 0)) {
this.resting = true
if (this.y < -20 && UFX.random() < 0.3) {
this.alive = false
}
}
}
this.x += this.vx * dt
this.y = getheight(this.x)
},
}
var TalksToYou = {
init: function (text) {
this.text = text || "yello"
},
activate: function () {
this.talking = true
playsound("yap")
},
think: function (dt) {
this.talking = this.talking && this.nearyou()
},
draw: function () {
if (this.talking) {
var texts = dialogue.wordwrap(this.text, 24)
context.font = settings.fonts.yapper
UFX.draw("fs white ss black lw 0.5 [ t 20 40 vflip textalign center textbaseline middle")
texts.forEach(function (text, jline, texts) {
var y = 24 * (-texts.length + jline)
context.fillText(text, 0, y)
context.strokeText(text, 0, y)
})
UFX.draw("]")
}
}
}
var AvoidsLand = {
bounce: function () {
if (getheight(this.x) > 0) {
this.vx = -this.vx
}
},
}
var BouncesRandomDirections = {
bounce: function () {
if (this.nearyou()) {
this.vx = this.vx * 0.8 + UFX.random(-15, 15)
} else {
this.vx = this.vx / 2 + UFX.random(-60, 60)
if (getheight(this.x) > 0) this.vx += getgrad(this.x) * 35
}
},
}
var PointsForward = {
draw: function () {
if (!this.vx && !this.vy) return
UFX.draw("r", Math.atan2(this.vy, this.vx))
},
}
var PointsUpward = {
draw: function () {
if (!this.vx && !this.vy) return
if (this.vx > 0) {
UFX.draw("r", Math.atan2(this.vy, this.vx) * 0.5)
} else {
UFX.draw("hflip r", Math.atan2(this.vy, -this.vx) * 0.5)
}
},
}
var StandsUpward = {
tilt: function () {
return -Math.atan2(0.5 * getgrad(this.x), 1)
},
draw: function () {
UFX.draw("r", this.tilt())
}
}
var DrawBall = {
draw: function () {
UFX.draw("b o 0 8 8 fs rgb(80,0,160) ss rgb(120,0,240) lw 2 f s")
},
}
var DrawFish = {
draw: function () {
UFX.draw("b o 0 0 8 fs rgb(140,0,140) ss rgb(200,0,200) lw 2 f s")
UFX.draw("( m -8 0 l -16 8 l -16 -8 ) fs rgb(100,0,100) ss rgb(160,0,160) lw 2 f s")
}
}
var DrawBird = {
draw: function () {
UFX.draw("b o 0 0 8 fs rgb(140,80,0) ss rgb(200,100,0) lw 2 f s")
UFX.draw("fs rgb(100,60,0) ss rgb(160,80,0)")
var A = this.ascending ? -1 * Math.abs(Math.sin(Date.now() / 200)) : 0
UFX.draw("[ t 5 5 r", A, "( m 0 0 l 9 -5 l 15 7 ) f s ]")
UFX.draw("[ hflip t 5 5 r", A, "( m 0 0 l 9 -5 l 15 7 ) f s ]")
}
}
var DrawWheel = {
draw: function () {
UFX.draw("t 0 16 r", -this.x / 16)
UFX.draw("b o 0 0 8 fs rgb(0,80,140) ss rgb(0,100,200) lw 2 f s")
UFX.draw("fs rgb(0,60,100) ss rgb(0,80,160)")
UFX.draw("( m 0 8 l 8 16 l -8 16 ) f s")
UFX.draw("( m 0 -8 l 8 -16 l -8 -16 ) f s")
UFX.draw("( m 8 0 l 16 8 l 16 -8 ) f s")
UFX.draw("( m -8 0 l -16 8 l -16 -8 ) f s")
}
}
var DrawGear = {
draw: function () {
UFX.draw("t 0 16 r", -this.x / 16)
UFX.draw("b o 0 0 8 fs rgb(140,0,0) ss rgb(200,0,0) lw 2 f s")
UFX.draw("fs rgb(100,0,0) ss rgb(160,0,0)")
for (var j = 0 ; j < 3 ; ++j) {
UFX.draw("[ r", j*2*Math.PI/3, "( m 0 6 l 0 22 l 8 14 ) f s ]")
}
}
}
var DrawGuy = {
draw: function () {
UFX.draw("fs rgb(160,160,160) ss rgb(240,240,240) lw 2")
UFX.draw("( m -8 0 l 8 0 l 0 8 ) f s")
UFX.draw("( m 3 7 l 0 16 l 10 20 ) f s")
UFX.draw("( m -3 7 l 0 16 l -10 20 ) f s")
UFX.draw("( m 5 36 l 8 48 l 20 46 ) f s")
UFX.draw("( m -5 36 l -8 48 l -20 46 ) f s")
UFX.draw("b o 0 30 8 fs rgb(0,140,0) ss rgb(0,200,0) lw 2 f s")
}
}
function Hopper(x) {
this.x = x
this.vx = 0
this.bounce()
this.alive = true
this.think(0)
}
Hopper.prototype = UFX.Thing()
.addcomp(Earthbound)
.addcomp(HorizontalClipping)
.addcomp(FollowsYou, 100)
.addcomp(BouncesRandomDirections)
.addcomp(RandomlyDiesOnBounce)
.addcomp(DisappearsUnderwater)
.addcomp(ReactsNearYou, 120, 100, 25)
.addcomp(Discharges)
.addcomp(Bounces)
.addcomp(DrawBall)
function Flopper(x) {
this.x = x
this.vx = UFX.random.choice([-1, 1]) * UFX.random(80, 140)
this.bounce()
this.alive = true
this.think(0)
}
Flopper.prototype = UFX.Thing()
.addcomp(Earthbound)
.addcomp(HorizontalClipping)
.addcomp(SwimsAbout)
.addcomp(AvoidsLand)
.addcomp(DisappearsUnderwater)
.addcomp(ReactsNearYou, 30, 30, 20)
.addcomp(CarriesYou)
.addcomp(RandomlyDiesOnBounce)
.addcomp(PointsForward)
.addcomp(DrawFish)
function Flapper(x, y) {
this.x0 = this.x = x
this.y0 = this.y = y
this.vy = UFX.random(10, 20)
this.vx = UFX.random.choice([-1, 1]) * UFX.random(80, 140)
this.alive = true
this.ascending = true
this.think(0)
}
Flapper.prototype = UFX.Thing()
.addcomp(Earthbound)
.addcomp(ReactsNearYou, 50, 120)
.addcomp(FlySplats)
.addcomp(HorizontalClipping)
.addcomp(FliesAbout)
.addcomp(PointsUpward)
.addcomp(DrawBird)
function Gripper(x) {
this.x = x
this.y = getheight(this.x)
this.vx = 0
this.resting = true
this.alive = true
this.think(0)
}
Gripper.prototype = UFX.Thing()
.addcomp(Earthbound)
.addcomp(HorizontalClipping)
.addcomp(WindsUpRandomly)
.addcomp(DisappearsUnderwater)
.addcomp(ReactsNearYou, 60, 60, 44)
.addcomp(LaunchesYou)
.addcomp(DrawWheel)
function Whipper(x) {
this.x = x
this.y = getheight(this.x)
this.vx = 0
this.resting = true
this.alive = true
this.think(0)
}
Whipper.prototype = UFX.Thing()
.addcomp(Earthbound)
.addcomp(HorizontalClipping)
.addcomp(WindsUpRandomly)
.addcomp(DisappearsUnderwater)
.addcomp(ReactsNearYou, 60, 60, 44)
.addcomp(WhipsItGood)
.addcomp(DrawGear)
function Yapper(x, text) {
this.x = x
this.x0 = x
this.bounce()
this.alive = true
this.text = text
this.think(0)
}
Yapper.prototype = UFX.Thing()
.addcomp(Earthbound)
.addcomp(HorizontalClipping)
.addcomp(ReactsNearYou, 120, 100, 55)
.addcomp(TalksToYou)
.addcomp({
bounce: function () {
this.y = getheight(this.x)
this.vy = UFX.random(200, 300)
this.vx = 0.5 * (this.x0 - this.x) + UFX.random(-50, 50)
this.bouncing = true
// if (this.exctime) playsound("boing")
},
think: function (dt) {
if (this.bouncing) {
this.vy -= dt * mechanics.gravity
if (this.y < getheight(this.x)) {
if (this.exctime) {
this.bouncing = false
this.vx = this.vy = 0
this.y = getheight(this.x)
} else {
this.bounce()
}
}
} else {
if (!this.exctime) {
this.bounce()
}
}
this.x += this.vx * dt
this.y += this.vy * dt
},
draw: function () {
var s = 1 + this.vy / 1000
UFX.draw("z", 1/s, s)
},
})
// .addcomp(StandsUpward)
.addcomp(DrawGuy)
var CrashLands = {
think: function (dt) {
if (this.y < 0 && getheight(this.x) < 0) {
this.alive = false
} else if (this.y < getheight(this.x)) {
this.alive = false
effects.push(new Discharge(this.x, this.y, 90))
}
},
}
function Zapper(x, y) {
this.x = x
this.y = y
this.vx = 0
this.vy = -50
this.alive = true
this.think(0)
}
Zapper.prototype = UFX.Thing()
.addcomp(Earthbound)
.addcomp(HorizontalClipping)
.addcomp({
nearyou: function () { return false },
think: function (dt) {
this.vx = UFX.random(-200, 200)
if (Math.abs(You.x - this.x) < 100 && Math.abs(You.y - this.y) < 200) {
this.vx += You.x > this.x ? 100 : -100
}
this.x += this.vx * dt
this.y += this.vy * dt
},
})
.addcomp({
draw: function () {
UFX.draw("fs rgba(255,255,128,0.3)")
for (var j = 0 ; j < 6 ; ++j) {
var A0 = UFX.random(100), A1 = UFX.random(100), s = UFX.random(1, 4)
UFX.draw("[ r", A0, "z", s, 1/s, "r", A1, "fr -6 -6 12 12 ]")
}
}
})
.addcomp(CrashLands)
|
(function() {
'use strict';
angular.module('app.usuarios.services', [])
.factory('Usuarios', Usuarios)
.factory('Generos', Generos)
.factory('Escolaridades', Escolaridades)
.factory('TipoDocumentos', TipoDocumentos)
.factory('EntidadesAdministradoras', EntidadesAdministradoras)
.factory('TipoAfiliados', TipoAfiliados)
.factory('Ips', Ips)
.factory('Ciudades', Ciudades);
Usuarios.$inject = ['$resource', 'BASEURL'];
function Usuarios($resource, BASEURL) {
return $resource(BASEURL + '/usuarios/:idUsuario', {
idUsuario: '@idUsuario'
}, {
'update': {
method: 'PUT'
},
queryByIdenti: {
url: BASEURL + '/usuarios/numero/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
},
findBySede: {
url: BASEURL + '/usuarios/sede/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
},
findByFisio: {
url: BASEURL + '/usuarios/numer/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
},
findByIdAndCode: {
url: BASEURL + '/usuarios/codigo/:idUsuario/:recuperacionPass',
method: 'GET',
params: {
idUsuario: '@idUsuario',
recuperacionPass: '@recuperacionPass',
}
},
updatePass: {
url: BASEURL + '/usuarios/passconfirm/:idUsuario',
method: 'PUT',
params: {
idUsuario: '@idUsuario'
}
}
});
}
Ciudades.$inject = ['$resource', 'BASEURL'];
function Ciudades($resource, BASEURL) {
return $resource(BASEURL + '/ciudades/:idCiudad', {
idCiudad: '@idCiudad'
}, {
queryByNombre: {
url: BASEURL + '/ciudades/nombre/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
}
});
}
EntidadesAdministradoras.$inject = ['$resource', 'BASEURL'];
function EntidadesAdministradoras($resource, BASEURL) {
return $resource(BASEURL + '/administradoras', {
codigoEntidad: '@codigoEntidad'
}, {
findByNombre: {
url: BASEURL + '/administradoras/nombre/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
}
});
}
Ips.$inject = ['$resource', 'BASEURL'];
function Ips($resource, BASEURL) {
return $resource(BASEURL + '/ips', {
idIps: '@idIps'
}, {
findByNombre: {
url: BASEURL + '/ips/nombre/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
}
});
}
TipoAfiliados.$inject = ['$resource', 'BASEURL'];
function TipoAfiliados($resource, BASEURL) {
return $resource(BASEURL + '/afiliados');
}
Generos.$inject = ['$resource', 'BASEURL'];
function Generos($resource, BASEURL) {
return $resource(BASEURL + '/generos/:idGenero', {
idGenero: '@idGenero'
}, {
queryByNombre: {
url: BASEURL + '/generos/nombre/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
}
});
}
Escolaridades.$inject = ['$resource', 'BASEURL'];
function Escolaridades($resource, BASEURL) {
return $resource(BASEURL + '/escolaridades/:idEscolaridad', {
idEscolaridad: '@idEscolaridad'
}, {
queryByNombre: {
url: BASEURL + '/escolaridades/nombre/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
}
});
}
TipoDocumentos.$inject = ['$resource', 'BASEURL'];
function TipoDocumentos($resource, BASEURL) {
return $resource(BASEURL + '/tipodocumentos/:idTipoDocumento', {
idTipoDocumento: '@idTipoDocumento'
}, {
queryByNombre: {
url: BASEURL + '/tipodocumentos/nombre/:query',
method: 'GET',
isArray: true,
params: {
query: '@query'
}
}
});
}
})();
|
// 通用操作按钮
export default {
add: '添加',
edit: '编辑',
new: '新增',
delete: '删除',
confirm: '确定',
close: '关闭',
cancel: '取消',
agree: '同意',
refuse: '拒绝',
detail: '详情',
opt: '操作',
prompt: '提示',
search: '查询',
inventory: '库存',
check: '查看',
modify: '修改',
bulkImport: '批量导入',
save: '保存',
enterComplete: '请输入完整',
deleteSuccess: '删除成功',
addSuccess: '添加成功',
modifySuccess: '修改成功',
successfulImport: '成功导入:',
data: '条数据',
pleaseChoose: '请选择',
willDeleteRecord: '此操作将删除该记录, 是否继续?',
saveSuccess: '保存成功',
loading: '加载中',
imageUpload: '图片上传',
imageTip1: '请选择图片',
imageFormatTip: '上传图片只能是 JPG、png 格式!',
imageFormatTip1: '上传图片只能是 JPG、Png 格式!上传图片大小不能超过1M!',
imageFormatTip2: '上传图片大小不能超过',
imageSizeTip: '超过了文件大小限制',
pleaseSelect: '请选择',
all: '全部',
searchKeyTip: '请输入关键字',
startDate: '开始日期',
endDate: '结束日期',
to: '至',
linkSet: '链接设置',
linkType: '类型',
linkType1: '商品',
linkType2: '文章',
linkType3: '地址',
qullEditorTip1: '请选择您要插入链接的对象',
qullEditorTip2: '上传视频只能是 MP4 格式!',
qullEditorTip3: '上传视频大小不能超过20MB!',
priceTip: '请正确输入价格,保留小数点后2位',
yes: '是',
no: '否',
imgUploadTip1: '将文件拖到此处,或',
imgUploadTip2: '点击上传',
imgUploadTip3: '只能上传jpg/png文件,且不超过',
selectAll: '全选',
copyLink: '复制链接',
copyLinkTip: '点击复制',
copySuccess: '复制成功',
shelfOn: '上架',
shelfOff: '下架',
export: '导出',
batchAdd: '批量添加',
uploadImgFormat: '上传图片只能是 JPG、PNG 格式!',
uploadImgNoMoreThan: '上传图片大小不能超过',
exportDetails: '导出明细',
}
|
import React from "react";
function Card(props) {
const { title, icon, des } = props.card_info;
return (
<div className="col-md-4">
<div className="my-card">
{icon}
<h4>{title}</h4>
<p>{des}</p>
</div>
</div>
);
}
export default Card;
|
module.exports = {
ensureAuthenticated: function(req, res, next){
if(req.isAuthenticated()){
//console.log('Authenticated');
return next();
}
//console.log('Not Authenticated');
req.flash('error_msg', 'Please Log Back In');
res.redirect('/');
},
ensureGuest: function(req, res, next){
if(req.isAuthenticated()){
//console.log('Authenticated');
res.redirect('/dashboard');
} else {
//console.log('Not Authenticated');
return next();
}
}
}
|
import { mul } from './calc'
const a = mul(3, 5)
console.log(a)
console.log(a)
|
// https://skillcode.fr/javascript-avance-exercices-poo/
// EXERCICE 1
var user = {
prenom: "John",
nom: "Maclane",
pays: "France",
age: 45,
paiement: ["visa", "mastercards", "paypal"],
paysOk: ["NOUVELLE-ZELANDE", "FRANCE", "ANGLETERRE", "ESPAGNE", "ITALIE"],
paiementOk: ["VISA", "MASTERCARDS"],
ageMini: 18,
getInfo: function() {
alert(this.prenom);
alert(this.nom);
alert(2017 - this.age);
if (this.age > user.ageMini) {
alert("Accès autorisé");
}
if (this.paysOk.includes(this.pays.toUpperCase())) {
alert("Pays accepté");
}
// for (var i=0; i<this.paiement.length; i++){
// for (var j=0; j< this.paiementOk.length; j++ ){
// if(this.paiement[i].toUpperCase()==this.paiementOk[j]){
// alert(this.paiementOk[j]);
// }
// }
// }
for (var i=0; i<this.paiement.length; i++){
if(this.paiementOk.includes(this.paiement[i].toUpperCase())){
alert(this.paiement[i]);
}
}
}
};
user.getInfo();
|
angular.module('loadTest', [])
.controller('LoadTestController', ['$scope', '$http', '$timeout', '$location', function ($scope, $http, $timeout, $location) {
// For each provided URL, spin off a test thread with a timeout
// For each group of provided URLs, spin off n test threads with the given timeout
var runningTests = [];
var testURLs = [];
var timeStarted = null;
var runningTestTimeout = null;
$scope.failedRequests = [];
$scope.message = "";
$scope.numErrors = 10;
$scope.testRan = false;
/* Test configuration */
$scope.getFrequency = 1;
$scope.numThreads = 2;
$scope.timeout = 5000;
$scope.timeElapsed = 1;
$scope.randomString = false;
/* ENTER THE URLS YOU WANT TO GET HERE, One Per Line. */
$scope.urlsToPing = ""; // Use \n as a separator between URLs
/* End URLS */
/* Some test statistics */
$scope.requestsMade = 0;
$scope.requestsSuccess = 0;
$scope.requestsFailure = 0;
$scope.requestsIncomplete = 0;
$scope.totalResponseTime = 0;
$scope.transferredMB = 0;
var transferredBytes = 0;
if(/autostartLoadTest/.test($location.$$absUrl.split('?').pop())) {
$scope.startTest();
}
$scope.startTest = function () {
$scope.stopTest();
$scope.testRan = false;
$scope.failedRequests = [];
$scope.requestsMade = 0;
$scope.requestsSuccess = 0;
$scope.requestsFailure = 0;
$scope.requestsIncomplete = 0;
$scope.totalResponseTime = 0;
$scope.transferredMB = 0;
transferredBytes = 0;
timeStarted = new Date();
var urls = $scope.urlsToPing.split('\n');
var addedUrls = false;
for (var i = 0; i < urls.length; i++) {
if (!urls[i]) continue;
addedUrls = true;
for (var j = 0; j < $scope.numThreads; j++) {
var urlConfig = {};
urlConfig.url = urls[i];
var index = runningTests.push(urlConfig) - 1;
urlConfig.id = index;
urlConfig.timeout = spawnTest(index);
}
}
if (!addedUrls) {
$scope.message = "No URLs found";
$scope.stopTest();
$scope.testStarted = false;
$scope.configHidden = false;
}
runningTestTimeout = setInterval(function() {
$scope.timeElapsed = parseInt((new Date() - timeStarted) / 1000);
},1000);
$scope.testRan = true;
};
$scope.stopTest = function () {
// Iterate over every test and stop it
while (runningTests.length >0) {
var test = runningTests.pop();
clearTimeout(test.timeout);
}
clearInterval(runningTestTimeout);
runningTestTimeout = null;
};
var spawnTest = function (testIndex) {
// Spawn tests
if (typeof (runningTests[testIndex]) === 'undefined') return;
$scope.requestsMade += 1;
var startDate = new Date();
var url = runningTests[testIndex].url;
if ($scope.randomString) {
url += '?' + Math.random().toString(36);
}
try {
$http({
method: 'GET',
url: url,
timeout: $scope.timeout,
cache: false
}).then(function success(data) {
$scope.requestsSuccess += 1;
if (data.headers('Content-Length')) {
transferredBytes += parseInt(data.headers('Content-Length'));
$scope.transferredMB = (transferredBytes / 1024 / 1024).toFixed(2);
}
$scope.totalResponseTime += new Date() - startDate;
}, function error(error, status) {
$scope.requestsFailure += 1;
$scope.failedRequests.push({
url: url,
code: error.status,
details: error.statusText
});
console.log("Error", runningTests[testIndex].url, error);
}).finally(function () {
runningTests[testIndex].timeout = $timeout(
function () {
spawnTest(testIndex);
}, $scope.getFrequency * 1000);
});
} catch (e) {
$scope.failedRequests.push({
url: url,
code: e.name,
details: e.message
});
}
};
}]);
|
//** Import Modules */
import React, { useEffect, useState } from 'react';
import { gsap } from 'gsap';
import { Button } from 'antd';
import { refresh } from 'less';
import { useHistory } from 'react-router-dom';
export default function ChooseChildModal(props) {
// Get the data to display
const history = useHistory();
const { childrenAccounts, handleCharacterClick } = props;
const [modalVisible, setModalVisible] = useState(false);
// // Timeout timer before the modal is removed from the DOM(in ms)
// const removeModalTimer = 1000;
// Function to close the modal
const closeModal = () => {
gsap.to('.modal-container', { y: '100vh', duration: 0.5 });
gsap.to('#notification-modal', { opacity: 0, duration: 0.5, delay: 0.5 });
gsap.to('#notification-modal', {
display: 'none',
duration: 0.1,
delay: 1,
});
// setTimeout(() => {
// props.disableModalWindow();
// }, removeModalTimer);
};
// Add some animation effects when component loads
useEffect(() => {
gsap.to('#notification-modal', {
display: 'flex',
duration: 0.1,
});
gsap.to('#notification-modal', { opacity: 1, duration: 0.5, delay: 0.5 });
gsap.to('.modal-container', { y: 0, duration: 0.5, delay: 1 });
}, []);
return (
<div id="notification-modal">
<div className="modal-container">
<div className="modal-content" style={{ width: '70%' }}>
<Button
className="exit-button"
onClick={evt => {
closeModal(evt);
setModalVisible(false);
history.push('/');
}}
>
{/* Modal closes but will not reopen without refresh*/}X
</Button>
<h2
style={{
textAlign: 'center',
fontSize: '3rem',
fontStyle: 'italic',
}}
>
CHOOSE CHILD
</h2>
<div
style={{
display: 'flex',
width: '100%',
justifyContent: 'space-between',
}}
>
{childrenAccounts.map(child => {
const { ID, Name, AvatarURL } = child;
return (
<div
key={`${Name}`}
style={{ display: 'flexbox', flexDirection: 'column' }}
>
<div
style={{
backgroundColor: '#FFFFFF',
borderRadius: '100%',
width: '111.54px',
height: '111.54px',
display: 'flex',
overflow: 'hidden',
cursor: 'pointer',
justifyContent: 'center',
}}
onClick={evt => {
handleCharacterClick(evt, ID);
closeModal();
}}
>
<img src={AvatarURL} alt={`child ${Name} hero avatar`} />
</div>
<span style={{ fontSize: '1.2rem' }}>
{Name.toUpperCase()}
</span>
</div>
);
})}
</div>
</div>
</div>
</div>
);
}
|
const queryString = require("querystring");
// 引入路由
const handleBlogRouter = require("./src/route/blog");
const handleUsersRouter = require("./src/route/users");
// 处理post Data数据
const getPostData = (req) => {
return new Promise((resolve, reject) => {
const { method } = req;
// 不是post 直接返回
if (method !== "POST") {
return resolve({});
}
// 请求类型头不正确 直接返回
if (req.headers["content-type"] !== "application/json") {
return resolve({});
}
let postData = "";
req.on("data", (chunk) => {
postData += chunk.toString(); // 收到的是二进制Buffer,使用toString转成字符串
});
req.on("end", () => {
// 判空
if (!postData) return resolve({});
return resolve(JSON.parse(postData));// 收到的已经是字符串JSON,需要解析
});
});
};
const serverHandle = (req, res) => {
// res.setHeader("Content-type", "text/plain");
const { url } = req;
const [path, query] = url.split("?");
req.path = path;
req.query = queryString.parse(query); // 解析query参数,返回格式为对象
getPostData(req).then((postData) => {
console.log("promise", postData);
req.body = postData;
const blogRes = handleBlogRouter(req, res);
const usersRes = handleUsersRouter(req, res);
console.log("req", req.body, postData);
// 设置响应头
res.setHeader("Content-type", "application/json");
// blog相关路由处理
if (blogRes) {
res.end(JSON.stringify(blogRes));
return;
}
// user相关路由处理
if (usersRes) {
res.end(JSON.stringify(usersRes));
return;
}
// 404相关
res.writeHead("404", {
"Content-type": "text/plain",
});
res.write("404 Not Found");
res.end();
});
};
// 导出
module.exports = serverHandle;
|
import React from 'react';
import Cookies from 'js-cookie';
import makeSpriteLoop from '../../../helpers/spriteHelper';
import TopWavesSvg from './TopWavesSvg';
import GameSounds from './GameSounds';
let MARIO_WALK_TIMEOUT = 0;
let MARIO_WALK_TIMER = 0;
let MARIO_JUMP_TIMEOUT = 0;
let MARIO_SEAT_TIMEOUT = 0;
let MARIO_DIRECTION = 'Right';
class SuperMarioGame extends React.Component {
componentDidMount(){
/**
* Start mario walking
*/
makeSpriteLoop({
canvas: 'marioCharacter',
image : '/static/images/mario/MarioSprite2.png',
width : 52,
height: 100,
frames: 3,
tick : 7
});
/**
* Add animation of Poisonous flower
*/
makeSpriteLoop({
canvas: 'PoisonousFlower',
image : '/static/images/mario/enemySprite.png',
width : 50,
height: 66,
frames: 3,
tick : 15
});
/**
* Add animation of custom scores
*/
makeSpriteLoop({
canvas: 'scoreCustom_j',
image : '/static/images/mario/Blocks/EmptyStripe.png',
width : 50,
height: 50,
frames: 2,
tick : 10
});
/**
* Add animation of custom scores
*/
makeSpriteLoop({
canvas: 'scoreCustom_s',
image : '/static/images/mario/Blocks/EmptyStripe.png',
width : 50,
height: 50,
frames: 2,
tick : 10
});
/**
* Add animation of score question
*/
makeSpriteLoop({
canvas: 'scoreQuestion',
image : '/static/images/mario/Blocks/ScoreStripe.png',
width : 50,
height: 50,
frames: 2,
tick : 10
});
setTimeout(() => {
window.marioCharacter_RAF_Paused = true;
this.updateMarioChar('stand');
}, 400);
if (Cookies.get('backgroundMusicControl') !== '0') {
this.playSound('background');
}
this.addKeypressEvents();
}
/**
* Check if mario should fall down
*/
checkMarioFallDown() {
/**
* Is mario on available boards
*/
const marioHolder = document.getElementById('marioCharacterHolder') || null;
const checkScoreBarHit = this.checkHitMario('.scoreBar', false);
const checkGroundHit = this.checkHitMario('.groundHolder > div', false);
if (!checkScoreBarHit.result && !checkGroundHit.result) {
marioHolder.style.bottom = '85px';
}
}
/**
* Change mario face
* @param to
*/
updateMarioChar(to = 'stand') {
const marioCharacter = document.getElementById('marioCharacter') || null;
if (marioCharacter) {
const context = marioCharacter.getContext('2d');
let frameNumber = 3;
switch (to) {
case 'stand':
frameNumber = 3;
break;
case 'jump':
frameNumber = 4;
break;
case 'seat':
frameNumber = 5.03;
break;
}
const spriteImage = new Image();
spriteImage.src = '/static/images/mario/MarioSprite2.png';
// clear and draw again
context.clearRect(0, 0, 52, 100);
context.drawImage(
spriteImage,
(frameNumber * 52),
0,
(52),
100,
0,
0,
(52),
100
);
}
}
/**
* Play sound based on key
* @param key
*/
playSound(key) {
const audio = document.querySelector(`audio[data-key="${key}"]`);
if (!audio) return;
audio.currentTime = 0;
if (key === 'background') {
audio.volume = 0.5;
}
audio.play();
}
/**
* Pause playing sound
* @param key
*/
pauseSound(key) {
const audio = document.querySelector(`audio[data-key="${key}"]`);
if (!audio) return;
audio.pause();
}
/**
* Check if mario character hit to object
* @param objectSelector
* @param sideHit
* @param headHit
* @returns {object}
*/
checkHitMario(objectSelector, sideHit = false, headHit = false) {
const marioHolder = document.getElementById('marioCharacterHolder') || null;
const hitObjects = document.querySelectorAll(objectSelector) || [];
const hisObjectsArray = Array.from(hitObjects);
if (hisObjectsArray) {
let hitObjectElement = {};
const mapObjectsResult = hisObjectsArray.some(hitObject => {
const styleMarioChar = window.getComputedStyle(marioHolder),
styleObjectElement = window.getComputedStyle(hitObject);
const
bottomSpaceMario = parseInt(styleMarioChar.getPropertyValue('bottom')),
leftSpaceMario = parseInt(styleMarioChar.getPropertyValue('left')),
marioTop = bottomSpaceMario + 100,
marioRight = leftSpaceMario + 52,
bottomSpaceObj = parseInt(styleObjectElement.getPropertyValue('bottom')),
leftSpaceObj = parseInt(styleObjectElement.getPropertyValue('left')),
objectTop = bottomSpaceObj + parseInt(styleObjectElement.getPropertyValue('height')),
objectRight = leftSpaceObj + parseInt(styleObjectElement.getPropertyValue('width'));
console.log('bottomSpaceMario :: ', bottomSpaceMario, 'objectTop : ', objectTop);
if (
leftSpaceMario <= objectRight
&& marioRight >= leftSpaceObj
&& (
(sideHit && bottomSpaceMario <= objectTop)
|| (!sideHit && !headHit && bottomSpaceMario >= objectTop)
|| (headHit && bottomSpaceMario < objectTop)
)
&& (
(sideHit || marioTop >= bottomSpaceObj)
|| (headHit || (marioTop + 85) >= bottomSpaceObj)
)
) {
hitObjectElement = {
object: hitObject,
left : leftSpaceObj,
right : objectRight,
top : objectTop,
bottom: bottomSpaceObj,
mario : {
left : leftSpaceMario,
right : marioRight,
top : marioTop,
bottom: bottomSpaceMario
}
};
return true;
}
});
if (mapObjectsResult) {
return {
result: true,
...hitObjectElement
};
}
}
return {
result: false
};
}
/**
* Change direction of mario
* @param dir
*/
turnMarioDirection(dir) {
const marioHolder = document.getElementById('marioCharacterHolder') || null;
MARIO_DIRECTION = dir;
if (dir === 'Right') {
marioHolder.classList.remove('toLeft');
marioHolder.classList.add('toRight');
} else {
marioHolder.classList.remove('toRight');
marioHolder.classList.add('toLeft');
}
}
/**
* Do jump mario character
*/
doJumpMario() {
clearTimeout(MARIO_JUMP_TIMEOUT);
window.marioCharacter_RAF_Paused = true;
this.updateMarioChar('jump');
const marioHolder = document.getElementById('marioCharacterHolder') || null;
const styleMarioChar = window.getComputedStyle(marioHolder),
bottomSpaceMario = parseInt(styleMarioChar.getPropertyValue('bottom'));
const checkHitToScore = this.checkHitMario('.scoreBar', false, true);
if (checkHitToScore.result) {
console.log('HIIIIIT :: ', checkHitToScore);
marioHolder.style.bottom = `${bottomSpaceMario + (checkHitToScore.bottom - 170)}px`;
this.playSound('bump');
} else {
this.playSound('jump');
marioHolder.style.bottom = `${bottomSpaceMario + 110}px`;
}
MARIO_JUMP_TIMEOUT = setTimeout(() => {
const checkScoreBarHit = this.checkHitMario('.scoreBar', false);
const checkGroundHit = this.checkHitMario('.groundHolder > div', false);
if (checkScoreBarHit.result) {
marioHolder.style.bottom = `${checkScoreBarHit.top + 1}px`;
} else if (checkGroundHit.result) {
marioHolder.style.bottom = `${checkGroundHit.top + 1}px`;
} else {
marioHolder.style.bottom = '85px';
}
setTimeout(() => this.updateMarioChar('stand'), 300);
}, 400);
}
/**
* Timeout for mario walking animation
*/
waitTillWalking() {
MARIO_WALK_TIMEOUT = setTimeout(() => {
const now = new Date().getTime();
if ((now - MARIO_WALK_TIMER) >= 400 && MARIO_WALK_TIMER !== 0) {
window.marioCharacter_RAF_Paused = true;
this.updateMarioChar('stand');
}
}, 400);
}
/**
* Do walk mario character
*/
doWalkMario() {
const marioHolder = document.getElementById('marioCharacterHolder') || null;
window.marioCharacter_RAF_Paused = false;
MARIO_WALK_TIMER = new Date().getTime();
clearTimeout(MARIO_WALK_TIMEOUT);
if (marioHolder) {
const fromLeft = marioHolder.offsetLeft;
let walkSize = 8;
if (MARIO_DIRECTION === 'Right') {
if (this.checkHitMario('.groundHolder .wellRight', true).result) {
walkSize = 0;
}
const newSpaceLeft = fromLeft + walkSize;
const maxSpaceLeft = window.innerWidth - 52;
marioHolder.style.left = `${newSpaceLeft > maxSpaceLeft ? maxSpaceLeft : newSpaceLeft}px`;
} else {
if (this.checkHitMario('.groundHolder .wellLeft', true).result) {
walkSize = 0;
}
const newSpaceLeft = parseInt(fromLeft) - walkSize;
marioHolder.style.left = `${newSpaceLeft > 0 ? newSpaceLeft : 0}px`;
}
this.checkMarioFallDown();
}
this.waitTillWalking();
}
/**
* Build keypress events
*/
addKeypressEvents() {
/**
* Manage key press
*/
document.removeEventListener('keydown', () => {
});
document.addEventListener('keydown', e => {
if (e.keyCode === 37 || e.key === 'ArrowLeft') {
e.preventDefault();
this.turnMarioDirection('Left');
this.doWalkMario();
} else if (e.keyCode === 39 || e.key === 'ArrowRight') {
e.preventDefault();
this.turnMarioDirection('Right');
this.doWalkMario();
} else if (e.keyCode === 32 || e.key === 'Space') {
e.preventDefault();
this.doJumpMario();
} else if (e.keyCode === 40 || e.key === 'Down') {
e.preventDefault();
clearTimeout(MARIO_SEAT_TIMEOUT);
this.updateMarioChar('seat');
MARIO_SEAT_TIMEOUT = setTimeout(() => this.updateMarioChar('stand'), 300);
}
}, false);
/**
* Game control btn click
*/
document.querySelector('.gameSettingsBtn').addEventListener('click', () => {
const menu = document.getElementById('gameSettingMenu');
const isBlock = (menu.getAttribute('data-display') || '') === 'block';
const newDisplay = (isBlock ? 'none' : 'block');
menu.style.display = newDisplay;
menu.setAttribute('data-display', newDisplay);
const liElements = Array.from(menu.querySelectorAll('li'));
liElements.map(li => {
li.addEventListener('click', () => {
const id = li.getAttribute('data-id');
switch (id) {
case 'backgroundMusicControl':
if (Cookies.get('backgroundMusicControl') !== '1') {
li.querySelector('span').classList.add('active');
Cookies.set('backgroundMusicControl', '1');
this.playSound('background');
} else {
li.querySelector('span').classList.remove('active');
Cookies.set('backgroundMusicControl', '0');
this.pauseSound('background');
}
break;
case 'soundEffectControl':
this.pauseSound('jump');
break;
}
});
});
});
}
render() {
return (
<React.Fragment>
<GameSounds />
<div className={'marioTek_container blueGamePlay'}>
<TopWavesSvg />
<div className={'cloudsHolder'}/>
<div className={'scoreBar'}>
<div className={'scoreCustom'} data-letter={'S'}>
<canvas id='scoreCustom_s'/>
</div>
<div className={'scoreCustom'} data-letter={'J'}>
<canvas id='scoreCustom_j'/>
</div>
<div className={'scoreBrick sc_Br1'}/>
<div className={'scoreBrick sc_Br2'}/>
<div className={'scoreBrick sc_Br3'}/>
<div className={'scoreBrick sc_Br4'}/>
<div className={'scoreQuestion'}>
<canvas id={'scoreQuestion'}/>
</div>
</div>
<div id='marioCharacterHolder' className={`marioCharacter to${MARIO_DIRECTION}`}>
<canvas id='marioCharacter'/>
</div>
<div className={'groundHolder'}>
<i className={'fa fa-cog gameSettingsBtn'}/>
<div id={'gameSettingMenu'} style={{ display: 'none' }}>
<ul>
<li data-id={'backgroundMusicControl'}>
<i className={'fa fa-music ml5'}/> آهنگ پس زمینه
<span className={Cookies.get('backgroundMusicControl') === '1' ? 'active' : ''}/>
</li>
<li data-id={'soundEffectControl'}>
<i className={'fa fa-microphone ml5'}/> افکت صوتی
<span className={Cookies.get('soundEffectControl') === '1' ? 'active' : ''}/>
</li>
</ul>
</div>
<div className={'wellRight'}/>
<div className={'wellLeft'}/>
</div>
<canvas id='PoisonousFlower'/>
</div>
</React.Fragment>
);
}
}
export default SuperMarioGame;
|
/**
* @param {string[]} A
* @return {number}
*/
var minDeletionSize = function(A) {
var ans = 0;
for (var i = 0; i<A[0].length; i++) {
for(var j = 0; j<A.length-1; j++) {
if(A[j].charCodeAt(i) > A[j+1].charCodeAt(i)) {
ans++;
break;
}
}
}
return ans;
};
console.log(minDeletionSize(["cba","daf","ghi"]));
|
'use strict'
const auth = require('./auth');
const error = require('./error');
const Promise = require('promise');
const queryString = require('querystring');
/**
* 사용자의 전체 repository 또는 하나의 repository 정보 가져온다.
* @ params
* @ {Object} authInfo : github 인증 정보
* @ {String} userName : 사용자 이름
* @ {String} password : 비밀번호
* @ {String} [repsId] : 찾을 repository의 ID (undefined인 경우 사용자의 전체 repository를 가져옴)
* @ return
* @ {Array} repositories : repository 또는 사용자의 전체 repository 정보
* @ error
* @ {Object} err : 인증 실패 또는 정보가 없음 또는 잘못된 요청 정보
**/
exports.getRepository = function(authInfo, repsId){
return new Promise((resolve, reject) => {
try{
let github = auth.auth(authInfo);
repsId ? github.repos.getById({
id: repsId
}, (err, res) => {
if(err){
err = error.errorCtl(err);
switch(err.code){
case 'E102':
err.repsId = repsId;
break;
}
reject(err);
}else{
resolve(res);
}
}) : github.repos.getForUser({
user: authInfo.userName
}, (err, res) => {
err ? reject(error.error.errorCtl(err)) : resolve(res);
});
}catch(err){
reject(err);
}
});
};
/**
* 사용자 또는 사용자가 참여한 repository 정보를 가져온다.
* @ params
* @ {Object} authInfo : github 인증 정보
* @ {String} userName : 사용자 이름
* @ {String} password : 비밀번호
* @ return
* @ {Array} repositories : 사용자 또는 사용자가 참여한 전체 repository 정보
* @ error
* @ {Object} err : 인증 실패 또는 정보가 없음 또는 잘못된 요청 정보
**/
exports.getRepositoryAll = function(authInfo){
return new Promise((resolve, reject) => {
try{
let github = auth.auth(authInfo);
github.repos.getAll({}, (err, res) => {
err ? reject(error.errorCtl(err)) : resolve(res);
});
}catch(err){
reject(err);
}
});
};
/**
* 해당 repository의 전체 branch 정보를 가져온다.
* @ params
* @ {Object} authInfo : github 인증 정보
* @ {String} userName : 사용자 이름
* @ {String} password : 비밀번호
* @ {Object} option : api parameter data
* @ {String} user : repository 소유자 이름
* @ {String} repo : repository 이름
* @ {String} branch : branch 이름
* @ return
* @ {Array} branches : branch 목록 정보
* @ error
* @ {Object} err : 인증 실패 또는 정보가 없음 또는 잘못된 요청 정보
**/
exports.getBranch = function(authInfo, option){
return new Promise((resolve, reject) => {
try{
let github = auth.auth(authInfo);
option.branch ? github.repos.getBranch(option, (err, res) => {
if(err){
err = error.errorCtl(err);
switch(err.code){
case 'E102':
err.option = option;
break;
}
reject(err);
}else{
resolve(res);
}
}) : github.repos.getBranches(option, (err, res) => {
if(err){
err = error.errorCtl(err);
switch(err.code){
case 'E102':
err.option = option;
break;
}
reject(err);
}else{
resolve(res);
}
});
}catch(err){
reject(err);
}
});
};
/**
* repository의 commit 목록 또는 commit 정보를 가져온다.
* @ params
* @ {Object} authInfo : github 인증 정보
* @ {String} userName : 사용자 이름
* @ {String} password : 비밀번호
* @ {Object} option : api parameter data
* @ {String} user : repository 소유자 이름
* @ {String} repo : repository 이름
* @ {String} [sha] : branch 이름
* @ {Number} [page] : page 번호
* @ {Number} [per_page] : 한 페이지의 commit 개수 (최대 100, 기본값 30)
* @ return
* @ {Array} commits
* @ {Object} commit
**/
exports.getCommit = function(authInfo, option){
return new Promise((resolve, reject) => {
try{
let github = auth.auth(authInfo);
if(option.sha){
github.repos.getCommit(option, (err, res) => {
if(err){
err = error.errorCtl(err);
switch(err.code){
case 'E102':
err.option = option;
break;
}
reject(err);
}else{
resolve(res);
}
})
}else{
let commits = new Array();
(function getCommits(option){
github.repos.getCommits(option, (err, res) => {
if(err){
err = error.errorCtl(err);
switch(err.code){
case 'E102':
err.option = option;
break;
}
reject(err);
}else{
res.forEach((commit) => {
commits.push(commit);
});
if(res.meta && res.meta.link){
let link = res.meta.link.split(',').shift();
let parsedlink = new Object();
let temp = link.trim().replace(/<|>|;|\"/g, '').replace(/\ /, '&');
let parsedData = queryString.parse(temp.split('?').pop());
parsedlink.isNext = parsedData.rel == 'first' ? false : true;
parsedlink.page = parsedData.page;
if(parsedlink.isNext){
option.page = parsedlink.page;
getCommits(option);
}else{
resolve(commits);
}
}else{
resolve(commits);
}
}
});
})(option);
}
}catch(err){
reject(err);
}
});
};
/**
* repository의 collaborator들의 정보를 가져온다
* @ params
* @ {Object} authInfo : github 인증 정보
* @ {String} userName : 사용자 이름
* @ {String} password : 비밀번호
* @ {Object} option : api parameter data
* @ {String} user : repository 소유자 이름
* @ {String} repo : repository 이름
**/
exports.getCollaborators = function(authInfo, option){
return new Promise((resolve, reject) => {
try{
let github = auth.auth(authInfo);
github.repos.getCollaborators(option, (err, res) => {
if(err){
err = error.errorCtl(err);
switch(err.code){
case 'E102':
err.option = option;
break;
}
reject(err);
}else{
resolve(res);
}
});
}catch(err){
reject(err);
}
});
};
|
import React from 'react';
import PropTypes from 'prop-types';
import {Redirect} from 'react-router-dom';
import {JobForYouWrapper} from './wrapper';
import {CollectionCard} from './component/collectionCard';
// import {TagSidebar} from '../../component/tag';
import {languageHelper} from '../../tool/language-helper';
import {removeUrlSlashSuffix} from '../../tool/remove-url-slash-suffix';
import {MDBRow} from 'mdbreact';
import classes from './index.module.css';
import {getAsync, isLogin} from '../../tool/api-helper';
class JobForYouReact extends React.Component {
constructor(props) {
super(props);
// state
this.state = {
collectionNum: 0,
collectionType: 'company'
};
// i18n
this.text = JobForYouReact.i18n[languageHelper()];
}
async componentDidMount() {
if(isLogin()){
try {
const result = await getAsync(`/users/${localStorage.getItem('id')}/attentions?type=${this.state.collectionType}`);
if (result && result.status && result.status.code === 2000) {
this.setState(() => {
return {collectionNum: result.content.company.item_count};
});
} else {
this.setState(() => {
return {collectionNum: 0};
});
}
} catch (error) {
// eslint-disable-next-line
console.log(error);
}
}
}
render() {
const pathname = removeUrlSlashSuffix(this.props.location.pathname);
if (pathname) {
return (<Redirect to={pathname} />);
}
if (!isLogin()) {
return (<Redirect to={`/login?to=${this.props.location.pathname}`} />);
}
return (
<div>
<div
className="cell-wall"
style={{backgroundColor: '#F3F5F7'}}
>
<div
className="cell-membrane"
>
<MDBRow style={{marginTop: '2vw'}}>
<main className={classes.mainBody}>
{/*<FilterRow number={25} />*/}
<JobForYouWrapper />
</main>
<aside className={classes.sidebar}>
<CollectionCard number={this.state.collectionNum} url={'job'} collectionType={'职位'}/>
{/*<TagSidebar tags={['面试经历', '删库经历', '跑路经历']} />*/}
</aside>
</MDBRow>
</div>
</div>
</div>
);
}
}
JobForYouReact.i18n = [
{},
{}
];
JobForYouReact.propTypes = {
// self
// React Router
match: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
location: PropTypes.object.isRequired
};
export const JobForYou = JobForYouReact;
|
export const GET_ALL_CATEGORY = 'GET_ALL_CATEGORY';
export const INSERT_CATEGORY = 'INSERT_CATEGORY';
export const GET_ALL_PRODUCT = 'GET_ALL_PRODUCT';
export const INSERT_PRODUCT = 'INSERT_PRODUCT';
|
import React from "react";
import "./PrimaryButton.css";
const PrimaryButton = ({ classList, text, onClick, active, bgBlue }) => {
return (
<div
className={`button_primary paragraph__text border-sm bg-white flex-fill d-flex justify-content-center align-items-center font-weight-bold text-decoration-none ${
classList ? classList : ""
} ${active ? "color_primary" : ""} ${bgBlue ? "bgBlue" : ""}`}
onClick={onClick && onClick}
>
{text && text}
</div>
);
};
export default PrimaryButton;
|
import React from 'react';
import axios from 'axios';
import { Image, Segment, List, Item, Grid } from 'semantic-ui-react';
import { connect } from 'react-redux';
import { listPlayer, changeActive } from '../actions';
import Stats from './Stats';
import CareerStats from './CareerStats';
import MLBMenu from './Menu';
import './Player.css';
class Player extends React.Component {
state = {
player: {},
position: '',
splits: [],
stat: {},
recentYear: 0,
aggStatInfo: {}
}
componentDidMount() {
let selectedPlayerId = localStorage.getItem("selectedPlayer");
axios.get(`https://statsapi.mlb.com/api/v1/people/${selectedPlayerId}?hydrate=stats(group=[hitting,pitching,fielding],type=[yearByYear])`)
.then((res) => {
this.props.listPlayer(res.data.people[0]);
return res.data.people[0];
})
.then((player) => {
this.setState({position: player.primaryPosition.name});
return this.getRecentSplit(player);
})
.then((splits) => {
this.setState({splits: splits});
this.setState({stat: splits[splits.length - 1].stat});
this.setState({recentYear: splits[splits.length - 1].season});
return this.aggregateData(splits);
})
.then((aggInfo) => {
this.setState({aggStatInfo: aggInfo});
})
.catch((err) => {
console.log(err);
});
};
componentDidUpdate() {
window.onpopstate = (e) => {
this.props.changeActive('roster');
this.props.history.push('/roster');
};
};
aggregateData = (splits) => {
let position = this.props.player.primaryPosition.name;
if (position === "Pitcher") {
let wins = 0, losses = 0, era = 0, gamesPlayed = 0, gamesStarted = 0, saves = 0, inningsPitched = 0, strikeOuts = 0, whip = 0;
for (let i = 0; i < splits.length; i++) {
wins += splits[i].stat.wins;
losses += splits[i].stat.losses;
era += splits[i].stat.era/splits.length;
gamesPlayed += splits[i].stat.gamesPlayed;
gamesStarted += splits[i].stat.gamesStarted;
saves += splits[i].stat.saves;
inningsPitched += parseFloat(splits[i].stat.inningsPitched);
strikeOuts += splits[i].stat.strikeOuts;
whip += parseFloat(splits[i].stat.whip)/splits.length;
}
return {
wins: wins,
losses: losses,
era: era.toFixed(2),
gamesPlayed: gamesPlayed,
gamesStarted: gamesStarted,
saves: saves,
inningsPitched: inningsPitched.toFixed(1),
strikeOuts: strikeOuts,
whip: whip.toFixed(2)
};
}
else {
let ab = 0, r = 0, h = 0, hr = 0, rbi = 0, sb = 0, avg = 0, obp = 0, ops = 0;
for (let i = 0; i < splits.length; i++) {
ab += splits[i].stat.atBats;
r += splits[i].stat.runs;
h += splits[i].stat.hits;
hr += splits[i].stat.homeRuns;
rbi += splits[i].stat.rbi;
sb += splits[i].stat.stolenBases;
avg += parseFloat(splits[i].stat.avg)/splits.length;
obp += parseFloat(splits[i].stat.obp)/splits.length;
ops += parseFloat(splits[i].stat.ops)/splits.length;
}
return {
atBats: ab,
runs: r,
hits: h,
homeRuns: hr,
rbi: rbi,
stolenBases: sb,
avg: avg.toFixed(3).toString().replace(/^0+/, ''),
obp: obp.toFixed(3).toString().replace(/^0+/, ''),
ops: ops.toFixed(3).toString().replace(/^0+/, '')
};
}
};
getRecentSplit = (player) => {
let index = 0;
for (let i = 0; i < player.stats.length; i++) {
if (player.primaryPosition.name !== "Pitcher" && player.stats[i].group.displayName === "hitting") {
index = i;
}
else if (player.primaryPosition.name === "Pitcher" && player.stats[i].group.displayName === "pitching") {
index = i;
}
}
return player.stats[index].splits;
};
render() {
const { stat, recentYear, aggStatInfo, position } = this.state;
const { player } = this.props;
return (
<div>
<MLBMenu/>
<Segment style={{height: "100%"}}>
<Grid>
<Grid.Column width={11}>
<div>
<List horizontal>
<List.Item><h1 className="highlight">{player.primaryNumber}</h1></List.Item>
<List.Item><h1>{player.fullName}</h1></List.Item>
</List>
</div>
<Image
src={`https://securea.mlb.com/mlb/images/players/head_shot/${player.id}.jpg`}
alt={player.fullName}
bordered
style={{
float:"left",
marginRight: "30px",
marginBottom: "30px"
}}
/>
<Item>
<Item.Content>
<Item.Header as="h2">{player.firstName} {player.middleName} {player.lastName}</Item.Header>
<Item.Description><strong>Nickname: </strong>{player.nickName}</Item.Description>
<Item.Description><strong>Born: </strong>{player.birthDate}</Item.Description>
<Item.Description><strong>Birth Location: </strong>{player.birthCity} {player.birthStateProvince}, {player.birthCountry}</Item.Description>
<Item.Description><strong>Draft Year: </strong>{player.draftYear} </Item.Description>
<Item.Description><strong>Debut: </strong>{player.mlbDebutDate} </Item.Description>
</Item.Content>
</Item>
<Stats
position={position}
stat={stat}
recentYear={recentYear}
aggStatInfo={aggStatInfo}
/>
</Grid.Column>
</Grid>
<CareerStats splits={this.state.splits} position={position}/>
</Segment>
</div>
);
};
};
const mapStateToProps = (state) => {
return { player: state.player };
};
export default connect(mapStateToProps, {
listPlayer: listPlayer,
changeActive: changeActive
}) (Player);
|
import React, { Fragment, useContext } from 'react';
import { Link, withRouter } from 'react-router-dom';
import axios from 'axios';
import { AppContext } from '../../context/appContext';
import { ApiAuthentication } from '../../api/auth';
import { StyledDropDownButton, StyledDropDownMenu } from './styles';
import { defaultPhoto100 } from '../../constants/defaultPhotos';
const DropDownMenu = ({ showMenu, show, history }) => {
const [auth, setAuth] = useContext(AppContext);
const { photo100 } = auth;
const logout = () => {
ApiAuthentication(
axios,
'get',
'/api/logout',
null,
auth,
setAuth,
null
);
return history.push('/');
};
return (
<Fragment>
<StyledDropDownButton type="button" onClick={showMenu}>
<img
src={photo100 || defaultPhoto100}
alt="profile"
width="50px"
/>
<h5>{auth.email}</h5>
<img
src="https://woojoo.s3-us-west-1.amazonaws.com/down.png"
alt="down"
/>
</StyledDropDownButton>
{show && (
<StyledDropDownMenu>
<Link to="/post">Sell on WJM</Link>
<Link to="/profile">My Profile</Link>
<Link to="/like">My Likes</Link>
<Link to="/cart">My Cart</Link>
<Link to="/order">My Orders</Link>
<Link to="/sale">My Sales</Link>
<Link to="/settings">Account Settings</Link>
<button type="button" onClick={logout}>
Logout
</button>
</StyledDropDownMenu>
)}
</Fragment>
);
};
export default withRouter(DropDownMenu);
|
//引入 CountUI组件
import CountUI from '../../components/Count'
//引入 connect 用于连接UI组件与redux
import { connect } from 'react-redux'
//引入CountAction
import {
createIncrementAction,
createDecrementAction,
createIncrementAsyncAction
} from '../../redux/count_action'
//使用 connect()()创建并暴露一个 Count 的容器组件
export default connect(
//mapStateToProps映射状态
state => ({ count: state }),
//mapDispatchToProps映射操作状态的方法,react-redux自动dispatch
{
increment:createIncrementAction,
decrement:createDecrementAction,
incrementAsync:createIncrementAsyncAction
}
)(CountUI)
|
var path = require('path');
module.exports = {
/**
* 模块化加载框架 [requirejs|modjs|seajs]
* 为null时,每个js文件用script标签引入
* e.g.
* <script src="/widget/a/a.js"></script>
* <script src="/widget/b/b.js"></script>
* 为requirejs|modjs|seajs时
* e.g.
* require(["/widget/a/a.js", "/widget/b/b.js"]);
* 或者
* seajs.use(["/widget/a/a.js", "/widget/b/b.js"]);
*/
loader: null,
/**
* 是否进行同步加载,默认为false,loader设置不为null时生效
* 因为allInOne打包时会被忽略异步依赖,所以使用allInOne时需要开启同步依赖
*/
loadSync: false,
// 全局macro文件,相对于root
macro: '/page/macro.vm',
// 是否编译内容,默认为true,为false时不编译velocity语法,只引用资源依赖
parse: false,
// 全局的mock文件,相对于root,默认为null
commonMock: null,
// velocity的root配置,默认为项目根目录
root: [path.resolve('.')],
// left_delimiter规则左边界
left_delimiter: '{',
// right_delimiter
right_delimiter: '}'
};
|
import React,{useState, useEffect} from 'react';
import "../Dashboard.css";
import "../Browse.css";
import 'react-activity-feed/dist/index.css';
import {Container, Col, Row, ListGroup,Nav, Navbar,Form , FormControl, Button} from 'react-bootstrap';
import axios from 'axios';
import logo from "./images/freelancerlogo.png";
import {
Link
} from "react-router-dom";
function Browseprojects(props) {
const [state, setState] = useState({
projects: [], areProjects:"false",
value:""
});
useEffect(()=>{
if (localStorage.getItem("token")) {
axios
.get("http://FreelancerLaravel.test/api/postaprojectall", {
headers: {
Authorization: "Bearer " + localStorage.getItem("token")
}
})
.then(response => {
setState({...state,
projects: response.data.map((project) => {
return {name:project.name,description:project.description, budget:project.budget,skills:project.skills,type:project.payment,id:project.id}
}),areProjects:true
});
})
.catch(() => {
});
} else {
}
//
},[]);
return (
<div>
<Navbar collapseOnSelect expand="lg" fluid>
<Navbar.Brand href="./">
<img
alt=""
src={logo}
width="140"
height="40"
className="d-inline-block align-top"
/>
</Navbar.Brand>
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
<Navbar.Collapse id="responsive-navbar-nav">
<Nav className="mr-auto">
<Nav.Link href="/dashboard">Dashboard</Nav.Link>
<Nav.Link href="#pricing">Inbox</Nav.Link>
</Nav>
<Nav>
<Form inline>
<FormControl type="text" placeholder="Search" className="mr-sm-3" />
<Button variant="primary">Search</Button>
</Form>
</Nav>
</Navbar.Collapse>
</Navbar>
<br/>
<Container>
<Row>
<Col className="col1" sm={4}>
<br/>
<Container className="container12">
<h1>Project Type</h1><hr/>
<input type="radio" id="male" name="gender" value="hourly" onChange={e => {
setState({...state,
value: e.target.value
});
}}/>
<label for="hourly"> Hourly</label><br/>
<input type="radio" id="female" name="gender" value="fixed" onChange={e => {
setState({...state,
value: e.target.value
});
}}/>
<label for="fixed"> Fixed</label><br/>
<input type="radio" id="other" name="gender" value="" onChange={e => {
setState({...state,
value: e.target.value
});
}}/>
<label for="allprojects"> Show all projects</label>
</Container><br/>
<Container className="container12">
<h1>Skills</h1><hr/>
<p className="skillset">
CSS, html, Javascript, Node Js, React Js, Wordpress, Photoshop, Illustrator, Sketch, shopify, Python, Excel. word, Joomla, Go Daddy, Java, C++
</p><br/>
</Container><br/>
<Container className="container12">
<h1>Languages</h1><hr/>
<p>English</p><hr/>
<p>French</p><hr/>
<p>Arabic</p>
</Container><br/>
</Col>
<Col className="cols" sm={8} ><br/><h4 className="projectheader">Projects<hr/></h4>
<Container className="col2" sm={8} >
{state.projects.map((item, index)=>{
return item.type==state.value?( <> <br/><Container className="cont1 " ><h4 className="budget text-muted"> ${item.budget}-{item.budget * 2}</h4><p>{item.name }<hr/></p>
<p>{ item.description}</p> <p className="bids">Bids:</p> <Link to={{ pathname:'/bid',state:{desc:item.description,skills:item.skills,budget:item.budget,id:item.id}}}><Button className="bidnow"disabled={props.role==="Employer"}>Bid Now</Button></Link><p className="skills">{item.skills}</p><br/><br/> </Container> <br/></>
):state.value==""? ( <> <br/> <Container className="cont1 " ><h4 className="budget text-muted"> ${item.budget}-{item.budget*2}</h4><p>{item.name }<hr/></p>
<p>{ item.description}</p> <p className="bids">Bids:</p> <Link disabled={props.role==="Employer"} to={{ pathname:'/bid',state:{desc:item.description,skills:item.skills,budget:item.budget,id:item.id}}}><Button className="bidnow" disabled={props.role==="Employer"}>Bid Now</Button></Link><p className="skills">{item.skills}</p><br/><br/> </Container></>):null
})}
</Container>
</Col>
</Row>
</Container>
</div>
);
}
export default Browseprojects;
|
let contextDelimiter = "::";
const responseTypes = {
message(p_sText) {
return {
"message": {
"text": p_sText
}
}
},
quickReply(title, payload, image_url) {
const reply = {
"content_type": "text",
title,
payload
}
if (image_url)
reply.image_url = image_url
return reply;
},
quickReplyGroup(title, replies, context) {
if (context) {
replies.forEach(reply => reply.payload += (contextDelimiter + context))
}
return {
"message": {
"text": title,
"quick_replies": replies
}
}
},
button(title, url, ratio) {
return {
"type": "web_url",
url,
title,
"webview_height_ratio": ratio || "full"
}
},
buttonGroup(title, buttons) {
return {
"message": {
"attachment": {
"type": "template",
"payload": {
"template_type": "button",
"text": title,
buttons
}
}
}
}
}
}
module.exports = {
getContextDelimiter() {
return contextDelimiter
},
setContextDelimiter(p_sDelimiter) {
contextDelimiter = p_sDelimiter;
},
responseTypes
};
|
(function ($) {
Drupal.behaviors.cr_donate_currency_buttons = {
attach: function(context) {
var $currency_buttons = $('img.currency-item');
var $select = $('#edit-currency');
// these vars are used for manually updated the dropkick select widget that
// does not update automatically in response to programmatic updates to
// its selectbox source
var currency_selectbox_values = [];
var $currency_selectbox_options = $('option', $select);
$currency_selectbox_options.each(function() {
currency_selectbox_values[this.value] = this.text;
});
$currency_buttons.on('click', context, function() {
var currency_clicked = this.id.toUpperCase();
$select.val(currency_clicked);
// Due to using dropdick select boxes we now have to add a little hack
// to update its value as it does not respond to programmatic changes
// we have to define the following vars in the click handler as we can't
// guarantee they have made it into the DOM at the time this behaviour
// is attached
var $dropkick_container = $('#dk_container_' + $select[0].id);
var $dk_label = $('.dk_label', $dropkick_container);
$dk_label.text(currency_selectbox_values[currency_clicked]);
});
}
}
})(jQuery);
|
import { Box, Grid, makeStyles } from "@material-ui/core";
import React from "react";
const usestyles = makeStyles({
card: {
backgroundColor: "#fff",
},
dFlex: {
display: "flex",
justifyContent: "center",
marginTop: 68,
},
name: {
fontWeight: 700,
fontSize: 22,
fontFamily: "Circular-Loom",
color: "#000000",
},
description: {
fontWeight: 400,
fontSize: 14,
fontFamily: "Circular-Loom",
color: "#000000",
width: "94%",
lineHeight: "29px",
marginTop: 10,
},
});
export const Cards = ({ image, name, description }) => {
const classes = usestyles();
return (
<Grid item xs={12} md={4} lg={4}>
<Box className={classes.card}>
<Grid className={classes.dFlex}>
{<img style={{ marginTop: 18 }} src={image} />}
</Grid>
<Grid style={{ padding: 32 }}>
<Grid className={classes.name}>{name}</Grid>
<Grid className={classes.description}>{description}</Grid>
</Grid>
</Box>
</Grid>
);
};
|
const Sequelize = require('sequelize');
module.exports = function(sequelize, DataTypes) {
return sequelize.define('SalesOrderStatusLabel', {
status: {
type: DataTypes.STRING(32),
allowNull: false,
primaryKey: true,
comment: "Status",
references: {
model: 'sales_order_status',
key: 'status'
}
},
store_id: {
type: DataTypes.SMALLINT.UNSIGNED,
allowNull: false,
primaryKey: true,
comment: "Store ID",
references: {
model: 'store',
key: 'store_id'
}
},
label: {
type: DataTypes.STRING(128),
allowNull: false,
comment: "Label"
}
}, {
sequelize,
tableName: 'sales_order_status_label',
timestamps: false,
indexes: [
{
name: "PRIMARY",
unique: true,
using: "BTREE",
fields: [
{ name: "status" },
{ name: "store_id" },
]
},
{
name: "SALES_ORDER_STATUS_LABEL_STORE_ID",
using: "BTREE",
fields: [
{ name: "store_id" },
]
},
]
});
};
|
const functions = require('firebase-functions')
const admin = require('firebase-admin')
try { admin.initializeApp() } catch (e) { console.log(e) }
const nodemailer = require('nodemailer')
const gmailEmail = encodeURIComponent(functions.config().gmail ? functions.config().gmail.email : '')
const gmailPassword = encodeURIComponent(functions.config().gmail ? functions.config().gmail.password : '')
const mailTransport = nodemailer.createTransport(`smtps://${gmailEmail}:${gmailPassword}@smtp.gmail.com`)
exports = module.exports = functions.auth.user().onDelete((userMetadata, context) => {
const uid = userMetadata.uid
const email = userMetadata.email
const displayName = userMetadata.displayName
console.log(userMetadata.providerData)
console.log(userMetadata)
console.log(context)
const provider = userMetadata.providerData.length ? userMetadata.providerData[0] : { providerId: email ? 'password' : 'phone' }
const providerId = provider.providerId ? provider.providerId.replace('.com', '') : provider.providerId
let promises = []
const mailOptions = {
from: `"Promania" <${gmailEmail}>`,
to: email,
subject: `We will miss you 😭`,
text: `Hi ${displayName || ''}!, We are sad to confirm that we have deleted your Promania account.`
}
const sendEmail = mailTransport.sendMail(mailOptions).then(() => {
console.log('Account deletion confirmation email sent to:', email)
return null
})
const deleteUser = admin.database().ref(`/users/${uid}`).set(null)
const deleteTokens = admin.database().ref(`/notification_tokens/${uid}`).set(null)
const deleteChats = admin.database().ref(`/users_chats/${uid}`).set(null)
const usersCount = admin.database()
.ref(`/users_count`)
.transaction(current => (current || 0) - 1)
if (providerId) {
promises.push(
admin.database()
.ref(`/provider_count/${providerId}`)
.transaction(current => (current || 0) - 1)
)
}
promises.push(sendEmail, deleteUser, usersCount, deleteTokens, deleteChats)
return Promise.all(promises)
})
|
import React, { useEffect, useState } from "react";
import Todo from "./Todo";
import TodoForm from "./TodoForm";
const LOCAL_STORAGE_KEY = "todoApp.todos";
export default function TodoList() {
const [todos, setTodos] = useState([]);
//READ todo from localStorage
useEffect(() => {
const storedTodos = JSON.parse(localStorage.getItem(LOCAL_STORAGE_KEY));
if (storedTodos) setTodos(storedTodos);
}, []);
//store to localStorage
useEffect(() => {
localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(todos));
}, [todos]);
//CREATE todo
const addTodo = (todo) => {
// if empty or contains white spaces
if (!todo.text || /^\s*$/.test(todo.text)) {
return;
}
const newTodos = [...todos, todo];
setTodos(newTodos);
};
//EDIT todo
const editTodo = (id, newValue) => {
if (!newValue.text || /^\s*$/.test(newValue.text)) {
return;
}
setTodos((prev) => prev.map((item) => (item.id === id ? newValue : item)));
};
//complete todo
const completeTodo = (id) => {
let updatedTodos = todos.map((todo) => {
if (todo.id === id) {
todo.isComplete = !todo.isComplete;
}
return todo;
});
setTodos(updatedTodos);
};
//DELETE todo
const deleteTodo = (id) => {
const removedTodo = [...todos].filter((todo) => todo.id !== id);
setTodos(removedTodo);
};
return (
<div className="todo-container">
<h1>What's the Plan for Today?</h1>
<TodoForm onSubmit={addTodo} />
<Todo
todos={todos}
editTodo={editTodo}
completeTodo={completeTodo}
deleteTodo={deleteTodo}
/>
</div>
);
}
|
export default {
thisBaseOn: '这是基于',
baseOnL18n: '该项目的国际化基于',
baseOn: '是根据',
documentation: '文献资料',
palette: '您可以在上生成调色板',
theme: '选择配色方案:',
dropHere: '将文件拖放到此处进行上传',
tinymceTips: '在线富文本编辑器作为LGPL下的开源软件发布。',
imageUploadTips: '改性。 如果要使用它,最好使用正式版本。',
dropzoneTips: '',
stickyTips: '当页面滚动到预设位置时,将在顶部粘贴。',
backToTop: '当页面滚动到指定位置时,“返回顶部”按钮将显示在右下角',
draggable: '允许您在其中拖动面板和项目'
};
|
function notify(data) {
Materialize.toast(data.message, 4000, '', function() {
if (data.refresh) {
window.location.reload();
}
});
}
|
import { Router } from 'express';
import PageController from '../controllers/IndexController';
const controller = new PageController();
const router = Router();
router.get('/', controller.index.bind(controller));
router.get('/ping', controller.ping.bind(controller));
export default router;
|
import React, {Component} from 'react';
import {
View,
Image,
SafeAreaView
} from 'react-native';
import styles from './styles'
import {compose} from "redux";
import {connect} from 'react-redux'
import {Text, Button, Icon, Form, Item, Label, Input, Container,Content} from "native-base";
import {SYSTEM_ROUTES} from "../../constants";
import { change, Field, reduxForm } from 'redux-form'
import {TextField} from '../../components'
class LoginAuthScreen extends Component {
_renderTextField (field) {
const { meta: { touched, error }, input: { value, onChange }, nameIcon, label, ...custom } = field;
const errorInput = touched && error ? error : null;
return (
<View style={styles.viewInput}>
<Input value={value} onChangeText={onChange} placeholderTextColor="#9F9F9F" placeholder={label}/>
<Icon type="MaterialIcons" name={nameIcon} style={styles.iconInput}/>
</View>
)
}
render() {
const {navigation: {navigate}} = this.props;
return (
<Container>
<Content>
<View style={styles.container}>
<View style={styles.viewButtonRegister}>
<Button iconRight transparent style={styles.buttonRegister} onPress={() => navigate(SYSTEM_ROUTES.REGISTER_ACCOUNT_SCREEN.ROUTE)}>
<Text style={styles.textRegister}>Cadastrar</Text>
<Icon style={styles.iconRegister} type="MaterialIcons" name="chevron-right"/>
</Button>
</View>
<View style={styles.viewImage}>
<Image
style={styles.image}
source={require('../../../public/images/logo.png')}
resizeMode='contain'
/>
</View>
<Form style={styles.form}>
<Field
name="login"
label="Login"
component={this._renderTextField}
nameIcon="perm-identity"
/>
<Field
name="senha"
label="Senha"
component={this._renderTextField}
nameIcon="lock"
/>
</Form>
<View style={styles.viewButtonLogin}>
<Button transparent>
<Text style={styles.textForgotPassword}>Esqueceu sua senha?</Text>
</Button>
<Button
full
style={styles.buttonLogin}
onPress={() => navigate(SYSTEM_ROUTES.APP_BOTTOM_TAB_NAVIGATOR.ROUTE)}
>
<Text style={styles.textButtonLogin}>Entrar no aplicativo</Text>
</Button>
</View>
</View>
</Content>
</Container>
);
}
}
LoginAuthScreen = compose(
connect(null, {}),
reduxForm({
form: 'LoginAuthScreen',
enableReinitialize: true,
}),
)(LoginAuthScreen);
export {LoginAuthScreen}
|
var LB=1, //Left Bottom
LT=2, //Left Top
RT=3, //Right Top
RB=4, //Right Bottom
HR=1, //Horizontal
VR=2, //Vertical
WordObjType='span',
DIV='div',
Word_Default_font_Family='Impact',
distance_Counter=1,
word_counter=1;
function Util(){}
//To Generate Random Colors For Words
Util.getRandomColor = function(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.round(Math.random() * 15)];
}
return color;
};
function space(spaceType,width,height,x,y){
this.spaceType=spaceType;
this.width=width;
this.height=height;
this.x=x;
this.y=y;
}
function Word(wordConfig){
this.word=wordConfig.word;
this.weight=wordConfig.weight;
this.fontFactor=wordConfig.fontFactor;
this.fontOffset=wordConfig.fontOffset;
this.minWeight=wordConfig.minWeight;
this.padding_left=wordConfig.padding_left;
this.font_family=wordConfig.font_family;
this.font=null;
this.color=wordConfig.color;
this.span=null;
this.width=null;
this.height=null;
this.word_class=wordConfig.word_class;
this._init();
}
Word.prototype = {
_init: function(){
this._setFont();
this._setSpan_Size();
},
_setFont: function(){
this.font=Math.floor(((this.weight-this.minWeight) *this.fontFactor ) + this.fontOffset);
},
_setSpan_Size: function(){
var span = document.createElement(WordObjType);
span.setAttribute('id', "Word_"+(word_counter++)+"_"+this.weight);
document.body.appendChild(span);
$(span).css({
position: 'absolute',
display: 'block',
left: -999990,
top: 0
});
$(span).css("font-size",this.font+"px");
if(this.font_family!=null && this.font_family!='')
$(span).css("font-family",this.font_family);
else
$(span).css("font-family",Word_Default_font_Family);
if(this.word_class!=null && this.word_class!='')
$(span).addClass(this.word_class);
if(this.color!=null && this.color!='')
$(span).css("color",this.color);
else
$(span).css("color",Util.getRandomColor());
$(span).css("-webkit-user-select","none").css("-moz-user-select","none").css("-ms-user-select","none");
$(span).css("user-select","none").css("-o-user-select","none");
$(span).css("line-height",this.font+"px");
if(this.padding_left==null)
this.padding_left=0;
$(span).css("padding-left",this.padding_left+"px");
$(span).html(this.word);
this.width=$(span).outerWidth()+(this.padding_left*2);
this.height=$(span).outerHeight();
$(span).remove();
this.span=span;
}
};
function WordCloud() {
this.defaultOptions={
title: 'JQ WOrd Cloud',
words: [],
minFont: 10,
maxFont: 50,
fontOffset: 0,
showSpaceDIV: false,
verticalEnabled: true,
cloud_color: null,
cloud_font_family: null,
spaceDIVColor: 'white',
padding_left: null,
word_common_classes: null,
word_click : function(){},
word_mouseOver : function(){},
word_mouseEnter : function(){},
word_mouseOut : function(){},
beforeCloudRender: function(){},
afterCloudRender: function(){}
};
this.minWeight=null;
this.maxWeight=null;
this.spaceDataObject=null;
this.spaceIdArray=null;
this.words=null;
this.fontFactor=1,
this.methods = {
destroy : this._destroy
};
};
WordCloud.prototype = {
_init: function(options){
//Calling Methods from this.Methods{}
if(options !=null && typeof options === 'string')
if(this.methods[options]!=null)
return this.methods[options].apply();
else
return null;
if(options==null)
this.options=this.defaultOptions;
else if(options !=null && typeof options === 'object')
this.options=$.extend(this.defaultOptions,options);
this.spaceDataObject={};
this.spaceIdArray=[];
this.words=this.options.words;
//Sorting Words according weight descending order
this.words.sort(function(a, b) { if (a.weight < b.weight) {return 1;} else if (a.weight > b.weight) {return -1;} else {return 0;} });
this.options.beforeCloudRender();
this._start();
this.options.afterCloudRender();
this._final();
},
_setFontFactor: function(){
this.maxWeight=this.words[0].weight;
this.minWeight=this.words[this.words.length-1].weight;
this.fontFactor=(this.options.maxFont-this.options.minFont)/(this.maxWeight-this.minWeight);
},
_start: function(){
this._destroy();
this._setFontFactor();
this._draw();
},
_final: function() {
},
_destroy: function(){
this.$target.html('');
},
_setTarget: function($target){
this.$target=$target;
$target.css("position","relative");
this.tWidth=$target.innerWidth();
this.xOffset=this.tWidth/2;
this.tHeight=$target.innerHeight();
this.yOffset=this.tHeight/2;
},
_draw: function() {
for(var index=0; index<this.words.length; index++){
var currWord=this.words[index];
var wordConfigObj={};
wordConfigObj['word']=currWord.word;
wordConfigObj['weight']=currWord.weight;
if(this.options.cloud_color!=null)
wordConfigObj['color']=this.options.cloud_color;
else
wordConfigObj['color']=currWord.color;
if(this.options.padding_left!=null)
wordConfigObj['padding_left']=this.options.padding_left;
wordConfigObj['word_class']=currWord.word_class;
if(this.options.cloud_font_family!=null)
wordConfigObj['font_family']=this.options.cloud_font_family;
else
wordConfigObj['font_family']=currWord.font_family;
wordConfigObj['fontFactor']=this.fontFactor;
wordConfigObj['fontOffset']=(this.options.fontOffset + this.options.minFont);
wordConfigObj['minWeight']=this.minWeight;
var wordObj=new Word(wordConfigObj);
if(this.options.word_common_classes!=null)
$(wordObj.span).addClass(this.options.word_common_classes);
$(wordObj.span).on("click",this.options.word_click);
$(wordObj.span).on("mouseover",this.options.word_mouseOver);
$(wordObj.span).on("mouseout",this.options.word_mouseOut);
$(wordObj.span).on("mouseenter",this.options.word_mouseEnter);
if(index==0)
this._placeFirstWord(wordObj);
else
this._placeOtherWord(wordObj);
}
},
_updateSpaceIdArray: function(distanceS, distance) {
if(this.spaceIdArray.length!=0){
for(var index=0;index<this.spaceIdArray.length;index++){
if(distance<parseFloat(this.spaceIdArray[index].split("_")[0])){
this.spaceIdArray.splice(index,0,distanceS);
return;
}
}
this.spaceIdArray.push(distanceS);
}
else
this.spaceIdArray.push(distanceS);
},
_showSpaceDiv: function(type, w, h, x, y) {
var xMul=1;
var yMul=1;
switch(type)
{
case LB:
xMul=0;
yMul=-1;
break;
case LT:
xMul=0;
yMul=0;
break;
case RT:
xMul=-1;
yMul=0;
break;
case RB:
xMul=-1;
yMul=-1;
break;
}
var div=document.createElement(DIV);
$(div).css("left",x+xMul*w).css("top",y+yMul*h).css("width",w).css("height",h).css("border","1px "+this.options.spaceDIVColor+" solid").css("position","absolute").css("display","block");
this.$target.append(div);
},
_pushSpaceData: function(type, w, h, x, y) {
//Calculating Distance between (x,y): Key point of Space and and Center of Container (this.xOffset,this.yOffset)
var distance=Math.sqrt((this.xOffset-x)*(this.xOffset-x) + (this.yOffset-y)*(this.yOffset-y));
var distanceS=distance+'_'+ (distance_Counter++);
//Update Space Id Array
this._updateSpaceIdArray(distanceS, distance);
//Add Space into Space Data Object
this.spaceDataObject[distanceS]=new space(type, w, h, x, y);
// To Show The Space
if(this.options.showSpaceDIV){
this._showSpaceDiv(type, w, h, x, y);
}
},
_placeFirstWord: function(word) {
var w=word.width;
var h=word.height;
var xoff=this.xOffset-w/2;
var yoff=this.yOffset-h/2;
var tw=this.tWidth;
var th=this.tHeight;
var span=word.span;
$(span).css("left",xoff).css("top",yoff).css("display","inline");
this.$target.append(span);
this._pushSpaceData(LB, tw-xoff-w, h, xoff+w, yoff+h/2); //M1
this._pushSpaceData(LT, w, th-yoff-h, xoff+w/2, yoff+h); //M2
this._pushSpaceData(RT, xoff, h, xoff, yoff+h/2); //M3
this._pushSpaceData(RB, w, yoff, xoff+w/2, yoff); //M4
this._pushSpaceData(LT, w/2, h/2, xoff+w, yoff+h/2); //C1
this._pushSpaceData(RT, w/2, h/2, xoff+w/2, yoff+h); //C2
this._pushSpaceData(RB, w/2, h/2, xoff, yoff+h/2); //C3
this._pushSpaceData(LB, w/2, h/2, xoff+w/2, yoff); //C4
this._pushSpaceData(LT, tw-xoff-w-w/2, th-yoff-h/2, xoff+w+w/2, yoff+h/2); //S1
this._pushSpaceData(RT, xoff+w/2, th-yoff-h-h/2, xoff+w/2, yoff+h+h/2); //S2
this._pushSpaceData(RB, xoff-w/2, yoff+h/2, xoff-w/2, yoff+h/2); //S3
this._pushSpaceData(LB, xoff+w/2, yoff-h/2, xoff+w/2, yoff-h/2); //S4
},
_placeOtherWord: function(word) {
for(var index=0;index<this.spaceIdArray.length;index++){
var spaceId=this.spaceIdArray[index];
var obj=this.spaceDataObject[spaceId];
var alignmentInd=0;
var alignmentIndCount=0;
if(word.width<=obj.width && word.height<=obj.height){
alignmentInd=HR;
alignmentIndCount++;
}
if(this.options.verticalEnabled){
if(word.height<=obj.width && word.width<=obj.height){
alignmentInd=VR;
alignmentIndCount++;
}
}
if(alignmentIndCount>0){
this.spaceDataObject[spaceId]=null;
this.spaceIdArray.splice(index,1);
//For Word's Span Position
var xMul=1;
var yMul=1;
//For new Child Spaces
var xMulS=1;
var yMulS=1;
switch(obj.spaceType)
{
case LB:
xMul=0;
yMul=-1;
xMulS=1;
yMulS=-1;
break;
case LT:
xMul=0;
yMul=0;
xMulS=1;
yMulS=1;
break;
case RT:
xMul=-1;
yMul=0;
xMulS=-1;
yMulS=1;
break;
case RB:
xMul=-1;
yMul=-1;
xMulS=-1;
yMulS=-1;
break;
}
if(alignmentIndCount>1){
//Making Horizontal Word in Larger Number
// Random number[0,5] is >0 and <3 --> HR
// Random number[0,5] is >3 --> VR
if(Math.random()*5>3)
alignmentInd=VR;
else
alignmentInd=HR;
}
var w=word.width;
var h=word.height;
switch(alignmentInd)
{
case HR:
var span=word.span;
$(span).css("left",obj.x + xMul*w).css("top", obj.y + yMul*h).css("display","inline");
this.$target.append(span);
if(Math.random()*2>1){
/*
* _________________________________
* | |
* | T |
* | |
* |_______________________________|
* | | |
* | WORD | R |
* | ******** | |
* |_______________|_______________|
*
*/
this._pushSpaceData(obj.spaceType, obj.width-w, h, obj.x+xMulS*w, obj.y); //R
this._pushSpaceData(obj.spaceType, obj.width, obj.height-h, obj.x, obj.y+yMulS*h); //T
}else{
/*
* _________________________________
* | | |
* | T | |
* | | |
* |_______________| R |
* | | |
* | WORD | |
* | ******** | |
* |_______________|_______________|
*
*/
this._pushSpaceData(obj.spaceType, obj.width-w, obj.height, obj.x+xMulS*w, obj.y); //R
this._pushSpaceData(obj.spaceType, w, obj.height-h, obj.x, obj.y+yMulS*h); //T
}
break;
case VR:
var span=word.span;
//IE Handling for Differenet way of Rotation Transforms
if(jQuery.browser && jQuery.browser.msie){
$(span).css("left",obj.x + xMul*h).css("top", obj.y + yMul*w);
}else{
$(span).css("left",obj.x + xMul*h - (w-h)/2).css("top", obj.y + yMul*w + (w-h)/2);
}
$(span).css("display","block").css("-webkit-transform","rotate(270deg)").css("-moz-transform","rotate(270deg)");
$(span).css("-o-transform","rotate(270deg)").css("filter","progid:DXImageTransform.Microsoft.BasicImage(rotation=3)");
this.$target.append(span);
if(Math.random()*2>1){
/*
* _________________________________
* | |
* | T |
* | |
* |_______________________________|
* | D | |
* | R | R |
* | O | |
* |_______W_______|_______________|
*
*/
this._pushSpaceData(obj.spaceType, obj.width-h, w, obj.x+xMulS*h, obj.y); //R
this._pushSpaceData(obj.spaceType, obj.width, obj.height-w, obj.x, obj.y+yMulS*w); //T
}else{
/*
* _________________________________
* | | |
* | T | |
* | | |
* |_______________| R |
* | D | |
* | R | |
* | O | |
* |_______W_______|_______________|
*
*/
this._pushSpaceData(obj.spaceType, obj.width-h, obj.height, obj.x+xMulS*h, obj.y); //R
this._pushSpaceData(obj.spaceType, h, obj.height-w, obj.x, obj.y+yMulS*w); //T
}
break;
}
return;
}
}
}
};
(function( $ ){
$.fn.jQWCloud = function(options) {
var wc=new WordCloud();
wc._setTarget($(this));
wc._init(options);
};
})( jQuery );
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Button, Glyphicon } from 'react-bootstrap';
import { Link } from 'react-router-dom';
//import { capitalize } from '../helpers'
import { votePost } from '../actions/posts';
import { voteComment } from '../actions/comments';
import '../styles.css';
//component that fills in the post features including author,score, and date
const stringifyVoteScore = voteScore => {
if (voteScore > 0) {
return `+${voteScore}`;
}
return voteScore;
};
const getDate = time => {
const date = new Date(time);
return date.toLocaleString();
};
class PostFeatures extends Component {
static propTypes = {
post: PropTypes.shape({
id: PropTypes.string.isRequired,
author: PropTypes.string.isRequired,
voteScore: PropTypes.number.isRequired,
timestamp: PropTypes.number.isRequired,
comments: PropTypes.array,
parentId: PropTypes.string,
}).isRequired,
actions: PropTypes.shape({
votePost: PropTypes.func.isRequired,
voteComment: PropTypes.func.isRequired,
}).isRequired,
categoryPath: PropTypes.string.isRequired,
};
handleVote(option) {
const { post, actions } = this.props;
if (post.parentId) {
actions.voteComment({ id: post.id, option });
} else {
actions.votePost({ id: post.id, option });
}
}
render() {
const { post, categoryPath } = this.props;
return (
<div>
<div className="postAuthor">By: {post.author}</div>
<div className="postFooter">
<div className="postFooterButtons">
<div className="btn-group">
<Button
className="postScore"
bsSize="small"
disabled>
{stringifyVoteScore(post.voteScore)}
</Button>
<Button
bsSize="small"
onClick={() => this.handleVote('upVote')}>
<Glyphicon glyph="arrow-up" />
</Button>
<Button bsSize="small" onClick={() => this.handleVote('downVote')}>
<Glyphicon glyph="arrow-down" />
</Button>
</div>
{!post.parentId && (
<Link to={`/${categoryPath}/${post.id}`}>
<Button bsSize="small">
<Glyphicon glyph="comment" /> {post.comments.length}
</Button>
</Link>
)}
</div>
<div className="postFooterDate">
{getDate(post.timestamp)}
</div>
</div>
</div>
);
}
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({ votePost, voteComment }, dispatch),
};
}
export default connect(null, mapDispatchToProps)(PostFeatures);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.