text stringlengths 7 3.69M |
|---|
document.addEventListener("DOMContentLoaded",() => {
const quoteList = document.querySelector('#quote-list')
const newQouteForm = document.querySelector('#new-quote-form')
fetch("http://localhost:3000/quotes?_embed=likes")
.then(resp => resp.json())
.then(quotes =>{
quotes.forEach(quote =>{
//debugger
quoteList.innerHTML += quoteIndex(quote)
})
})
function quoteIndex(quote){
return `<li class='quote-card' id='${quote.id}'>
<blockquote class='blockquote'>
<p class='mb-0'>${quote.quote}</p>
<footer class='blockquote-footer'>${quote.author}</footer>
<br>
<button class='btn-success' id='like ${quote.id}'>Likes: <span>${quote.likes.length}</span></button>
<button class='btn-danger' id='delete ${quote.id}'>Delete</button>
</blockquote>
</li>`
}
newQouteForm.addEventListener('submit', (event) => {
event.preventDefault()
const formData = {
quote: event.target['quote'].value,
author: event.target['author'].value
}
event.target.reset()
const reqObj = {
method: 'POST',
headers:{
'Content-Type':'application/json'
},
body: JSON.stringify(formData)
}
fetch('http://localhost:3000/quotes', reqObj)
.then(resp => resp.json())
.then(quote => {
let li = document.createElement('li')
li.className = 'quote-card'
li.id = `${quote.id}`
li.innerHTML = `
<blockquote class='blockquote'>
<p class='mb-0'>${quote.quote}</p>
<footer class='blockquote-footer'>${quote.author}</footer>
<br>
<button class='btn-success' id='like ${quote.id}'>Likes: <span>0</span></button>
<button class='btn-danger' id='delete ${quote.id}'>Delete</button>
</blockquote>`
quoteList.appendChild(li)
})
})
quoteList.addEventListener('click', (event) => {
if (event.target.className === 'btn-danger'){
quoteId = parseInt(event.target.id.split(' ')[1])
const formData = {
id: quoteId
}
const configObj = {
method: 'DELETE',
headers: {
'Content-Type':'application/json',
},
body: JSON.stringify(formData)
}
fetch(`http://localhost:3000/quotes/${quoteId}`, configObj)
let liRemove = event.target.parentNode.parentNode
liRemove.remove()
}
})
function likes(){
quoteList.addEventListener('click', (event) => {
if (event.target.className === 'btn-success'){
console.log(event.target.className)
quoteId = parseInt(event.target.id.split(' ')[1])
const formData = {
quoteId: quoteId
}
const reqObj = {
method: 'POST',
headers: {
'Content-Type':'application/json',
},
body: JSON.stringify(formData)
}
fetch('http://localhost:3000/likes', reqObj)
let likeCount = parseInt(event.target.innerText.split(' ')[1])
likeCount += 1
event.target.innerHTML = `Likes: <span>${likeCount}</span>`
}
})
}
likes()
}) |
import React, { Component } from 'react';
import { Link } from 'react-router';
import { setLoginDataToLS } from '../../services/auth';
import base from '../../base';
import LogOut from './LogOut';
class LoginForm extends Component {
constructor(){
super();
this.login = this.login.bind(this);
this.state = {
error: null
}
}
componentWillMount(){
/*
if(localStorage.getItem("uid")){
this.context.router.push('/home');
}
*/
}
login(e){
e.preventDefault();
base.auth().signInWithEmailAndPassword(this.email.value, this.password.value)
.then((user) => {
//console.log(user);
const userInfo = {
name: user.displayName,
email: user.email
}
this.loginForm.reset();
setLoginDataToLS(user.uid, userInfo);
const { location } = this.context.router;
if (location.state && location.state.nextPathname) {
// if requested other URL than default after login, this handles that:
this.props.router.replace(location.state.nextPathname)
} else {
this.props.router.replace('/home')
}
//this.context.router.push('/');
})
.catch((error) => {
//const errorCode = error.code;
const errorMessage = error.message;
this.setState({ error: errorMessage });
console.log(error);
});
}
render(){
const user = JSON.parse(localStorage.getItem("user"));
const loggedIn = (user) ? true : false;
var displayName;
if(loggedIn){
displayName = (user.name) ? user.name : user.email;
}
return (
<div className="row">
<div className="col-md-4 col-md-offset-4">
<div className="login-form">
<h1>Logg inn</h1>
{ loggedIn &&
<div className="alert alert-info">Du er logget inn som { displayName }.<br /><LogOut router={this} /></div>
}
<form className="login-form" ref={(input) => this.loginForm = input} onSubmit={(e) => this.login(e)}>
<fieldset>
{this.state.error &&
<div className="alert alert-danger">{this.state.error}</div>
}
<legend>Login form</legend>
<div className="form-group">
<label htmlFor="email">E-post</label>
<input type="email" id="email" ref={(input) => this.email = input} className="form-control" />
</div>
<div className="form-group">
<label htmlFor="pwd">Passord</label>
<input type="password" id="pwd" ref={(input) => this.password = input} className="form-control" />
</div>
</fieldset>
<button className="btn btn-success">Login</button>
</form>
<hr />
<Link to="/reset-pwd">Glemt passord?</Link>
<hr />
<Link to="/register">Registrer ny bruker</Link>
</div>
</div>
</div>
)
}
}
LoginForm.contextTypes = {
router: React.PropTypes.object
}
export default LoginForm; |
exports.create = options => {
let payload = `${method}&${path}&api_key=${config.se.apiKey}&api_timestamp=${+(new Date())}&${JSON.stringify(body)}`;
let hash = crypto.createHmac('sha256', config.se.apiSecret)
.update(payload)
.digest('base64');
};
|
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { trackItem } from '../../state/actions'
const LookupButtons = ({ item, setSelectedItem }) => {
const isSignedIn = useSelector(state => state.auth.isSignedIn)
const dispatch = useDispatch()
if (isSignedIn) {
return(
<div className="lookup-result-button">
<span className="lookup-button" onClick={() => setSelectedItem(null)}>Keep Searching</span>
<span className="lookup-button" onClick={() => dispatch(trackItem(item))}>Track on Trends</span>
</div>
)
} else {
return(
<div className="lookup-result-button">
<span className="lookup-button" onClick={() => setSelectedItem(null)}>Keep Searching</span>
</div>
)
}
}
export default LookupButtons |
const { query } = require("../index.js");
require("dotenv").config();
console.log(env);
const sqlStatement = `
SELECT * FROM wysteria`;
const getTable = async () => {
const result = await query(sqlStatement);
console.log(result);
};
getTable();
|
import React, {
Component,
PropTypes,
} from 'react'
import {
View,
Text,
StyleSheet,
ScrollView,
Dimensions,
Image
} from 'react-native'
import { PRIMARY_COLOR, ACCENT_COLOR } from '@resources/colors'
import { withNavigation } from '@exponent/ex-navigation'
import ViewPager from 'react-native-viewpager'
import Button from '@components/Button'
const imageWelcome1 = require('@assets/images/welcome1.png')
const imageWelcome2 = require('@assets/images/welcome2.png')
const imageWelcome3 = require('@assets/images/welcome3.png')
const pages = [{
imageSource: imageWelcome1,
title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean suscipit lorem at efficitur aliquet. Phasellus at orci ligula. Cras quis faucibus sem, at sagittis velit. Donec in finibus mauris.',
backgroundColor: PRIMARY_COLOR
}, {
imageSource: imageWelcome2,
title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean suscipit lorem at efficitur aliquet. Phasellus at orci ligula. Cras quis faucibus sem, at sagittis velit. Donec in finibus mauris.',
backgroundColor: PRIMARY_COLOR
}, {
imageSource: imageWelcome3,
title: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean suscipit lorem at efficitur aliquet. Phasellus at orci ligula. Cras quis faucibus sem, at sagittis velit. Donec in finibus mauris.',
backgroundColor: PRIMARY_COLOR
}]
const deviceWidth = Dimensions.get('window').width
@withNavigation
export default class Welcome extends Component {
static defaultProps = {}
static propTypes = {}
constructor(props) {
super(props)
this.state = {}
const dataSource = new ViewPager.DataSource({
pageHasChanged: (p1, p2) => p1 !== p2
})
this.dataSource = dataSource.cloneWithPages(pages)
this._renderPage = this._renderPage.bind(this)
}
_renderPage(page, i) {
return (
<View style={{backgroundColor: page.backgroundColor, width: deviceWidth, paddingVertical: 20}}>
<View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Image
source={page.imageSource}
resizeMode={Image.resizeMode.contain}
style={styles.image}
/>
</View>
<View style={{flex: 0.5, alignItems: 'center', justifyContent: 'center'}}>
<Text style={styles.text}>{page.title}</Text>
</View>
<View style={{flex: 0.5, alignItems: 'center', justifyContent: 'center'}}>
{
parseInt(i, 10) === parseInt(pages.length - 1, 10) ?
<Button
title="Começar"
backgroundColor={ACCENT_COLOR}
onPress={() => this.props.navigator.push('signIn')}
/> :
<Button
title="Próximo"
onPress={() => this.viewPager.goToPage(this.viewPager.getCurrentPage() + 1)}
/>
}
</View>
</View>
)
}
render() {
return (
<View style={styles.container}>
<ViewPager
ref={(viewPager) => this.viewPager = viewPager}
style={styles.viewPager}
dataSource={this.dataSource}
renderPage={this._renderPage}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: PRIMARY_COLOR
},
viewPager: {
flex: 1,
backgroundColor: PRIMARY_COLOR
},
image: {
width: 200,
height: 200
},
text: {
color: '#FFF',
paddingHorizontal: 20,
fontSize: 16
}
})
|
import React, { Component, propTypes } from 'react';
import './table.css';
import Select from '../../Forms/Select/select.js';
import { connect } from 'react-redux';
import { getData } from '../../Actions/index.js';
export class Element extends React.Component {
constructor(props) {
super(props);
this.nameofteam = this.nameofteam.bind(this);
}
componentDidMount() {
// parse info here
// const url = `http://localhost:8080/src/Components/Containers/signin/${ this.props.url}`;
const url = `https://raw.githubusercontent.com/eyusone/newreactapp/master/src/Components/Containers/signin/${ this.props.url}`;
fetch(url)
.then(res => res.json())
.then(parsedata => this.props.getTableData(parsedata))
.catch(err => {
console.log('Fetch Error :-S', err);
});
// console.log(this.props.url);
}
nameofteam(url) {
const teamname = [];
switch (url) {
case 'databox.json':
teamname[0] = [
'MILAN', 'INTER', 'JUVENTUS', 'NAPOLI',
'ROMA',
'ATALANTA',
'LAZIO',
'FIORENTINA'
];
return teamname[0];
case 'epl.json':
teamname[1] = [
'MANUTD', 'CHELSEA', 'ARSENAL', 'TOTTENHAM',
'EVERTON',
'LIVERPOOL',
'LEICESTER',
'MANCITY'
];
return teamname[1];
case 'laliga.json':
teamname[2] = [
'REALM', 'BARCA', 'ATLETICOM', 'VILLAREAL',
'SEVILLA',
'VALENCIA',
'ATLETICOB',
'CELTA'
];
return teamname[2];
case 'bundesliga.json':
teamname[3] = [
'BAYERNM', 'BORUSSIAD', 'SCHALKE04', 'WOLFSBURG',
'BORUSSIAM',
'FREIBURG',
'MAINZ',
'BAYER04'
];
return teamname[3];
}
}
render() {
const teams = this.nameofteam(this.props.url);
const datanames = ['databox.json', 'epl.json', 'laliga.json', 'bundesliga.json'];
return (
<Select name='team' first = {this.props.data.first} options={teams}
identified = {
this.props.data.table
} initTeam = {this.props.team}
/>
);
}
}
const mapStateToProps = (state) => {
// console.log(state.GraphData.data);
return {
data: state.GraphData.data,
teamname: state.GraphData.data.teamname
};
};
const mapDispatchToProps = (dispatch) => {
return {
getTableData: (value) => {
dispatch(getData(value));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Element);
|
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import logger from 'redux-logger';
const requestFields = {
verb: 'POST',
path: '/products.json',
params: JSON.stringify({
product: {
title: "Burton Custom Freestyle 151",
body_html: "<strong>Good snowboard!<\/strong>",
vendor: "Burton",
product_type: "Snowboard"
}
}, null, 2)
};
const initState = {
requestFields,
requestInProgress: false,
requestError: null,
responseBody: '',
selectAllProducts: false,
productIds: [],
selectEveryVariants: false,
selectEveryColor: {},
selectAllVariants: [],
inventoryIds: [],
priceIds: [],
colorVariantIds: []
};
function reducer(state = initState, action) {
switch (action.type) {
case "CREATE_ALL_POSSIBLE_VARIANTS":
return {
...state,
selectEveryColor: action.payload
}
case "SELECT_EVERY_COLOR":
let retSelectEveryColor = { ...state.selectEveryColor }
retSelectEveryColor[action.payload] = true;
return {
...state,
selectEveryColor: retSelectEveryColor
}
case "UNSELECT_EVERY_COLOR":
let retUnselectEveryColor = { ...state.selectEveryColor }
retUnselectEveryColor[action.payload] = false;
return {
...state,
selectEveryColor: retUnselectEveryColor
}
case "SELECT_EVERY_VARIANTS":
return {
...state,
selectEveryVariants: action.payload
};
case "ADD_COLOR_VARIANT_ID":
return {
...state,
colorVariantIds: [
...state.colorVariantIds,
...action.payload
]
}
case "REMOVE_COLOR_VARIANT_ID":
// REFACTORING:
let ret = [...state.colorVariantIds];
action.payload.forEach((i) => {
let isIdPresent = false;
ret.forEach((j) => {
if (j === i && isIdPresent === false) isIdPresent = true;
})
if (isIdPresent === true) ret.splice(ret.indexOf(i), 1)
})
return {
...state,
colorVariantIds: [...ret]
}
case "ADD_ALL_VARIANTS":
return {
...state,
selectAllVariants: [
...state.selectAllVariants,
action.payload
]
}
case "REMOVE_ALL_VARIANTS":
return {
...state,
selectAllVariants: state.selectAllVariants.filter((item) => item !== action.payload)
}
case "SELECT_ALL_PRODUCTS":
return {
...state,
selectAllProducts: action.payload
};
case "ADD_PRODUCT_ID":
return {
...state,
productIds: [
...state.productIds,
action.payload
]
}
case "REMOVE_PRODUCT_ID":
return {
...state,
productIds: state.productIds.filter((item) => item !== action.payload)
}
case "ADD_INVENTORY_ID":
return {
...state,
inventoryIds: [
...state.inventoryIds,
action.payload
]
};
case "REMOVE_INVENTORY_ID":
return {
...state,
inventoryIds: state.inventoryIds.filter((item) => item !== action.payload)
};
case "ADD_PRICE_ID":
return {
...state,
priceIds: [
...state.priceIds,
action.payload
]
};
case "REMOVE_PRICE_ID":
return {
...state,
priceIds: state.priceIds.filter((item) => item !== action.payload)
}
case 'UPDATE_VERB':
return {
...state,
responseBody: '',
requestFields: {
...state.requestFields,
verb: action.payload.verb,
},
};
case 'UPDATE_PATH':
return {
...state,
responseBody: '',
requestFields: {
...state.requestFields,
path: action.payload.path,
},
};
case 'UPDATE_PARAMS':
return {
...state,
responseBody: '',
requestFields: {
...state.requestFields,
params: action.payload.params,
},
};
case 'REQUEST_START':
return {
...state,
requestInProgress: true,
requestError: null,
responseBody: ''
};
case 'REQUEST_COMPLETE':
return {
...state,
requestInProgress: false,
requestError: null,
responseBody: action.payload.responseBody
};
case 'REQUEST_ERROR':
return {
...state,
requestInProgress: false,
requestError: action.payload.requestError,
};
default:
return state;
}
}
const middleware = applyMiddleware(thunkMiddleware, logger);
const store = createStore(reducer, middleware);
export default store;
|
import React from 'react'
//import PostForm from './PostForm'
const Post = ({post}) => {
return (
<div className="tile" key={post.id} >
<h4>{post.title}</h4>
<p>{post.body}</p>
</div>
)
}
export default Post |
$(document).ready(function(){
$("#link-show-brands").click(function(){
$("#productfrontsearch-brand_id label:not(:nth-child(-n+10))").show(500);
$(this).hide();
$("#link-hide-brands").show();
});
$("#link-hide-brands").click(function () {
$("#productfrontsearch-brand_id label:not(:nth-child(-n+10))").hide(500);
$("html, body").animate({ scrollTop: 260 }, "slow");
$(this).hide();
$("#link-show-brands").show();
})
}); |
//var addNumbersLocal=function(){
// var firstNumber=$('#firstNumber').val();
// var secondNumber=$('#secondNumber').val();
// var sum=firstNumber+secondNumber;
// $( "#result" ).html(sum);
//}
// this function waits for the page to be loaded, this is because if we need
// to bind elements, they need to exist first.
//$(document).ready(function(){
// console.log('The paga has now loaded')
// $('#adderButton').bind('click',addNumbersLocal)
//});
var NumberplateRemote=function(){
var plate1=$('#plate1').val();
// these are your GET parameters
var data={
plate1:plate1
}
$("#result").html('Loading - Please Wait');
$("body").css("cursor", "progress");
//this is our ajax call
$.get("/uploadrego", data,function(result) {
$("#result").html(result);
$("body").css("cursor", "default");
if ('speechSynthesis' in window) { // Chrome only !
if (result.includes("Rego does not exist")){
var speech = new SpeechSynthesisUtterance('Sorry, could not find details regarding this registration number' );
speech.lang = 'en-US';
window.speechSynthesis.speak(speech);
}
else if (result.includes("Rego is")){
var speech = new SpeechSynthesisUtterance('Vehicle details found' );
speech.lang = 'en-US';
window.speechSynthesis.speak(speech);
}
}
});
}
$(document).ready(function(){
console.log('The page has now loaded')
$('#submitButton').bind('click touch',NumberplateRemote)
});
var ImageuploadRemote=function(){
var file = $('#file').val();
var data={
file:file
}
$("#result").html('Loading - Please Wait');
$("body").css("cursor", "progress");
// this is our ajax call
$.post("/upload", data,function(result) {
$("#result").html(result);
$("body").css("cursor", "default");
});
}
$(document).ready(function(e){
$("#uploadimage").on('submit',(function(e) {
$("#result").html('Loading - Please Wait');
$("body").css("cursor", "progress");
e.preventDefault();
$.ajax({
url: "/upload",
type: "POST",
data: new FormData(this),
beforeSend: function(){$("#body-overlay").show();},
contentType: false,
processData:false,
success: function(data)
{
$("#result").html(data);
$("#result").css('opacity','1');
$("body").css("cursor", "default");
if ('speechSynthesis' in window) { // Chrome only !
if (data.includes("Rego does not exist")){
var speech = new SpeechSynthesisUtterance('Sorry, could not find details regarding this registration number' );
speech.lang = 'en-US';
window.speechSynthesis.speak(speech);
}
else if (data.includes("Rego is")){
var speech = new SpeechSynthesisUtterance('Vehicle details found' );
speech.lang = 'en-US';
window.speechSynthesis.speak(speech);
}
}
},
error: function()
{
}
});
}));
});
$(document).ready(function(e){
$("#captureimage").on('submit',(function(e) {
$("#result").html('Loading - Please Wait');
$("body").css("cursor", "progress");
e.preventDefault();
$.ajax({
url: "/upload",
type: "POST",
data: new FormData(this),
beforeSend: function(){$("#body-overlay").show();},
contentType: false,
processData:false,
success: function(data)
{
$("#result").html(data);
$("#result").css('opacity','1');
$("body").css("cursor", "default");
if ('speechSynthesis' in window) { // Chrome only !
if (data.includes("Rego does not exist")){
var speech = new SpeechSynthesisUtterance('Sorry, could not find details regarding this registration number' );
speech.lang = 'en-US';
window.speechSynthesis.speak(speech);
}
else if (data.includes("Rego is")){
var speech = new SpeechSynthesisUtterance('Vehicle details found' );
speech.lang = 'en-US';
window.speechSynthesis.speak(speech);
}
}
},
error: function()
{
}
});
}));
});
|
import React from 'react';
import { Alert as ReactAlert } from 'reactstrap';
class Alert extends React.Component {
render() {
const { data } = this.props
return (
<ReactAlert color={data.color}>{data.text}</ReactAlert>
);
}
}
export default Alert
|
$(document).ready(function() {
function resizeElement(inizial) {
$(inizial).resizable({
handles: {
'ne': '#negrip',
'se': '#segrip',
'sw': '#swgrip',
'nw': '#nwgrip',
'n': '#ngrip',
'e': '#egrip',
's': '#sgrip',
'w': '#wgrip'
}
});
};
function disabledResizeElement(inizial) {
$(inizial).draggable({ disabled: true });
}
function enabledResizeElement(inizial) {
$(inizial).draggable('enable');
}
// element pada content div di click
$('.body').on('click','div[resize=false]', function() {
$('.submenuWidget').remove();
var init = $(this).attr('init');
var contentEditable = $('div[init='+init+']').attr('resize');
if(contentEditable != 'true') {
// disabled element resize yang tidak terpilih ( untuk type element )
$('div[resize=true]').attr('resize','false');
$('div[resize=false]').css(
{'border':'none',
'cursor':'default',
});
disabledResizeElement('.body div[resize=false]');
$('div[resize=false] .btnDeleteResize').remove();
$('div[resize=false] .ui-resizable-handle').hide();
$('div[resize=false] .btnmenuWidget').remove();
$('div[resize=false] .btnmenuWidgetLayout').remove();
$('div[resize=false]').removeAttr('contenteditable');
// disabled element resizelayout yang tidak terpilih ( untuk type layout )
$('div[element=layout]').attr('resizelayout','false');
$('div[resizelayout=false]').css(
{'border':'none',
'cursor':'default',
});
disabledResizeElement('.body div[resizelayout=false]');
$('div[resizelayout=false] .btnDeleteResizeLayout').css({'display':'none'});
$('div[resizelayout=false] .ui-resizable-handle').css({'display':'none'});
$('div[resizelayout=false] .btnmenuWidgetLayout').css({'display':'none'});
$('div[resizelayout=false] .btnmenuWidget').css({'display':'none'});
// set element resize yang terpilih
var inizial = 'div[init='+init+']';
$('div[init='+init+']').attr('resize','true');
if($('div[init='+init+'] .ui-resizable-handle').length){
$('div[resize=true] .ui-resizable-handle').css({'display':'block'});
$('div[init='+init+']').append('<img style="cursor:pointer" class="btnDeleteResize" param="'+init+'" src="'+base_url+'assets/pic/tools/sidebar/iconDelElement.png" width="23" height="22" ></img>');
$('div[init='+init+']').append('<img style="cursor:pointer" class="btnmenuWidget" param="'+init+'" src="'+base_url+'assets/pic/tools/sidebar/pan.png" width="47" height="24" ></img>');
} else {
$('div[init='+init+']').append('<div class="ui-resizable-handle ui-resizable-nw" id="nwgrip"></div><div class="ui-resizable-handle ui-resizable-ne" id="negrip"></div><div class="ui-resizable-handle ui-resizable-sw" id="swgrip"></div><div class="ui-resizable-handle ui-resizable-se" id="segrip"></div><div class="ui-resizable-handle ui-resizable-n" id="ngrip"></div><div class="ui-resizable-handle ui-resizable-s" id="sgrip"></div><div class="ui-resizable-handle ui-resizable-e" id="egrip"></div><div class="ui-resizable-handle ui-resizable-w" id="wgrip"></div>');
$('div[init='+init+']').append('<img style="cursor:pointer" class="btnDeleteResize" param="'+init+'" src="'+base_url+'assets/pic/tools/sidebar/iconDelElement.png" width="23" height="22" ></img>');
$('div[init='+init+']').append('<img style="cursor:pointer" class="btnmenuWidget" param="'+init+'" src="'+base_url+'assets/pic/tools/sidebar/pan.png" width="47" height="24" ></img>');
}
$('div[init='+init+']').css(
{'border':'1px solid red',
'cursor':'move',
});
$('div[init='+init+'] .ui-resizable-handle').css(
{
'border':'1px solid red'
});
$('div[init='+init+'] #segrip').css(
{'right':'-5px',
'bottom':'-5px'
});
resizeElement(inizial);
enabledResizeElement('div[init='+init+']');
}else {
}
});
//click menu resize elemen sub menu
$('div').on('click','.btnmenuWidget', function() {
if($('.submenuWidget').length) {
}else {
var elementType = $('div[resize=true] ').attr('type');
// show sub menu element button
if(elementType == "button" ) {
var init = $(this).attr('param');
$('div[init='+init+']').append('<span class="submenuWidget"><section class="head">Button<img src="'+base_url+'assets/pic/tools/sidebar/closemenuwidget.png" id="closemenuwidget" style="width:14px;margin-right:15px;cursor:pointer;float:right;margin-top:2px;" /></section><ul><li id="LinkTo">Link To</li><li id="settingButton">Settings</li></ul><div class="bring-forward"></div><div class="send-backward"></div></span>');
// show submenu element menu
} else if(elementType == "menu" ) {
var init = $(this).attr('param');
$('div[init='+init+']').append('<span class="submenuWidget"><section class="head">Menu<img src="'+base_url+'assets/pic/tools/sidebar/closemenuwidget.png" id="closemenuwidget" style="width:14px;margin-right:15px;cursor:pointer;float:right;margin-top:2px;" /></section><ul><li id="LinkTo">Link To</li><li id="settingMenu">Settings Menu</li></ul><div class="bring-forward"></div><div class="send-backward"></div></span>');
// show submenu element im
} else if(elementType == "images" ) {
var init = $(this).attr('param');
var url = $('div[init='+init+'] img').attr('src');
$('div[init='+init+']').append('<span class="submenuWidget"><section class="head">Gambar<img src="'+base_url+'assets/pic/tools/sidebar/closemenuwidget.png" id="closemenuwidget" style="width:14px;margin-right:15px;cursor:pointer;float:right;margin-top:2px;" /></section><ul><li href="#imageManager" data-toggle="modal" id="Ubahgambar">Ubah Gambar</li><li id="editgambar">Edit Gambar</li><li id="settingGambar">Setting Gambar</li></ul><div class="bring-forward"></div><div class="send-backward"></div></span>');
$('#editgambar').attr("onclick","return launchEditor('"+init+"','"+url+"');");
// show submenu element title and paragraph
} else {
var init = $(this).attr('param');
$('div[init='+init+']').append('<span class="submenuWidget"><section class="head">Text<img src="'+base_url+'assets/pic/tools/sidebar/closemenuwidget.png" id="closemenuwidget" style="width:14px;margin-right:15px;cursor:pointer;float:right;margin-top:2px;" /></section><ul><li id="LinkTo">Link To</li><li id="editTextMn">Edit Text</li><li id="settingText">Settings</li></ul><div class="bring-forward"></div><div class="send-backward"></div></span>');
}
}
});
//edit text menu click
$('.body').on('click','#editTextMn', function() {
$('.submenuWidget').remove();
var restval = 'true';
var par = $('div[resize='+restval+']').attr('init');
$('div[init='+par+']').attr('contenteditable','true');
$('div[init='+par+']').css({'cursor':'text'});
$('div[init='+par+']').draggable({ disabled: true });
$('div[init='+par+']').popline();
});
// close submenu widget
$('.body').on('click','#closemenuwidget', function() {
$('.submenuWidget').remove();
});
// proses delete element
$('div').on('click','.btnDeleteResize', function() {
var restval = $(this).attr('param');
var par = $('div[init='+restval+']').attr('init');
$('div[init='+par+']').remove();
});
});
|
var gulp = require('gulp');
var purify = require('gulp-purifycss');
var cleanCSS = require('gulp-clean-css');
var uglify = require('gulp-uglify');
var pump = require('pump');
gulp.task('default', function () {
return gulp.src('css/*.css')
.pipe(purify(['./js/*.js', './*.html']))
.pipe(cleanCSS())
.pipe(gulp.dest('./out'));
});
gulp.task('compress', function (cb) {
pump([
gulp.src('js/*.js'),
uglify(),
gulp.dest('dist')
],
cb
);
}); |
var ExampleApp = artifacts.require("ExampleApp");
var Token = artifacts.require("LimitedMintableNonFungibleToken");
contract('ExampleApp', (accounts) => {
it('should not be able to mint if not from app wallet', () => {
const tokenId = web3.utils.randomHex(32);
const tokenIdString = web3.utils.hexToNumberString(tokenId);
const tokenURI = `https://foo.bar/tokens/${tokenIdString}`;
return ExampleApp.deployed().then(instance => {
return instance.mint(accounts[0], tokenId, tokenURI, { from: accounts[1] }).catch(error => {
assert.ok(error);
});
});
});
it('should be able to mint a token', () => {
const tokenId = web3.utils.randomHex(32);
const tokenIdString = web3.utils.hexToNumberString(tokenId);
const tokenURI = `https://foo.bar/tokens/${tokenIdString}`;
return ExampleApp.deployed().then(instance => {
return instance.mint(accounts[0], tokenId, tokenURI);
}).then(result => {
return Token.deployed().then(tokenInstance => {
return tokenInstance.ownerOf(tokenId);
}).then(result => {
assert.equal(result.valueOf(), accounts[0]);
});
});
});
it('should not be able to update the address if not the app wallet', () => {
return ExampleApp.deployed().then(instance => {
return instance.setAppWalletAddress(accounts[1], { from: accounts[1] }).catch(error => {
assert.ok(error);
});
});
});
it('should be able to update the app wallet address', () => {
const tokenId = web3.utils.randomHex(32);
const tokenIdString = web3.utils.hexToNumberString(tokenId);
const tokenURI = `https://foo.bar/tokens/${tokenIdString}`;
return ExampleApp.deployed().then(instance => {
return instance.setAppWalletAddress(accounts[1], { from: accounts[0] }).then(() => {
return instance.mint(accounts[0], tokenId, tokenURI, { from: accounts[1] });
}).then(result => {
assert.ok(result);
});
});
});
});
|
import instanceAxios from '../api.config'
class TextAnswerAPI {
// The fields from the text update must be the same as in the TextWithAnswer model (see backend)
async update(id, updateBody) {
const { data } = await instanceAxios.patch(`/lesson/textanswer/update/${id}`, updateBody)
return data
}
async create(lessonId) {
const { data } = await instanceAxios.post(`lesson/textanswer/create/${lessonId}`)
return data
}
async getOne(id) {
const { data } = await instanceAxios.get(`/lesson/textanswer/${id}`)
return data
}
}
export default new TextAnswerAPI()
|
var arrow = "<img class='subHeadImg' style='float:right;' src='imgs/arrow.png' width='20px'></img>";
var actualCode = "default";
$(document).ready(function(){
$(document).contextmenu(function() {
return false;
});
$('.contextMenuContainer').ready(function(){
$(document).mousedown(function(e){
if(e.which==3 && !$(e.target).hasClass('contextMenuVoice') && !$(e.target).hasClass('contextMenuTitle') && !$(e.target).hasClass('contextMenuContainer')){
if($(e.target).attr('menuCode')!=undefined){
actualCode = $(e.target).attr('menuCode');
}else{
actualCode = "default";
}
$('.contextMenuContainer').each(function(){
if($(this).attr('menuCode')==actualCode){
var cursorX = e.pageX;
var cursorY = e.pageY;
$(this).css('top', cursorY+"px");
$(this).css('left', cursorX+"px");
$(this).css('visibility', "visible");
$(this).show();
}else{
$(this).hide();
}
});
}
if(e.which==1 && ($(e.target).hasClass('contextMenuVoiceSubMenu')
|| $(e.target).hasClass('voice')
|| $(e.target).hasClass('subHeadImg'))){
//submenu opener
//}else if(e.which==1 && !$(e.target).hasClass('contextMenuTitle')){
}else if(e.which==1 && $(e.target).hasClass('internalDiv')){
if($(e.target).parent().attr("target")!=undefined){
location.href = $(e.target).parent().attr("target");
}
$('.contextMenuContainer').hide();
}else if(e.which==1 && (
$(e.target).hasClass('headImg')
|| $(e.target).hasClass('clickableVoice')
|| $(e.target).hasClass('subHeadImg'))){
if($(e.target).parent().parent().attr("target")!=undefined){
location.href = $(e.target).parent().parent().attr("target");
}
$('.contextMenuContainer').hide();
}else if(e.which==1 && !$(e.target).hasClass('contextMenuTitle')){
$('.contextMenuContainer').hide();
}
});
$('.contextMenuVoiceSubMenu').mouseover(function(){
$(this).children().css({visibility: 'visible', top: $(this).position().top+'px'});
//console.log($(this).css('left')+">"+parseInt($(this).css('width')));
});
$('.contextMenuVoiceSubMenu').mouseleave(function(){
$(this).children().css({top: '-1000px'});
});
$('.submenu').mouseover(function(e){
var y = e.pageY;
var x = $('.contextMenuContainer').position().left+parseInt($('.contextMenuContainer').css('width'));
$('.contextMenuContainerSubmenu').css({top: y+'px', left: x+'px', position: 'absolute'});
});
});
});
//gerenates the base html for the context menu
function generateMenus(structures){
structures.forEach(function(structure){
var ris = "<div class='contextMenuContainer'";
for(var key in structure){
if(key=='code'){
ris+=" menuCode='"+structure[key]+"'";
break;
}
}
ris+="><ul class='contextMenuList'>";
for(var key in structure){
//there can be only a title for this context menu
if(key=='title'){
ris+="<li class='contextMenuTitle'>"+structure[key]+"</li>";
}else if(key=='voicesList'){
for (let i = 0; i < structure[key].length; i++) {
if(structure[key][i].submenu==undefined){
ris+=getNormalVoice(structure[key][i]);
}else{
ris+=getSubVoice(structure[key][i])
}
}
}
}
ris+="</ul></div>";
//attach menu to the body
$(document).ready(function(){
$("body").append(ris);
});
});
//warning message if default menu not found
$(document).ready(function(){
var found = false;
$(".contextMenuContainer").each(function(){
if($(this).attr('menucode')=="default"){
found = true;
}
});
if(!found){
console.log('Without field code:\"default\" inside on of the menus inside menus.js there no default menu will be displayed')
}
});
}
//generate the html code for submenus
function submenu(submenuVal){
var ris = "";
if(submenuVal!=undefined){
ris+="<ul class='submenu'>";
for (let i = 0; i < submenuVal.length; i++) {
if(submenuVal[i].submenu==undefined){
ris+=getNormalVoice(submenuVal[i]);
}else{
ris+=getSubVoice(submenuVal[i])
}
}
ris+="</ul>";
}
return ris;
}
//creates a normal voice
function getNormalVoice(structure){
var ris = "";
ris+="<li class='contextMenuVoice";
if(structure.separator!=undefined && structure.separator){
ris+=" separator";
}
ris+="'";
if(structure.link!=undefined){
ris+=" target='"+structure.link+"'";
}
ris+="><div class='internalDiv'>";
var imgSrc = "imgs/empty.png";
if(structure.img!=undefined){
imgSrc = structure.img;
}
ris+="<img class='headImg' src='"+imgSrc+"' width='12px'></img>";
if(structure.voice!=undefined){
var voiceClass = "voice"
if(structure.link!=undefined){
voiceClass = "clickableVoice"
}
ris+="<span class='"+voiceClass+"'>"+structure.voice+"</span>";
}
ris+="</div></li>";
return ris;
}
//create a subvoice
function getSubVoice(structure){
var ris = "<li class='contextMenuVoiceSubMenu";
var imgSrc = "imgs/empty.png";
if(structure.separator!=undefined && structure.separator){
ris+=" separator";
}
ris+="'>"+arrow;
if(structure.img!=undefined){
imgSrc = structure.img;
}
ris+="<img class='subHeadImg' src='"+imgSrc+"' width='12px'><span class='voice'>"+structure.voice+"</span></img>";
ris+=submenu(structure.submenu)+"</li>";
return ris;
} |
import React from 'react';
import { withRouter, Link } from 'react-router';
import SearchBarContainer from './search_bar_container';
class Greeting extends React.Component {
constructor(props) {
super(props);
this.handleLogout = this.handleLogout.bind(this);
}
handleLogout(e) {
e.preventDefault();
this.props.logout();
this.props.router.replace("/");
}
render () {
let { currentUser } = this.props;
return (
<hgroup className="header-group">
<h2>Welcome, {currentUser.username}!</h2>
<SearchBarContainer />
<Link to="/" onClick={this.handleLogout}>Log Out</Link>
</hgroup>
);
}
}
export default withRouter(Greeting);
|
var rest = require('../API/RestClient');
var builder = require('botbuilder');
//Calls 'getYelpData' in RestClient.js with 'displayRestaurantCards' as callback to get list of restaurant information
exports.displayMusicArtistCards = function getMusicArtistData(session){
var url ='http://ws.audioscrobbler.com/2.0/?method=artist.getinfo&artist='+session.dialogData.artistName+'&api_key=174f36952d07f45aec30c3ba9bb522ea&format=json';
rest.getMusicAPIData(url,session,displayMusicArtistCards);
}
function displayMusicArtistCards(message, session) {
var attachment = [];
var jsonResult = JSON.parse(message);
//For each restaurant, add herocard with name, address, image and url in attachment
var artistName = jsonResult.artist.name;
var artistURL = jsonResult.artist.url;
var artistWikiURL = jsonResult.artist.bio.links.link.href;
var artistSummary = jsonResult.artist.bio.summary;
var imageURL = jsonResult.artist.image[2]["#text"];
var card = new builder.HeroCard(session)
.title(artistName)
.subtitle(artistSummary)
.images([
builder.CardImage.create(session, imageURL)
])
.buttons([
builder.CardAction.openUrl(session, artistURL, 'More Information'),
builder.CardAction.openUrl(session, artistWikiURL, 'More Information on Wiki')
]);
attachment.push(card);
//Displays restaurant hero card carousel in chat box
var message = new builder.Message(session)
.attachmentLayout(builder.AttachmentLayout.carousel)
.attachments(attachment);
session.send(message);
} |
function watchForm() {
$('#numberofpics').submit(function(e) {
e.preventDefault();
var images = document.getElementById("images").value;
getImages(images);
})
}
function getImages(images) {
fetch(`https://dog.ceo/api/breeds/image/random/${images}`)
.then (response => response.json())
.then (responseJson => console.log(responseJson))
.catch(error => alert ('There was an error, please try again.'));
}
$(function() {
console.log('Form is ready! Waiting for submit');
watchForm();
});
|
import React from 'react';
import { withDesign } from 'storybook-addon-designs';
import { Bestsellers } from './Bestsellers';
export default {
title: 'Component/Bestsellers',
component: Bestsellers,
decorators: [
(Story) => (
<div style={{ backgroundColor: '#FAEFE3', padding: '2rem', maxWidth: '407px' }}>
<Story />
</div>
),
],
argTypes: {},
};
const Story = (args) => <Bestsellers {...args} />;
export const Basic = Story.bind({});
Basic.args = {
label: 'Bestsellers',
products: [
{
imageURL: '/assets/image-2.png',
imageAlt: 'photo of shoe',
name: 'Nike Air Max 270',
brand: 'Nike',
price: '$195.80',
selected: true,
},
{
imageURL: '/assets/image-1.png',
imageAlt: 'photo of shoe',
name: 'Nike Air Max 90',
brand: 'Nike',
price: '$195.80',
selected: false,
},
{
imageURL: '/assets/image.png',
imageAlt: 'photo of shoe',
name: 'Nike Air Max Plus',
brand: 'Nike',
price: '$195.80',
selected: false,
},
],
};
Basic.story = {
parameters: {
design: {
type: 'image',
url: 'https://res.cloudinary.com/elie-tech/image/upload/v1604444026/frontwork-prod/40:2.png',
},
},
};
|
import React from 'react'
import zerooned from '../icons/01d.png'
import zeroonen from '../icons/01n.png'
import zerotwod from '../icons/02d.png'
import zerotwon from '../icons/02n.png'
import zerothreed from '../icons/03d.png'
import zerothreen from '../icons/03n.png'
import zerofourd from '../icons/04d.png'
import zerofourn from '../icons/04n.png'
import zeronined from '../icons/09d.png'
import zeroninen from '../icons/09n.png'
import tend from '../icons/10d.png'
import tenn from '../icons/10n.png'
import elevend from '../icons/11d.png'
import elevenn from '../icons/11n.png'
import thirteend from '../icons/13d.png'
import thirteenn from '../icons/13n.png'
import fiftyd from '../icons/50d.png'
import fiftyn from '../icons/50n.png'
let weatherIcon = 0
function Icon({data}){
if (data.icon === '01d') {
weatherIcon = zerooned;
} else if (data.icon === '02d') {
weatherIcon = zerotwod;
} else if (data.icon === '01n') {
weatherIcon = zeroonen;
}else if (data.icon === '02n') {
weatherIcon = zerotwon;
}else if (data.icon === '03d') {
weatherIcon = zerothreed;
}else if (data.icon === '03n') {
weatherIcon = zerothreen;
}else if (data.icon === '04d') {
weatherIcon = zerofourd;
}else if (data.icon === '04n') {
weatherIcon = zerofourn;
}else if (data.icon === '09d') {
weatherIcon = zeronined;
}else if (data.icon === '09n') {
weatherIcon = zeroninen;
}else if (data.icon === '10d') {
weatherIcon = tend;
}else if (data.icon === '10n') {
weatherIcon = tenn;
}else if (data.icon === '11d') {
weatherIcon = elevend;
}else if (data.icon === '11n') {
weatherIcon = elevenn;
}else if (data.icon === '13d') {
weatherIcon = thirteend;
}else if (data.icon === '13n') {
weatherIcon = thirteenn;
}else if (data.icon === '50d') {
weatherIcon = fiftyd;
}else if (data.icon === '50n') {
weatherIcon = fiftyn;
}
return <img src={weatherIcon} alt="" style={{height:'5rem', width:'5rem'}}/>
}
export default Icon |
var comments = [];
var onCommentsLoaded = function(data){
console.log('some data returned from getcomments.mw');
$("#commentsModal .input-span").html(state.currentspotname);
var randomint = 1+Math.floor(Math.random() * 4);
var imgpath = 'img/bathrooms/bathroom'+randomint+'.jpg';
var content = '';
content+= '<img style="width:100%;" src="'+imgpath+'"/>';
$("#commentsModal .content-input-frame.id0a").html(content);
var rating = 0;
var count = 0;
data.forEach(function(elm,index){
rating += elm.rating;
count++;
});
rating = Math.round(rating / count * 100) / 100;
content = '';
var ratingsaved = rating;
var numstar = 0;
while(numstar<5){
if(rating>=2){
rating -= 2;
content+='<span class="fas fa-star"></span>';
}else if(rating >0){
rating = 0;
content+='<span class="fas fa-star-half-alt"></span>';
}else{
content+='<span class="far fa-star"></span>';
}
numstar++;
}
content+='<span><br class="responsive-br">  '+ratingsaved+'/10.0</span>';
content+='<br>';
content+= '<h6>some info about bathroom</h6>';
$("#commentsModal .content-input-frame.id0b").html(content);
content = '';
data.forEach(function(elm,index){
content+= '<div class="modal-body modal-body-my" style="padding: 20px 25px;">';
content+= '<h3>'+elm.userid+'</h3>';
content+= '<h5>'+elm.content+'</h5>';
var rating = elm.rating;
var ratingsaved = rating;
var numstar = 0;
while(numstar<5){
if(rating>=2){
rating -= 2;
content+='<span class="fas fa-star"></span>';
}else if(rating >0){
rating = 0;
content+='<span class="fas fa-star-half-alt"></span>';
}else{
content+='<span class="far fa-star"></span>';
}
numstar++;
}
content+= '</div>';
});
$("#commentsModal .content-input-frame.id0c").html(content);
}
var onCommentsRegistered = function(data){
data = JSON.parse(data);
if(data.status == 'success'){
console.log('comment register success');
$("#commentsRegModal").modal('hide');
$("#commentsModal").modal('show');
$("#commentsModal .content-input-frame").html('<h3>contents are being loaded<h3>');
$.ajax({
type: 'GET',
url: 'getcomments.mw',
data: {
spotid: state.currentspotid
},
success: onCommentsLoaded,
dataType: 'json'
});
}else{
console.log('comment register fail');
}
}
$(document).ready(function(){
$("#commentsModal .btn-btn1").on('click',function(){
if(state.id != undefined){
$("#commentsModal").modal('hide');
$("#commentsRegModal").modal();
}else{
$("#commentsModal").modal('hide');
state.activitybeforelogin = 'addcomment';
$("#Login").modal();
}
});
$('.content-frame-scrollable').scroll(function(){
var vh = $(this).height();
var sh = $(this).prop('scrollHeight');
var st = $(this).scrollTop();
if((st+vh)>(sh-50)){
//
}
});
});
var markerClickCallbackFunction = function() {
map.setZoom(18);
map.setCenter(this.getPosition());
//information
var information = this.information;
state.currentspotname = information.name;
state.currentspotid = information.id;
$.ajax({
type: 'GET',
url: 'getcomments.mw',
data: {
spotid: state.currentspotid
},
success: onCommentsLoaded,
dataType: 'json'
});
$("#commentsModal .content-input-frame").html('<h3>contents are being loaded<h3>');
$("#commentsModal").modal();
};
var makeMarkerInfoBoxContent = function(information){
var content = "<div><table id = 'customers' border='1'>";
content += "<tr><td style='border:1px solid;'>"+information.name+"</td></tr>";
content += "<tr><td style='border:1px solid;'>"+information.category+"</td></tr>";
content += "</table></div>";
return content;
};
|
var _dec, _dec2, _class;
// @ts-nocheck
// src/demo03.js
// 装饰器的执行顺序
function log(name) {
// 接收参数层
console.log('log.name:', name);
return function logDecorator(target) {
// 装饰器层
console.log('log.target: ', target);
};
}
function connect(name) {
// 接收参数层
console.log('connect.name', name);
return function connectDecorator(target) {
// 装饰器层
console.log('connect.target: ', target);
};
}
function withRouter(target) {
// 装饰器层
console.log('withRouter.target: ', target);
}
let App = (_dec = log('日志'), _dec2 = connect('连接器'), _dec(_class = withRouter(_class = _dec2(_class = class App {}) || _class) || _class) || _class); |
/**
* Holds the scroll position, while inserting elements to the page.
*
* Basis taken from http://kirbysayshi.com/2013/08/19/maintaining-scroll-position-knockoutjs-list.html
*
* @author Andrew Petersen <senofpeter@gmail.com>
* @param node - The DOM element, in which the scrolling happens
* @param element - The DOM element, which needs to be at or over the top of the viewport
* @constructor
*/
function ScrollPosition(node, element) {
this.node = node;
this.previousScrollHeightMinusTop = 0;
this.readyFor = 'up';
var rect = element.getBoundingClientRect()
if (rect.top >= 0) {
this.restore = function(){}
this.prepareFor = function(){}
}
}
ScrollPosition.prototype.restore = function () {
if (this.readyFor === 'up') {
this.node.scrollTop = this.node.scrollHeight - this.previousScrollHeightMinusTop;
}
// 'down' doesn't need to be special cased unless the
// content was flowing upwards, which would only happen
// if the container is position: absolute, bottom: 0 for
// a Facebook messages effect
}
ScrollPosition.prototype.prepareFor = function (direction) {
this.readyFor = direction || 'up';
this.previousScrollHeightMinusTop = this.node.scrollHeight - this.node.scrollTop;
}
export default ScrollPosition |
describe('Game Screen', () => {
beforeEach(() => {
cy.visit('/');
cy.get('section > button:first-child').click();
cy.get('[data-cy="spider-solitaire-program"]').dblclick();
});
it('should decrease score when click hint', () => {
cy.get('[data-cy="score-span"]')
.invoke('text')
.then((beforeScore) => {
cy.get('[data-cy="hint-area"]').click();
cy.get('[data-cy="score-span"]')
.invoke('text')
.should((afterScore) => {
expect(beforeScore).not.to.eq(afterScore);
});
});
});
});
|
var express = require('express');
var app = express();
var http = require('http');
var redis = require('redis')
var client = redis.createClient(6379,'127.0.0.1');
app.get('/start', function (req, res) {
client.get('R',function(err, R) {
if (!R) {
var rand = Math.round(Math.random() * 100)
client.set('R',rand)
res.send('OK')
}
})
});
app.get('/:number', function(req,res) {
var number = req.params['number']
client.get('R',function(err, R) {
console.log(R)
if (err)
res.send(err)
else if (Number(number) < Number(R))
res.send('smaller')
else if (Number(number) > Number(R))
res.send('bigger')
else {
var rand = Math.round(Math.random() * 100)
client.set('R',rand)
res.send('equal')
}
})
});
// listen to port 3000
var server = app.listen(4000);
console.log('Server running at port 4000.') |
var NAVTREEINDEX0 =
{
".html":[1,0,0],
"Action_8hpp_source.html":[2,0,0,0,0],
"Ast_8hpp_source.html":[2,0,0,0,1],
"Exceptions_8hpp_source.html":[2,0,0,0,2],
"FlatMachine_8hpp_source.html":[2,0,0,0,3],
"FlatStep_8hpp_source.html":[2,0,0,0,4],
"Generator_8hpp_source.html":[2,0,0,0,5],
"InputOutput_8hpp_source.html":[2,0,0,0,6],
"Machine_8hpp_source.html":[2,0,0,0,7],
"Parser_8hpp_source.html":[2,0,0,0,8],
"SampleFsml_8hpp_source.html":[2,0,0,1],
"State_8hpp_source.html":[2,0,0,0,9],
"Step_8hpp_source.html":[2,0,0,0,10],
"annotated.html":[1,0],
"classes.html":[1,1],
"classfsml_1_1Action.html":[1,0,0,0],
"classfsml_1_1Action.html#a40fbbd85f83fd1c0b5260584a24469ee":[1,0,0,0,6],
"classfsml_1_1Action.html#a75707a7d786622601b21642b05668edf":[1,0,0,0,0],
"classfsml_1_1Action.html#aa2434deec70591006e204eb7fb0e97d7":[1,0,0,0,1],
"classfsml_1_1Action.html#ab158f49a59dea6cf40ba08210dcd09cc":[1,0,0,0,3],
"classfsml_1_1Action.html#ab5da63bc94cdd0b4110c87fd3e4ee271":[1,0,0,0,7],
"classfsml_1_1Action.html#ac41cfae7343d8b96fbd204451bee840f":[1,0,0,0,5],
"classfsml_1_1Action.html#acfdc73a5600e1f5e855918a8293c173f":[1,0,0,0,2],
"classfsml_1_1Action.html#ae5b8ae5409ea58bed119bc860a803897":[1,0,0,0,4],
"classfsml_1_1Machine.html":[1,0,0,15],
"classfsml_1_1Machine.html#a02a00a80f4f77625cd1fbcb2314d3c21":[1,0,0,15,9],
"classfsml_1_1Machine.html#a0666d3b6834e968bd0fe1461164de7ef":[1,0,0,15,0],
"classfsml_1_1Machine.html#a0c60fab103e0e65343c729ed3502ebac":[1,0,0,15,1],
"classfsml_1_1Machine.html#a146384b88619887f03613f439781e9e0":[1,0,0,15,5],
"classfsml_1_1Machine.html#a4c02303acf2c3bd89ffc6ceda604b02d":[1,0,0,15,6],
"classfsml_1_1Machine.html#a517f29b8c2e2b1815dd43c59a93a8390":[1,0,0,15,2],
"classfsml_1_1Machine.html#a51b789ab95db22995529818bed9fef20":[1,0,0,15,8],
"classfsml_1_1Machine.html#a5bce113183b6d59b652b33f4369bb45c":[1,0,0,15,4],
"classfsml_1_1Machine.html#a7d184c839fe996141a692152b9b37e0a":[1,0,0,15,7],
"classfsml_1_1Machine.html#a863ac1a16a82e0fc0a8e85553061686f":[1,0,0,15,3],
"classfsml_1_1Machine.html#a8c4e7bc3c75c8b40a28d0b33a457be9d":[1,0,0,15,10],
"classfsml_1_1Machine.html#a8d777492e8e8b0e79b041444f386c319":[1,0,0,15,11],
"classfsml_1_1State.html":[1,0,0,16],
"classfsml_1_1State.html#a0a28f6f4a995313d9bc85d1fdf51fb9b":[1,0,0,16,2],
"classfsml_1_1State.html#a0c7aafd6216a785c159e70f00a12d3f8":[1,0,0,16,6],
"classfsml_1_1State.html#a22711ba81bad4eb0b4a98b17a45cfd36":[1,0,0,16,0],
"classfsml_1_1State.html#a2cbbbb658b8d6da4b6b0f0a4e97fed7b":[1,0,0,16,5],
"classfsml_1_1State.html#a4acc37de347d0e4a66d6470a4d6ebcf7":[1,0,0,16,7],
"classfsml_1_1State.html#a4f474c955acf4daed72ca6be257c8234":[1,0,0,16,1],
"classfsml_1_1State.html#ad96fe3074f0c3d8bd3dcb9a7cd7e25ed":[1,0,0,16,4],
"classfsml_1_1State.html#aeb0c3fe997b186b77e3c363709a1bfea":[1,0,0,16,8],
"classfsml_1_1State.html#af13128f0b9cdf6433f4307bb16159477":[1,0,0,16,3],
"classfsml_1_1State.html#af9c12ff54dd9712d43b3a10609445642":[1,0,0,16,9],
"classfsml_1_1Step.html":[1,0,0,17],
"classfsml_1_1Step.html#a02a455c14aa6b6435137d37040da1576":[1,0,0,17,6],
"classfsml_1_1Step.html#a1ae0946da94f7b31564374f32ed6ab87":[1,0,0,17,1],
"classfsml_1_1Step.html#a1d0ba0e93765b946de082651f68cd3fb":[1,0,0,17,3],
"classfsml_1_1Step.html#a5f656cb2f850f8a24afc710f4904ef43":[1,0,0,17,0],
"classfsml_1_1Step.html#a7d310d684bca136ddc95ca8454dfad40":[1,0,0,17,2],
"classfsml_1_1Step.html#ab71a0687e8cfff12deed6b1916ff1ba3":[1,0,0,17,4],
"classfsml_1_1Step.html#acefa781aa49679af3c151194e58c6a85":[1,0,0,17,5],
"dir_d44c64559bbebec7f509842c48db8b23.html":[2,0,0],
"dir_ecb4356f156568b1fba2c4ccbd2ea743.html":[2,0,0,0],
"files.html":[2,0],
"functions.html":[1,3,0],
"functions_func.html":[1,3,1],
"functions_vars.html":[1,3,2],
"hierarchy.html":[1,2],
"index.html":[],
"md_README.html":[0],
"pages.html":[],
"structfsml_1_1AstMachine.html":[1,0,0,3],
"structfsml_1_1AstMachine.html#a007b560f2e500f7f51c570f0316843e2":[1,0,0,3,0],
"structfsml_1_1AstState.html":[1,0,0,2],
"structfsml_1_1AstState.html#a39a00b99d02537f2b014556c203d9c36":[1,0,0,2,2],
"structfsml_1_1AstState.html#a3e7e96d12d2e17d8d35d313b232cb4f5":[1,0,0,2,0],
"structfsml_1_1AstState.html#a89a44c91811564d41c48343cf34560cd":[1,0,0,2,1],
"structfsml_1_1AstStep.html":[1,0,0,1],
"structfsml_1_1AstStep.html#a2244e46f2cff2fa65fda13931a377356":[1,0,0,1,1],
"structfsml_1_1AstStep.html#a308747ad3a3acc808f6c654ff1942e96":[1,0,0,1,0],
"structfsml_1_1AstStep.html#ac7eb1fb884326a326da14c054d3f7777":[1,0,0,1,2],
"structfsml_1_1DeterministicException.html":[1,0,0,4],
"structfsml_1_1DeterministicException.html#ac8f4f6c7ee0d7cad65cd1f90ef506b71":[1,0,0,4,0],
"structfsml_1_1FileReadException.html":[1,0,0,5],
"structfsml_1_1FileReadException.html#a659fb09fec2fb56251b07ff27ddc1389":[1,0,0,5,0],
"structfsml_1_1FileWriteException.html":[1,0,0,6],
"structfsml_1_1FileWriteException.html#aa8b9c1d366dbf76392a775279bc2dd19":[1,0,0,6,0],
"structfsml_1_1FlatMachine.html":[1,0,0,13],
"structfsml_1_1FlatMachine.html#a2fc01c07d6bc3f62fba880e96e538390":[1,0,0,13,7],
"structfsml_1_1FlatMachine.html#a3069121ea01eab1cec46590ab186b622":[1,0,0,13,5],
"structfsml_1_1FlatMachine.html#a3c50e3140f7629c8c34f2c760522203b":[1,0,0,13,4],
"structfsml_1_1FlatMachine.html#a506e347690aa39f7eb7637fd7a952e40":[1,0,0,13,0],
"structfsml_1_1FlatMachine.html#a5f3c317f5a3a8f13f10160dcaeef63e3":[1,0,0,13,6],
"structfsml_1_1FlatMachine.html#a79e252b2ba388c1064d9570a6df275af":[1,0,0,13,3],
"structfsml_1_1FlatMachine.html#a939aa63ea93b644c498cf2e31f67499f":[1,0,0,13,1],
"structfsml_1_1FlatMachine.html#af9260de8b6528b4d8839d3a21b7dd68c":[1,0,0,13,2],
"structfsml_1_1FlatStep.html":[1,0,0,14],
"structfsml_1_1FlatStep.html#a0d750cd9f657776ffc88627a44d9fdf6":[1,0,0,14,6],
"structfsml_1_1FlatStep.html#a2056fa8fd3e527dd04fffb7011fe3d16":[1,0,0,14,0],
"structfsml_1_1FlatStep.html#a264b67de20cbd29b079aa46cc332f336":[1,0,0,14,2],
"structfsml_1_1FlatStep.html#a2a4242c4ad9b86ce6e1fc638ed4427be":[1,0,0,14,7],
"structfsml_1_1FlatStep.html#a69f42f7f8091dff898b7944a12cb563e":[1,0,0,14,5],
"structfsml_1_1FlatStep.html#a7aace1121f06d55c9452e3837387976b":[1,0,0,14,1],
"structfsml_1_1FlatStep.html#a910a78d294c31aea42fc23babd361cdb":[1,0,0,14,4],
"structfsml_1_1FlatStep.html#aa855ca1535e6dbffb556ee28bd91779f":[1,0,0,14,3],
"structfsml_1_1InitialStateException.html":[1,0,0,7],
"structfsml_1_1InitialStateException.html#ae4cf2e419f5f5d221af4d7de2907dbb5":[1,0,0,7,0],
"structfsml_1_1InvalidInputException.html":[1,0,0,8],
"structfsml_1_1InvalidInputException.html#aa7373c1db918bf47817d2d85e089ee50":[1,0,0,8,0],
"structfsml_1_1ParserException.html":[1,0,0,9],
"structfsml_1_1ParserException.html#a022b04432a881271696b5e9e7f9df5af":[1,0,0,9,0],
"structfsml_1_1ReachableException.html":[1,0,0,10],
"structfsml_1_1ReachableException.html#a10ee53b62caeefb43be52d96420d0798":[1,0,0,10,0],
"structfsml_1_1ReachableException.html#a6101b6deeeaba35c21944812ab71bf5d":[1,0,0,10,1],
"structfsml_1_1ResolvableException.html":[1,0,0,11],
"structfsml_1_1ResolvableException.html#abe17276c3a06e7a331d9e3db7d480af8":[1,0,0,11,0],
"structfsml_1_1UniqueException.html":[1,0,0,12],
"structfsml_1_1UniqueException.html#a14fc471605daa57d638a35756fa66901":[1,0,0,12,0]
};
|
import React from 'react';
import Icon from 'react-native-vector-icons/MaterialIcons';
//import { View, Text, Image, Alert } from 'react-native';
import Background from '~/components/Background';
import Header from '~/components/Header';
import { Container, Title, Services, Avatar, Name, ServicesList, ServicesRow } from './styles';
export default function Servicos() {
return (
<Background>
<Header />
<Container>
<Title>Serviços</Title>
<ServicesRow>
<Services>
<Avatar
source={{ uri: 'https://api.adorable.io/avatar/50/rocketseat.png' }}
/>
<Name>Serviço 1</Name>
</Services>
<Services>
<Avatar
source={{ uri: 'https://api.adorable.io/avatar/50/rocketseat.png' }}
/>
<Name>Serviço 2</Name>
</Services>
</ServicesRow>
<ServicesRow>
<Services>
<Avatar
source={{ uri: 'https://api.adorable.io/avatar/50/rocketseat.png' }}
/>
<Name>Serviço 1</Name>
</Services>
<Services>
<Avatar
source={{ uri: 'https://api.adorable.io/avatar/50/rocketseat.png' }}
/>
<Name>Serviço 2</Name>
</Services>
</ServicesRow>
<ServicesRow>
<Services>
<Avatar
source={{ uri: 'https://api.adorable.io/avatar/50/rocketseat.png' }}
/>
<Name>Serviço 1</Name>
</Services>
<Services>
<Avatar
source={{ uri: 'https://api.adorable.io/avatar/50/rocketseat.png' }}
/>
<Name>Serviço 2</Name>
</Services>
</ServicesRow>
</Container>
</Background>
);
}
Servicos.navigationOptons = {
tabBarLabel: 'Serviços',
tabBarIcon: ({ tintColor }) => (
<Icon name="settings" size={20} color={tintColor} />
),
};
|
import PropTypes from "prop-types";
import { connect } from "react-redux";
const itemCard = ({
item,
buttonMessage,
cartFunction,
cardStyles,
buttonStyles,
body,
}) => {
const { inStock } = item;
const availability = inStock ? "In Stock" : "Out of Stock";
return (
<div style={cardStyles}>
{body}
<button
disabled={!inStock}
style={buttonStyles}
onClick={() => cartFunction(item)}
>
{buttonMessage}
</button>
</div>
);
};
itemCard.propTypes = {
item: PropTypes.object.isRequired,
buttonMessage: PropTypes.string.isRequired,
cartFunction: PropTypes.func.isRequired,
buttonStyles: PropTypes.object.isRequired,
cardStyles: PropTypes.object.isRequired,
body: PropTypes.object.isRequired,
};
export default connect()(itemCard);
|
// YIELD
document.addEventListener("DOMContentLoaded", function() {
// ITERATOR
let it = foo();
let x = it.next().value;
let y = it.next(7).value;
console.log(`${x} ${y} ${it.next().value}`);
var it2 = step(foo);
it2();
console.log(it2());
gimmeSomething(); //this returns an unexecuted function
console.log(gimmeSomething()); //this returns and executes the function, but only if the function assigned to it is IIFE
var ar = [1, 2, 3, 4, 5];
var arIt = ar[Symbol.iterator]();
console.log(arIt.next().value);
console.log(arIt.next().value);
});
// GENERATOR
function *foo() {
var a = yield "hi";
var b = yield "bye";
var c = 8;
return a * c;
}
// ITERATOR HELPER
function step(gen) {
var it = gen();
var last; //keep it in this scope
return function () {
last = it.next(last).value;
return last;
};
}
// CLOSURE ITERATOR
var gimmeSomething = (function() {
var nextVal;
return function() {
if (nextVal === undefined) {
nextVal = 1;
}
else {
nextVal = (3 * nextVal) + 6;
}
return nextVal;
};
})();
// STANDARD ITERATOR INTERFACE
var gimmeNext = (function() {
var nextVal;
return {
[Symbol.iterator]: function() {return this}, //computed property name
next: function() {
if (nextVal === undefined) {
nextVal = 1;
}
else {
nextVal = nextVal * 3 + 6;
}
return {done: false, value: nextVal};
}
};
})(); |
function() {
var pre = $(this).prev('pre');
var js = pre.text();
var lines = js.split('\n').length;
var ta = $('<textarea rows="'+lines+'" class="code"></textarea>');
ta.text(js);
pre.replace(ta);
return false;
};
|
const api = {
login: {
method: 'post',
url: ''
},
test: {
method: 'get',
url: 'testing'
}
}
export default api |
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
TextInput,
Platform,
ActivityIndicator,
Alert,
ListView,
DeviceEventEmitter
} from 'react-native';
var Dimensions = require('Dimensions');
var {width, height} = Dimensions.get('window');
import Tab from '../Tab'
import Moment from 'moment'
Moment().format();
import Toast from'../../../node_modules/antd-mobile/lib/toast/index'
import Radio from'../../../node_modules/antd-mobile/lib/radio/index'
const RadioItem = Radio.RadioItem;
import List from'../../../node_modules/antd-mobile/lib/list/index'
import TextareaItem from'../../../node_modules/antd-mobile/lib/textarea-item/index'
import Settings from '../../Tool/Settings'
import User from '../../Tool/User'
export default class Questionnaire extends Component{
//state
constructor(props){
super(props);
this.state = {
dataSource:null,
selectData:[],
data:null,
text:'',
responseJson:null
};
}
// 加载完成 复杂的操作:定时器\网络请求
componentDidMount(){
Toast.loading('请稍候',60);
//发送登录网络请求
fetch('https://ffeb8020-8134-4daf-8fda-04ad189426d2.mock.pstmn.io/api/surveys/1', {
method: 'GET',
headers: {
'Bearer' : 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o',
}
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
for (let i = 0; i < responseJson.questions.length; i++){
if (responseJson.questions[i].answer.type !== 'Free-Text'){
this.state.selectData.push([]);
}
}
var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2});
this.setState({
responseJson:responseJson,
dataSource: ds.cloneWithRows(responseJson.questions),
data:responseJson.questions
});
Toast.hide()
// if (responseJson.error !== null){
// Alert.alert(
// '温馨提示',
// responseJson.error.message,
// [
// {text: '确定'}
// ]
// );
// }
})
.catch((error) => {//错误
Toast.hide()
Toast.fail('请检查您的网络!!!', 1);
});
}
// 退出时调用
componentWillUnmount() {
}
render() {
if (this.state.dataSource === null){
return (
<View style={styles.container}>
</View>
)
}else {
return (
<View style={styles.container}>
<ListView
dataSource={this.state.dataSource}//数据源
renderRow={this.renderRow.bind(this)}
/>
</View>
)
}
}
//返回具体的cell
renderRow(rowData,sID,rID){
var views = [];
var selectType = this.state.selectData[rID];
if (rowData.answer.type === 'Free-Text'){
views.push(
<View key = '111'>
<TextareaItem
key = '333'
title="标题"
placeholder="请输入内容..."
data-seed="logId"
rows={5}
onChange={this.customFocusInst.bind(this)}
/>
<TouchableOpacity key = '222' style={styles.dengluBtnStyle} onPress={this.getDetermine.bind(this)}>
<Text style={{color:'white',fontSize: 14,marginLeft:15}}>
提 交
</Text>
<ActivityIndicator
animating={false}
style={[styles.centering, {height: 30}]}
size="small"
color="white"
/>
</TouchableOpacity>
</View>
)
}else {
for (let i = 0 ; i < rowData.answer.format.length ; i++){
views.push(
<RadioItem checked = {selectType.indexOf(i) === -1 ? false : true} key={i+'R'} onChange = {()=> this.onChange(i,sID,rID)}>{rowData.answer.format[i]}</RadioItem>
)
}
}
return(
<View>
<List renderHeader={() => rowData.desc}>
{views.map((elem, index) => {
return elem;
})}
</List>
</View>
)
}
//点击确定
getDetermine(){
for (var i = 0 ; i < this.state.selectData.length ; i++){
if (this.state.selectData[i].length === 0){
//错误
Alert.alert(
'温馨提示',
'问卷未全部完成',
[
{text: '确定'}
]
)
return;
}
}
if (this.state.text.length === 0){
//错误
Alert.alert(
'温馨提示',
'问卷未全部完成',
[
{text: '确定'}
]
)
return;
}
DeviceEventEmitter.emit('getHome');
return;
Toast.loading('请稍候',60);
let answers = [];
for (let i = 0 ; i < this.state.selectData.length ; i++){
answers.push({
questionId:this.state.selectData[i].id,
type:this.state.selectData[i].answer.type,
// answer:
})
}
let json = {
id:this.state.responseJson.id,
date : moment().format("YYYY-MM-DD"),
answers : answers
}
//发送登录网络请求
fetch(Settings.Url + "/api/surveys/1/answers", {
method: 'POST',
headers: {
'Bearer': 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.XbPfbIHMI6arZ3Y922BhjWgQzWXcXNrz0ogtVhfEd2o',
'Content-Type': 'application/json',
},
body: JSON.stringify(json)
})
.then((response) => response.json())
.then((responseJson) => {
console.log('12123123123123');
console.log(responseJson);
Toast.hide()
User.Token = responseJson.id_token;
this.props.navigation.navigate('SetUserData')
})
.catch((error) => {//错误
Toast.hide()
Toast.fail('请检查您的网络!!!', 1);
});
}
//输入
customFocusInst(text){
this.setState({
text:text
})
}
//点击选择
onChange(i,sID,rID){
console.log(sID+'qqqqqq'+rID)
let data = this.state.data[rID];
var selectType = this.state.selectData[rID];
if (data.answer.type === 'Multi-Select'){//多选
if (selectType.indexOf(i) == -1){
selectType.push(i);
}else{
var index = selectType.indexOf(i);
while(index>-1){
selectType.splice(index, 1);
index = selectType.indexOf(i);
}
}
}else{
selectType.length === 0 ? selectType.push(i) : selectType.splice(0,1,i);
}
this.state.selectData.splice(rID,1,selectType);
//更新列表
var ds = new ListView.DataSource({rowHasChanged:(r1, r2) => r1 !== r2});
this.setState({
dataSource: ds.cloneWithRows(this.state.data),
});
}
}
const styles = StyleSheet.create({
container:{
},
dengluBtnStyle:{
// 设置主轴的方向
flexDirection:'row',
// 垂直居中 ---> 设置侧轴的对齐方式
alignItems:'center',
// 设置主轴的对齐方式
justifyContent:'center',
width:width - 40,
marginTop:20,
marginBottom:20,
marginLeft:20,
height:40,
backgroundColor:'rgba(48,192,255,1.0)',
// 设置圆角
borderRadius:5,
},
}) |
import { LitIcon } from "./LitIcon.js";
customElements.define('lit-icon', LitIcon);
|
// SEARCH
export const GET_SEARCH_RESULTS = "GET_SEARCH_RESULTS";
//SEARHINPUT
export const SET_SEARCH_TEXT = "SET_SEARCH_TEXT";
export const GET_SEARCH_TEXT = "GET_SEARCH_TEXT";
export const SET_SEARCH_COUNTRY = "SET_SEARCH_COUNTRY";
export const GET_SEARCH_COUNTRY = "GET_SEARCH_COUNTRY";
//Company
export const GET_COMPANY = "GET_COMPANY";
|
const UserRepository = module.exports;
const { db } = require('../utils/Database');
UserRepository.insertNewUser = (data) => db('user').insert(data).returning('*');
UserRepository.getUserById = (userId) => db('user').where({ id: userId }).first();
UserRepository.getUserByUsername = (username) => db('user').where({ username }).first();
UserRepository.getUsers = () => db('user').select();
UserRepository.updateUserById = (userId, data) => db('user').where({ id: userId }).update(data).returning('*');
UserRepository.deleteUser = (userId) => db('user').where({ id: userId }).del();
|
const bitcoinMessage = require('bitcoinjs-message');
const address = 'COPY ADDRESS FROM ELECTRUM';
const signature = 'COPY SIGNATURE FROM ELECTRUM';
const message = 'COPY WHATEVER MESSAGE ';
console.log(bitcoinMessage.verify(message, address, signature)); // you should get 'true' if everything is ok |
import React from 'react';
let hover = '';
class ReactCycleImage extends React.Component {
constructor(props) {
super(props);
this.state = {
currentImage: props.children[0] || ''
}
this.cycleImage = this.cycleImage.bind(this);
this.clearImageCycle = this.clearImageCycle.bind(this);
}
//Changes images on hover
cycleImage() {
console.log(this.props);
const { children } = this.props;
let imageIndex = 1;
hover = setInterval(() => {
if(!children[imageIndex]) {
imageIndex = 0;
}
this.setSelectedImage(children[imageIndex]);
imageIndex++;
}, 1200)
}
//Stops changing image
clearImageCycle() {
clearTimeout(hover);
}
setSelectedImage(image) {
this.setState({
currentImage: image
});
}
render() {
const { children } = this.props;
const { currentImage } = this.state;
return (
<div onMouseOver={this.cycleImage} onMouseOut={this.clearImageCycle} style={this.props.style}>
{currentImage}
</div>
);
}
}
export default ReactCycleImage; |
/** @jsx jsx */
import styled from '@emotion/styled';
import { jsx } from 'theme-ui';
const PlantContainer = styled.div`
width: 260px;
height: 230px;
position: absolute;
z-index: 10;
&::before {
right: 22px;
transform: rotateZ(35deg);
}
&::after {
left: 22px;
transform: rotateZ(-35deg);
}
`;
const Glass = styled.div`
border-top: 51px solid rgba(255, 255, 255, 0.5);
border-left: 27px solid transparent;
border-right: 27px solid transparent;
height: 0;
bottom: 2px;
width: 80%;
left: 10%;
position: absolute;
`;
const Shine = styled.div`
background: rgba(255, 255, 255, 0.4);
height: 51px;
width: 20px;
display: block;
left: 0;
bottom: 0;
position: absolute;
transform: skew(28deg);
&::after {
content: '';
display: block;
position: absolute;
bottom: inherit;
background: inherit;
height: inherit;
width: 8px;
left: 26px;
}
`;
const Soil = styled.div`
clip-path: polygon(0 0, 100% 0, 88% 100%, 12% 100%);
background: repeating-linear-gradient(
#efa63c,
#efa63c 50%,
#ba6d20 50%,
#ba6d20 100%
);
width: 190px;
height: 44px;
position: absolute;
left: 0;
right: 0;
margin: 0 auto;
bottom: -1px;
`;
const PlantRight = styled.div`
width: 46px;
height: 96px;
position: absolute;
bottom: 42px;
right: 56px;
div {
clip-path: polygon(50% 0%, 0% 100%, 100% 100%);
position: absolute;
bottom: 0;
}
div:nth-of-type(1) {
height: 100%;
width: 24px;
background: repeating-linear-gradient(
#abaf25,
#abaf25 20%,
#f7f8e5 20%,
#f7f8e5 23%
);
left: 12px;
}
div:nth-of-type(2) {
height: 62px;
width: 24px;
background: repeating-linear-gradient(
#d1de00,
#d1de00 20%,
#f7f8e5 20%,
#f7f8e5 24%
);
-webkit-transform: rotate(-15deg);
transform: rotate(-15deg);
}
div:nth-of-type(3) {
height: 50px;
width: 16px;
background: repeating-linear-gradient(
#bec60a,
#bec60a 20%,
#f7f8e5 20%,
#f7f8e5 24%
);
-webkit-transform: rotate(15deg);
transform: rotate(15deg);
right: 0;
}
`;
const PlantLeft = styled.div`
border-radius: 60% 60% 60% 60% / 90% 90% 30% 30%;
background: #d1de00;
width: 22px;
height: 48px;
position: absolute;
bottom: 40px;
left: 90px;
&::before,
&::after {
content: '';
display: block;
position: absolute;
background: inherit;
height: inherit;
width: inherit;
border-radius: inherit;
transform-origin: bottom center;
bottom: 8px;
z-index: -3;
}
&::before {
transform: rotate(78deg);
right: -2px;
}
&::after {
transform: rotate(-78deg);
left: -2px;
}
`;
const LeafMiddle = styled.div`
border-radius: 60% 60% 60% 60% / 90% 90% 30% 30%;
background: #abaf25;
width: 18px;
height: 44px;
-webkit-transform-origin: bottom center;
transform-origin: bottom center;
-webkit-transform: rotate(-56deg);
transform: rotate(-56deg);
bottom: 5px;
left: 2px;
position: absolute;
z-index: -2;
&::before {
content: '';
display: block;
position: absolute;
transform: rotate(112deg);
border-radius: inherit;
background: inherit;
width: inherit;
height: inherit;
-webkit-transform-origin: inherit;
transform-origin: inherit;
}
`;
const LeafTop = styled.div`
border-radius: 60% 60% 60% 60% / 90% 90% 30% 30%;
background: #bec60a;
width: 16px;
height: 44px;
transform-origin: bottom center;
transform: rotate(-30deg);
bottom: 2px;
left: 4px;
position: absolute;
z-index: -1;
&::before {
content: '';
display: block;
position: absolute;
transform: rotate(60deg);
border-radius: inherit;
background: inherit;
width: inherit;
height: inherit;
transform-origin: inherit;
}
`;
const PlantRear = styled.div`
width: 4px;
border-radius: 6px;
background: #878561;
position: absolute;
height: 90px;
left: 144px;
bottom: 40px;
z-index: -4;
&::before,
&::after {
content: '';
display: block;
position: absolute;
width: 7px;
height: 16px;
background: #878561;
border-radius: 50% 50% 50% 50% / 70% 70% 30% 30%;
}
&::before {
right: 5px;
top: 12px;
transform: rotate(-50deg);
box-shadow: 0 0 0 2px #878561, -26px 16px 0 5px #878561;
}
&::after {
left: 5px;
transform: rotate(50deg);
box-shadow: 22px 14px 0 3px #878561, 50px 32px 0 7px #878561;
}
`;
const Plant = (props) => (
<PlantContainer {...props}>
<PlantLeft>
<LeafMiddle />
<LeafTop />
</PlantLeft>
<PlantRear />
<PlantRight>
<div />
<div />
<div />
</PlantRight>
<Soil />
<Glass>
<Shine />
</Glass>
</PlantContainer>
);
export default Plant;
|
module.exports = {
content: ['./index.html',
'./src/**/*.{vue,js,ts,jsx,tsx}',],
theme: {
extend: {
keyframes:{
wiggle: {
'0%, 100%': { transform: 'rotate(-3deg)' },
'50%': { transform: 'rotate(3deg)' },
}
}
},
},
plugins: [],
}
|
import FileCreate from './FileCreate'
export {FileCreate}
export default FileCreate
|
import React from "react";
import { View, Text, StyleSheet } from "react-native";
import { CustomButton } from "../components/utilities/CustomButton";
import { CustomTextInput } from "../components/utilities/CustomTextInput";
const Login = (props) => {
return (
<View style={styles.container}>
<Text style={styles.header}>Sign In</Text>
<View>
<CustomTextInput placeholder="Email" />
<CustomTextInput secureTextEntry={true} placeholder="Password" />
<CustomButton
backgroundColor="#af2e1c"
color="#ffffff"
height={50}
width={280}
style={{ marginLeft: 10 }}
onPress={() => props.navigation.navigate("Home")}
>
Sign In
</CustomButton>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
justifyContent: "center",
flex: 1,
backgroundColor: "#161616",
padding: 30,
},
header: {
color: "#ffffff",
fontSize: 36,
marginLeft: 10,
marginBottom: 15,
},
});
export default Login;
|
let Joi = require('joi')
Joi.objectId = require('joi-objectid')(Joi)
class tweetValidator {
constructor() {}
get wordCloud() {
return {
query: Joi.object().keys({
type: Joi.string().required()
}).unknown(false)
}
}
get sunBurst() {
return {
query: Joi.object().keys({
type: Joi.string().required(),
start: Joi.string().required(),
stop: Joi.string().required()
}).unknown(false)
}
}
get heatMap() {
return {
query: Joi.object().keys({
start: Joi.string().required(),
stop: Joi.string().required()
})
}
}
get mentions() {
return {
query: Joi.object().keys({
start: Joi.string().required(),
stop: Joi.string().required()
})
}
}
get hashtags() {
return {
query: Joi.object().keys({
start: Joi.string().required(),
stop: Joi.string().required()
})
}
}
}
module.exports = new tweetValidator() |
const {Schema, model} = require('mongoose')
const Categories = new Schema({
name: {
type: String,
required: true
},
img: {
type: String,
required: true
},
description: {
type: String,
required: false
},
records: {
type: Number,
default: 0,
required: false
},
child:{
type: Array,
default: []
},
parent:{
type: String,
default: ''
}
})
module.exports = model('Categories',Categories) |
import Vue from 'vue'
import Router from 'vue-router'
import Loginwindow from '@/components/common/Signin_login'
import HelloWorld from '@/components/pages/HelloWorld'
import FindDirection from '@/components/pages/FindDirection'
import ReadPaper from '@/components/pages/ReadPaper'
import ArticleDetail from '@/components/pages/ArticleDetail'
import Contribute from '@/components/pages/Contribute'
import KeywordDetail from '@/components/pages/KeywordDetail'
import JournaDetail from '@/components/pages/JournaDetail'
import OrgDetail from '@/components/pages/OrgDetail'
import Rank from '@/components/pages/Rank'
import FirstSignin from '@/components/pages/FirstSignin'
import PersonalDateEdit from '@/components/pages/PersonalDateEdit'
import AuthorHomePage from '@/components/pages/AuthorHomePage'
import Email from '@/components/pages/Email'
import Search from '@/components/pages/Search'
import Author from '@/components/pages/Author'
import Test from '@/components/pages/Test'
import TestWordClound from '@/components/test/TestWordClound'
Vue.use(Router)
export default new Router({
routes: [
{path: '/',name: 'Main',component: HelloWorld,meta: {requiresAuth: true}},
{path:'/findDirection',name:'FindDirection',component:FindDirection,meta: {requiresAuth: true}},
{path:'/readPaper',name:'ReadPaper',component:ReadPaper},
{path:'/login',name:'Login',component:Loginwindow},
{path:'/articleDetail',name:'ArticleDetail',component:ArticleDetail},
{path:'/contribute',name:'Contribute',component:Contribute},
{path:'/keywordDetail',name:'KeywordDetail',component:KeywordDetail},
{path:'/journaDetail',name:'JournaDetail',component:JournaDetail},
{path:'/orgDetail',name:'OrgDetail',component:OrgDetail},
{path:'/rank',name:'Rank',component:Rank},
{path:'/firstSignin',name:'FirstSignin',component:FirstSignin},
{path:'/personalDateEdit',name:'PersonalDateEdit',component:PersonalDateEdit},
{path:'/authorHomePage',name:'AuthorHomePage',component:AuthorHomePage},
{path:'/email',name:'Email',component:Email},
{path:'/search',name:'Search',component:Search},
{path:'/test',name:'Test',component:Test},
{path:'/author',name:"author",component:Author},
{path:'/testWordClound',name:'TestWordClound',component:TestWordClound},
]
})
|
const assert = require('assert')
// const mocha = require('mocha')
const app = require('../../src/app')
let user
process.env.NODE_ENV = 'test'
describe('\'users\' service', () => {
it('registered the service', () => {
const service = app.service('users')
assert.ok(service, 'Registered the service')
})
it('Can create a new user', async () => {
const data = {
displayName: 'John Smith',
email: `t${~~(Math.random() * 10000000)}est${~~(Math.random() * 10000000)}@test.com`,
addresses: [{
streetNumber: ~~((Math.random() * 50000000)),
suite: '12a',
street: 'St Johns',
city: 'Montreal',
province: 'QC',
postalCode: 'H4H 2G4',
country: 'Canada'
}]
}
user = await app.service('users').create(data)
assert(user._id)
})
it('Can find user by street number', async () => {
const result = await app.service('users').find({
query: {
'addresses.streetNumber': user.addresses[0].streetNumber
}
})
assert(result.data[0]._id.toString() === user._id.toString())
})
it('Can change user country', async () => {
const result = await app.service('users').patch(user._id, {
addresses: {
...user.addresses[0],
country: 'United States'
}
})
assert(result.addresses[0].country === 'United States')
})
it('Only GET/PATCH the profile of the logged in user', async () => {
const data = {
displayName: 'New Smith',
email: `test${~~(Math.random() * 1000)}@test.com`
}
const newUser = await app.service('users').create(data)
const result = await app.service('users').get(newUser._id, {
user
})
assert(result._id.toString() === user._id.toString())
const patchedResult = await app.service('users').patch(newUser._id, {
displayName: 'Tried To Hack'
}, { user })
const updatedUser = await app.service('users').get(user._id)
const updatedNewUser = await app.service('users').get(newUser._id)
assert(patchedResult._id.toString() === updatedUser._id.toString())
assert(updatedNewUser.displayName === 'New Smith')
assert(updatedUser.displayName === 'Tried To Hack')
})
it('Can delete the user', async () => {
await app.service('users').remove(user._id)
const TryToFindUserShouldFail = await app.service('users').find({
query: {
_id: user._id
}
})
assert(TryToFindUserShouldFail.total === 0)
})
})
|
import sTheme from "../../src/styledTheme";
import { NextSeo } from "next-seo";
import { makeStyles } from "@material-ui/core/styles";
import sizes from "../../src/sizes";
import {
faStarOfLife,
faTooth,
faCalendarCheck,
faCalendarAlt,
faHeartbeat,
faHeart as faHeartFull
} from "@fortawesome/free-solid-svg-icons";
import { faHeart } from "@fortawesome/free-regular-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import CostCalculator from "../../components/CostCalculator";
import Button from "@material-ui/core/Button";
import clsx from "clsx";
import Form from "../../components/Form";
import DentalImplantsInIstanbul from "../../components/DentalImplantsInIstanbul";
import WhyChooseIsc from "../../components/WhyChooseIsc";
import HowAreWeAffordable from "../../components/HowAreWeAffordable";
import Layout from "../../components/Layout";
const useStyles = makeStyles((theme) => ({
fontAwesomeIcon: {
fontSize: "3rem",
marginRight: ".5rem",
color: theme.palette.third.dark,
[sizes.down("lg")]: {
fontSize: "2.8rem"
},
[sizes.down("md")]: {
fontSize: "2.5rem"
}
},
fontAwesomeIconCheck: {
fontSize: "2.5rem",
position: "relative",
top: "3px",
marginRight: "1rem",
[sizes.down("lg")]: {
fontSize: "2.3rem"
},
[sizes.down("md")]: {
fontSize: "2rem"
}
},
regularButton: {
borderRadius: "20px",
fontSize: "1.5rem",
backgroundColor: theme.palette.third.dark,
letterSpacing: "1px",
padding: "10px 25px",
position: "relative",
zIndex: 100,
fontWeight: "bold",
"&::before": {
borderRadius: "inherit",
content: "close-quote",
backgroundImage:
"linear-gradient(to right, rgba(26,59,112,1) 0%, rgba(40,85,130,1) 52%, rgba(0,164,189,1) 100%)",
position: "absolute",
top: 0,
left: 0,
opacity: 0,
width: "100%",
height: "100%",
zIndex: -100,
transition: "opacity 250ms cubic-bezier(0.4, 0, 0.2, 1) 0ms",
display: "block"
},
"&:hover": {
// backgroundColor: theme.palette.primary.main,
// background:
// "linear-gradient(to right, rgba(26,59,112,1) 0%, rgba(40,85,130,1) 52%, rgba(0,164,189,1) 100%)",
"&::before": {
opacity: 1
},
color: theme.palette.secondary.main
}
},
pricesButton: {
marginRight: "auto",
marginLeft: "50%",
transform: "translateX(-50%)",
padding: "1rem 6rem"
}
}));
const treatmentTemplate = (props) => {
const classes = useStyles();
const handleChat = () => {
if (typeof Tawk_API !== "undefined") {
Tawk_API.maximize();
}
};
const { open, handleCallbackClose, handleCallbackOpen } = props;
return (
<Layout openCallback={open} handleCallbackOpen={handleCallbackOpen} handleCallbackClose={handleCallbackClose}>
<NextSeo
title="Dental Implants in Istanbul, Turkey - Dental Cost Calculator | Istanbul Smile Center"
description="Calculate your dental implant cost with our dental cost calculator. We provide high quality and affordable dental implant treatments. Learn more about our easy dental implant treatment process."
openGraph={{
url: "https://www.istanbulsmilecenter.co/dental-implants",
title: "Dental Implants in Istanbul, Turkey - Dental Cost Calculator | Istanbul Smile Center",
description:
"Calculate your dental implant cost with our dental cost calculator. We provide high quality and affordable dental implant treatments. Learn more about our easy dental implant treatment process."
}}
/>
<section className="treatment-img-section">
<div className="treatment-img-div" />
</section>
<section className="treatment-section">
<div className="treatment-header">
<h1 className="treatment-header-text">Dental Implants</h1>
</div>
<section className="treatment-paragraph-section">
<DentalImplantsInIstanbul treatmentName="Dental Implants" />
</section>
<section className="treatment-paragraph-section">
<WhyChooseIsc treatmentName="implant" />
</section>
<section className="our-prices-section cost-calculator-section">
<div className="our-prices-header">
<h2 className="our-prices-header-text">Dental Cost Calculator</h2>
<p className="our-prices-header-paragraph-text">
We even provide you a cost calculator to calculate the dental cost by yourself for your
convenience. If you got your teeth checked up by a doctor and know your exact treatment
needs or you need an estimated cost, feel free to use our calculator.
</p>
</div>
<div className="cost-calculator-wrapper">
<CostCalculator />
</div>
<div className="dental-treatments-buttons-div">
<Button
variant="contained"
color="primary"
className={clsx(classes.regularButton, classes.pricesButton)}
onClick={handleChat}
>
Chat Now
</Button>
</div>
</section>
<section className="treatment-paragraph-section">
<div className="treatment-paragraph-img-div-div">
<div className="treatment-paragraph-img-div treatment-paragraph-img-3" />
</div>
<div className="treatment-general-text-div treatment-general-text-div-double treatment-general-text-div-double-extra ">
<div className="treatment-general-text-side-div">
<h2 className="treatment-paragraph-header">
<FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> What Are
Dental Implants?
</h2>
<p className="treatment-paragraph">
The implant can be referred to as the screw-like structure made of titanium. Usually,
the missing teeth are filled with implants. The treatment begins with engraving of the
jawbone in the area of the tooth. This is done in a very simple way. A suitable implant
is selected according to the size of the location and placed in this area. There is
nothing to be afraid of the placement process. Unless there are extreme conditions, the
screws will be placed in the jawbone within 10 minutes. Following implant placement and
healing period, the upper part is mounted with porcelain, E-max, or zirconium crowns.
</p>
</div>
<div className="treatment-general-text-side-div">
<h2 className="treatment-paragraph-header">
<FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faStarOfLife} /> Who Is
Suitable For Implant Treatment?
</h2>
<p className="treatment-paragraph">
The main reason for implant treatment is missing teeth. Bone tissue and structure should
be suitable for the treatment. If there is a weakness in the bone structure, bone
grafting is added to the area, and the structure is strengthened. This is very common.
In addition, implantation may be inconvenient if there are diseases or conditions such
as heart disease, diabetes, pregnancy, breastfeeding, hemophilia problems. Patients who
have health issues should consult their doctors before implant treatment. The patient is
expected to be able to tend to implant area after the procedure. Apart from these
exceptions, there is no circumstance to prevent dental implant treatment.
</p>
</div>
<div className="dental-treatments-buttons-div">
<Button
variant="contained"
color="primary"
className={clsx(classes.regularButton, classes.pricesButton)}
onClick={handleChat}
>
Chat Now
</Button>
</div>
</div>
</section>
<section className="treatment-paragraph-section">
<div className="treatment-paragraph-img-div-div">
<div className="treatment-paragraph-img-div treatment-paragraph-img-4" />
</div>
<div className="treatment-general-text-div">
<h2 className="treatment-paragraph-header">
<FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faTooth} /> Implant Brands We Use
</h2>
<p className="treatment-paragraph">
Implants should be very durable, comfortable, and aesthetic since they will be used for a
lifetime. In Istanbul Smile Center, our dentists use the best implant brands that are well
known and have worldwide use. Our implant brands are{" "}
<b> Straumann (Made in Switzerland ) </b> and <b> Hiossen (Made in the USA)</b>.
</p>
<div className="dental-treatments-buttons-div">
<Button
variant="contained"
color="primary"
className={clsx(classes.regularButton, classes.pricesButton)}
onClick={handleChat}
>
Chat Now
</Button>
</div>
</div>
</section>
<section className="treatment-paragraph-section">
<div className="treatment-general-text-div treatment-general-text-div-double treatment-general-text-div-multiple">
<h2 className="treatment-paragraph-header treatment-process-header">
<FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faCalendarCheck} /> Dental
Implant Treatment Process
</h2>
<div className="treatment-general-text-side-div">
<h2 className="treatment-paragraph-header">
<FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faCalendarAlt} /> 1)
Scheduling
</h2>
<p className="treatment-paragraph">
You can contact us through many channels, the fastest way is{" "}
<b> Live Chat and WhatsApp</b>, you can also send us a form or an email. Sending an
X-Ray image is crucial in pinpointing your treatment plan and cost. You can also request
a video call with a doctor. After the treatment plan is determined, our international
patients' department will be in contact with you to find the perfect date for your
treatment. There is no waiting period, we will schedule your appointment to the exact
date you request or maybe the next day but not further. We value our patient's time.
</p>
</div>
<div className="treatment-general-text-side-div">
<h2 className="treatment-paragraph-header">
<FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faHeartbeat} /> 2) Treatment
</h2>
<p className="treatment-paragraph">
On the day of your appointment with our clinic, you will be picked up by one of our
international patient coordinators right from your hotel. At the clinic, you will be
greeted by our doctors, and your treatment will start. Our doctor will initially examine
your teeth physically and take an X-Ray image. For implant patients, our doctors usually
request an MRI Image to be taken for perfect accuracy in implant locations. After the
tests, the diameter and length of the implant are selected, local anesthesia will be
applied, and the implant area will be prepared with dental burr. This process is not
painful and takes only 5-10 minutes per implant. Later, the implants will be placed, and
the upper sides of your gum will be stitched. After your treatment, you will be taken
back to your hotel.
</p>
</div>
<div className="treatment-general-text-side-div">
<h2 className="treatment-paragraph-header">
<FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faHeart} /> 3) Initial
Healing
</h2>
<p className="treatment-paragraph">
After the implants are placed, an average period of waiting is about 3 to 5 days. After
this period, stitches are removed. You can either stay here in Turkey and come back to
our clinic for stitch removal, or you can go back home and get the stitches removed by a
local dentist. But we usually suggest our patients to stay here and come back to the
clinic for a final check and stitch removal before you leave.
</p>
</div>
<div className="treatment-general-text-side-div">
<h2 className="treatment-paragraph-header">
<FontAwesomeIcon className={classes.fontAwesomeIcon} icon={faHeartFull} /> 4) Complete
Recovery
</h2>
<p className="treatment-paragraph">
Depending on your bone structure, age, and number of implants, you need to wait for 2 to
6 months to achieve complete recovery. This is crucial for the success of the treatment.
If there are specific conditions, this period may be reduced or increased. This period
must pass for the implant to bond with the bone to complete the healing process. After
recovery, you will need to come to our clinic for a second visit. In that visit, the
crowns are placed on the implants as the last stage of your treatment.
</p>
</div>
<div className="dental-treatments-buttons-div">
<Button
variant="contained"
color="primary"
className={clsx(classes.regularButton, classes.pricesButton)}
onClick={handleChat}
>
Chat Now
</Button>
</div>
</div>
</section>
<section className="treatment-paragraph-section">
<HowAreWeAffordable />
</section>
<section className="our-prices-section form-section">
<div className="our-prices-header">
<h2 className="our-prices-header-text">Get A Free Quote</h2>
<p className="our-prices-header-paragraph-text">
Contacting us through live chat or WhatsApp is always the fastest way, but you may prefer
sending us a good old form. Tell us your dental needs, and don't forget to attach at least
the pictures of your teeth to the form. If you have an X-Ray or CT Scan, it's even better
and crucial for most patients; this will help our doctors to make the right dental plan for
you. It will also help us in giving you a more accurate quote for your treatment. Go ahead
and fill out the form! Let's make your smile perfect!
</p>
</div>
<div className="form-wrapper">
<Form />
</div>
</section>
</section>
<style jsx>{`
.treatment-img-section {
width: 100%;
}
:global(.webp) .treatment-img-div {
background-image: url(${require("../../public/treatments/dental-implants-page/dental-implant-intro-background-img.webp")});
}
:global(.no-webp) .treatment-img-div {
background-image: url(${require("../../public/treatments/dental-implants-page/dental-implant-intro-background-img.jpg")});
}
.treatment-img-div {
width: 100%;
height: 66vh;
background-repeat: no-repeat;
background-size: cover;
background-position: left 37% bottom 80%;
clip-path: ellipse(100% 100% at 50% 0%);
}
.treatment-section {
display: flex;
align-items: center;
flex-direction: column;
padding: 2rem 1rem;
}
.treatment-header {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
width: 100%;
text-align: center;
}
.treatment-process-header {
width: 100%;
text-align: center;
margin-bottom: 1rem;
}
.treatment-header-text {
font-family: ${sTheme.typography.serif};
color: ${sTheme.palette.primary.main};
font-size: 4rem;
}
.treatment-paragraph-section {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
margin-top: 2rem;
}
.treatment-paragraph-img-div-div {
width: 65%;
}
.treatment-paragraph-img-div {
height: 300px;
border-top-left-radius: 20px;
border-top-right-radius: 20px;
background-repeat: no-repeat;
background-size: cover;
background-position: left 50% bottom 80%;
background-color: ${sTheme.palette.secondary.main};
}
:global(.webp) .treatment-paragraph-img-3 {
background-image: url(${require("../../public/treatments/dental-implants-page/dental-implant-img.webp")});
}
:global(.no-webp) .treatment-paragraph-img-3 {
background-image: url(${require("../../public/treatments/dental-implants-page/dental-implant-img.jpg")});
}
.treatment-paragraph-img-3 {
max-height: 750px;
height: 50vmax;
background-position: left 70% bottom 80%;
}
:global(.webp) .treatment-paragraph-img-4 {
background-image: url(${require("../../public/treatments/dental-implants-page/implant-brands-img.webp")});
}
:global(.no-webp) .treatment-paragraph-img-4 {
background-image: url(${require("../../public/treatments/dental-implants-page/implant-brands-img.jpg")});
}
.treatment-paragraph-img-4 {
height: 300px;
background-position: left 50% bottom 80%;
}
.treatment-general-text-div {
width: 65%;
border: 0px solid ${sTheme.palette.primary.main};
border-bottom-left-radius: 20px;
border-bottom-right-radius: 20px;
border-top: none;
padding: 3rem;
background-color: ${sTheme.palette.secondary.main};
margin-top: 0;
}
.treatment-general-text-div-double {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.treatment-general-text-div-double-extra {
align-items: center;
}
.treatment-general-text-div-multiple {
flex-wrap: wrap;
border-radius: 20px;
align-items: center;
}
.treatment-general-text-side-div {
width: 48%;
}
.treatment-paragraph-header {
font-size: 3rem;
color: ${sTheme.palette.primary.main};
font-family: ${sTheme.typography.serif};
}
.treatment-paragraph {
font-size: 2rem;
font-weight: normal;
margin-bottom: 1rem;
}
.our-prices-section {
display: flex;
justify-content: center;
flex-wrap: wrap;
margin-top: -5px;
padding-bottom: 4rem;
width: 100%;
}
.our-prices-header {
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
width: 100%;
text-align: center;
}
.our-prices-header-text {
font-family: ${sTheme.typography.serif};
color: ${sTheme.palette.primary.main};
font-size: 4rem;
}
.our-prices-header-paragraph-text {
color: ${sTheme.palette.secondary.dark};
font-size: 2rem;
width: 50%;
}
.cost-calculator-section {
margin-top: 2rem;
}
.cost-calculator-wrapper {
width: 70%;
}
@media (max-width: ${sizes.sizes.xl}) {
.cost-calculator-wrapper {
width: 80%;
}
}
@media (max-width: ${sizes.sizes.lg}) {
.cost-calculator-wrapper {
width: 90%;
}
}
@media (max-width: ${sizes.sizes.md}) {
.cost-calculator-wrapper {
width: 95%;
}
}
.dental-treatments-buttons-div {
display: flex;
justify-content: flex-start;
width: 100%;
align-items: baseline;
margin: 0 auto;
margin-top: 4rem;
}
.form-section {
margin-top: 2rem;
}
.form-wrapper {
width: 97%;
}
.guarantees-div {
margin: 1rem 0 2rem 0;
}
.guarantees-div .treatment-paragraph {
font-weight: bold;
color: ${sTheme.palette.primary.main};
}
@media (min-width: ${sizes.sizes.fullhd}) {
.treatment-paragraph-img-4 {
height: 400px;
}
}
@media (max-width: ${sizes.sizes.xl}) {
.treatment-paragraph-img-div-div,
.treatment-general-text-div {
width: 70%;
}
.our-prices-header-paragraph-text {
width: 60%;
}
}
@media (max-width: ${sizes.sizes.lg}) {
.treatment-img-div {
height: 60vh;
}
.treatment-paragraph-img-div-div,
.treatment-general-text-div {
width: 80%;
}
.our-prices-header-paragraph-text {
width: 70%;
font-size: 1.8rem;
}
.our-prices-header-text {
font-size: 3.5rem;
}
.treatment-header-text {
font-size: 3.5rem;
}
.treatment-paragraph-header {
font-size: 2.5rem;
}
.treatment-paragraph {
font-size: 1.8rem;
}
}
@media (max-width: ${sizes.sizes.md}) {
.treatment-img-div {
height: 50vh;
}
.treatment-paragraph-img-div-div,
.treatment-general-text-div {
width: 90%;
}
.our-prices-header-paragraph-text {
width: 80%;
font-size: 1.6rem;
}
.our-prices-header-text {
font-size: 3rem;
}
.treatment-header-text {
font-size: 3rem;
}
.treatment-paragraph-header {
font-size: 2.2rem;
}
.treatment-paragraph {
font-size: 1.6rem;
}
}
@media (max-width: ${sizes.sizes.mdsm}) {
.treatment-img-div {
height: 40vh;
}
.treatment-paragraph-img-div-div,
.treatment-general-text-div {
width: 100%;
}
.treatment-paragraph-img-1 {
height: 250px;
}
.treatment-paragraph-img-4 {
height: 250px;
}
}
@media (max-width: ${sizes.sizes.sm}) {
.treatment-img-div {
height: 30vh;
}
.treatment-general-text-div {
padding: 2.5rem;
}
.treatment-paragraph-img-4 {
height: 200px;
}
}
@media (max-width: ${sizes.sizes.xs}) {
.treatment-img-div {
height: 25vh;
}
.treatment-paragraph-img-1 {
height: 200px;
}
.treatment-general-text-side-div {
width: 100%;
}
.treatment-general-text-div-double-extra {
flex-wrap: wrap;
}
.treatment-general-text-div {
text-align: center;
}
.treatment-paragraph-img-4 {
height: 175px;
}
}
@media (max-width: ${sizes.sizes.xxs}) {
.treatment-general-text-div {
padding: 2rem;
}
.treatment-paragraph-img-4 {
height: 100px;
}
}
`}</style>
</Layout>
);
};
export default treatmentTemplate;
|
import React from 'react'
const Lazy = (<div>this is a lazy component</div>)
export default Lazy
|
function findDigits(n) {
let cnt = 0;
let divideArr = n.toString().split('');
while (divideArr.length > 0) {
let divider = divideArr.shift();
if (n % divider == 0) cnt++;
}
return cnt;
}
|
// pages/linkbt/linkbt.js
// const neededDeviceId = {
// // IOS
// 'CBEB0DFF-AA6F-8D25-3639-A9FAE9C5EF32': '图书管自习室1',
// '1645CF86-2EBA-A131-EDB9-3E1BD24DE6CD': '图书管自习室2',
// '336FA2B6-C8E8-F7AD-48E2-54BC1A3C51E8': '赵老板倾情赞助自习室',
// '88C731B9-BC35-1A9F-4ADE-8B649C10D466': '刘宇之父赞助自习室',
// '9A5F4FD7-3D12-09B2-EA56-C675DBD71C46': '刘宇之父赞助自习室2',
// '829C072F-96BB-0EEE-B3F3-30C5C313D244': '刘宇之二父赞助自习室',
// // Android
// // '': '图书管自习室1',
// // '': '图书管自习室2',
// // '': '赵老板倾情赞助自习室',
// 'E7:F6:2C:C7:7F:CD': '刘宇之父赞助自习室',
// 'EC:3C:8F:72:FC:1E': '刘宇之父赞助自习室2',
// 'C4:06:83:11:04:AF': '刘宇之二父赞助自习室',
// }
const neededServiceUUID = {
'00001812-0000-1000-8000-00805F9B34FB' : '刘宇之父赞助自习室',
'0000FEE0-0000-1000-8000-00805F9B34FB' : '赵老板倾情赞助自习室',
'00001812-0000-1000-8000-00805F9B34fB' : '刘宇之父赞助父爱自习室',
// '' : '',
}
function inArray(arr, key, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === val) {
return i
}
}
return -1
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function (bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join('')
}
const app = getApp()
let up=require('../updateinfor/updateInfor.js')
Page({
/**
* 页面的初始数据
*/
data: {
tableNum:[1,2,3,4,5,6,7], //这个存桌号
tableSelect:0, //选择的桌子号
devices: [],
chs: [],
appointmentNum:0,
leaveNum:0,
allinfor:[],
discoveryStarted: false,
connected: false,
haveConnected: false,
connectedSuccess: false,
connectedFail: false,
},
radioChange(e){
console.log(e)
var tmp=e.detail.value
this.data.tableSelect=parseInt(tmp)
this.setData({
tableSelect:this.data.tableSelect
})
app.data.tableSelect=parseInt(tmp)
},
// backToSeat : function(){
// setTimeout(function () {
// // 自动切换页面返回
// wx.switchTab({
// url : '../seat/seat',
// success : function() {
// console.log("SUCCESS: Tab linkbt to seat.")
// },
// fail : function() {
// console.log("FAIL: Tab linkbt to seat.")
// }
// })
// }, 500)
// },
Link:function(){
console.log(this.data)
console.log(app.data.userStatus)
if(app.data.userStatus==3){//未就坐
console.log("判断成功!")
console.log(app.data)
up.upseat(app.data.tableSelect)
console.log("操作完成!")
// this.backToSeat()
}else if(app.data.userStatus==2){//暂离
console.log("判断为暂离!")
const db = wx.cloud.database()
db.collection('seat').where({
openid:app.globalData.openid,
status:4
}).get({
success:function(res){
console.log(res)
up.updateSeatStatus(res.data[0].seatNum,2,"")
up.upUserStatus(1)
console.log(res)
}
})
// wx.showToast({
// title: '就坐'
// })
// this.backToSeat()
}else{
wx.showToast({
title: '就坐失败'
})
}
//up.querySeat()
//up.upUserStatus(1)//1:就坐 2:暂时离开 3:结束
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
console.log(app.globalData.openid)
const db = wx.cloud.database()
db.collection('seat').where({
status:3,
openid:app.globalData.openid
})
.get({
success: res => {
if(res.data.length==1){
this.setData({
appointmentNum:res.data[0].seatNum
})
}else{
appointmentNum:null
}
}
})
db.collection('seat').where({
status:4,
openid:app.globalData.openid
})
.get({
success: res => {
if(res.data.length==1){
this.setData({
leaveNum:res.data[0].seatNum
})
}else{
leaveNum:null
}
}
})
db.collection('seat').where({
})
.get({
success: res => {
console.log("list:")
console.log(res)
var list4=[]
var list5=[]
var i
if(res.data.length>0){
for(i=0;i<res.data.length;i++){
list4.push(res.data[i])
if(res.data[i].status==1){
list5.push(res.data[i].seatNum)
}
}
}
console.log("hello:")
console.log(list5)
this.setData({
allinfor:list4,
tableNum:list5
})
}
})
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
console.log(app.globalData.openid)
const db = wx.cloud.database()
db.collection('seat').where({
status:3,
openid:app.globalData.openid
})
.get({
success: res => {
if(res.data.length==1){
this.setData({
appointmentNum:res.data[0].seatNum
})
}else{
appointmentNum:null
}
}
})
db.collection('seat').where({
status:4,
openid:app.globalData.openid
})
.get({
success: res => {
if(res.data.length==1){
this.setData({
leaveNum:res.data[0].seatNum
})
}else{
leaveNum:null
}
}
})
db.collection('seat').where({
})
.get({
success: res => {
console.log("list:")
console.log(res)
var list4=[]
var i
if(res.data.length>0){
for(i=0;i<res.data.length;i++){
list4.push(res.data[i])
}
}
this.setData({
allinfor:list4
})
}
})
// console.log(app.globalData.openid)
// const db = wx.cloud.database()
// db.collection('seat').where({
// status:1
// })
// .get({
// success: res => {
// console.log("list:")
// console.log(res)
// var list=[]
// var i
// for(i=0;i<res.data.length;i++){
// list.push(res.data[i].seatNum)
// }
// this.setData({
// tableNum:list
// })
// wx.showToast({
// title: '获取空余座位成功!'
// })
// }
// })
// db.collection('seat').where({
// status:4
// })
// .get({
// success: res => {
// console.log("list1:")
// console.log(res)
// var list1=[]
// var i
// for(i=0;i<res.data.length;i++){
// list1.push(res.data[i].seatNum)
// }
// this.setData({
// liuyushabi_allleave:list1
// })
// wx.showToast({
// title: '获取暂离座位成功!'
// })
// }
// })
// db.collection('seat').where({
// status:3,
// openid:app.globalData.openid
// })
// .get({
// success: res => {
// console.log("list2:")
// console.log(res)
// var list2=[]
// var i
// for(i=0;i<res.data.length;i++){
// list2.push(res.data[i].seatNum)
// }
// this.setData({
// liuyuzhizhang_nowappoint:list2
// })
// wx.showToast({
// title: '获取暂离座位成功!'
// })
// }
// })
// db.collection('seat').where({
// status:4,
// openid:app.globalData.openid
// })
// .get({
// success: res => {
// console.log("list3:")
// console.log(res)
// var list3=[]
// var i
// if(res.data.length>0){
// for(i=0;i<res.data.length;i++){
// list3.push(res.data[i].seatNum)
// }
// }
// this.setData({
// liuyuchishi_nowleave:list3
// })
// wx.showToast({
// title: '获取暂离座位成功!'
// })
// }
// })
// db.collection('seat').where({
// })
// .get({
// success: res => {
// console.log("list3:")
// console.log(res)
// var list4=[]
// var i
// if(res.data.length>0){
// for(i=0;i<res.data.length;i++){
// list4.push(res.data[i])
// }
// }
// this.setData({
// liuyubeigan_allinfor:list4
// })
// wx.showToast({
// title: '获取暂离座位成功!'
// })
// }
// })
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
this.closeBluetoothAdapter()
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
},
successTipClose: function () {
this.setData({
connectedSuccess: false
})
},
failTipClose: function () {
this.setData({
connectedFail: false
})
},
openBluetoothAdapter() {
wx.openBluetoothAdapter({
success: (res) => {
console.log('openBluetoothAdapter success', res)
this.startBluetoothDevicesDiscovery()
},
fail: (res) => {
if (res.errCode === 10001) {
wx.showModal({
title: '错误',
content: '未找到蓝牙设备, 请打开蓝牙后重试。',
showCancel: false
})
wx.onBluetoothAdapterStateChange(function (res) {
console.log('onBluetoothAdapterStateChange', res)
if (res.available) {
this.startBluetoothDevicesDiscovery()
}
})
}
}
})
},
getBluetoothAdapterState() {
wx.getBluetoothAdapterState({
success: (res) => {
console.log('getBluetoothAdapterState', res)
if (res.discovering) {
this.onBluetoothDeviceFound()
} else if (res.available) {
this.startBluetoothDevicesDiscovery()
}
}
})
},
startBluetoothDevicesDiscovery() {
if (this._discoveryStarted) {
return
}
this._discoveryStarted = true
this.setData({
discoveryStarted : true
})
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
powerLevel: "high",
success: (res) => {
console.log('startBluetoothDevicesDiscovery success', res)
this.onBluetoothDeviceFound()
},
})
},
stopBluetoothDevicesDiscovery() {
wx.stopBluetoothDevicesDiscovery({
complete: () => {
this._discoveryStarted = false
this.setData({
discoveryStarted : false
})
}
})
},
onBluetoothDeviceFound() {
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach(device => {
if (!device.name && !device.localName) {
return
}
if (!(device.advertisServiceUUIDs in neededServiceUUID)) {
// console.log(device.name + ' UUID: ' + device.deviceId + ' SeID: ' + device.advertisServiceUUIDs, res)
console.log(device.name + ' ServiceUUID: ' + device.advertisServiceUUIDs, res)
}
else {
// console.log(device.name + ' SeID: ' + device.advertisServiceUUIDs, res)
device.name = neededServiceUUID[device.advertisServiceUUIDs]
// this.data.devices.name = neededServiceUUID[device.advertisServiceUUIDs]
const foundDevices = this.data.devices
const idx = inArray(foundDevices, 'deviceId', device.deviceId)
const data = {}
if (idx === -1) {
data[`devices[${foundDevices.length}]`] = device
} else {
data[`devices[${idx}]`] = device
}
this.setData(data)
}
})
})
},
createBLEConnection(e) {
const ds = e.currentTarget.dataset
const deviceId = ds.deviceId
const name = ds.name
wx.showLoading()
wx.createBLEConnection({
deviceId,
success: () => {
this.setData({
connected: true,
haveConnected: true,
connectedSuccess: true,
name,
deviceId,
})
// this.getBLEDeviceServices(deviceId)
this.closeBLEConnection()
this.closeBluetoothAdapter()
},
fail: () => {
this.setData({
connectedFail: true,
})
},
complete() {
wx.hideLoading()
}
})
this.stopBluetoothDevicesDiscovery()
},
closeBLEConnection() {
wx.closeBLEConnection({
deviceId: this.data.deviceId
})
this.setData({
connected: false,
chs: [],
canWrite: false,
})
},
getBLEDeviceServices(deviceId) {
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].isPrimary) {
this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
return
}
}
}
})
},
getBLEDeviceCharacteristics(deviceId, serviceId) {
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log('getBLEDeviceCharacteristics success', res.characteristics)
for (let i = 0; i < res.characteristics.length; i++) {
var item = res.characteristics[i]
if (item.properties.read) {
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
})
}
if (item.properties.write) {
this.setData({
canWrite: true
})
this._deviceId = deviceId
this._serviceId = serviceId
this._characteristicId = item.uuid
this.writeBLECharacteristicValue()
}
if (item.properties.notify || item.properties.indicate) {
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: item.uuid,
state: true,
})
}
}
},
fail(res) {
console.error('getBLEDeviceCharacteristics', res)
}
})
// 操作之前先监听,保证第一时间获取数据
wx.onBLECharacteristicValueChange((characteristic) => {
const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
const data = {}
if (idx === -1) {
data[`chs[${this.data.chs.length}]`] = {
uuid: characteristic.characteristicId,
value: ab2hex(characteristic.value)
}
} else {
data[`chs[${idx}]`] = {
uuid: characteristic.characteristicId,
value: ab2hex(characteristic.value)
}
}
// data[`chs[${this.data.chs.length}]`] = {
// uuid: characteristic.characteristicId,
// value: ab2hex(characteristic.value)
// }
this.setData(data)
})
},
writeBLECharacteristicValue() {
// 向蓝牙设备发送一个0x00的16进制数据
const buffer = new ArrayBuffer(1)
const dataView = new DataView(buffer)
// eslint-disable-next-line
dataView.setUint8(0, Math.random() * 255 | 0)
wx.writeBLECharacteristicValue({
deviceId: this._deviceId,
serviceId: this._deviceId,
characteristicId: this._characteristicId,
value: buffer,
})
},
closeBluetoothAdapter() {
wx.closeBluetoothAdapter()
this._discoveryStarted = false
this.setData({
discoveryStarted : false
})
},
}) |
function Queue() {
this.head = null
this.tail = null
}
function QueueNode(elt) {
this.elt = elt;
this.next = null;
this.prev = null;
}
Queue.prototype.push = function(elt) {
const n = new QueueNode(elt);
if (this.head === null) {
this.head = n;
this.tail = n;
} else {
this.tail.next = n;
this.tail = n;
}
}
Queue.prototype.poll = function(elt) {
if (this.head === null) { return null; }
const n = this.head;
this.head = this.head.next;
if (this.head === null) { this.tail = null; }
return n.elt;
}
Queue.prototype.empty = function() {
return this.head === null;
} |
var base_url = document.getElementById('base_url').innerHTML;
function show_message($icon, $title, $message){
Swal.fire({
icon: $icon,
html:
'<div class="col-12">'+
'<center>'+
'<strong>'+$title+'</strong><br>'+
'<small>'+$message+'</small>'+
'</center>'+
'</div>',
showCloseButton: false,
showCancelButton: false,
showConfirmButton: true
});
} |
const socket = io()
socket.on('connect', () => console.log(`Socket connected: ${socket.id}`));
socket.on('disconnect', () => console.log('disconnected'));
const boardState = [
['','',''],
['','',''],
['','','']
]
const drawBoard = (boardState) => {
document.querySelector('.board').innerHTML = `
<table>
<tr>
<td>${boardState[0][0]}</td>
<td>${boardState[0][1]}</td>
<td>${boardState[0][2]}</td>
</tr>
<tr>
<td>${boardState[1][0]}</td>
<td>${boardState[1][1]}</td>
<td>${boardState[1][2]}</td>
</tr>
<tr>
<td>${boardState[2][0]}</td>
<td>${boardState[2][1]}</td>
<td>${boardState[2][2]}</td>
</tr>
</table>
`
};
drawBoard(boardState)
let nextPlayer = 'X'
const board = document.querySelector('.board');
board.addEventListener('click', evt => {
const col = evt.target.cellIndex;
const row = evt.target.closest('tr').rowIndex;
if (boardState[row][col]) {
return console.log('cannot move there');
}
boardState[row][col] = nextPlayer;
nextPlayer = nextPlayer === 'X'? 'O' : 'X';
drawBoard(boardState)
}) |
import React from 'react';
import Choices from '../connectors/Choices';
import Toggles from '../connectors/Toggles';
import Character from '../connectors/Character';
import { CSSTransitionGroup } from 'react-transition-group';
class EncounterContainer extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
var encounter = this.props.user.encounter;
this.changeEncounter(encounter);
};
changeEncounter(id) {
fetch(`/api/v1/encounters/${id}`, {
credentials: 'same-origin',
method: 'GET',
headers: { 'Content-Type': 'application/json'},
})
.then(response => response.json())
.then(data => {
this.props.dispatch({type: 'CHANGE_ENCOUNTER', encounter: data, choices: data["choices"]})
});
};
updateUser(id){
let user = this.props.user;
let payload = {
user: user,
new_encounter: id
};
fetch(`/api/v1/users/${user.id}`, {
credentials: 'same-origin',
method: 'PATCH',
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify(payload)
})
};
handleClick(event) {
let id = this.props.encounter.id;
if (event.target.id == 'prev') {
id = id - 1
this.updateUser(id)
this.changeEncounter(id)
} else if (event.target.id == 'next') {
id = id + 1
this.updateUser(id)
this.changeEncounter(id)
};
};
render() {
let encounterText = this.props.encounter.body;
let encounterid = this.props.encounter.id;
let chapter = this.props.encounter.chapter;
return(
<div className="flex-container">
<div className="banner-container">
<h1>{chapter}</h1>
</div>
<CSSTransitionGroup
transitionName="encountertext"
transitionAppear={true}
transitionAppearTimeout={500}
transitionEnter={false}
transitionLeave={false}>
<div
key={1}
className="encounter-container">
<span>
{encounterText}
</span>
<Choices/>
</div>
</CSSTransitionGroup>
<div className="utility">
<button
onClick={this.handleClick}
className='hvr-back-pulse'
id='prev'>
Previous Page
</button>
<button
onClick={this.handleClick}
className='hvr-back-pulse'
id='next'>
Next Page
</button>
</div>
<Toggles />
</div>
);
};
};
export default EncounterContainer;
|
const counter = document.getElementById("counter"),
up = document.getElementById("+"),
down = document.getElementById("-"),
commentForm = document.getElementById("comment-form"),
controlButton = document.getElementById("pause"),
buttons = document.querySelectorAll("body > button:not(#pause)"),
likeButton = document.getElementById('<3'),
likeCount = {};
document.addEventListener("DOMContentLoaded", () => {
up.addEventListener("click", addValue);
down.addEventListener("click", subtractValue);
commentForm.addEventListener("submit", addComment);
controlButton.addEventListener("click", runApp);
likeButton.addEventListener("click", addLike);
runCounter();
}
)
function addValue(event) {
counter.innerText++
//counter.innerText = parseInt(counter.innerText)+1;
}
function subtractValue(event) {
counter.innerText--
// counter.innerText = parseInt(counter.innerText)-1;
}
function addComment(event) {
event.preventDefault();
const commentList = document.getElementById("form-input");
const comments = document.getElementById("list");
comments.innerHTML += `<li>${commentList.value}</li>`;
}
function addLike(event) {
likeCount[document.getElementById("counter").innerText] = likeCount[document.getElementById("counter").innerText]+1 || 1;
// console.log(likeCount)
const likeList = document.getElementById("likes");
likeList.innerHTML = ''; // reset list content
for (n in likeCount){
likeList.innerHTML += `<li>${n} has ${likeCount[n]} likes</li>`;
}
}
function runCounter() {
if (controlButton.innerText == "pause") {
counter.innerText = parseInt(counter.innerText)+1
}
setTimeout(runCounter, 1000);
}
function runApp(event) {
event.preventDefault();
if (controlButton.innerText == "pause") {
controlButton.innerText = "resume";
for (var i = 0; i <= buttons.length-1; i++) {
buttons[i].disabled=true;
}
} else {
controlButton.innerText = "pause";
for (var i = 0; i <= buttons.length-1; i++) {
buttons[i].disabled=false;
}
}
}
|
import axios from "axios";
export const config = {
apiUrl: "https://lambda-mud-test.herokuapp.com",
axiosWithAuth: function() {
return axios.create({
baseURL: this.apiUrl,
headers: {
Authorization: 'Token ${localStorage.getItem("authToken")}'
}
});
}
};
export default config; |
import React, { useRef } from 'react'
import { Link } from "gatsby"
import { CSSTransition } from 'react-transition-group'
import githubIcon from '../images/icon-github.png'
import linkedinIcon from '../images/icon-linkedin.png'
import emailIcon from '../images/icon-email.png'
const MenuSmall = (props) => {
const { appState, appDispatch, isVisible, toggleMenu } = props;
const ref = useRef();
const divStyle = {zIndex: "100", position: "absolute", top: "0", left: "0", height: "100vh", width: "100vw", backgroundColor: "rgba(255, 0, 0, 0.9)"};
const ulStyle = {padding: "15vh 0 25vh 0", height: "100vh", display: "flex", flexFlow: "column", justifyContent: "space-around", listStyle: "none"};
const liStyle = {margin: "auto", textAlign: "center"};
function handleClick() {
toggleMenu(prev => {
return !prev
})
}
return (
<CSSTransition nodeRef={ref} in={isVisible} timeout={500} classNames="menu-transition">
<div ref={ref} onClick={() => handleClick()} onKeyUp={e => {
if (e.key === "Escape") {
handleClick()
}
}} style={divStyle} className="menu-small" role="menu" tabIndex="0">
<nav style={{margin: "auto", width: "60%"}}>
<ul className="header__nav__list" style={ulStyle}>
<li className="header__nav__list-item" style={liStyle}>
<Link to="/" onClick={() => appDispatch({type: "setLocation", location: "/"})}>home</Link>
<span className={`${appState.location === "/" ? "animation--flash" : ""}`} style={appState.location === "/" ? {display: "inline-block", opacity: "1", color: "white"} : {opacity: "0"}}>_</span>
</li>
<li className="header__nav__list-item" style={liStyle}>
<Link to="/skills/" onClick={() => appDispatch({type: "setLocation", location: "/skills/"})}>skills</Link>
<span className={`${appState.location === "/skills/" ? "animation--flash" : ""}`} style={appState.location === "/skills/" ? {display: "inline-block", opacity: "1", color: "white"} : {opacity: "0"}}>_</span>
</li>
<li className="header__nav__list-item" style={liStyle}>
<Link to="/projects/" onClick={() => appDispatch({type: "setLocation", location: "/projects/"})}>projects</Link>
<span className={`${appState.location === "/projects/" ? "animation--flash" : ""}`} style={appState.location === "/projects/" ? {display: "inline-block", opacity: "1", color: "white"} : {opacity: "0"}}>_</span>
</li>
<li className="header__nav__list-item" style={liStyle}>
<Link to="/about/" onClick={() => appDispatch({type: "setLocation", location: "/about/"})}>about</Link>
<span className={`${appState.location === "/about/" ? "animation--flash" : ""}`} style={appState.location === "/about/" ? {display: "inline-block", opacity: "1", color: "white"} : {opacity: "0"}}>_</span>
</li>
<li className="header__nav__list-item" style={liStyle}>
<Link to="/contact/" onClick={() => appDispatch({type: "setLocation", location: "/contact/"})}>contact</Link>
<span className={`${appState.location === "/contact/" ? "animation--flash" : ""}`} style={appState.location === "/contact/" ? {display: "inline-block", opacity: "1", color: "white"} : {opacity: "0"}}>_</span>
</li>
<li className="header__nav__list-item header__nav__icons-container" style={liStyle}>
<a href="mailto:me@sandrofi.com" className=""><img src={emailIcon} alt="email" className="header__nav__icon header__nav__icon--email"/></a>
<a href="https://github.com/sandrofi84" target="_blank" rel="noreferrer" className=""><img src={githubIcon} alt="github" className="header__nav__icon"/></a>
<a href="https://www.linkedin.com/in/sandrofillinich/" target="_blank" rel="noreferrer" className=""><img src={linkedinIcon} alt="linkedin" className="header__nav__icon"/></a>
</li>
</ul>
</nav>
</div>
</CSSTransition>
)
}
export default MenuSmall
|
import { extend } from 'flarum/extend';
import app from 'flarum/app';
import Post from 'flarum/models/Post';
import Model from 'flarum/Model';
import NotificationGrid from 'flarum/components/NotificationGrid';
import PostRevisedNotification from './PostRevisedNotification';
import addSubscribeAction from './addSubscribeAction';
import addSubscribedIndicator from './addSubscribedIndicator';
app.initializers.add('flarum-post-subscriptions', () => {
Post.prototype.subscription = Model.attribute('subscription');
app.notificationComponents.postRevised = PostRevisedNotification;
addSubscribeAction();
addSubscribedIndicator();
extend(NotificationGrid.prototype, 'notificationTypes', function (items) {
items.add('postRevised', {
name: 'postRevised',
icon: 'far fa-star',
label: app.translator.trans('flarum-post-subscriptions.forum.settings.notify_post_revised_label')
});
});
});
|
import React, { Component } from 'react';
import { NavLink } from 'react-router-dom';
import Siema from 'siema';
import './Siema.css';
import Data from '../data';
/**
* Component: Slide
* Props: dataImage, dataTitle
*/
class Slide extends Component
{
render() {
return(
<div className="siema-slide">
<img src={this.props.dataImage} alt="" />
<div className="siema-caption">
<h4>
<NavLink to="post">
{this.props.dataTitle}
</NavLink>
</h4>
</div>
</div>
);
}
}
/**
* Component: Slider
*/
class Slider extends Component
{
constructor(props) {
super(props);
this.state = {
preparedSiema: null
};
}
componentWillMount() {
const dataSlides = Data.slides;
const preparedSiema = [];
dataSlides.forEach(function(item){
preparedSiema.push(<Slide dataImage={item.image} dataTitle={item.title} />);
});
this.setState({preparedSiema: preparedSiema});
}
componentDidMount() {
new Siema({
selector: '.siema-container',
duration: 200,
easing: 'ease-out',
perPage: 1,
startIndex: 0,
draggable: true,
multipleDrag: true,
threshold: 20,
loop: false
});
}
render() {
return (
<div className="siema-container">
{this.state.preparedSiema}
</div>
);
}
}
export {Slide, Slider};
|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*
* - Created on 2016-05-16.
*/
'use strict';
// external libs
const _ = require('lodash');
const Promise = require('bluebird');
// services
const LKE = require('../index');
const Scheduler = LKE.getScheduler();
const Utils = LKE.getUtils();
const Log = LKE.getLogger(__filename);
const Data = LKE.getData();
const Db = LKE.getSqlDb();
const Config = LKE.getConfig();
const Errors = LKE.getErrors();
// locals
const AlertDAO = require('./AlertDAO');
const ALERT_GROUP = 'alert';
const DEFAULT_NUMBER_OF_VIEWERS_IN_GET_MATCHES = 7;
/**
* It will delete old unconfirmed matches that lived beyond their expiration date.
*
* @returns {Bluebird<void>}
*/
function cleanUpOldMatches() {
return AlertDAO.cleanUpOldMatches();
}
class AlertService {
constructor() {
this._alertIdToSchedulerTaskId = new Map();
this._semaphores = new Map();
}
/**
* Format an alert instance to a public alert:
* - Add `nextRun` if `isAdmin` is true
*
* @param {AlertInstance} alertInstance
* @param {boolean} isAdmin
* @returns {PublicAlert}
* @private
*/
_formatToPublicAlert(alertInstance, isAdmin) {
const publicAlert = Db.models.alert.instanceToPublicAttributes(alertInstance);
if (isAdmin) {
const schedulerTaskId = this._alertIdToSchedulerTaskId.get(alertInstance.id);
// schedulerTaskId doesn't exist if the alert is not enabled or the alert service is not started
if (Utils.hasValue(schedulerTaskId)) {
const nextRun = new Date(Scheduler.getTimeToSchedule(
schedulerTaskId
));
const currentTime = new Date();
// nextRun can be a date of the past, e.g. if the scheduler failed or it has yet to schedule
if (nextRun < currentTime) {
// in that case, we set it as the current time
publicAlert.nextRun = currentTime;
} else {
publicAlert.nextRun = nextRun;
}
} else {
publicAlert.nextRun = null;
}
}
return publicAlert;
}
/**
* Format a match instance to a public match:
* - Create the `columns` property (if `columnsDescription` is defined)
* - Filter the `user` property
* - Create the `viewers` property
*
* @param {MatchInstance} matchInstance
* @param {Array<{type: string, columnName: string, columnTitle: string}>} [columnsDescription]
* @returns {PublicMatch}
* @private
*/
_formatToPublicMatch(matchInstance, columnsDescription) {
const publicMatch = Db.models.match.instanceToPublicAttributes(
matchInstance, columnsDescription
);
// 1) filter the `user` property
if (Utils.hasValue(matchInstance.user)) {
publicMatch.user = {
id: matchInstance.user.id,
username: matchInstance.user.username,
email: matchInstance.user.email
};
} else {
publicMatch.user = null;
}
if (Utils.noValue(matchInstance.matchActions)) {
publicMatch.viewers = [];
return /**@type {PublicMatch}*/ (publicMatch);
}
// 2) discover who are the viewers and their infos
// viewers are users who performed an "open" match action on the match
const viewerToDateMap = new Map();
const viewerToUserObject = new Map();
for (const action of matchInstance.matchActions) {
const previousTime = viewerToDateMap.get(action.userId);
if (Utils.noValue(previousTime) || previousTime < action.createdAt) {
viewerToDateMap.set(action.userId, action.createdAt);
}
if (!viewerToUserObject.has(action.userId)) {
viewerToUserObject.set(action.userId, {
id: action.user.id,
username: action.user.username,
email: action.user.email
});
}
}
// 3) sort viewers by date and limit the number of viewers
let viewerToDate = Array.from(viewerToDateMap.entries());
viewerToDate = _.orderBy(viewerToDate, item => item[1], ['desc']);
viewerToDate.slice(0, DEFAULT_NUMBER_OF_VIEWERS_IN_GET_MATCHES);
// 4) populate the match object with the viewers
publicMatch.viewers = _.map(viewerToDate, item => {
const viewer = viewerToUserObject.get(item[0]);
viewer.date = item[1];
return viewer;
});
return /**@type {PublicMatch}*/ (publicMatch);
}
/**
* Format a match action instance to a public match action:
* - Filter the `user` property
*
* @param {MatchActionInstance} matchActionInstance
* @returns {PublicMatchAction}
* @private
*/
_formatToPublicMatchAction(matchActionInstance) {
const publicMatchAction = Db.models.matchAction.instanceToPublicAttributes(matchActionInstance);
// 1) filter the `user` property
if (Utils.hasValue(matchActionInstance.user)) {
publicMatchAction.user = {
id: matchActionInstance.user.id,
username: matchActionInstance.user.username,
email: matchActionInstance.user.email
};
} else {
publicMatchAction.user = null;
}
return publicMatchAction;
}
/**
* Schedule all the alerts in the system.
* For each enabled alert, if lastRun is null, it will execute the query the next time compatible
* with `alert.cron`. If lastRun isn't null, it will check if it should have executed in the past.
* If true, it will execute the query immediately.
*/
start() {
try {
Scheduler.setGroupConcurrency(ALERT_GROUP, Config.get('alerts.maxConcurrency', 1));
// cleanup old matches everyday at 00:00 (local timezone)
Scheduler.scheduleTask(cleanUpOldMatches, '0 0 * * *', {group: ALERT_GROUP});
return AlertDAO.getAlerts(null, true).then(alerts => {
for (const alert of alerts) {
if (alert.enabled) {
const id = Scheduler.scheduleTask(
this.runAlert.bind(this, alert),
alert.cron,
{
group: ALERT_GROUP,
lastRun: alert.lastRun ? alert.lastRun : new Date(alert.createdAt)
}
);
this._alertIdToSchedulerTaskId.set(alert.id, id);
}
}
this._isAlertServiceStarted = true;
});
} catch(err) {
Log.error('The alert manager couldn\'t schedule the alert due to invalid arguments.');
}
}
/**
* Run the alert.
* It will query the db, generate the matches and update `alert.lastRun` to new Date().
*
* @param {AlertInstance} alert
* @returns {Bluebird<AlertRunProblem | null>} null, if there were no problems
*/
runAlert(alert) {
return Data.alertQuery({
dialect: alert.dialect,
query: alert.query,
sourceKey: alert.sourceKey,
limit: alert.maxMatches
}).then(queryMatchStream => {
/**
* If at least one match is created, partial will be set to true so that if we have a problem
* we know that it depends on some particular matches.
*/
return this.createMatchesInBulk(queryMatchStream, alert);
}).catch(err => {
if (err instanceof Promise.CancellationError) {
throw err;
}
Log.error('RunAlert: Could not create matches in bulk: ', err);
if (Utils.hasValue(err.message)) {
return {error: err.message, partial: false};
}
return {error: err, partial: false};
}).then(problem => {
// "problem" is null if there wasn't any problem
alert.lastRunProblem = problem;
alert.lastRun = new Date();
return alert.save().catch(err => {
if (!(err instanceof Promise.CancellationError)) {
Log.error(`RunAlert: Could not update alert #${alert.id} in the database.`, err);
}
}).return(problem);
});
}
/**
* AlertDAO.createMatchesInBulk under semaphore lock for the alert.
*
* @param {Readable<QueryMatch>} queryMatchStream
* @param {AlertInstance} alert
* @returns {Bluebird<AlertRunProblem | null>} null, if there were no problems
*/
createMatchesInBulk(queryMatchStream, alert) {
return this._acquireAlertSemaphore(alert.id).then(() => {
return AlertDAO.createMatchesInBulk(queryMatchStream, alert);
}).finally(() => this._releaseAlertSemaphore(alert.id));
}
/**
* Create a new alert and schedule its first run.
*
* @param {AlertAttributes} newAlert
* @param {WrappedUser} currentUser
* @returns {Bluebird<PublicAlert>}
*/
createAlert(newAlert, currentUser) {
return AlertDAO.createAlert(newAlert, currentUser).then(alert => {
if (alert.enabled && this._isAlertServiceStarted) {
const id = Scheduler.scheduleTask(
this.runAlert.bind(this, alert),
alert.cron,
{group: ALERT_GROUP, lastRun: new Date(0)} // new alerts will schedule immediately
);
this._alertIdToSchedulerTaskId.set(alert.id, id);
}
return this._formatToPublicAlert(alert, true);
});
}
/**
* Get all the alerts within a given source.
* Fields are masked for non-admin users if `allFields` is false.
*
* @param {string} sourceKey
* @param {boolean} allFields
* @param {WrappedUser} currentUser
* @returns {Bluebird<PublicAlert[]>}
*/
getAlerts(sourceKey, allFields, currentUser) {
Utils.check.exist('currentUser', currentUser);
return AlertDAO.getAlerts(sourceKey, allFields)
.map(alert => this._formatToPublicAlert(alert, allFields))
.filter(alert => currentUser.canReadAlert(sourceKey, alert.id, false));
}
/**
* Get an alert by id.
* Fields are masked for non-admin users if `allFields` is false.
*
* @param {string} sourceKey
* @param {number} alertId
* @param {boolean} allFields
* @param {WrappedUser} currentUser
* @returns {Bluebird<PublicAlert>}
*/
getAlert(sourceKey, alertId, allFields, currentUser) {
Utils.check.exist('currentUser', currentUser);
return currentUser.canReadAlert(sourceKey, alertId).then(() => {
return AlertDAO.getAlert(alertId, allFields);
}).then(alert => this._formatToPublicAlert(alert, allFields));
}
/**
* Create/acquire the semaphore for the given alert.
*
* @param {number} alertId
* @returns {Bluebird<void>} resolved when the slot is available
* @private
*/
_acquireAlertSemaphore(alertId) {
if (!this._semaphores.has(alertId)) {
this._semaphores.set(alertId, Utils.semaphore(1));
}
return this._semaphores.get(alertId).acquire();
}
/**
* Release/destroy the semaphore for the given alert.
*
* @param {number} alertId
* @private
*/
_releaseAlertSemaphore(alertId) {
const semaphore = this._semaphores.get(alertId);
semaphore.release();
if (semaphore.queue.length === 0 && semaphore.active === 0) {
this._semaphores.delete(alertId);
}
}
/**
* Delete an alert.
*
* @param {number} id
* @param {WrappedUser} currentUser
* @returns {Bluebird<void>}
*/
deleteAlert(id, currentUser) {
return this._acquireAlertSemaphore(id).then(() => {
Utils.check.exist('currentUser', currentUser);
const schedulerTaskId = this._alertIdToSchedulerTaskId.get(id);
// schedulerTaskId doesn't exist if the alert is not enabled or the alert service is not started
if (Utils.hasValue(schedulerTaskId)) {
Scheduler.cancel(schedulerTaskId);
}
return AlertDAO.deleteAlert(id).then(() => {
this._alertIdToSchedulerTaskId.delete(id);
});
}).finally(() => this._releaseAlertSemaphore(id));
}
/**
* Update an alert.
*
* id, sourceKey, userId, lastRun and lastRunProblem cannot be updated and will be silently
* ignored.
*
* @param {number} alertId
* @param {AlertAttributes} newProperties
* @param {WrappedUser} currentUser
* @returns {Bluebird<PublicAlert>}
*/
updateAlert(alertId, newProperties, currentUser) {
return this._acquireAlertSemaphore(alertId).then(() => {
Utils.check.exist('currentUser', currentUser);
return AlertDAO.updateAlert(alertId, newProperties).then(alert => {
// if the columns field was changed, all the matches and actions
// of the update alert are deleted and the alert, if enabled, rescheduled immediately
const needCleanAlert = Utils.hasValue(newProperties.columns);
// if the cron field was changed, we reschedule immediately
const needReschedule = Utils.hasValue(newProperties.cron);
return Promise.resolve().then(() => {
if (needCleanAlert) {
Log.info(`Update of alert #${alertId} required to delete all previous matches.`);
return AlertDAO.deleteMatchAndActions(alertId);
}
}).then(() => {
const schedulerTaskId = this._alertIdToSchedulerTaskId.get(alert.id);
// schedulerTaskId doesn't exist if the alert is not enabled or the alert service is not started
if (Utils.hasValue(schedulerTaskId)) {
Scheduler.cancel(schedulerTaskId);
}
if (alert.enabled) {
const id = Scheduler.scheduleTask(
this.runAlert.bind(this, alert),
alert.cron,
{
group: ALERT_GROUP,
lastRun: (needCleanAlert || needReschedule) ? new Date(0) : alert.lastRun
}
);
if (this._isAlertServiceStarted) {
this._alertIdToSchedulerTaskId.set(alert.id, id);
}
} else {
this._alertIdToSchedulerTaskId.delete(alert.id);
}
return this._formatToPublicAlert(alert, true);
});
});
}).finally(() => this._releaseAlertSemaphore(alertId));
}
/**
* Get all the matches for a given alert.
*
* All the matches have an addition field called 'viewers'.
* It shows the last `DEFAULT_NUMBER_OF_VIEWERS_IN_GET_MATCHES` unique viewers (excluding the
* current user) ordered by date.
*
* @param {string} sourceKey
* @param {number} alertId
* @param {object} options
* @param {string} [options.sortDirection]
* @param {string} [options.sortBy]
* @param {number} [options.offset=0]
* @param {number} [options.limit=20]
* @param {string} [options.status]
* @param {WrappedUser} currentUser
* @returns {Bluebird<PublicMatch[]>}
*/
getMatches(sourceKey, alertId, options, currentUser) {
Utils.check.exist('currentUser', currentUser);
let columnsDescription;
return currentUser.canReadAlert(sourceKey, alertId).then(() => {
return AlertDAO.getAlert(alertId, true).then(alert => {
columnsDescription = alert.columns;
});
}).then(() => {
return AlertDAO.getMatches(alertId, currentUser, options);
}).map(match => this._formatToPublicMatch(match, columnsDescription));
}
/**
* Get the count for each possible status of all the matches for a given alert.
*
* @param {string} sourceKey
* @param {number} alertId
* @param {WrappedUser} currentUser
* @returns {Bluebird<{unconfirmed: number, confirmed: number, dismissed: number}>}
*/
getMatchCount(sourceKey, alertId, currentUser) {
Utils.check.exist('currentUser', currentUser);
return currentUser.canReadAlert(sourceKey, alertId).then(() => {
return AlertDAO.getMatchCount(alertId);
});
}
/**
* @param {number} matchId
* @param {WrappedUser} currentUser
* @param {string} [sourceKey]
* @param {number} [alertId]
* @returns {Bluebird<MatchInstance>}
* @private
*/
_getMatch(matchId, currentUser, sourceKey, alertId) {
Utils.check.posInt('matchId', matchId);
Utils.check.exist('currentUser', currentUser);
return AlertDAO.getMatch(matchId, currentUser).then(match => {
if (Utils.hasValue(alertId) && alertId !== match.alertId) {
return Errors.business(
'invalid_parameter', `Match #${matchId} doesn't belong to alert #${alertId}.`, true
);
}
if (Utils.hasValue(sourceKey) && sourceKey !== match.sourceKey) {
return Errors.business(
'invalid_parameter',
`Match #${matchId} doesn't belong to data-source "${sourceKey}".`,
true
);
}
return currentUser.canReadAlert(match.sourceKey, match.alertId).return(match);
});
}
/**
* Get a match by id.
*
* @param {number} matchId
* @param {WrappedUser} currentUser
* @param {string} [sourceKey]
* @param {number} [alertId]
* @returns {Bluebird<PublicMatch>}
*/
getMatch(matchId, currentUser, sourceKey, alertId) {
let columnsDescription;
return Promise.resolve().then(() => {
if (Utils.hasValue(alertId)) {
return AlertDAO.getAlert(alertId, true).then(alert => {
columnsDescription = alert.columns;
});
} // else we don't populate the columns property in the match
// This case occurs in populate sandbox by match id (where the alert id is not immediately available)
}).then(() => {
return this._getMatch(matchId, currentUser, sourceKey, alertId);
}).then(match => this._formatToPublicMatch(match, columnsDescription));
}
/**
* Do an action on a match.
*
* @param {string} sourceKey
* @param {number} alertId
* @param {number} matchId
* @param {string} action
* @param {WrappedUser} currentUser
* @returns {Bluebird<void>}
*/
doMatchAction(sourceKey, alertId, matchId, action, currentUser) {
return this._getMatch(matchId, currentUser, sourceKey, alertId).then(match => {
return AlertDAO.doMatchAction(match, action, currentUser).return();
});
}
/**
* Get all the actions for a given match.
*
* @param {string} sourceKey
* @param {number} alertId
* @param {number} matchId
* @param {object} options
* @param {number} [options.offset=0]
* @param {number} [options.limit=20]
* @param {WrappedUser} currentUser
* @returns {Bluebird<PublicMatchAction[]>}
*/
getMatchActions(sourceKey, alertId, matchId, options, currentUser) {
/**
* _getMatch is used for access control.
* We need to retrieve the match to be sure that `alertId` is equal to `match.alertId`
*/
return this._getMatch(matchId, currentUser, sourceKey, alertId).then(() => {
return AlertDAO.getMatchActions(matchId, options)
.map(action => this._formatToPublicMatchAction(action));
});
}
/**
* Get the promise of the next execution of a given alert by id.
*
* @param {number} alertId
* @returns {Bluebird<void>}
*/
getPromise(alertId) {
return Scheduler.getPromise(this._alertIdToSchedulerTaskId.get(alertId)).return();
}
}
module.exports = new AlertService();
|
import React, { Component } from 'react';
import {
Text,
View,
ListView,
ScrollView,
StyleSheet,
Dimensions,
Alert,
NativeModules,
DeviceEventEmitter,
} from 'react-native';
import {
Icon,
List,
ListItem
} from 'react-native-elements';
import DeviceInfo from 'react-native-device-info';
import ProgressBar from './ProgressBar/index';
import { globalConfig } from '../config';
import { configData } from '../branding/index';
import I18n from '../i18n/index'
import RNFS from 'react-native-fs';
const { width, height } = Dimensions.get('window');
let RNUploader = NativeModules.RNUploader;
class SendInformation extends React.Component {
constructor(props){
super(props);
this.state = {
uploading: false,
uploadProgress: 0,
uploadTotal: 0,
uploadWritten: 0,
uploadStatus: undefined,
cancelled: false,
images: props.photopiker.photos,
};
this._uploadImages = this._uploadImages.bind(this);
}
componentDidMount() {
DeviceEventEmitter.addListener('RNUploaderProgress', (data) => {
let bytesWritten = data.totalBytesWritten;
let bytesTotal = data.totalBytesExpectedToWrite;
let progress = data.progress;
this.setState({uploadProgress: (progress / 100), uploadTotal: bytesTotal, uploadWritten: bytesWritten});
});
this._uploadImages()
}
// _clearUploadState() {§
// this.setState({ uploadProgress: 0, uploadTotal: 0, uploadWritten: 0, images: [], cancelled: false, });
// }
// _cancelUpload() {
// RNUploader.cancel();
// this.setState({uploading: false, cancelled: true});
// }
_uploadImages() {
// let files = this.state.images.map( (file) => {
// return {
// name: 'file',
// filename: _generateUUID + '.jpg',
// filepath: file.uri,
// filetype: 'image/jpeg',
// }
// });
let files = this.state.images.map( (file) => {
// return `data:image/jpeg;base64,${file.uri}`;
return `${file.uri}`;
});
// console.log('!!! files 0 ', files[0]);
let opts = {
url: globalConfig.BackendURL,
//files: files,
params: {
patname: this.props.photopiker.namePatient,
patnote: this.props.photopiker.comment,
os: `${DeviceInfo.getSystemName()} ${DeviceInfo.getVersion()}`,
device: `${DeviceInfo.getManufacturer()} ${DeviceInfo.getModel()}`,
deployType: process.env.NODE_ENV,
appversion: DeviceInfo.getVersion() ? DeviceInfo.getVersion() : globalConfig.version,
appinstanz: "",
appname: configData.App.appTitle,
appid: DeviceInfo.getBundleId() ? DeviceInfo.getBundleId() : configData.App.id,
theme: globalConfig.theme,
praxis_email: this.props.settings.practiceEmail,
praxis_ort: this.props.settings.practiceLocation,
praxis_name: this.props.settings.practiceName,
praxis_pin: configData.App.PRAXIS_PIN,
sw_bilderEmail: this.props.settings.getImagesByEmail,
img1: files[0],
img2: files[1],
img3: files[2],
img4: files[3],
}
};
this.setState({ uploading: true, });
RNUploader.upload(opts, (err, res) => {
if (err || res.status != 200) {
Alert.alert(
'FEHLER',
`Es ist folgender Fehler aufgetreten`,
[
{text: 'Ok', onPress: () => {
this.props.navigation.goBack();
}},
]
);
return;
}
let status = res.status;
let responseString = res.data;
// console.log('Upload complete with status ' + status);
// console.log(responseString);
this.setState({uploading: false, uploadStatus: status});
this.props.clearPhotos();
Alert.alert(
'Übertragung erfolgreich',
responseString,
[
{text: 'Ok', onPress: () => {
this.props.navigation.goBack();
}},
]
);
});
}
render() {
const { settings, photopiker }= this.props;
return (
<ScrollView>
<Text style={styles.Label}>
{I18n.t('UPLOAD_DATA_PATDATA')}
</Text>
<List>
<ListItem
title="Name"
rightTitle={photopiker.namePatient!== '' ? photopiker.namePatient.toString() : null}
hideChevron
/>
<ListItem
title={I18n.t('TF_COMMENT')}
rightTitle={photopiker.comment!== '' ? photopiker.comment.toString() : null}
hideChevron
/>
</List>
<Text style={styles.Label}>
{I18n.t('PRAXIS_SETTING')}
</Text>
<List>
<ListItem
title={I18n.t('PRAXIS_NAME')}
rightTitle={settings.practiceName!== '' ? settings.practiceName.toString() : null}
hideChevron
/>
<ListItem
title={I18n.t('UPLOAD_DATA_ORT')}
rightTitle={settings.practiceLocation!== '' ? settings.practiceLocation.toString() : null}
hideChevron
/>
<ListItem
title="Email"
rightTitle={settings.practiceEmail!== '' ? settings.practiceEmail.toString() : null}
hideChevron
/>
</List>
<Text style={styles.Label}>
Datenuebertragung
</Text>
<ProgressBar
fillStyle={{backgroundColor: '#00897b'}}
backgroundStyle={{backgroundColor: '#cccccc', borderRadius: 2}}
style={{marginTop: 10,marginLeft: 15, marginRight: 15, width: width-30 }}
progress={this.state.uploadProgress}
/>
<View style={styles.underBottom}>
<Text style={{ fontSize: 11, color: 'gray', marginTop: 5, }}>
{ ( this.state.uploadWritten / 1024 ).toFixed(0) }/{ ( this.state.uploadTotal / 1024 ).toFixed(0) } KB
</Text>
</View>
<View style={styles.underBottom}>
<Icon
style={{marginRight: 5,}}
name={'lock'}
type={'font-awesome'}
color={'#00897b'}
/>
<Text>
{I18n.t('SSL_CLAIM')}
</Text>
</View>
</ScrollView>
);
}
}
function _generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&0x3|0x8)).toString(16);
});
return uuid;
};
const styles = StyleSheet.create({
underBottom: {
marginTop: 10,
marginLeft: 20,
marginRight: 20,
marginBottom: 10,
flex: 1,
flexDirection: 'row',
justifyContent:'flex-start',
alignItems: 'center'
},
Label: {
fontSize: 20,
marginTop: 15,
marginLeft: 15
},
scrollView: {
},
container: {
flex: 1,
marginTop: 20,
},
separator: {
flex: 1,
height: 1,
backgroundColor: '#8E8E8E',
},
});
export default SendInformation;
|
CodeMirror.defineMode("htsql", function(conf) {
return {
startState: function() {
return { locator: 0 };
},
token: function(stream, state) {
if (stream.eatSpace()) {
return null;
}
if (state.locator) {
if (stream.match(/^(\[|\()/)) {
state.locator += 1;
return 'htsql-punctuation';
}
if (stream.match(/^(\]|\))/)) {
state.locator -= 1;
return 'htsql-punctuation';
}
if (stream.match(/^\./)) {
return 'htsql-punctuation';
}
if (stream.match(/^\'([^\']|\'\')*\'/)) {
return 'htsql-string';
}
if (stream.match(/^[0-9a-zA-Z_-]+/)) {
return 'htsql-string';
}
stream.next();
return null;
}
if (stream.match(/^:\s*[a-zA-Z_][0-9a-zA-Z_]*/)) {
return 'htsql-function';
}
if (stream.match(/^[a-zA-Z_][0-9a-zA-Z_]*/)) {
if (stream.match(/^\s*\(/, false)) {
return 'htsql-function';
}
return 'htsql-attribute';
}
if (stream.match(/^((\d*\.)?\d+[eE][+-]?\d+|\d*\.\d+|\d+\.?)/)) {
return 'htsql-number';
}
if (stream.match(/^\'([^\']|\'\')*\'/)) {
return 'htsql-string';
}
if (stream.match(/^(~|!~|<=|<|>=|>|==|=|!==|!=|!|&|\||->|\?|\^|\/|\*|\+|-)/)) {
return 'htsql-operator';
}
if (stream.match(/^(\.|,|\(|\)|\{|\}|:=|:|\$|@)/)) {
return 'htsql-punctuation';
}
if (stream.match(/^\[/)) {
state.locator += 1;
return 'htsql-punctuation';
}
if (stream.match(/^\#[^\r\n]*/)) {
return 'htsql-comment';
}
stream.next();
return null;
}
};
});
CodeMirror.defineMIME("text/x-htsql", "htsql");
|
class CarInsurance {
constructor(products = []) {
this.products = products;
}
stringByDay = (day, beforePrint = () => {}) => {
const { products } = this;
beforePrint();
return `${'\n'}-------- day ${day} --------${'\n'}name, sellIn, price${'\n'}${products
.map(product => `${product.toString()}`)
.join('\n')}`;
};
stringAll = days => {
const { products } = this;
let stringInit = this.stringByDay(0);
[...Array(days).keys()].forEach(day => {
stringInit = `${stringInit}${'\n'}${this.stringByDay(day + 1, () =>
products.forEach(product => product.handleDecrementDate()),
)}`;
});
return stringInit;
};
}
export default CarInsurance;
|
/*
* Copyright (c) 2013-2014 Tim Burgess. All rights reserved.
*
* @author Tim Burgess <info@tim-burgess.com>
* @license Tim Burgess 2014
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4,
maxerr: 50, node: true, white: true, evil: true */
/*globals HOST:true,PORT:true,USER:true,PWD:true,LOCALROOT:true,REMOTEROOT:true,ftp:true,emit:true,_domainManager:true,connect*/
var assert = require("assert"),
fs = require("fs"),
util = require("util"),
events = require("events"),
Connection = require("ssh2");
function MockDomainManager() {
this._eventCount = 0;
}
util.inherits(MockDomainManager, events.EventEmitter);
MockDomainManager.prototype.emitEvent = function(domainName, eventName, parameters) {
if (parameters)
console.log("[%s] %s", eventName, parameters);
else
console.log("[%s]", eventName);
// we need to emit events for test completion checking but
// emitting an error will cause it to be rethrown so we
// avoid if an error
if (eventName !== 'error')
this.emit(eventName);
++this._eventCount;
};
// load default settings
var defaultConfig = require('./config.sftp.json');
// load node-side
var ftpsync = require("../core.js");
// mock domainmanager for event capture
var _domainManager = new MockDomainManager();
// directory where ftp server puts you at login
var LOCALPREFIX = config.localprefix;
// where the remote root directory is located locally
// A directory named ftptest will be created here for testing
var LOCALPATH;
var PRIVATEKEYFILE = '/Users/tim/.ssh/id_rsa';
// override config with options and
// return an opts object for ssh2
function config(options) {
var opts = {
connect: 'SFTP',
host: defaultConfig.host,
port: 22,
user: defaultConfig.user,
pwd: defaultConfig.pwd
// debug: console.log
}
if (options) {
// TODO - better way to iterate thru properties
if (options.host) opts.host = options.host;
if (options.remoteRoot) opts.remoteRoot = options.remoteRoot;
if (options.username) opts.username = options.username;
if (options.password) opts.password = options.password;
if (options.pwd) opts.pwd = options.pwd;
if (options.privateKeyFile) opts.privateKeyFile = options.privateKeyFile;
}
return opts;
};
// accept an array of pathnames and sizes
// and confirm sizes of remote paths
function statSize(remotePaths, callback) {
var c = new Connection();
c.on('ready', function() {
c.sftp(function(err, sftp) {
for (var i=0; i < remotePaths.length; ++i) {
(function(i) {
sftp.stat(remotePaths[i][0], function(err, stats) {
assert.equal(remotePaths[i][1], stats.size,
'** '+remotePaths[i][0]+' is not size '+remotePaths[i][1]+', it is '+stats.size+' **');
// disconnect if final path check
if (i === remotePaths.length-1) {
c.end();
callback();
}
});
})(i);
}
});
});
c.connect(opts);
}
// execute command remotely
function exec(command, callback) {
var c = new Connection();
c.on('ready', function() {
c.exec(command, function(err, stream) {
if (err) throw err;
stream.on('exit', function(code, signal) {
c.end();
callback();
});
});
});
// no SFTP so pass ssh2 opts
var opts = config({ username: 'tim',
password: 'nishidaikoku' });
c.connect(opts);
}
// before each test, rm -rf ftptest
// describe('FTP-Sync', function() {
//
// beforeEach(function(done) {
// this.timeout(0);
// exec('rm -rf ftptest', function() {
// console.log('deleted remote ftptest dir');
// done();
// });
// });
// describe('SFTP test:', function() {
//
// // test password authentication
// it('password auth', function(done) {
//
// this.timeout(0);
// opts = config({ pwd: "nishidaikoku",
// remoteRoot: "ftptest/public_html" });
// localRoot = "./testdata/test1";
//
// exec('mkdir -p ' + opts.remoteRoot, function() {
// console.log('created remoteroot');
//
// ftpsync.connect(opts, localRoot, _domainManager);
// // wait for disconnect and then assert files exist
// _domainManager.once('disconnected', function() {
// done();
// });
// });
// });
// test key authentication
// it('key auth', function(done) {
//
// this.timeout(0);
// opts = config({ pwd: "nishidaikoku1",
// privateKeyFile: PRIVATEKEYFILE,
// remoteRoot: "ftptest/public_html" });
// localRoot = "./testdata/test1";
//
// exec('mkdir -p ' + opts.remoteRoot, function() {
// console.log('created remoteroot');
//
// ftpsync.connect(opts, localRoot, _domainManager);
// // wait for disconnect and then assert files exist
// _domainManager.once('disconnected', function() {
// done();
// });
// });
// });
// test bad keyfile passphrase
// it('bad password', function(done) {
// this.timeout(0);
// opts = config({ pwd: "badpwd",
// remoteRoot: "ftptest/public_html" });
// localRoot = "./testdata/test1";
//
// ftpsync.connect(opts, localRoot, _domainManager);
// _domainManager.once('error', function() {
// done();
// });
// });
// });
opts = config({ host: "localhost",
pwd: "puddlejump",
remoteRoot: "ftptest/public_html" });
localRoot = "./testdata/test1";
ftpsync.connect(opts, localRoot, _domainManager);
// // test file changes
// it('sync file changes', function(done) {
//
// this.timeout(0);
// opts.localRoot = "./testdata/test1";
// opts.remoteRoot = "ftptest/public_html";
//
// // create remote public_html dir
// exec('mkdir -p ' + opts.remoteRoot, function() {
// console.log('created remoteroot');
//
// ftpsync.connect(opts, _domainManager);
//
// // wait for disconnect and then assert files exist
// _domainManager.once('disconnected', function() {
// // assert remote file states
// var remotePaths = [[opts.remoteRoot + '/bin.py', 220],
// [opts.remoteRoot + '/index.html', 136],
// [opts.remoteRoot + '/re.py', 444]];
//
// statSize(remotePaths, function() {
// opts.localRoot = "./testdata/test1A";
// ftpsync.connect(opts, _domainManager);
//
// _domainManager.once('disconnected', function() {
//
// var remotePaths = [[opts.remoteRoot + '/bin.py', 220],
// [opts.remoteRoot + '/foo.html', 72],
// [opts.remoteRoot + '/index.html', 165],
// [opts.remoteRoot + '/re.py', 444]];
//
// // assert remote file state
// statSize(remotePaths, function() { done(); });
// });
// });
// });
// });
// });
//
// // test dir and file changes
// it('sync dir and file changes', function(done) {
// opts.localRoot = "./testdata/test2";
// opts.remoteRoot = "ftptest/public_html";
//
// // create public_html dir
// exec('mkdir -p ' + opts.remoteRoot, function() {
//
// ftpsync.connect(opts, _domainManager);
//
// // wait for disconnect and then assert files exist
// _domainManager.once('disconnected', function() {
//
// var remotePaths = [[opts.remoteRoot + '/bin.py', 220],
// [opts.remoteRoot + '/index.html', 136],
// [opts.remoteRoot + '/code/re.py', 444]];
//
// // assert file state
// statSize(remotePaths, function() { done(); });
// });
// });
// });
//
// // test sync to root
// it('sync directory structure to ftp root', function(done) {
// opts.localRoot = "./testdata/test3";
// opts.remoteRoot = ".";
//
// ftpsync.connect(opts, _domainManager);
//
// // wait for disconnect and then assert files exist
// _domainManager.once('disconnected', function() {
//
// var remotePaths = [['ftptest/application/cache/index.html', 136],
// ['ftptest/application/views/generix/bogus.php', 444],
// ['ftptest/application/views/generix/some_long_filename.php', 220]];
//
// // assert file state
// statSize(remotePaths, function() { done(); });
//
// // TODO - check for presence of subdirs
//// stats = fs.statSync(LOCALPATH + '/ftptest/application/cache');
//// assert(stats.isDirectory);
//// stats = fs.statSync(LOCALPATH + '/ftptest/application/views');
//// assert(stats.isDirectory);
//// stats = fs.statSync(LOCALPATH + '/ftptest/application/views/generix');
//// assert(stats.isDirectory);
// });
// });
//
// // test to remote root empty string
// it('sync directory structure to empty string root', function(done) {
// opts.localRoot = "./testdata/test3";
// opts.remoteRoot = "";
//
// ftpsync.connect(opts, _domainManager);
//
// // wait for disconnect and then assert files exist
// _domainManager.once('disconnected', function() {
//
// var remotePaths = [['ftptest/application/cache/index.html', 136],
// ['ftptest/application/views/generix/bogus.php', 444],
// ['ftptest/application/views/generix/some_long_filename.php', 220]];
//
// // assert file state
// statSize(remotePaths, function() { done(); });
//
// // TODO - check for presence of subdirs
// });
// });
//
// // test to remoteroot as null
// it('sync directory structure to null remoteroot', function(done) {
// opts.localRoot = "./testdata/test3";
// opts.remoteRoot = null;
//
// ftpsync.connect(opts, _domainManager);
//
// // wait for disconnect and then assert files exist
// _domainManager.once('disconnected', function() {
//
// var remotePaths = [['ftptest/application/cache/index.html', 136],
// ['ftptest/application/views/generix/bogus.php', 444],
// ['ftptest/application/views/generix/some_long_filename.php', 220]];
//
// // assert file state
// statSize(remotePaths, function() { done(); });
//
// // TODO - check for presence of subdirs
// });
// });
//
// // test to remoteroot as undefined
// it('sync directory structure to undefined remoteroot', function(done) {
// opts.localRoot = "./testdata/test3";
// opts.remoteRoot = undefined;
//
// ftpsync.connect(opts, _domainManager);
//
// // wait for disconnect and then assert files exist
// _domainManager.once('disconnected', function() {
//
// var remotePaths = [['ftptest/application/cache/index.html', 136],
// ['ftptest/application/views/generix/bogus.php', 444],
// ['ftptest/application/views/generix/some_long_filename.php', 220]];
//
// // assert file state
// statSize(remotePaths, function() { done(); });
//
// // TODO - check for presence of subdirs
// });
// });
// });
// });
|
import mongoose from "mongoose";
const RecipesSchema = new mongoose.Schema({
patient: { type: String, required: true },
doctor: { type: String, required: true },
date: { type: Date, required: true },
treatment: { type: String, required: true },
file: { type: String, required: false },
});
export default mongoose.model("Recipes", RecipesSchema);
|
import { connect } from 'react-redux';
import Categories from './CategoriesComponent';
// State of the Aplication
const mapStateToProps = (state, props) => {
const rootCategories = props.categories.getOrphan();
const newProps = { rootCategories };
return newProps;
}
// Actions of the application
const mapDispatchToProps = (dispatch) => {
return { };
}
const CategoriesContainer = connect(mapStateToProps,mapDispatchToProps)(Categories);
export default CategoriesContainer;
|
const {expect} = require('chai');
const compressHtml = require('../lib/compress-html');
const input = `
<!doctype html>
<html>
<head></head>
<body></body>
</html>
`;
describe('compressHtml()', () => {
it('compresses HTML', () => {
const output = compressHtml(input, '', {
compress: true
});
// The indentation should be removed from the output
expect(output).to.contain('<!doctype html>\n<html>\n<head>');
});
it('does not compress HTML if the `compress` option is `false`', () => {
const output = compressHtml(input, '', {
compress: false
});
// The indentation should be removed from the output
expect(output).to.contain('<!doctype html>\n<html>\n <head>');
});
});
|
export default async function convert(currency, value) {
const rawResponse = await fetch(`/exchange-rate`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
currency,
value
}),
});
return await rawResponse.json();
} |
import React from 'react';
import './App.css';
import './assets/font-awesome/css/font-awesome.min.css';
import { BrowserRouter as Router, Route } from "react-router-dom";
import Logo from './assets/images/logo.png';
import LogoSquare from './assets/images/logosquare.png';
import HomePage from './components/home';
import AboutPage from './components/about';
import Cartpage from './components/cart';
import Modal1 from './components/Modal1';
import { Container, Row, Col, Input } from 'reactstrap';
function App() {
function Home() {
return (
<div>
<HomePage />
</div>
);
}
function About() {
return (
<div>
<AboutPage />
</div>
);
}
return (
<div>
<Container fluid="True">
<Row style={{paddingTop:"1vh",paddingBottom:"1vh"}}>
<Col xs="12" sm="12" md="2" lg="2" xl="2" style={{display:"flex",justifyContent:"center",alignItems:"center"}}>
<img src={Logo} alt="Logo" style={{width:"100%"}}/>
</Col>
<Col xs="12" sm="12" md="7" lg="7" xl="7" style={{display:"flex",justifyContent:"center",alignItems:"center"}}>
<Input type="email" name="email" id="exampleEmail" placeholder="with a placeholder" />
</Col>
<Col xs="12" sm="12" md="3" lg="3" xl="3" style={{display:"flex",justifyContent:"center",alignItems:"center"}}>
<div style={{width:"100%"}}>
<Modal1 />
</div>
</Col>
</Row>
<Row className="MainWraper">
<Col xs="12" sm="12" md="12" lg="12" xl="12">
<Router>
<Route exact path="/" component={Cartpage} />
<Route path="/about" component={About} />
<Route path="/home" component={Home} />
</Router>
</Col>
</Row>
<Row>
<Col xs="2" sm="2" md="1" lg="1" xl="1" style={{display:"flex",justifyContent:"center",alignItems:"center"}}>
<img src={LogoSquare} alt="Logo" style={{width:"75%"}}/>
</Col>
<Col xs="10" sm="10" md="11" lg="11" xl="11" style={{display:"flex",justifyContent:"left",alignItems:"center"}}>
<p>Copyright © Footer 2014. All right reserved.</p>
</Col>
</Row>
</Container>
</div>
);
}
export default App;
|
module.exports = {
MONGODB: "mongodb+srv://Taylor:gX3jrHOwMmBFmxkI@cluster0.lfzeg.mongodb.net/merng?retryWrites=true&w=majority",
SECRET_KEY: "some-very-secret-key"
}; |
import styled from 'styled-components'
import {CardElement} from '@stripe/react-stripe-js'
export const Container = styled.section `
display: flex;
justify-content: center;
align-items: center;
width: 100%;
margin: 2em 0;
`
export const Inner = styled.div `
display: flex;
flex-direction: column;
width: 90%;
max-width: 1100px;
background-color: #303030;
border-radius: 10px;
color: white;
min-height: 70vh;
justify-content: space-between;
`
export const Title = styled.h1 `
font-size: 2rem;
letter-spacing: 1.6;
margin: 1em auto;
`
export const Item = styled.div `
display: flex;
box-sizing: border-box;
width: 90%;
justify-content: space-between;
margin: 1em auto;
background: #1c1c1c;
padding: .5em 1em;
flex-flow: row wrap;
border-radius: 10px;
@media (min-width: 1000px) {
width: 75%;
padding: 1em 2em;
}
`
export const ItemName = styled.h2 `
font-size: 1rem;
width: 50%;
text-align: left;
@media (min-width: 1000px) {
font-size: 1.5em;
}
`
export const ItemQuantity = styled.h2 `
font-size: 1rem;
width: 50%;
text-align: right;
@media (min-width: 1000px) {
font-size: 1.5em;
}
`
export const ItemPrice = styled.h2 `
font-size: 1rem;
width: 100%;
text-align: right;
@media (min-width: 1000px) {
font-size: 1.5em;
}
`
export const Form = styled.form `
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
width: 90%;
margin: 1em auto;
@media (min-width: 1000px) {
width: 75%;
}
`
export const CardInput = styled(CardElement) `
box-sizing: border-box;
color: white;
margin: 1em auto;
border: 1px solid #1c1c1c;
width: 95%;
padding: 1em;
`
export const Btn = styled.button `
width: 50%;
padding: .75em 2em;
color: white;
background-color: #eb8c2d;
border: none;
border-radius: 10px;
text-transform: uppercase;
letter-spacing: 1.6;
font-weight: 600;
margin: 1em auto;
text-decoration: none;
&:focus {
outline: none;
}
&:hover,:focus {
cursor: pointer;
background-color: #e87909;
}
@media (min-width: 1000px) {
width: 33%;
}
`
export const Input = styled.input `
box-sizing: border-box;
width: 95%;
margin: 1em auto;
padding: .75em 2em;
color: white;
background-color: #1c1c1c;
border: none;
&:focus {
box-shadow: 0 0 1pt 2pt #eb8c2d;
outline: none;
}
` |
const valor = 'String'
function minhaFuncao() {
console.log(valor)
}
function exec() {
const valor = 'Numeral'
minhaFuncao()
}
exec()
// retorna string
// a function busca dentro do escopo que ela foi definida
// não no local de execução
|
import Component from '@ember/component';
import { inject as service } from '@ember/service';
export default Component.extend({
classNames: ['gallery-view', 'grey', 'darken-4'],
websockets: service(),
store: service(),
socketRef: null,
didInsertElement() {
this._super(...arguments);
const socket = this.get('websockets').socketFor('ws://localhost:4567/gallery/');
socket.on('open', this.myOpenHandler, this);
socket.on('message', this.myMessageHandler, this);
socket.on('close', this.myCloseHandler, this);
this.set('socketRef', socket);
},
willDestroyElement() {
this._super(...arguments);
const socket = this.get('socketRef');
socket.off('open', this.myOpenHandler);
socket.off('message', this.myMessageHandler);
socket.off('close', this.myCloseHandler);
},
myOpenHandler(event) {
const socket = this.get('socketRef');
socket.send('parse_path');
},
myMessageHandler(event) {
let { name, description, type, size, uri, active } = JSON.parse(event.data);
if (active) {
this.get('store').push({
data: [{
id: name,
type: 'gallery-item',
attributes: {
name: name,
description: description,
type: type,
size: size,
uri: uri,
active: undefined
},
relationships: {}
}]
});
} else {
this.get('store').push({
data: [{
id: name,
type: 'gallery-item',
attributes: {
name: name,
description: description,
type: type,
size: size,
uri: uri,
},
relationships: {}
}]
});
}
},
myCloseHandler(event) {
console.log(`On close event has been called: ${event}`);
},
actions: {
galleryItemClick(galleryItem) {
this.get('galleryItemClick')(galleryItem);
},
galleryItemDoubleClick() {
this.get('galleryItemDoubleClick')();
}
}
});
|
const LogService = require("matrix-js-snippets").LogService;
const config = require("config");
LogService.configure(config["logging"]);
const sdk = require("matrix-js-sdk");
const Doge = require("./src/Doge");
const matrixUtils = require("matrix-js-snippets");
const client = sdk.createClient({
baseUrl: config['homeserverUrl'],
accessToken: config['accessToken'],
userId: config['userId']
});
matrixUtils.autoAcceptInvites(client);
Doge.start(client);
client.startClient({initialSyncLimit: 3}); |
import $ from 'jquery';
import gui from './module/gui';
import controller from './module/controller-webform';
import settings from './module/settings';
import connection from './module/connection';
import { init as initTranslator, t, localize } from './module/translator';
import utils from './module/utils';
const $loader = $( '.main-loader' );
const $formheader = $( '.main > .paper > .form-header' );
const survey = {
enketoId: settings.enketoId,
instanceId: settings.instanceId,
};
initTranslator( survey )
.then( survey => Promise.all( [
connection.getFormParts( survey ),
connection.getExistingInstance( survey )
] ) )
.then( responses => {
const formParts = responses[ 0 ];
formParts.instance = responses[ 1 ].instance;
formParts.instanceAttachments = responses[ 1 ].instanceAttachments;
if ( formParts.form && formParts.model && formParts.instance ) {
return gui.swapTheme( formParts );
} else {
throw new Error( t( 'error.unknown' ) );
}
} )
.then( _init )
.then( connection.getMaximumSubmissionSize )
.then( _updateMaxSizeSetting )
.catch( _showErrorOrAuthenticate );
function _updateMaxSizeSetting( maxSize ) {
if ( maxSize ) {
// overwrite default max size
settings.maxSize = maxSize;
$( 'form.or' ).trigger( 'updateMaxSize' );
}
}
function _showErrorOrAuthenticate( error ) {
$loader.addClass( 'fail' );
if ( error.status === 401 ) {
window.location.href = `${settings.loginUrl}?return_url=${encodeURIComponent( window.location.href )}`;
} else {
gui.alert( error.message, t( 'alert.loaderror.heading' ) );
}
}
function _init( formParts ) {
$formheader.after( formParts.form );
localize( document.querySelector( 'form.or' ) );
$( document ).ready( () => {
controller.init( 'form.or:eq(0)', {
modelStr: formParts.model,
instanceStr: formParts.instance,
external: formParts.externalData,
instanceAttachments: formParts.instanceAttachments,
} ).then( () => {
$( 'head>title' ).text( utils.getTitleFromFormStr( formParts.form ) );
} );
} );
}
|
'use strict';
const path = require('path');
const fs = require('fs');
const mm = require('mm');
const assert = require('assert');
const FileLoader = require('../');
describe('fileloader.test.js', () => {
const fixtures = path.join(__dirname, 'fixtures');
const dirs = [
path.join(fixtures, 'dir1'),
path.join(fixtures, 'dir2'),
];
const charsets = {};
charsets[dirs[1]] = 'gbk';
const loader = new FileLoader(dirs, true, charsets);
afterEach(mm.restore);
it('should get change file dir1', done => {
let info = loader.getSource('foo.txt');
const filepath = path.join(dirs[0], 'foo.txt');
assert(info.path === filepath);
assert(info.src === 'bar\n');
loader.once('update', function(name) {
assert(name === 'foo.txt');
done();
});
fs.writeFileSync(filepath, 'bar change');
info = loader.getSource('foo.txt');
assert(info.path === filepath);
assert(info.src === 'bar change');
fs.writeFileSync(filepath, 'bar\n');
});
it('should get change file dir1/subdir1/subdirfile.txt', done => {
let info = loader.getSource('subdir1/subdirfile.txt');
const filepath = path.join(dirs[0], 'subdir1', 'subdirfile.txt');
assert(info.path === filepath);
assert(info.src === 'subfile\n');
loader.once('update', function(name) {
assert(name === 'subdir1/subdirfile.txt');
done();
});
fs.writeFileSync(filepath, 'subfile change');
info = loader.getSource('subdir1/subdirfile.txt');
assert(info.path === filepath);
assert(info.src === 'subfile change');
fs.writeFileSync(filepath, 'subfile\n');
});
it('should get change file and decode gbk charset content', done => {
const filepath = path.join(dirs[1], 'dir2file.txt');
const orginal = fs.readFileSync(filepath);
let info = loader.getSource('dir2file.txt');
assert(info.path === filepath);
assert(info.src.includes('知道'));
loader.once('update', name => {
assert(name === 'dir2file.txt');
done();
});
fs.writeFileSync(filepath, 'gbk change');
info = loader.getSource('dir2file.txt');
assert(info.path === filepath);
assert(info.src === 'gbk change');
fs.writeFileSync(filepath, orginal);
});
it('should return null when view not exists', () => {
assert(!loader.getSource('not-exists.txt'));
});
it('should work with upper case charset', () => {
const cs = {};
cs[path.join(dirs[0], 'subdir1')] = 'UTF-8';
cs[dirs[0]] = 'UTF8';
cs[dirs[1]] = 'GBK';
const loader = new FileLoader([ dirs[0], dirs[1], path.join(dirs[0], 'subdir1') ], false, cs);
let info = loader.getSource('dir2file.txt');
assert(info.src.includes('知道'));
info = loader.getSource('foo.txt');
assert(info.src === 'bar\n');
info = loader.getSource('subdirfile.txt');
assert(info.src === 'subfile\n');
});
it('should get from current dir when dirs param missing', () => {
mm(process, 'cwd', () => {
return dirs[0];
});
const loader = new FileLoader();
const info = loader.getSource('foo.txt');
assert(info.src === 'bar\n');
});
it('should support dirs as string', () => {
const loader = new FileLoader(dirs[0]);
const info = loader.getSource('foo.txt');
assert(info.src === 'bar\n');
});
it('should support custom watch', done => {
let cb;
function watch(dirs, listener) {
cb = listener;
}
const loader = new FileLoader(dirs, watch);
let info = loader.getSource('foo.txt');
assert(info.src === 'bar\n');
info = loader.getSource('subdir1/subdirfile.txt');
const filepath = path.join(dirs[0], 'subdir1', 'subdirfile.txt');
assert(info.path === filepath);
assert(info.src === 'subfile\n');
loader.once('update', function(name) {
assert(name === 'subdir1/subdirfile.txt');
done();
});
setTimeout(() => {
cb({ path: path.join(dirs[0], 'subdir1', 'subdirfile.txt') });
}, 10);
});
it('should support fullpath', () => {
let filepath = path.join(dirs[0], 'foo.txt');
let info = loader.getSource(filepath);
assert(info.path === filepath);
assert(info.src === 'bar\n');
info = loader.getSource('/foo.txt');
assert(info.path === filepath);
info = loader.getSource('/home');
assert(info.path === path.join(dirs[0], 'home'));
filepath = path.join(dirs[0], 'noexist.txt');
info = loader.getSource(filepath);
assert(info === null);
filepath = path.join(dirs[1], 'dir2file.txt');
info = loader.getSource(filepath);
assert(info.path === filepath);
assert(info.src.includes('知道'));
});
});
|
$(document).ready(function(){
// your jQuery codes will go here
$("img").click( function(){
$(this).parent().css("height","104px");
$(this).parent().css("width","104px");
$(this).fadeOut();
});
$("button").click( function(){
$("img").fadeIn();
});
}); |
const gulp = require('gulp');
const message = require('./lib/message');
const browsersync = require('browser-sync').create();
/*
|--------------------------------------------------------------------------
| Control tasks
|--------------------------------------------------------------------------
|
| Here is a collection of control task used to work with Gulp tasks.
*/
gulp.task('dev', [ 'sync', 'watch' ]);
gulp.task('build', [ 'env:prod', 'scss', 'html', 'image', 'javascript', 'font' ]);
/*
|--------------------------------------------------------------------------
| Watching Tasks
|--------------------------------------------------------------------------
|
| Here is a collection of watching tasks. They look for the files
| changes and runs building tasks. We're watching each domain
| and recompiling separetly for better performance.
|
*/
gulp.task('watch', [ 'env:dev' ], () => {
gulp.watch([ 'resources/assets/scss/**/*.scss' ], {}, [ 'scss:lint', 'scss:build' ]).on('error', message.error('WATCH: Styles build'));
gulp.watch([ 'resources/assets/scss/vendor.scss', 'resources/assets/scss/vendor/**/*.scss' ], {}, [ 'scss:lint', 'scss:vendor' ]).on('error', message.error('WATCH: Vendor Styles build'));
gulp.watch([ 'resources/views/**/*.njk', 'resources/data/**/*.json' ], {}, [ 'html:build' ]).on('error', () => { message.error('WATCH: Views'); this.emit('end') });
gulp.watch([ 'resources/assets/img/*.{jpg,jpeg,png,gif,svg}' ], {}, [ 'image:build' ]).on('error', () => { message.error('WATCH: Images'); this.emit('end') });
gulp.watch([ 'resources/assets/js/**/*.js' ], {}, [ 'javascript:lint', 'javascript:build' ]).on('error', () => { message.error('WATCH: Javascript'); this.emit('end') });
gulp.watch([ 'resources/assets/fonts/**/*.{eot,woff,woff2,ttf,svg}' ], {}, [ 'font:build' ]).on('error', () => { message.error('WATCH: Fonts'); this.emit('end') });
});
// Tasks are using `NODE_ENV` variable to adjust its settings
// to working enviourment. It is required to propertly
// run tasks so we cant process without it.
gulp.task('env:dev', () => {
return process.env.NODE_ENV = 'development';
});
gulp.task('env:prod', () => {
return process.env.NODE_ENV = 'production';
});
/*
|--------------------------------------------------------------------------
| SCSS Tasks
|--------------------------------------------------------------------------
*/
gulp.task('scss:lint', require('./tasks/scss/lint'));
gulp.task('scss:build', require('./tasks/scss/build'));
gulp.task('scss:vendor', require('./tasks/scss/vendor'));
/*
|--------------------------------------------------------------------------
| HTML Tasks
|--------------------------------------------------------------------------
*/
gulp.task('html:clean', require('./tasks/html/clean'));
gulp.task('html:build', require('./tasks/html/build'));
/*
|--------------------------------------------------------------------------
| Fonts Tasks
|--------------------------------------------------------------------------
*/
gulp.task('font:clean', require('./tasks/font/clean'));
gulp.task('font:build', require('./tasks/font/build'));
/*
|--------------------------------------------------------------------------
| Images Tasks
|--------------------------------------------------------------------------
*/
gulp.task('image:clean', require('./tasks/image/clean'));
gulp.task('image:build', require('./tasks/image/build'));
/*
|--------------------------------------------------------------------------
| JavaScript Tasks
|--------------------------------------------------------------------------
*/
gulp.task('javascript:clean', require('./tasks/javascript/clean'));
gulp.task('javascript:lint', require('./tasks/javascript/lint'));
gulp.task('javascript:build', [ 'javascript:clean' ], require('./tasks/javascript/build'));
/*
|--------------------------------------------------------------------------
| Domain Tasks
|--------------------------------------------------------------------------
|
| A domain specific tasks for each part of the building process.
| They compose a complete building pipline for each domain.
|
*/
gulp.task('scss', [ 'scss:lint', 'scss:build', 'scss:vendor' ]);
gulp.task('html', [ 'html:clean', 'html:build' ]);
gulp.task('image', [ 'image:clean', 'image:build' ]);
gulp.task('javascript', [ 'javascript:clean', 'javascript:lint', 'javascript:build' ]);
gulp.task('font', [ 'font:clean', 'font:build' ]);
/*
|--------------------------------------------------------------------------
| Synchornize Browser Tasks
|--------------------------------------------------------------------------
|
| Bootstraps a BrowserSync and starts a localhost development. Compiled
| files are outputted into `www` directory, so we are
| telling BrowserSync to to use it as a base.
|
*/
gulp.task('sync', () => {
browsersync.init({
server: {
open: false,
baseDir: 'www'
}
});
gulp.watch('www/*.html').on('change', browsersync.reload);
gulp.watch('www/assets/css/*.css').on('change', browsersync.reload);
gulp.watch('www/assets/js/*.js').on('change', browsersync.reload);
gulp.watch('www/assets/img/*').on('change', browsersync.reload);
});
|
import styled from 'styled-components';
import React, { useContext, useState, useEffect } from 'react';
import { Container } from "../../../styles/styles";
import { getHistoryDailyHabit } from '../../../service/trackit';
import UserContext from "../../../contexts/UserContext";
import Calendar from 'react-calendar';
import dayjs from "dayjs";
import "dayjs/locale/pt-br";
import 'react-calendar/dist/Calendar.css';
const History = () => {
const { user } = useContext(UserContext);
const [days, setDays] = useState([]);
useEffect(() => {
getHistoryDailyHabit(user.token)
.then(e => setDays(e.data))
.catch(() => alert("Erro ao obter lista de dias."))
}, []);
return (
<Container color="#E5E5E5" bottom="72px">
<ContainerCalendar>
<h1>
Histórico
</h1>
<FormCalendar
minDate={new Date("8/29/2021")}
maxDate={new Date()}
calendarType={"US"}
formatDay={(locale, date) => dayjs(date).format('DD')}
/>
</ContainerCalendar>
</Container>
);
};
const ContainerCalendar = styled.div`
margin: 100px 0 18px 0;
width: 340px;
h1 {
font-size: 23px;
color: #126BA5;
}
h2 {
font-size: 18px;
color: #8FC549;
line-height: 26px;
}
`;
const FormCalendar = styled(Calendar)`
margin-top: 12px;
height: 400px;
border-radius: 10px;
border: none;
background-color: #FFF;
div {
margin-top: 5px;
}
button {
color: black;
border-radius: 50%;
font-size: 14px;
}
`
export default History; |
var mergeTwoLists = function(l1, l2) {
let smallerL
let largerL
if (l1.val < l2.val) {
smallerL = l1;
largerL = l2;
} else {
smallerL = l2;
largerL = l1;
}
while (smallerL && largerL) {
}
}; |
import React from 'react';
import '../../stylesheets/component/home/characterSummary.css';
const CharacterSummary = props => {
return (
<div id='character-summary'>
this
</div>
);
}
export default CharacterSummary; |
/* eslint-disable no-undef */
/// <reference types="cypress" />
context("Mood tracking", () => {
beforeEach(() => {
cy.visit("http://localhost:3000/");
});
it("Check-ins interface expands and collapses", () => {
cy.assertCheckInsOpen(false)
.showCheckIns()
.assertCheckInsOpen(true)
.hideCheckIns()
.assertCheckInsOpen(false);
});
it("Check-ins are registered when check-ins interface is closed", () => {
cy.checkIn(1)
.checkIn(3)
.checkIn(5)
.checkIn(3)
.showCheckIns()
.assertAverageMood(3)
.assertMoods([1, 3, 5, 3]);
});
it("Check-ins are registered when check-ins interface is open", () => {
cy.showCheckIns()
.checkIn(1)
.checkIn(3)
.checkIn(5)
.checkIn(3)
.assertAverageMood(3)
.assertMoods([1, 3, 5, 3]);
});
});
|
/*jshint maxstatements: false */
var express = require('express');
var fs = require('fs');
var path = require('path');
var winston = require('winston');
var requirejs = require('requirejs');
var basicAuth = require('node-basicauth');
var rateLimit = require('express-rate-limit');
// Express middleware modules which have been separated out now
var compression = require('compression');
var errorHandler = require('errorhandler');
var error = require('./error');
module.exports = {
getApp: function (environment, rootDir, requireBaseUrl) {
var app = express(),
transactionVolumesCSV = fs.readFileSync(
path.join(rootDir, 'assets', 'data', 'transaction-volumes.csv'));
app.disable('x-powered-by');
(function () {
// The number of milliseconds in one day
var oneDay = 86400000;
var scrapers = /^Pcore-HTTP.*|.*360Spider.*/i;
app.set('environment', environment);
app.set('requirePath', requireBaseUrl || '/app/');
app.set('assetPath', global.config.assetPath);
app.set('assetDigest', JSON.parse(fs.readFileSync(path.join(rootDir, 'spotlight_assets', 'asset-digest.json'), {encoding: 'utf8'})));
app.set('backdropUrl', global.config.backdropUrl);
app.set('externalBackdropUrl', global.config.externalBackdropUrl);
app.set('clientRequiresCors', global.config.clientRequiresCors);
app.set('port', global.config.port);
app.set('stagecraftUrl', global.config.stagecraftUrl);
app.use(compression());
var limiter = new rateLimit({
// Returning false will increment the counter
skip: function(req, res) {
// Ignore 'assets' URLs
if (req.originalUrl.indexOf('assets') !== -1) {
return true;
}
// Rate-limit all requests from clients where the user-agent matches our scraper regex above.
var source = req.headers['user-agent'] || "";
return !source.match(scrapers);
},
windowMs: 60 * 1000, // 1 minute
max: 60, // limit each IP to 60 requests per minute if skip: returns false
delayMs: 0, // disable delaying
skipFailedRequests: true, // when true failed requests (response status >= 400) won't be counted
message: "Too many requests from this IP. Please get in touch if you require the raw data.",
});
// apply limiter to all /performance requests
app.use('/performance', limiter);
// Serve static files from the configured assetPath.
app.use(global.config.assetPath, express.static(path.join(rootDir, 'spotlight_assets'), { maxAge: oneDay }));
}());
if (environment === 'development') {
global.logger.debug('Winston is logging in development');
// In development, overwrite the asset digest so that each value is equal to the key,
// because Sass will recompile itself to the non-cachebusted filename with each change.
var assetDigest = app.get('assetDigest');
_.each(assetDigest, function (value, key) {
assetDigest[key] = key;
});
app.set('assetDigest', assetDigest);
app.use(errorHandler());
app.use('/app', express.static(path.join(rootDir, 'app')));
app.use('/.grunt', express.static(path.join(rootDir, '.grunt')));
app.use('/spec', express.static(path.join(rootDir, 'spec')));
app.use('/tests', function (req, res) {
res.sendfile(path.join(rootDir, '_SpecRunner.html'));
});
// We use Sass sourcemaps in development. When you click a Sass filename from in
// your browser, it will attempt to GET the file from /styles
app.use('/styles', function (req, res) {
res.sendfile(path.join(rootDir, req.originalUrl));
});
} else {
global.logger.add(winston.transports.File, {
filename: 'log/production.json.log',
level: 'info',
colorize: false,
json: true,
logstash: true
});
global.logger.remove(winston.transports.Console);
app.set('etag', 'strong');
}
// If environment variables are set for basic authentication, protect
// everything under /performance. We don't want to protect things like
// /stagecraft-stub.
if (process.env.BASIC_AUTH_USER && process.env.BASIC_AUTH_PASS) {
var auth = {};
auth[process.env.BASIC_AUTH_USER] = process.env.BASIC_AUTH_PASS;
app.get('/performance*', basicAuth(auth));
}
app.get('/', function (req, res) {
res.redirect(301, '/performance');
});
app.get('/robots.txt', function (req, res) {
res.set('Content-Type', 'text/plain');
res.send('User-agent: *\nDisallow: /');
});
app.get('/_status', require('./healthcheck_controller'));
app.get('*.png', function (req, res) {
error.render(410, req, res);
});
app.get('/performance', _.bind(require('./server/controllers/services'), this, 'home'));
app.get('/performance/about', require('./server/controllers/about'));
app.get('/performance/accessibility', require('./server/controllers/accessibility'));
app.get('/performance/services', _.bind(require('./server/controllers/services'), this, 'services'));
app.get('/performance/web-traffic', _.bind(require('./server/controllers/simple-dashboard-list'), this, 'web-traffic'));
app.get('/performance/other', _.bind(require('./server/controllers/simple-dashboard-list'), this, 'other'));
app.get('/performance/prototypes', require('./server/controllers/prototypes'));
app.get('/performance/data/transaction-volumes.csv', function (req, res) {
res.set('Content-Type', 'text/csv; charset=utf-8');
res.set('Content-Disposition', 'attachment;filename=transaction-volumes.csv');
res.send(transactionVolumesCSV);
res.end();
});
app.get('/performance/*', require('./process_request'));
return app;
}
};
|
var express = require('express');
var router = express.Router();
const attachmentsController = require('../controllers/attachmentsController');
const loggedIn = require('../middleware/loggedIn');
const { attachmentUpload } = require('../middleware/multer');
router
.use(loggedIn)
.route('/upload')
.post(
attachmentUpload,
attachmentsController.createAttachment
);
router.delete('/', loggedIn, attachmentsController.deleteAttachment)
module.exports = router;
|
// animals name toys
class Animal {
constructor(name = 'mike') { // initialize
this.name = name
}
getName() {
return this.name.toUpperCase()
}
}
var a1 = new Animal()
var a2 = new Animal('codebusters')
console.log(a1)
console.log(a2.getName()) |
import { LightningElement, track, api } from 'lwc';
import { ResponseParser, log, l } from './helper.js';
const WEATHER_URL = 'https://api.openweathermap.org/data/2.5/weather?q=';
const WEATHER_API = '&appid=dc14a4d0c2ab97c643acd3e8447fd074';
const DELAY = 5000; //in ms
export default class Weather extends LightningElement{
@track currentWeather={};
@track cached;
@track error;
@api city;
constructor(){
super();
this.currentWeather = {
dayTypeImage : '',
feels_like : 25,
dayType : 'Cloudy',
location : 'Kolkata, India',
date : new Date().getDate(),
humidity: 50,
dayTypeImage : '../../../resources/images/daytypes/wi-cloudy.svg',
tempMinC : 25,
tempMaxC : 45
}
}
connectedCallback(){
setInterval(()=>{
let r = Math.random(1);
this.city = r < 0.1 ? 'Paris' :
r < 0.2 ? 'Amsterdam' :
r < 0.3 ? 'Delhi' :
r < 0.4 ? 'Oslo' :
r < 0.5 ? 'Houston' :
r < 0.6 ? 'London' :
r < 0.7 ? 'Dubai' :
r < 0.8 ? 'Moscow' :
r < 0.9 ? 'Barcelona' : 'Kolkata';
log('City => ' + this.city);
let url = WEATHER_URL + this.city + WEATHER_API; //In the form [api.openweathermap.org/q=][cityName][&appid=<appId>]
fetch(url)
.then((result) => {
//console.dir(result);
return result.json();
})
.then(data=>{
log(`Data received for ${this.city} as ${JSON.stringify(data)}`);
log('data' + JSON.stringify(ResponseParser.parse(data)) );
this.currentWeather = ResponseParser.parse(data); //Or Object.assign({}, this.currentWeather, data);
console.log('I am here');
this.error = undefined;
})
.catch((error) => {
console.log(`Encountered error during fetch : ${error}`);
this.error = error;
//throw error;
});
}, DELAY);
}
// fetchData(){
// }
} |
var searchData=
[
['observer',['Observer',['../classObserver.html',1,'']]],
['observeur',['Observeur',['../classObserveur.html',1,'']]]
];
|
import androidImage from '../assets/img/card-images/android.svg';
import acerImage from '../assets/img/card-images/acer.svg';
import appleImage from '../assets/img/card-images/apple.svg';
import beatsImage from '../assets/img/card-images/beats.svg';
import hpImage from '../assets/img/card-images/hp.svg';
import lenovoImage from '../assets/img/card-images/lenovo.svg';
import nokiaImage from '../assets/img/card-images/nokia.svg';
import intelImage from '../assets/img/card-images/intel.svg';
import dellImage from '../assets/img/card-images/dell.svg';
import ciscoImage from '../assets/img/card-images/cisco.svg';
import htcImage from '../assets/img/card-images/htc.svg';
const gameCardImages = {
android: androidImage,
acer: acerImage,
apple: appleImage,
beats: beatsImage,
hp: hpImage,
lenovo: lenovoImage,
nokia: nokiaImage,
intel: intelImage,
dell: dellImage,
cisco: ciscoImage,
htc: htcImage,
};
export default gameCardImages;
|
$(".back-button").on( "click", function(event) {
event.preventDefault();
alert("reached back");
window.history.back();
}); |
/*
* jQuery File Upload User Interface Plugin 7.4
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
/*jslint nomen: true, unparam: true, regexp: true */
/*global define, window, URL, webkitURL, FileReader */
(function (factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
// Register as an anonymous AMD module:
define([
'jquery',
'vendor/bluimp-upload/jquery.ui.widget',
'vendor/bluimp-upload/jquery.iframe-transport',
'vendor/bluimp-upload/jquery.fileupload'
], factory);
} else {
// Browser globals:
factory(
window.jQuery
);
}
}(function ($) {
'use strict';
// The UI version extends the basic fileupload widget and adds
// a complete user interface based on the given upload/download
// templates.
$.widget('blueimpUI.fileupload', $.blueimp.fileupload, {
options: {
// By default, files added to the widget are uploaded as soon
// as the user clicks on the start buttons. To enable automatic
// uploads, set the following option to true:
autoUpload: true,
// The following option limits the number of files that are
// allowed to be uploaded using this widget:
//maxNumberOfFiles: 1,
// The maximum allowed file size:
maxFileSize: 5000000,
// The minimum allowed file size:
minFileSize: 1,
// To limit the number of files uploaded with one XHR request,
// set the following option to an integer greater than 0:
//limitMultiFileUploads: 1,
// To limit the number of concurrent uploads,
// set the following option to an integer greater than 0:
//limitConcurrentUploads: 1,
// The regular expression for allowed file types, matches
// against either file type or file name:
acceptFileTypes: /(\.|\/)(gif|jpe?g|png|bmp)$/i, // /(gif|jpeg|png|bmp)$/i,
// The container for the list of files. If undefined, it is set to
// an element with class "files" inside of the widget element:
filesContainer: undefined,
// By default, files are appended to the files container.
// Set the following option to true, to prepend files instead:
prependFiles: false,
// The expected data type of the upload response, sets the dataType
// option of the $.ajax upload requests:
dataType: 'json',
// The add callback is invoked as soon as files are added to the fileupload
// widget (via file input selection, drag & drop or add API call).
// See the basic file upload widget for more information:
add: function (e, data) {
var that = $(this).data('blueimpUIFileupload'),
options = that.options,
files = data.files;
that.options.fid = $(this).data('id');
that._adjustMaxNumberOfFiles(-files.length);
data.isAdjusted = true;
data.files.valid = data.isValidated = that._validate(files);
if (! data.files.valid){
that._showError(data.files);
return false;c
}
data.context = that._renderTemplate(data.files).data('data', data);
if ((that._trigger('added', e, data) !== false) &&
(options.autoUpload || data.autoUpload) &&
data.autoUpload !== false && data.isValidated) {
data.submit();
}
},
// Callback for the start of each file upload request:
send: function (e, data) {
},
// Callback for successful uploads:
done: function (e, data) {
var that = $(this).data('blueimpUIFileupload'),
$dropZone = that.options.dropZone,
context = $(data.context);
if (data.result.error) {
data.errorThrown = data.result.error;
that._trigger('fail', e, data);
} else {
// Set bar
context.find('.progressbar').
removeClass('progress-info').
removeClass('active').
addClass('progress-success').
find('.bar').
css({'width': '100%'});
context.remove();
$dropZone.find('.helper_text').show();
$dropZone.find('.drop_target').show();
var fid = 'fid_' + $(this).data('id');
if ($dropZone.find('input[type=hidden][namce=' + fid + ']').length > 0){
$dropZone.find('input[type=hidden][name=' + fid + ']').val(data.result.fid);
}else{
var $input = $('<input />', {'type': 'hidden', 'name': fid}).val(data.result.fid);
$dropZone.append($input);
}
// Render Preview
that._renderPreview(data.result, context);
}
},
// Callback for failed (abort or error) uploads:
fail: function (e, data) {
var that = $(this).data('blueimpUIFileupload'),
$dropZone = that.options.dropZone,
$poolParent = $dropZone.parent('div');
$poolParent.prepend($('<div />', {'class': 'upload-status alert-message error'}).text(data.errorThrown));
data.context.remove();
$dropZone.find('.helper_text').show();
$dropZone.find('.drop_target').show();
var fid = 'fid_' + $(this).data('id');
data.form.find('input[type=hidden][name=' + fid + ']').remove();
},
// Callback for upload progress events:
progress: function (e, data) {
/*var $dropZone = data.dropZone,
percent = parseInt(data.loaded / data.total * 100, 10);
$dropZone.find('div.progressbar').find('div.bar').css({'width': percent + '%'});
$dropZone.find('span.status').html('uploading...' + percent + '%');*/
var that = $(this).data('blueimpUIFileupload'),
percent = parseInt(data.loaded / data.total * 100, 10);
data.context.find('div.progressbar').find('div.bar').css({'width': percent + '%'});
}
},
_adjustMaxNumberOfFiles: function (operand) {
if (typeof this.options.maxNumberOfFiles === 'number') {
this.options.maxNumberOfFiles += operand;
/*if (this.options.maxNumberOfFiles < 1) {
this._disableFileInputButton();
} else {
this._enableFileInputButton();
}*/
}
},
_create: function () {
if (! _.isNull(this.options.dropZone)) {
$.blueimp.fileupload.prototype._create.call(this);
return;
}
// Set dropZone
this.options.dropZone = this.element.closest('.fileuploadpool');
// Bind remove uploaded
var that = this,
$poolParent = this.options.dropZone.parent('div'),
$dropZone = this.options.dropZone;
// Append remove button
$poolParent.on('click', '#post-media a.icon-remove', function(e) {
e.preventDefault();
$dropZone.find('input[type=hidden][name^=fid_]').remove();
$poolParent.find('#post-media').remove();
// Show drop zone
$dropZone.show();
});
$.blueimp.fileupload.prototype._create.call(this);
},
_initEventHandlers: function () {
$.blueimp.fileupload.prototype._initEventHandlers.call(this);
var eventData = {fileupload: this};
this.options.dropZone
.delegate(
'.remove',
'click.' + this.options.namespace,
eventData,
this._cancelHandler
);
},
_cancelHandler: function (e) {
e.preventDefault();
var tmpl = $(this).hasClass('fileupload_cancel') ? e.data.fileupload.options.dropZone.find('li') : $(this).closest('li'),
data = tmpl.data('data') || {};
if (!data.jqXHR) {
data.errorThrown = 'abort';
e.data.fileupload._trigger('fail', e, data);
} else {
data.jqXHR.abort();
}
tmpl.fadeOut(300, function(){ $(this).remove(); });
},
_formatFileSize: function (bytes) {
if (typeof bytes !== 'number') {
return '';
}
if (bytes >= 1000000000) {
return (bytes / 1000000000).toFixed(2) + ' GB';
}
if (bytes >= 1000000) {
return (bytes / 1000000).toFixed(2) + ' MB';
}
return (bytes / 1000).toFixed(2) + ' KB';
},
_hasError: function (file) {
if (file.error) {
return file.error;
}
// The number of added files is subtracted from
// maxNumberOfFiles before validation, so we check if
// maxNumberOfFiles is below 0 (instead of below 1):
if (this.options.maxNumberOfFiles < 0) {
return 'maxNumberOfFiles';
}
// Files are accepted if either the file type or the file name
// matches against the acceptFileTypes regular expression, as
// only browsers with support for the File API report the type:
if (!(this.options.acceptFileTypes.test(file.type) ||
this.options.acceptFileTypes.test(file.name))) {
return 'acceptFileTypes';
}
if (this.options.maxFileSize &&
file.size > this.options.maxFileSize) {
return 'maxFileSize';
}
if (typeof file.size === 'number' &&
file.size < this.options.minFileSize) {
return 'minFileSize';
}
return null;
},
_validate: function (files) {
var that = this,
valid = !!files.length;
$.each(files, function (index, file) {
file.error = that._hasError(file);
if (file.error) {
valid = false;
}
});
return valid;
},
_renderTemplate: function(files) {
var $dropZone = this.options.dropZone,
$dropTarget = $dropZone.find('.drop_target'),
$helper = $dropZone.find('.helper'),
$uploading = $('<div />', {'class': 'uploading'}),
$progress = $('<div />', {'class': 'progressbar progress active progress-info progress-striped'}).append($('<div />', {'class': 'bar', 'style': 'width:0%'}));
//$helper.hide();
//$dropZone.parent('div').find('.upload-status').remove();
//$helper.find('.uploaded, .uploading').remove();
$dropZone.find('.uploaded, .uploading').remove();
$dropZone.addClass('on-progress').removeClass('over');
if (! $dropTarget.hasClass('option-fileupload')) {
//$dropTarget.hide();
}
$.each(files, function(index, file) {
$uploading.append($progress);
$dropZone.append($uploading);
})
return $uploading;
},
_renderPreview: function(result, node) {
var that = this,
$dropZone = that.options.dropZone,
$poolParent = $dropZone.parent('div'),
$preview = $('<div />', {'id': 'post-media'}).append('<span><a class="icon-remove"></a></span>');
$preview.find('span').append(result.img);
$poolParent.find('#post-media').remove();
$poolParent.prepend($preview);
// Hide drop zone
$dropZone.hide();
// $(result.img).one('load', function() {
// $preview.find('span').addClass('shadow-effect');
// });
},
_showError: function(files) {
$.each(files, function (index, file) {
switch(file.error) {
case 'acceptFileTypes':
alert('File type not accepted!');
break;
case 'maxFileSize':
alert('File size to big!');
break;
case 'minFileSize':
alert('File size to small!');
break;
}
});
}
});
}));
|
'use strict';
angular.module('tags').controller('TagsCtrl', ['$scope', '$log', '$stateParams', '$location', 'Authentication', 'Tags',
function($scope, $log, $stateParams, $location, Authentication, Tags) {
$scope.authentication = Authentication;
$scope.tag = {};
// ui.select
$scope.selected = {};
// ui.bootstrap.alert
$scope.alerts = [];
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
// ui.bootstrap.collapse
$scope.isCollapsed = true;
// CRUD Operations
$scope.create = function () {
var tagObj = new Tags({
content: this.tag.content,
category: this.tag.category
});
tagObj.$save(function (response) {
$scope.alerts.push({msg: 'Tag wurde erfolgreich gespeichert.', type: 'success'});
$scope.tag.content = '';
$scope.tag.category = '';
}, function (errorResponse) {
$log.debug(errorResponse);
$scope.alerts.push({msg: errorResponse.data.message, type: 'danger'});
});
};
$scope.remove = function (tagObj) {
if (tagObj) {
// Delete the object
tagObj.$remove();
// Take it out from the current view
for (var i in $scope.tags) {
if ($scope.tags[i] === tagObj) {
$scope.tags.splice(i, 1);
}
}
// Display an alert info
$scope.selected = {};
$scope.alerts.push({msg: 'Ihr Tag wurde gelöscht.', type: 'info'});
} else {
$scope.tag.$remove(function () {
$location.path('tags');
$scope.alerts.push({msg: 'Ihr Tag wurde gelöscht.', type: 'info'});
});
}
};
$scope.update = function () {
var tagObj = $scope.selected.tag;
tagObj.$update(function () {
// Set $location path
$location.path('tags');
// Recollect the tags from the database
$scope.find();
// Unselect the selected tag
$scope.selected = {};
// Send an alert info message
$scope.alerts.push({msg: 'Tag wurde erfolgreich bearbeitet.', type: 'info'});
}, function (errorResponse) {
$scope.alerts.push({msg: errorResponse.data.message, type: 'danger'});
});
};
$scope.find = function () {
$scope.tags = Tags.query();
};
$scope.findOne = function () {
$scope.tag = Tags.get({
tagId: $stateParams.tagId
});
};
}]); |
function updateWeatherWidget(state,city){
var i,icon,htemp,ltemp,temp;
var state1=state.replace(" ","_");
var city1=city.replace(" ","_");
var url="http://api.wunderground.com/api/fbe844bcf20b90cd/geolookup/conditions/forecast10day/q/"+state1+"/"+city1+".json";
jQuery.ajax({
url: url,
dataType: "jsonp",
success: function(parsed_json) {
temp=Math.round(parsed_json['current_observation']['temp_f']);
icon=parsed_json['current_observation']['icon'];
$('#topIcon').html('<img src="images/top_'+icon+'.png"/>');
$('#city').text(city+','+state);
$('#tempF').html(temp+'°');
for(i=0;i<6;i++){
icon=parsed_json['forecast']['simpleforecast']['forecastday'][i]['icon'];
htemp=Math.round(parsed_json['forecast']['simpleforecast']['forecastday'][i]['high']['fahrenheit']);
ltemp=Math.round(parsed_json['forecast']['simpleforecast']['forecastday'][i]['low']['fahrenheit']);
if(i==0){
$('#day'+(i+1)).text('Today');
}else{
$('#day'+(i+1)).text(parsed_json['forecast']['simpleforecast']['forecastday'][i]['date']['weekday_short']);
}
$('#image'+(i+1)).html('<img src="images/'+icon+'.png"/>');
$('#highTemp'+(i+1)).html(htemp+'°F');
$('#lowTemp'+(i+1)).html(ltemp+'°F');
}
//For table
/*$('#weather_report').empty();
var append='<tr style="font-weight: bold;"><td colspan="5">'+city +','+state+'</tr><tr>';
for(i=0;i<6;i++){
append=append+'<td>'+parsed_json['forecast']['simpleforecast']['forecastday'][i]['date']['weekday_short']+'</td>';
}
append=append+'</tr><tr>';
for(i=0;i<6;i++){
append=append+'<td>'+parsed_json['forecast']['simpleforecast']['forecastday'][i]['high']['fahrenheit']+'°F </td>';
}
append=append+'</tr><tr>';
for(i=0;i<6;i++){
append=append+'<td>'+parsed_json['forecast']['simpleforecast']['forecastday'][i]['low']['fahrenheit']+'°F </td>';
}
append=append+'</tr>';
$('#weather_report').html(append);*/
}
});
} |
import React, { useContext } from 'react';
import AuthContext from '../../AuthContext';
import { Link, useHistory } from 'react-router-dom';
import styles from './index.module.css';
const Header = () => {
const { loggedIn, user, logout } = useContext(AuthContext);
const history = useHistory();
const logoutHandler = () => {
logout();
history.push('/');
}
return (<header className={`${styles.masthead} mb-auto`}>
<div className="inner">
<h3 className={`${styles['masthead-brand']}`} style={{marginRight: '20px'}}>Recipes</h3>
<nav className={`nav ${styles['nav-masthead']} justify-content-center`}>
{!loggedIn && (<Link className={styles['nav-link']} to="/" style={{marginRight: '20px'}}>Home</Link>)}
{ loggedIn ? (<>
<Link className={styles['nav-link']} style={{marginRight: '20px'}} to="/" >Welcome, {user.firstName} {user.lastName}!</Link>
<Link className={styles['nav-link']} style={{marginRight: '20px'}} to="/create">Share recipe</Link>
<Link className={styles['nav-link']} to="/" onClick={logoutHandler}>Logout</Link></>) : (<>
<Link className={styles['nav-link']} style={{marginRight: '20px'}} to="/login">Login</Link>
<Link className={styles['nav-link']} to="/register">Register</Link>
</>)}
</nav>
</div>
</header>)
}
export default Header; |
module.exports = {
url: '/Users/baijhl/mmmmmm/worktree/student-file/src/pages/Aaaaa/lazyCom.jsx',
name: 'heiheihei'
}
|
import React, { Component } from 'react';
class Sidebar extends Component {
state = { }
render() {
return (
<div className="sidenav">
<br/>
<li><h2>Project</h2></li>
<li><a href="/">List Project</a></li>
<li><a href="/AddProject">Create Project</a></li>
</div>
);
}
}
export default Sidebar; |
(function($) {
$("#nav-primary-list").smartmenus({
subIndicators: false,
subMenusMinWidth: "15em",
subMenusMaxWidth: "20em",
collapsibleBehavior: 'accordion',
subMenusSubOffsetX: 8,
subMenusSubOffsetY: 10,
showFunction: function($ul, complete) { $ul.fadeIn(250, complete); },
rightToLeftSubMenus: true
});
})(jQuery); |
const express = require('express');
const app = express();
const port = 5000;
const users = [
{ id: '1', name: 'Aamir khan', profession: 'Actor', age: '50' },
{ id: '2', name: 'Salman khan', profession: 'Actor', age: '51' },
{ id: '3', name: 'Shahrukh khan', profession: 'Actor', age: '52' },
{ id: '4', name: 'Shakib khan', profession: 'Actor', age: '53' },
{ id: '5', name: 'Amin khan', profession: 'Actor', age: '54' },
{ id: '6', name: 'Imran khan', profession: 'President', age: '55' },
]
app.get('/users', (req, res) => {
res.send(users)
});
app.get('/users/:id', (req, res) => {
const id = req.params.id;
const user = users[id];
// console.log(req.parems.id);
res.send(user);
})
app.listen(port, () => {
console.log('Listenning to port', port);
}) |
export const fetcher = (url, options = {}) =>
fetch(url, {
...options,
headers: {
Authorization: `Bearer ${localStorage.getItem("token")}`,
"Content-Type": "application/json"
}
}).then(r => r.json());
|
import axios from "axios";
import { useContext, useEffect, useState } from "react";
import { Link, useParams } from "react-router-dom";
import { allPostsPath } from "../constants/endpoints";
import { capitalise } from "../constants/functions";
import { UserContext } from "../context/UserProvider";
const BlogDetail = () => {
const userContext = useContext(UserContext);
const { slugName } = useParams();
const [blogPost, setBlogPost] = useState({});
const getBlogPost = async (slug) => {
try {
const response = await axios.get(`${process.env.REACT_APP_BACKEND_URL}${allPostsPath}${slug}/`);
setBlogPost(response.data);
} catch (err) {
console.log(err.response);
}
};
useEffect(() => {
getBlogPost(slugName);
}, []);
return (
<div className="container">
<img src={blogPost.image} className="img-fluid shadow-sm" alt={blogPost.title}/>
<h1 className="display-3 fst-italic my-2">{blogPost.title}</h1>
<h3 className="mb-4">{blogPost.excerpt}</h3>
<h4 className="text-success">
{blogPost.category && capitalise(blogPost.category.category_name)}
</h4>
<h6>
{blogPost.month} {blogPost.day}
</h6>
<hr />
<div className="row">
<div className="col-sm-12 col-md-8"><p className="blog-content">{blogPost.content}</p></div>
</div>
<hr />
<div className="row justify-content-center">
{userContext.state.isAuthenticated && <div className="col"><Link to={`/edit/${slugName}`}>Edit Post</Link></div>}
<div className="col"><Link to="/">Back to Posts</Link></div>
</div>
</div>
);
};
export default BlogDetail;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.