text
stringlengths 7
3.69M
|
|---|
import $ from '$';
import _ from 'underscore';
import d3 from 'd3';
import HAWCModal from 'utils/HAWCModal';
import RiskOfBiasScore from 'riskofbias/RiskOfBiasScore';
import {
renderCrossStudyDisplay,
} from 'robTable/components/CrossStudyDisplay';
import {
renderRiskOfBiasDisplay,
} from 'robTable/components/RiskOfBiasDisplay';
import RoBLegend from './RoBLegend';
import D3Visualization from './D3Visualization';
class RoBHeatmapPlot extends D3Visualization {
constructor(parent, data, options){
// heatmap of risk of bias information. Criteria are on the y-axis,
// and studies are on the x-axis
super(...arguments);
this.setDefaults();
this.modal = new HAWCModal();
}
render($div){
this.plot_div = $div.html('');
this.processData();
if(this.dataset.length === 0){
return this.plot_div.html('<p>Error: no studies with risk of bias selected. Please select at least one study with risk of bias.</p>');
}
this.get_plot_sizes();
this.build_plot_skeleton(false);
this.add_axes();
this.draw_visualization();
this.resize_plot_dimensions();
this.add_menu();
this.build_labels();
this.build_legend();
this.trigger_resize();
}
get_plot_sizes(){
this.w = this.cell_size*this.xVals.length;
this.h = this.cell_size*this.yVals.length;
var menu_spacing = 40;
this.plot_div.css({'height': (this.h + this.padding.top + this.padding.bottom +
menu_spacing) + 'px'});
}
setDefaults(){
_.extend(this, {
firstPass: true,
included_metrics: [],
padding: {},
x_axis_settings: {
scale_type: 'ordinal',
text_orient: 'top',
axis_class: 'axis x_axis',
gridlines: true,
gridline_class: 'primary_gridlines x_gridlines',
axis_labels: true,
label_format: undefined, //default
},
y_axis_settings: {
scale_type: 'ordinal',
text_orient: 'left',
axis_class: 'axis y_axis',
gridlines: true,
gridline_class: 'primary_gridlines x_gridlines',
axis_labels: true,
label_format: undefined, //default
},
});
}
processData(){
var dataset = [],
included_metrics = this.data.settings.included_metrics,
studies, metrics, xIsStudy;
_.each(this.data.aggregation.metrics_dataset, function(metric){
_.chain(metric.rob_scores)
.filter(function(rob){
return _.contains(included_metrics, rob.data.metric.id);
}).each(function(rob){
// Check for short_name setting on the metric
var metric_name = rob.data.metric.name;
if (rob.data.metric.use_short_name === true && rob.data.metric.short_name !== '') {
metric_name = rob.data.metric.short_name;
}
dataset.push({
riskofbias: rob,
study: rob.study,
study_label: rob.study.data.short_citation,
metric: rob.data.metric,
metric_label: metric_name,
score: rob.data.score,
score_text: rob.data.score_text,
score_color: rob.data.score_color,
score_text_color: rob.data.score_text_color,
});
});
});
studies = _.chain(dataset)
.map(function(d){return d.study_label;})
.uniq()
.value();
metrics = _.chain(dataset)
.map(function(d){return d.metric_label;})
.uniq()
.value();
if(this.firstPass){
_.extend(this.padding, {
top: this.data.settings.padding_top,
right: this.data.settings.padding_right,
bottom: this.data.settings.padding_bottom,
left: this.data.settings.padding_left,
top_original: this.data.settings.padding_top,
right_original: this.data.settings.padding_right,
left_original: this.data.settings.padding_left,
});
this.firstPass = false;
}
xIsStudy = (this.data.settings.x_field!=='metric');
_.extend(this,{
cell_size: this.data.settings.cell_size,
dataset,
studies,
metrics,
title_str: this.data.settings.title,
x_label_text: this.data.settings.xAxisLabel,
y_label_text: this.data.settings.yAxisLabel,
xIsStudy,
xVals: (xIsStudy) ? studies : metrics,
yVals: (!xIsStudy) ? studies : metrics,
xField: (xIsStudy) ? 'study_label' : 'metric_label',
yField: (!xIsStudy) ? 'study_label' : 'metric_label',
});
}
add_axes() {
_.extend(this.x_axis_settings, {
domain: this.xVals,
rangeRound: [0, this.w],
number_ticks: this.xVals.length,
x_translate: 0,
y_translate: 0,
});
_.extend(this.y_axis_settings, {
domain: this.yVals,
rangeRound: [0, this.h],
number_ticks: this.yVals.length,
x_translate: 0,
y_translate: 0,
});
this.build_y_axis();
this.build_x_axis();
d3.select(this.svg).selectAll('.x_axis text')
.style('text-anchor', 'start')
.attr('dx', '5px')
.attr('dy', '0px')
.attr('transform', 'rotate(-25)');
}
draw_visualization(){
var self = this,
x = this.x_scale,
y = this.y_scale,
width = this.cell_size,
half_width = width/2,
showSQs = function(v){
self.print_details(self.modal.getBody(), $(this).data('robs'));
self.modal
.addHeader('<h4>Study evaluation details: {0}</h4>'.printf(this.textContent))
.addFooter('')
.show({maxWidth: 900});
},
getMetricSQs = function(i, v){
var vals = self.dataset.filter(function(e,i,a){return e.metric_label===v.textContent;});
vals = vals.map(function(v){return v.riskofbias;});
$(this).data('robs', {type: 'metric', robs: vals});
},
getStudySQs = function(i, v){
var vals = self.dataset.filter(function(e,i,a){return e.study_label===v.textContent;});
vals = vals.map(function(v){return v.riskofbias;});
$(this).data('robs', {type: 'study', robs: vals});
},
hideHovers = function(v){
self.draw_hovers(this, {draw: false});
};
this.cells_group = this.vis.append('g');
this.cells = this.cells_group.selectAll('svg.rect')
.data(this.dataset)
.enter().append('rect')
.attr('x', function(d){return x(d[self.xField]);})
.attr(
'y'
,function(d) {
return y(d[self.yField]);
}
)
.attr('height', width)
.attr('width', width)
.attr(
'class',
function(d) {
var returnValue = "heatmap_selectable";
if (d.metric.domain.is_overall_confidence) {
returnValue = "heatmap_selectable_bold";
}
return returnValue;
}
)
.style('fill', function(d){return d.score_color;})
.on('mouseover', function(v,i){self.draw_hovers(v, {draw: true, type: 'cell'});})
.on('mouseout', function(v,i){self.draw_hovers(v, {draw: false});})
.on('click', function(v){
self.print_details(self.modal.getBody(), {type: 'cell', robs: [v]});
self.modal
.addHeader('<h4>Study evaluation details</h4>')
.addFooter('')
.show({maxWidth: 900});
});
this.score = this.cells_group.selectAll('svg.text')
.data(this.dataset)
.enter().append('text')
.attr('x', function(d){return (x(d[self.xField]) + half_width);})
.attr('y', function(d){return (y(d[self.yField]) + half_width);})
.attr('text-anchor', 'middle')
.attr('dy', '3.5px')
.attr(
'class'
,function(d) {
var returnValue = "centeredLabel";
if (
(typeof(d.metric) != "undefined")
&& (typeof(d.metric.domain) != "undefined")
&& (typeof(d.metric.domain.is_overall_confidence) === "boolean")
&& (d.metric.domain.is_overall_confidence)
) {
returnValue = "centeredLabel_bold";
}
return returnValue;
}
)
.style('fill', function(d){return d.score_text_color;})
.text(function(d){return d.score_text;});
$('.x_axis text').each( (this.xIsStudy) ? getStudySQs : getMetricSQs )
.attr('class', 'heatmap_selectable')
.on('mouseover', function(v){self.draw_hovers(this, {draw: true, type: 'column'});})
.on('mouseout', hideHovers)
.on('click', showSQs);
$('.y_axis text').each( (!this.xIsStudy) ? getStudySQs : getMetricSQs )
.attr(
'class'
,function(d) {
var returnValue = "heatmap_selectable";
if (
(typeof(self.data) != "undefined")
&& (typeof(self.data.aggregation) != "undefined")
&& (typeof(self.data.aggregation.metrics_dataset) != "undefined")
&& (d < self.data.aggregation.metrics_dataset.length)
&& (typeof(self.data.aggregation.metrics_dataset[d].domain_is_overall_confidence) == "boolean")
&& (self.data.aggregation.metrics_dataset[d].domain_is_overall_confidence)
) {
var returnValue = "heatmap_selectable_bold";
}
return returnValue;
}
)
.on('mouseover', function(v){self.draw_hovers(this, {draw: true, type: 'row'});})
.on('mouseout', hideHovers)
.on('click', showSQs);
this.hover_group = this.vis.append('g');
}
resize_plot_dimensions(){
// Resize plot based on the dimensions of the labels.
var ylabel_height = this.vis.select('.x_axis').node().getBoundingClientRect().height,
ylabel_width = this.vis.select('.x_axis').node().getBoundingClientRect().width,
xlabel_width = this.vis.select('.y_axis').node().getBoundingClientRect().width;
if ((this.padding.top < this.padding.top_original + ylabel_height) ||
(this.padding.left < this.padding.left_original + xlabel_width) ||
(this.padding.right < ylabel_width - this.w + this.padding.right_original)){
this.padding.top = this.padding.top_original + ylabel_height;
this.padding.left = this.padding.left_original + xlabel_width;
this.padding.right = ylabel_width - this.w + this.padding.right_original;
this.render(this.plot_div);
}
}
draw_hovers(v, options){
if (this.hover_study_bar) this.hover_study_bar.remove();
if (!options.draw) return;
var draw_type;
switch (options.type){
case 'cell':
draw_type = {
x: this.x_scale(v[this.xField]),
y: this.y_scale(v[this.yField]),
height: this.cell_size,
width: this.cell_size};
break;
case 'row':
draw_type = {
x: 0,
y: this.y_scale(v.textContent),
height: this.cell_size,
width: this.w};
break;
case 'column':
draw_type = {
x: this.x_scale(v.textContent),
y: 0,
height: this.h,
width: this.cell_size};
break;
}
this.hover_study_bar = this.hover_group.selectAll('svg.rect')
.data([draw_type])
.enter().append('rect')
.attr('x', function(d){return d.x;})
.attr('y', function(d){return d.y;})
.attr('height', function(d){return d.height;})
.attr('width', function(d){return d.width;})
.attr('class', 'heatmap_hovered');
}
build_labels(){
var svg = d3.select(this.svg),
visMidX = parseInt(this.svg.getBoundingClientRect().width/2, 10),
visMidY = parseInt(this.svg.getBoundingClientRect().height/2, 10),
midX = d3.mean(this.x_scale.range()),
midY = d3.mean(this.y_scale.range());
if($(this.svg).find('.figureTitle').length === 0){
svg.append('svg:text')
.attr('x', visMidX)
.attr('y', 25)
.text(this.title_str)
.attr('text-anchor', 'middle')
.attr('class','dr_title figureTitle');
}
var xLoc = this.padding.left + midX+20,
yLoc = visMidY*2-5;
svg.append('svg:text')
.attr('x', xLoc)
.attr('y', yLoc)
.text(this.x_label_text)
.attr('text-anchor', 'middle')
.attr('class','dr_axis_labels x_axis_label');
yLoc = this.padding.top + midY;
svg.append('svg:text')
.attr('x', 15)
.attr('y', yLoc)
.attr('transform','rotate(270, {0}, {1})'.printf(15, yLoc))
.text(this.y_label_text)
.attr('text-anchor', 'middle')
.attr('class','dr_axis_labels y_axis_label');
}
build_legend(){
if (this.legend || !this.data.settings.show_legend) return;
let options = {
dev: this.options.dev || false,
collapseNR: false,
};
this.legend = new RoBLegend(
this.svg,
this.data.settings,
options
);
}
print_details($div, d){
var config = {
display: 'all',
isForm: false,
};
// delay rendering until modal is displayed, as component depends on accurate width.
window.setTimeout(function(){
switch (d.type){
case 'cell':
_.extend(config, {
show_study: true,
study: {
name: d.robs[0].study_label,
url:d.robs[0].study.data.url,
},
});
renderRiskOfBiasDisplay(
RiskOfBiasScore.format_for_react([d.robs[0].riskofbias], config),
$div[0]);
break;
case 'study':
renderRiskOfBiasDisplay(
RiskOfBiasScore.format_for_react(d.robs, config),
$div[0]);
break;
case 'metric':
renderCrossStudyDisplay(
RiskOfBiasScore.format_for_react(d.robs, config),
$div[0]);
break;
}
}, 200);
}
}
export default RoBHeatmapPlot;
|
import React from 'react'
import { XRay } from '../src'
import { Box, Button } from 'rebass'
export default props => (
<Box p={3}>
<XRay>
<Button m={2}>Hello</Button>
</XRay>
</Box>
)
|
var application = require("application");
application.start({ moduleName: "./scenarios/remove-button-borders-nativescript/main.js" });
|
import React from 'react'
function SingleWorkFacts({client, date, timeframe, website}){
return(
<>
<section id="singleFactsSection">
<div className="container-fluid-small">
<div className="row">
<div className="col-3 anim-bot">
<h6>Client</h6>
<p>{client}</p>
</div>
<div className="col-3 anim-bot">
<h6>Completed</h6>
<p>{date}</p>
</div>
<div className="col-3 anim-bot">
<h6>Timeframe</h6>
<p>{timeframe}</p>
</div>
<div className="col-3 anim-bot">
<h6>Website</h6>
<p>{website}</p>
</div>
</div>
</div>
</section>
</>
)
}
export default SingleWorkFacts
|
const { getComplexityData } = require('./src/getComplexityData')
module.exports = {
getComplexityData,
}
|
const ingredients = [
'Картошка',
'Грибы',
'Чеснок',
'Помидоры',
'Зелень',
'Приправы',
];
const elementRef = document.getElementById('ingredients');
const ingredientsRef = ingredients.map(el => {
const list = document.createElement('li');
list.append(el);
return list;
});
elementRef.append(...ingredientsRef);
console.log(elementRef);
// =========================================================================
// const elementRef = document.getElementById("ingredients");
// console.log(elementRef)
// const ingredientsRef = ingredients.forEach(el => {
// const list = document.createElement('li');
// list.textContent = el;
// elementRef.appendChild(list)
// });
|
var BookingController = require('../controllers/BookingController');
module.exports = function (app) {
app.post('/booking/getBookingBy', function (req, res) {
console.log('/booking/getBookingBy', req.body)
BookingController.getBookingBy(req.body, function (err, task) {
if (err) {
res.send(err);
}
// console.log('res', task);
res.send(task);
});
})
app.post('/booking/getBookingByCode', function (req, res) {
console.log('/booking/getBookingByCode', req.body)
BookingController.getBookingByCode(req.body, function (err, task) {
if (err) {
res.send(err);
}
// console.log('res', task);
res.send(task);
});
})
app.post('/booking/getBookingMaxCode', function (req, res) {
console.log('/booking/getBookingMaxCode', req.body)
BookingController.getBookingMaxCode(req.body, function (err, task) {
if (err) {
res.send(err);
}
// console.log('res', task);
res.send(task);
});
})
app.post('/booking/insertBooking', function (req, res) {
console.log('/booking/insertBooking', req.body)
BookingController.insertBooking(req.body, function (err, task) {
if (err) {
res.send(err);
}
// console.log('res', task);
res.send(task);
});
})
app.post('/booking/checkBook', function (req, res) {
console.log('/booking/checkBook', req.body)
BookingController.checkBook(req.body, function (err, task) {
if (err) {
res.send(err);
}
// console.log('res', task);
res.send(task);
});
})
app.post('/booking/checkTable', function (req, res) {
console.log('/booking/checkTable', req.body)
BookingController.checkTable(req.body, function (err, task) {
if (err) {
res.send(err);
}
// console.log('res', task);
res.send(task);
});
})
app.post('/booking/deleteBooking', function (req, res) {
console.log('/booking/deleteBooking', req.body)
BookingController.deleteBooking(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
app.post('/booking/getBookingByCustomer', function (req, res) {
console.log('/booking/getBookingByCustomer', req.body)
BookingController.getBookingByCustomer(req.body, function (err, task) {
if (err) {
res.send(err);
}
res.send(task);
});
})
}
|
export default {
dictionaries: {
data: {
countries: {
0: ''
},
currencies: {
0: ''
},
genders: {
0: ''
}
}
},
articles: {
data: {
localeArticles: {
MultimediaRecharge: [
{
active: null,
article_full_name: '',
article_name: '',
article_price: null,
article_type_id: null,
currency_id: null,
id: null,
type_name: '',
}
],
common: [
{
active: null,
article_full_name: '',
article_name: '',
article_price: null,
article_type_id: null,
currency_id: null,
id: null,
type_name: '',
}
],
deliveries: [
{
active: null,
article_full_name: '',
article_name: '',
article_price: null,
article_type_id: null,
currency_id: null,
id: null,
type_name: '',
}
]
}
}
},
current_user: {
data: {
user: null
}
},
}
|
/**
classe para criar uma Opção
[arg1] Objeto _data - Dados da opção.
**/
function Option(_data, _inputType)
{ Div.call(this, "option", "Option LightColor LightColorHover"); //Extends DIV
this.data = _data;
this.inputType = _inputType;
var _that = this;
this.alert = null;
this.effortPrice = null;
this.input = new Object();
this.value = new Array();
this.subOptionSelected = new Array();
/**
- create (construtor)
De acordo com o tipo do input da opção, insiro conteúdo no Option;
Se tiver subOptions, as adiciono;
Seto value como value da opção;
**/
this.create = function()
{
switch(this.inputType){
case "TextArea":
this.appendDescription();
this.appendInput();
break;
default:
this.appendInput();
this.appendDescription();
break;
}
if(this.data.subOptions.length > 0) this.appendSubOptions();
if(_data.effortPrice) this.effortPrice = _data.effortPrice;
this.setValue(_data.value);
}
/**
- appendInput
Seta e insere o Input dentro da opção de acordo com o tipo.
**/
this.appendInput = function()
{
switch(this.inputType){
case "TextArea":
this.input = new TextArea(this.data.label);
new Div("textContainer", "TextContainer").writeInnerAndAppendOnDiv(this.input, this);
break;
default:
this.input = new Input( this.inputType, _that.selectIt );
new Div("inputContainer", "InputContainer").writeInnerAndAppendOnDiv(this.input, this);
break;
}
}
/**
- appendDescription
Crio as div com o titulo e descrição da opção e as insiro nela.
Se não for textArea, adiciono o atributo for ao input;
**/
this.appendDescription = function()
{
var newLabel = new Div("label", "Label MediumFont", "p").appendOnInnerContent(this.data.label);
var newDescription = new Div("description", "Description SmallFont").appendOnInnerContent(this.data.description);
var newOptionLabel = new Div("optionLabel", "OptionLabel", "label");
if(this.inputType != "TextArea") newOptionLabel.setAttribute("for", this.input.id);
newOptionLabel.writeInnerAndAppendOnDiv( newLabel.getScript() + newDescription.getScript(), this);
}
/**
- appendSubOptions
Insiro a subOption na opção.
Cria uma array e insere todas as subOpções nela;
Seta o alert como um novo objeto Alert passando a nova array como parametro;
Insiro o alert dentro dessa Opção;
**/
this.appendSubOptions = function()
{
var newSubOptions = new Array();
for(w in this.data.subOptions) newSubOptions.push(new SubOption(this.data.subOptions[w], newSubOptions.length));
this.alert = new Alert(newSubOptions);
this.appendOnInnerContent(this.alert);
this.subOptionSelected = new Array(newSubOptions.length);
}
/**
- selectIt
Método executado quando o usuário seleciona a opção.
Altero a visibilidade dos Alerts;
Salvo a opção selecionada;
Libero o botão avançar da sessão;
**/
this.selectIt = function()
{
_that.toggleAlertVisibility();
_that.saveOptionSelected();
var parentSection = _that.getParentDiv().getParentDiv();
parentSection.getNavigationButtons().goOn.enable(true);
}
/**
- toggleAlertVisibility
Mostro o alert da opção e escondo outros se necessário.
Se tiver algum alert visivel e o tipo da seção for radio, escondo o alert aberto;
Se existir um alert;
Se o input estiver selecionado;
Mostro o alert;
Seto opennedAlert como esse alert;
Caso contrário;
Escondo o Alert;
**/
this.toggleAlertVisibility = function()
{
var thisSection = _that.getParentDiv().getParentDiv();
if(thisSection.opennedAlert != null && _that.getInputType() == "Radio" && thisSection.opennedAlert != _that.alert ) thisSection.opennedAlert.close();
if(_that.alert){
if(_that.input.getjQueryObject().is(':checked')){
_that.alert.open();
thisSection.opennedAlert = _that.alert;
}else{
_that.alert.close();
}
}
}
/**
- setSubOptionValue
Seto um index especifico da Array subOptionValue
[arg1] String _subOptionValue - valor da opção selecionada
[arg2] Number _index - index no subOptionValue da opção selecionada
**/
this.setSubOptionSelected = function(_subOptionValue, _index)
{
this.subOptionSelected[_index] = _subOptionValue;
}
/**
- saveOptionSelected
Salvo a opção selecionada e o valor das subopções na seção.
**/
this.saveOptionSelected = function()
{
var parentSection = _that.getParentDiv().getParentDiv();
parentSection.setOptionSelected( this );
}
/**
- setValue
Seto value.
[arg] String _value - valor da opção selecionada
**/
this.setValue = function(_value)
{
this.value = _value;
}
/**
- getInputType
Retorna o tipo dos inputs;
**/
this.getInputType = function()
{
return this.input.type;
}
/**
- getEffort
**/
this.getEffort = function()
{
if(this.data.effort) {
if(this.data.price) this.data.effort.price = this.data.price;
if(this.data.days) this.data.effort.days = this.data.days;
return this.data.effort;
}else if(this.subOptionSelected.length > 0){
return this.getSubOptionsEfforts(this.subOptionSelected);
}
if(this.data.price){
return {price: this.data.price};
}
if(this.data.days){
return {days: this.data.days};
}
}
/**
- getEffort
**/
this.getSubOptionsEfforts = function(_subOptionsArray)
{
var subOptionsEfforts = new Object();
for(var w = 0; w < _subOptionsArray.length; w++) {
if(_subOptionsArray[w].price){
if(!subOptionsEfforts.price) subOptionsEfforts.price = new Number();
subOptionsEfforts.price += _subOptionsArray[w].price;
}
for(var z in _subOptionsArray[w].effort ) {
if(!subOptionsEfforts[z]) subOptionsEfforts[z] = new Number();
subOptionsEfforts[z] += _subOptionsArray[w].effort[z];
}
// console.log(_subOptionsArray[w].days);
if(_subOptionsArray[w].days){
if(!subOptionsEfforts.days) subOptionsEfforts.days = new Number();
subOptionsEfforts.days += _subOptionsArray[w].days;
}
};
return subOptionsEfforts;
}
//
//
//
this.create();
}
|
import React from "react";
import bgfoot from "../video/bgfoot.mp4";
const Bgvideo = () => {
return (
<video
className="bgVideo position-absolute rounded"
autoPlay={1}
muted={1}
loop
id="myVideo"
src={bgfoot}
></video>
);
};
export default Bgvideo;
|
angular.module('webix')
.controller('studentResultController',function ($scope,$rootScope,$http,auth,$interval,$state,webNotification,searchQueryAlert,$mdToast,$filter, $mdDialog) {
if(auth.isAuthed()){
$scope.score = [];
var getScore = function (value) {
if (auth.isAuthed()){
if ($scope.score.length === 0 || value === 1)
$http.get($scope.apiUrl + "/scores/list_score_by_student/?student_id=" + $rootScope.selectedStudent.student_id).then(function (response) {
$scope.score = response.data.results;
for (var i = 0; i < $scope.score.length; i ++ ){
if ($scope.score[i].score >= 9.0)
$scope.score[i].text_score = 'A+';
else if ($scope.score[i].score >= 8.5)
$scope.score[i].text_score = 'A';
else if ($scope.score[i].score >= 8.0)
$scope.score[i].text_score = 'B+';
else if ($scope.score[i].score >= 7.0)
$scope.score[i].text_score = 'B';
else if ($scope.score[i].score >= 6.5)
$scope.score[i].text_score = 'C+';
else if ($scope.score[i].score >= 5.5)
$scope.score[i].text_score = 'C';
else if ($scope.score[i].score >= 5.0)
$scope.score[i].text_score = 'D+';
else if ($scope.score[i].score >= 3.5)
$scope.score[i].text_score = 'D';
else if ($scope.score[i].score === -1){
$scope.score[i].text_score = 'NOT ACTIVE';
$scope.score[i].score = 'NOT ACTIVE';
}
else
$scope.score[i].text_score = 'F';
}
});
}
else{
alert ('Phiên làm việc của bạn đã hết ! Xin mời đăng nhập lại.');
auth.logout();
}
};
getScore(1);
$scope.editScoreModal = function (value){
if(auth.isAuthed()) {
var sessions = [];
for (var i = 0; i < $rootScope.selectedStudent.sessions.length; i++){
for (var j = 0; j < $rootScope.profile.sessions.length; j++){
if ($rootScope.selectedStudent.sessions[i] === $rootScope.profile.sessions[j].id)
sessions.push($rootScope.selectedStudent.sessions[i]);
}
}
if (sessions.length === 0){
$mdToast.show(
$mdToast.simple()
.content("You don't teach this student in any class!")
.hideDelay(2000)
.position('right bottom')
);
}
else {
$mdDialog.show({
locals: {sessions: sessions, student: $rootScope.selectedStudent},
controller: DialogEditScoreController,
templateUrl: 'components/alerts/positive/editScoreTemplate.html',
parent: angular.element(document.body),
clickOutsideToClose: true,
fullscreen: true
})
}
} else {
alert ('Phiên làm việc của bạn đã hết ! Xin mời đăng nhập lại.');
auth.logout();
}
};
function DialogEditScoreController($scope, sessions, student) {
$scope.sessions = sessions;
$scope.tmpscore = {};
$scope.student = student;
var toastSuccess = $mdToast.simple()
.textContent(student.last_name + student.first_name + '\'s Score Updated Successfully.')
.position('right bottom');
var toastFail = $mdToast.simple()
.textContent(student.last_name + student.first_name + '\'s Score Updated Failed.')
.position('right bottom');
$scope.hide = function() {
$mdDialog.hide();
};
$scope.cancel = function() {
$mdDialog.cancel();
};
$scope.edit = function () {
if (auth.isAuthed) {
$scope.tmpscore.session = Number($scope.tmpscore.session);
console.log($scope.tmpscore);
$http({
method: 'POST',
url: $rootScope.apiUrl + '/scores/edit_many/',
data: [{
score: $scope.tmpscore.score,
session_id: $scope.tmpscore.session,
student_id: $scope.student.id
}]
}).then(function (response) {
if (response.data.result) {
$mdDialog.hide();
$mdToast.show(toastSuccess);
getScore(1);
}
else {
$mdDialog.hide();
$mdToast.show(toastFail);
}
})
} else {
alert ('Phiên làm việc của bạn đã hết ! Xin mời đăng nhập lại.');
auth.logout();
}
};
}
} else {
alert ('Phiên làm việc của bạn đã hết ! Xin mời đăng nhập lại');
auth.logout();
}
});
|
import { inject, observer } from 'mobx-react'
import { string } from 'prop-types'
import React, { Component } from 'react'
import AboutProject from './AboutProject'
function storeMapper (stores) {
const { project } = stores.store
return {
projectName: project.display_name
}
}
@inject(storeMapper)
@observer
class AboutProjectContainer extends Component {
render () {
const { projectName, description } = this.props
return <AboutProject description={description} projectName={projectName} />
}
}
AboutProjectContainer.propTypes = {
description: string,
projectName: string
}
AboutProjectContainer.defaultProps = {
description:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis volutpat quam sed nibh interdum, interdum bibendum nisi commodo. In id dui enim. Etiam euismod leo sit amet eros pharetra ullamcorper. Fusce sed dui tincidunt, lobortis tortor a, gravida magna. Quisque ac ligula tristique, iaculis metus vel, pellentesque nulla.'
}
export default AboutProjectContainer
|
const body = document.getElementById('body')
const hideButton = document.getElementById('hide-modal')
const hideButton2 = document.getElementById('hide-modal2')
const modal = document.getElementById('modal')
const overlay = document.getElementById('overlay')
const cancelButton = document.getElementById('cancelButton')
var bandera = false
hideButton.addEventListener('click', () => {
modal.style.animation = 'modalOut .8s forwards'
overlay.classList.remove('active')
})
hideButton2.addEventListener('click', () => {
modal.style.animation = 'modalOut .8s forwards'
overlay.classList.remove('active')
})
cancelButton.addEventListener('click', () => {
modal.style.animation = 'modalOut .8s forwards'
overlay.classList.remove('active')
})
modal.addEventListener('mouseenter' , () => {
bandera = true
console.log(bandera)
return bandera
})
modal.addEventListener('mouseleave' , ()=>{
bandera = false
console.log(bandera)
return bandera
})
overlay.addEventListener('click', () => {
if(!bandera){
modal.style.animation = 'modalOut .8s forwards'
overlay.classList.remove('active')
}
})
|
import React, { PropTypes, Component } from 'react';
import { Button, DropdownButton, MenuItem, Modal } from 'react-bootstrap';
import Router from "../../router.js"
import { ContextPasser } from "meteor/nova:core";
//const ModalTrigger = Core.ModalTrigger;
//const ContextPasser = Core.ContextPasser;
import Portal from 'react-portal';
// note: cannot use ModalTrigger component because of https://github.com/react-bootstrap/react-bootstrap/issues/1808
class PseudoModal extends React.Component {
render() {
({Icon} = Telescope.components);
return (
<div className="modal modal-full">
<div className="modal-content">
{React.cloneElement(
this.props.children,
{closePortal: this.props.closePortal}
)}
</div>
<button className="modal-close btn-floating waves-effect waves-light" onClick={this.props.closePortal}><Icon name="close"/></button>
</div>
);
}
}
class CategoriesList extends Component {
constructor() {
super();
this.openCategoryEditModal = this.openCategoryEditModal.bind(this);
this.openCategoryNewModal = this.openCategoryNewModal.bind(this);
this.closeModal = this.closeModal.bind(this);
this.state = {
openModal: false
}
}
openCategoryNewModal() {
// new category modal has number 0
this.setState({openModal: 0});
}
openCategoryEditModal(index) {
// edit category modals are numbered from 1 to n
this.setState({openModal: index+1});
}
closeModal() {
this.setState({openModal: false});
}
renderCategoryEditModal(category, index) {
const CategoriesEditForm = Telescope.components.CategoriesEditForm;
return (
<Modal key={index} show={this.state.openModal === index+1} onHide={this.closeModal}>
<Modal.Header closeButton>
<Modal.Title>Edit Category</Modal.Title>
</Modal.Header>
<Modal.Body>
<ContextPasser currentUser={this.context.currentUser} closeCallback={this.closeModal}>
<CategoriesEditForm category={category}/>
</ContextPasser>
</Modal.Body>
</Modal>
)
}
renderCategoryNewButton() {
const CategoriesNewForm = Telescope.components.CategoriesNewForm;
const Icon = Telescope.components.Icon;
return (<li className="list-categories_item"><Portal closeOnEsc closeOnOutsideClick openByClickOn={<button className="btn btn-inline"> <Icon name="plus"/> New Category</button>}>
<PseudoModal currentUser={this.context.currentUser}>
<CategoriesNewForm/>
</PseudoModal>
</Portal></li>);
}
renderChildrenCat(allcategory, parent) {
const Category = Telescope.components.Category;
const {category, index} = this.props;
const context = this.context;
const currentRoute = context.currentRoute;
const currentCategorySlug = currentRoute.queryParams.cat;
const childarray = allcategory.filter( (child) => parent._id === child.parentId);
if (childarray.length > 0) {
return <ul> {childarray.map((item, index, array) => <Category
key={index}
category={item}
index={index}
currentCategorySlug={currentCategorySlug}
openModal={_.partial(this.openCategoryEditModal, index)}>
{this.renderChildrenCat(allcategory, item) }
</Category>)}</ul>
} else {
return '';
}
}
renderCatList() {
const Category = Telescope.components.Category;
const categories = this.props.categories;
const context = this.context;
const currentRoute = context.currentRoute;
const currentCategorySlug = currentRoute.queryParams.cat;
if (categories && categories.length > 0 ) {
return categories.map( (category, index, array) => {
if (!_.has(category, 'parentId')) {
return <Category
key={index}
category={category}
index={index}
currentCategorySlug={currentCategorySlug}
allcategory={array} openModal={_.partial(this.openCategoryEditModal, index)}>
{this.renderChildrenCat(array, category)}
</Category>
}
});
} else {
return ('');
}
}
render() {
const Category = Telescope.components.Category;
const categories = this.props.categories;
const context = this.context;
const currentRoute = context.currentRoute;
const currentCategorySlug = currentRoute.queryParams.cat;
return (
<div className="post-list-categories">
<ul className="list-categories with-header">
<li className="list-categories_item-header">
<a href={Router.path("posts.list")} eventKey={0} className="post-category">Categories</a>
</li>
{this.renderCatList()}
{Users.is.admin(this.context.currentUser) ? this.renderCategoryNewButton() : null}
</ul>
<div>
{/* modals cannot be inside DropdownButton component (see GH issue) */}
{categories && categories.length > 0 ? categories.map((category, index) => this.renderCategoryEditModal(category, index)) : null}
</div>
</div>
)
}
};
// <DropdownButton
// bsStyle="default"
// className="categories btn-secondary"
// title="Categories"
// id="categories-dropdown"
// >
// <MenuItem href={Router.path("posts.list")} eventKey={0} className="dropdown-item post-category">All Categories</MenuItem>
// {categories && categories.length > 0 ? categories.map((category, index) => <Category key={index} category={category} index={index} currentCategorySlug={currentCategorySlug} openModal={_.partial(this.openCategoryEditModal, index)}/>) : null}
// {Users.is.admin(this.context.currentUser) ? this.renderCategoryNewButton() : null}
// </DropdownButton>
CategoriesList.propTypes = {
categories: React.PropTypes.array
}
CategoriesList.contextTypes = {
currentUser: React.PropTypes.object,
currentRoute: React.PropTypes.object
};
module.exports = CategoriesList;
export default CategoriesList;
|
$(function ($) {
if ($('#block-small-nav').find("#make-small-nav").length) {
$('#page-wrapper').toggleClass(getCookie('nav'));
}
$('#make-small-nav').on('click', function () {
$('#page-wrapper').toggleClass('nav-small');
var navSmall = '';
if (!$('#page-wrapper').hasClass('nav-small')) {
navSmall = 'nav-small';
}
setCookie('nav', navSmall);
});
});
|
// ------------------------------------
// Constants
// ------------------------------------
export const GET_EVENTS = 'GET_EVENTS'
export const CREATE_EVENT = 'CREATE_EVENT'
// ------------------------------------
// Actions
// ------------------------------------
export const getEvents = () => {
return (dispatch, getState) => {
const { terrapin, coinbase } = getState().init;
return new Promise((resolve, reject) => {
terrapin.getEvents.call(coinbase, (err, eventMatrix) => {
if (err) return reject(err)
// parse ints from events matrix
eventMatrix = eventMatrix.map((val) => parseInt(val.toString()))
console.log('dispach get events', eventMatrix);
dispatch({
type: GET_EVENTS,
eventMatrix
})
resolve();
})
})
}
}
export const createEvent = () => {
return (dispatch, getState) => {
const { terrapin, coinbase } = getState().init
return new Promise((resolve, reject) => {
terrapin.createEvent({ from: coinbase, gas: 4476768 }, (err) => {
if (err) return reject(err)
console.log('created event returned');
terrapin.numEvents.call((err, ans) => {
console.log(err, ans)
dispatch({ type: CREATE_EVENT }) // TODO: currently no handler
resolve();
})
})
})
}
}
export const actions = {
createEvent,
getEvents
}
// ------------------------------------
// Action Handlers
// ------------------------------------
const ACTION_HANDLERS = {
[GET_EVENTS]: (state, action) => {
return {
...state,
eventMatrix: action.eventMatrix
}
}
}
// ------------------------------------
// Reducer
// ------------------------------------
const initialState = 0
export default function counterReducer(state = initialState, action) {
const handler = ACTION_HANDLERS[action.type]
return handler ? handler(state, action) : state
}
|
var builder = require('botbuilder');
module.exports = [
function (session) {
// Prompt the user to select their preferred locale
builder.Prompts.choice(session,
'What\'s your preferred language?',
'English|Deutsch|Pirate',
{
listStyle: builder.ListStyle.button
});
},
function (session, results) {
// Update preferred locale
var locale;
switch (results.response.entity) {
case 'English':
locale = 'en';
break;
case 'Deutsch':
locale = 'de';
break;
case 'Pirate':
locale = 'pirate';
break;
}
session.preferredLocale(locale, function (err) {
if (!err) {
// Locale files loaded
session.endDialog(`Your preferred language is now ${results.response.entity}`);
} else {
// Problem loading the selected locale
session.error(err);
}
});
}
]
|
// Arithmetic Operator
// Addition +
// Subtraction -
// Multiplication *
// Division /
// Exponentiation **
// Modulus %
// Increment ++
// Decrement --
let i = 10;
i--; // i = i - 1
console.log(i);
|
const express = require('express');
const helmet = require('helmet');
const bodyParser = require('body-parser');
const mainController = require('./controllers/main.controller')
const server = express();
server.use(helmet());
server.use(bodyParser.json());
server.post("/nuevoAutor", mainController.registrarAutor);
server.put("/actualizarAutor", mainController.actualizarAutor);
server.get("/autor/:_id", mainController.leerAutorPorId);
server.get("/autores", mainController.leerTodosLosAutores);
server.delete("/eliminarAutor/:_id", mainController.eliminarAutorPorId)
server.post("/registrarReceta", mainController.registrarReceta);
server.get("/leerRecetaPorId/:_id", mainController.leerRecetaPorId)
const PORT = process.env.PORT;
server.listen(PORT, () => {
console.log( `Servidor escuchando en el puerto ${PORT}`)
});
|
/**
* Created by fdr08 on 2016/7/5.
*/
import "../../style/css/awesome.less";
import "../../style/css/base.less";
import "../../style/css/com.less";
import "../../style/css/info.less";
import {core} from "../common/com";
function teleplayClick() {
$(this).css({backgroundColor: "#000", color: "#fff"})
.siblings("button").css({backgroundColor: "#fff", color: "#000"})
}
$(".select").on("click", ">button", teleplayClick);
|
import React from 'react';
import {
Text,
StyleSheet,
View,
Image,
ToastAndroid,
} from 'react-native';
import Navbar from './HomeElement/navbar'
import BackButton from './HomeElement/backbutton'
import { TouchableOpacity } from 'react-native-gesture-handler';
export default class Home extends React.Component {
constructor(props){
super(props)
this.state = {
data:''
}
}
styles = StyleSheet.create({
body: {
backgroundColor: "#FFFFFF",
flex: 1,
},
header: {
flexDirection: "row",
height: 62,
marginBottom: 5
},
headerItem: {
marginLeft: 20,
marginRight: 20,
},
title: {
flex: 10,
fontSize: 40,
fontFamily: "SVN-Journey-Bold",
letterSpacing: 2,
padding: 2,
},
avatar: {
width: 35,
height: 35,
flex: 2,
alignItems: "flex-end",
paddingTop: 12
},
avatarImg: {
width: 35,
height: 35,
borderRadius: 999,
},
})
render(){
console.disableYellowBox = true;
console.log("userID ", this.state.data)
return (
<View style={this.styles.body}>
<TouchableOpacity onPress={() => this.props.navigation.goBack()}>
<BackButton></BackButton>
</TouchableOpacity>
<View style={[this.styles.header, this.styles.headerItem]}>
<View>
<Text style={this.styles.title}>Little garden </Text>
</View>
<View style={this.styles.avatar}>
<TouchableOpacity onPress={()=>this.props.navigation.navigate('User')}>
<Image style={this.styles.avatarImg} source={require('../assets/images/ava2.png')} />
</TouchableOpacity>
</View>
</View>
<Navbar></Navbar>
</View>
);
}
}
|
var saxn = require('saxn-saxjs');
var fs = require('fs');
var util = require('util');
var sax = require('sax').parser(true, {lowercasetags:true, trim:true});
var items = [];
var parser = saxn.createSaxnSaxjsParser(sax, {
'item': function(tag) {
var fields = [];
return {
'*': function(tag) {
var innerText = '';
return {
$text: function(text) {
innerText += text;
},
$end: function() {
fields.push('\t\t' + tag.name + ': "' + innerText + '"');
}
};
},
// ignore the description for the sake of clarity
'description': {},
$end: function() {
items.push('\t{\n' + fields.join(',\n') + '\n\t}');
}
};
}
});
var readStream = fs.createReadStream(process.argv[2], { encoding: 'utf8' });
readStream.on('data', function(data) { parser(data); });
readStream.on('end', function() {
process.stdout.write('[\n' + items.join(',\n') + '\n]\n');
});
|
import { Container } from "./TextDiv.styles";
export default function TextDiv({ children, isExhibition }) {
return <Container isExhibition={isExhibition} className="animeLeft">{children}</Container>;
}
|
//收获信息
$(window).load(function(){
$(".addli li").hide();
$(".addli li:eq(0)").show();
$(".addli li:eq(1)").show();
$(".addli li:eq(2)").show();
$(".addli li:eq(3)").show();
//页面加载出来就计算
//得到商品的属性 图片 标题 颜色 尺寸 单价 数量 小计
//图片
//$(".simg").attr('src', '');
//标题
//$(".stite").attr("")
//颜色
//$(".scolor").html();
//尺寸
//$(".ssize").html();
// 单价
//$(".sprice").html()
// 数量
//$(".smum").html();
// 小计
//$(".smoneyall").html();
//应付金额--总商品金额+运费
//拿到运费
var fre=$(".fremoeny").html();
//ajaxna拿到购物车商品的价格+运费
//拿到总价格
var summoney=$(".paynum").html();
});
//显示更多的按钮
$(".show-address .myshowselect").click(function(){
$(".addli li").show();
$(this).css("color", "grey");
});
//删除地址
$(".handle-delete").click(function(){
that=this;
$(".myconfirm").click(function(){
$(that).parent(".myinfo").parent(".li-inner").parent("li").remove();
$(this).attr("data-dismiss","modal");
});
// if(confirm("您真的要删除该数据吗?")){
// $(this).parent(".myinfo").parent(".li-inner").parent("li").remove();
// }
});
$(".select-address").mouseenter(function(){
//$(this).siblings("li").find(".addr-set").html("设置默认");
});
$(".select-address").mouseleave(function(){
});
$(".addli li").mouseenter(function(){
$(this).find(".handle-delete").show();
$(this).find(".addr-set").show();
$(this).find(".addr-alter").show();
$(".select-address").find(".addr-set").hide();
});
$(".addli>li").mouseleave(function(){
$(this).find(".handle-delete").hide();
$(this).find(".addr-set").hide();
$(".select-address").find(".addr-set").hide();
$(this).find(".addr-alter").hide();
$(".select-address").find(".addr-alter").show();
});
$(".addli>li").click(function(){
// $(this).addClass("select-address").siblings("li").removeClass("select-address");
$(".addli>li").find(".addr-alter").hide();
$(".select-address").find(".addr-alter").show();
});
//点击修改
$(".addr-alter").click(function(){
// 姓名
var name=$(this).parent(".li-inner").children(".myinfo").find(".myname").html();
// 省
var province=$(this).parent(".li-inner").children(".myinfo-address").find(".myprovince").html();
var city=$(this).parent(".li-inner").children(".myinfo-address").find(".mydistrict").html();
var street=$(this).parent(".li-inner").children(".myinfo-address").find(".mystreet").html();
var home=$(this).parent(".li-inner").children(".myinfo-address").find(".myhome").html();
var telephone=$(this).parent(".li-inner").children(".myinfo-address").find(".mytelephone").html();
$(".update-info .addrmyname-input .adrname").val(name);
$(".update-info .addrmyphone .adrphone").val(telephone);
$(".update-info .addrmyadr .adrarea").val(province+city+ street);
$(".update-info .mydetailed .adrdetailed").val(home);
});
$(".addr-set").click(function(){
$(this).parent(".li-inner").parent("li").addClass("select-address").siblings("li").removeClass("select-address");
$(".addli>li").find(".addr-alter").hide();
$(".select-address").find(".addr-alter").show();
});
//支付方式
$(".paymode>li").click(function(){
$(this).css("border","2px solid gold").siblings("li").css("border","none");
$(this).addClass("paydefault").siblings("li").removeClass("paydefault");
// 拿到支付方式
});
//商品服务
//返回购物车
$(".returncar").click(function(){
window.location.href ='shopcar.html';
});
//点击商品链接
//提交订单
$(".pay-btn").click(function(){
// 拿到各个商品
//修改支付状态
//商品留言mywrite
$(".mywrite").val();
location.href="mypay.html";
});
//增加地址
//定义三个锁
var falgincreone=false;
var falgincretwo=false;
var falgincrethree=false;
$(".increasename").focus(function(){
$(this).siblings("p").hide();
});
$(".increasename").blur(function(){
var value=$(this).val();
var reg=/^([\u4e00-\u9fa5]|[A-Za-z0-9])+$/g;
if(value=="") {
$(this).siblings(".increasenameerr-one").show();
falgincreone=false;
return
}else if(!reg.test(value)){
$(this).siblings(".increasenameerr-two").show();
falgincreone=false;
return
}
falgincreone=true;
$(this).siblings(".increasesucces-one").show();
});
//电话
$(".increasephone").focus(function(){
$(this).siblings("p").hide();
});
$(".increasephone").blur(function(){
var value=$(this).val();
var reg=/^1(3|4|5|6|7|8|9)\d{9}$/;
if(value=="") {
$(this).siblings(".increasephoneerr-one").show();
falgincretwo=false;
return
}else if(!reg.test(value)){
$(this).siblings(".increasephoneerr-two").show();
falgincretwo=false;
return
}
falgincretwo=true;
$(this).siblings(".increasesucces-two").show();
});
//区域地址
//详细地址
$(".incredetailed").focus(function(){
$(this).siblings("p").hide();
});
$(".incredetailed").blur(function(){
var value=$(this).val();
if(value==""){
$(this).siblings(".incredetailederr-three").show();
falgincrethree=false;
return
}
falgincrethree=true;
$(this).siblings(".increasesucces-three").show();
});
//提交保存
$(".savemyincrease").click(function(){
if(!falgincreone){
$(".increasename").focus();
return
}else if(!falgincretwo){
$(".increasephone").focus();
return
}else if(!falgincrethree){
$(".incredetailed").focus();
return
}
$(".increasename").val();
$(".increasephone").val();
$(".incredetailed").val();
// 存入数据库
//显示页面
});
//修该地址
//姓名输入
//定义三个锁
var falgone=false;
var falgtwo=false;
var falgthree=false;
$(".adrname").focus(function(){
$(this).siblings("p").hide();
});
$(".adrname").blur(function(){
var value=$(this).val();
var reg=/^([\u4e00-\u9fa5]|[A-Za-z0-9])+$/g;
if(value=="") {
$(this).siblings(".mynameerr-one").show();
falgone=false;
return
}else if(!reg.test(value)){
$(this).siblings(".mynameerr-two").show();
falgone=false;
return
}
falgone=true;
$(this).siblings(".mysucces-one").show();
});
//电话
$(".adrphone").focus(function(){
$(this).siblings("p").hide();
});
$(".adrphone").blur(function(){
var value=$(this).val();
var reg=/^1(3|4|5|6|7|8|9)\d{9}$/;
if(value=="") {
$(this).siblings(".myphoneerr-one").show();
falgtwo=false;
return
}else if(!reg.test(value)){
$(this).siblings(".myphoneerr-two").show();
falgtwo=false;
return
}
falgtwo=true;
$(this).siblings(".mysucces-two").show();
});
//详细地址
$(".adrdetailed").focus(function(){
$(this).siblings("p").hide();
});
$(".adrdetailed").blur(function(){
var value=$(this).val();
if(value==""){
$(this).siblings(".detailederr-three").show();
falgthree=false;
return
}
falgthree=true;
$(this).siblings(".mysucces-three").show();
});
//提交保存
$(".savemyaddr").click(function(){
if(!falgone){
$(".adrname").focus();
return
}else if(!falgtwo){
$(".adrphone").focus();
return
}else if(!falgthree){
$(".adrdetailed").focus();
return
}
//得到值
// $(".adrname").val();
alert("修改成功")
});
|
var openPhotoSwipe = function(images) {
//console.log('function images', images);
var pswpElement = document.querySelectorAll('.pswp')[0];
var photoImage = images.split(",");
// console.log(photoImage);
// build image items array
var items = [];
$.each(photoImage, function(index, imageDetails){
console.log(imageDetails);
var imageDet = String(imageDetails);
var imageRecord = imageDet.split('|');
var imageLoc = imageRecord[0];
var imageCap = imageRecord[1];
//console.log(imageLoc);
var imageObj = {src: imageLoc, w: 0, h: 0, title: imageCap}
//console.log(imageObj);
items.push(imageObj);
});
// define options (if needed)
var options = {
// history & focus options are disabled on CodePen
index: 0
};
var gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
gallery.listen('gettingData', function(index, item) {
if (item.w < 1 || item.h < 1) { // unknown size
var img = new Image();
img.onload = function() { // will get size after load
// console.log(this.width);
item.w = this.width; // set image width
item.h = this.height; // set image height
gallery.invalidateCurrItems(); // reinit Items
gallery.updateSize(true); // reinit Items
}
img.src = item.src; // let's download image
}
});
gallery.init();
};
$(document).ready(function() {
$("#viewEventGallery").on('click', function(){
var postImages = $("#postimages").val();
//console.log(postImages);
openPhotoSwipe(postImages);
});
});
|
import React from "react";
import data from "./data";
import Data from "./data";
import Names from "./component/Names";
import Card from "./component/Card";
class App extends React.Component{
state = {names: [], ultities: [], bornbefore90: []}
messageData = () => {
this.setState({ultities: data})
}
names = () => {
const names = Data.map((data) => data.name);
this.setState({names: names})
}
before1990 = () => {
const res = data.filter((people) => people.birthday.split("-")[2]< 1990)
this.setState({bornbefore90: res})
}
componentDidMount(){
this.messageData()
this.names()
this.before1990()
}
render(){
return <div>
<Names data={this.state.names}/>
<Card card={this.state.bornbefore90}/>
</div>
}
}
export default App;
|
var contextMenu = require("sdk/context-menu");
var self = require("sdk/self");
var tabs = require("sdk/tabs");
var menuItem = contextMenu.Item({
label: "Open in Jira",
image: self.data.url("jira.png"),
context: contextMenu.SelectionContext(),
contentScript: 'self.on("click", function () {' +
' var text = window.getSelection().toString();' +
' self.postMessage(text);' +
'});',
onMessage: function (selectionText) {
var url = "https://photorank.atlassian.net/browse/";
tabs.open(url + selectionText);
}
});
|
var symbols = ["a", "b", "c"];
var numbers = [1, 2, 3];
var newArr = symbols.concat(numbers);
console.log(newArr);
|
module.exports = function($scope, UserService) {
$scope.username = UserService.username()
if ((UserService.username() == undefined) || (UserService.username() == '')){
$scope.userStatus = 'signedOut'
} else {
$scope.userStatus = 'signedIn'
}
}
|
var fs = require("fs");
fs.readFileSync("input.txt").toString().split("\n").forEach(function (line) {
if (line !== "") {
penultimateWord(line);
}
});
function penultimateWord(line) {
var words = line.trim().split(" ");
console.log(words[words.length - 2]);
}
|
let Sequelize = require("sequelize");
let Model = Sequelize.Model;
let { sequelize } = require("../DB/mysql");
class DriverBooking extends Model { }
DriverBooking.init({
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
driver_id: {
type: Sequelize.INTEGER,
allowNull: false
},
date: {
type: Sequelize.DATE,
allowNull: false
},
trip_start: {
type: Sequelize.TIME,
allowNull: false
},
trip_end: {
type: Sequelize.TIME,
allowNull: false
}
}, { sequelize, underscored: true, tableName: "driver_booking" });
module.exports.DriverBooking = DriverBooking;
|
function clone(x) {
const uniq = [];
let root = {};
const loopList = [{
parent: root,
key: undefined,
data: x
}]
while(loopList.length) {
const node = loopList.pop();
const parent = node.parent;
const key = node.key;
const data = node.data;
let res = parent;
if(typeof key !=="undefined") {
res = parent[key] = {}
}
let uniqData = find(uniq, data);
if(uniqData) {
parent[key] = uniqData.target;
continue;
}
uniq.push({
source: data,
target: res
})
for(let k in data) {
if(data.hasOwnProperty(k)) {
if(typeof data[k] === 'object') {
loopList.push({
parent: res,
key: k,
data: data[k]
})
} else {
res[k] = data[k]
}
}
}
}
return root;
}
function find(arr, item) {
console.log(arr, ">>>>>>>>>>>>>>>>>" , item)
for(let i = 0;i < arr.length; i++) {
if(arr[i].source === item) {
return arr[i];
}
}
return null;
}
var a = {
b: 1,
c: {
d: 2,
e: 3
}
}
var k = clone(a);
console.log(k);
|
import express from 'express'
const app = express()
import api from './routes'
app.use('/api',api)
export default app;
|
(global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/activity_a/common/vendor" ], {
6115: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.default = void 0;
var s = i("64ed"), c = {
getThematicBuildings: function(e) {
return (0, s.getActivity)("".concat(s.ACT_API_PREFIX_AAA, "thematic_buildings"), e, {
loading: !0
});
}
};
t.default = c;
},
e020: function(e, t, i) {
Object.defineProperty(t, "__esModule", {
value: !0
}), t.Tabs_TYPS = void 0;
var s = [ {
index: 0,
first: "年度买房",
sec: "必看榜",
type: "see",
desc: "以楼盘2020年全年度楼盘自身品质、价值潜力、品牌美誉为主要依据,结合楼盘线上用户关注度等指标,严格挑选出高品质必看楼盘。",
list_items: []
}, {
index: 1,
first: "年度",
sec: "口碑楼盘",
type: "mouth",
desc: "以楼盘2020年全年度用户综合好评率为主要依据,体现出具有良好口碑的优质楼盘。",
list_items: []
}, {
index: 2,
first: "年度",
sec: "人气楼盘",
type: "sentiment",
desc: "以楼盘2020年全年度用户浏览量、搜索量、关注量等为依据,综合体现用户关注度高的楼盘。",
list_items: []
}, {
index: 3,
first: "年度品质",
sec: "服务楼盘",
type: "service",
desc: "以楼盘2020年全年度置业顾问线上服务的水平、电话接通率、微聊响应速度等为依据,综合考虑楼盘的自身品质服务水平。",
list_items: []
}, {
index: 4,
first: "2021年度值得",
sec: "期待楼盘",
type: "forward",
desc: "预计楼盘的开盘时间节点为2021年度,且以用户关注量、搜索量、浏览量为依据,综合体现2021年度值得用户期待的楼盘;",
list_items: []
} ];
t.Tabs_TYPS = s;
}
} ]);
|
// collapse sidebar into buttons
$(function() {
var $el2 = $(".skin-blue");
$el2.addClass("sidebar-mini");
var $sidebarInput = $("#maps");
var $logo = $(".logo");
$(".sidebar-toggle").click(function() {
$sidebarInput.toggle(400);
$logo.toggle(400);
});
});
|
// JavaScript Document
alert("Esto se carga desde externo");
|
module.exports = {
secret: "kudo-secret-key"
};
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(function(){
//刷新
$("#freshbtn").click(function(){
$.ajax({
type:'POST',
url:'/loadrole/loadrole',
data:"",
dataType:'json',
success:function(result){
if(result.errcode == 0){
$("#showTable").html("");
$("#loading").html("");
$("#showTable").html(result.msg);
}else{
$("#loading").html("");
}
},
beforeSend:function()
{
$("#loading").html("<img src='../img/spinner.gif' />");
}
});
});
});
|
import React from 'react'
import "./gallows.css"
export default function Gallows({strikes}) {
return (
<div className="gallowsContainer">
<div className="gallows">
{strikes >= 1 && <div className="frame">
<div className="bottom"></div>
<div className="post"></div>
<div className="top"></div>
<div className="down"></div>
<div className="angle"></div>
</div>}
<div className="person">
{strikes >= 2 && <div className="head"></div>}
{strikes >= 3 && <div className="torso"></div>}
{strikes >= 4 && <div className="leftArm"></div>}
{strikes >= 5 && <div className="rightArm"></div>}
{strikes >= 6 && <div className="leftLeg"></div>}
{strikes >= 7 && <div className="rightLeg"></div>}
</div>
</div>
</div>
)
}
|
(function(window, angular, undefined) {
'use strict';
angular.module('manageChallenge')
.constant("TC_URLS", {
"baseChallengeDetailsUrl": "http://www.topcoder.com/challenge-details/",
"baseMemberProfileUrl": "https://www.topcoder.com/member-profile/"
})
.constant("TC_DATA_SOURCE", {
"challenge": {
useLocal: false
}
});
})(window, window.angular);
|
var myrules = {
'form#pForm' : function(element){
element.onsubmit = function(){
if(this.user_id.value == "") {
alert("Please select a user before submitting info.");
this.user_id.focus();
return false ;
}
if (this.comments.value == "") {
alert("Please add a comment before submitting info.");
this.comments.focus();
return false;
}
return true;
}
}
};
Behaviour.register(myrules);
|
import React from 'react'
import { Link } from 'react-router-dom'
import styled,{keyframes} from 'styled-components'
import { AiOutlineArrowRight } from 'react-icons/ai';
const arrowanimation = keyframes`
0%{
transform: translateX(0);
}
100%{
transform: translateX(1rem);
}
`;
const Buttona = styled(Link)`
text-decoration: none;
font-weight: 500;
text-transform: capitalize;
border-radius: 50px;
padding: ${({ big }) => (big ? '0 3rem' : '0 1.5rem')};
background-color: #d99923;
color: #fff;
text-align: center;
user-select: none;
line-height: 40px;
height: 4rem;
letter-spacing: ${({ big }) => (big ? '0.4rem' : '0.02rem')};
width: ${({ big }) => (big ? '16rem' : '12rem')};
transition: all 0.3s ease-in-out;
display: flex;
&:hover {
color: #d99923;
background-color: #0d0d0d;
}
`;
const Textcontainer = styled.span`
margin: 0 auto;
font-size: ${({ big }) => (big ? '1.9rem' : '1.8rem')};
display: flex;
justify-content: center;
align-items: center;
`;
const Arrow = styled(AiOutlineArrowRight)`
animation-name: ${arrowanimation};
animation-duration: 1s;
animation-iteration-count: infinite;
margin-left: 1rem;
font-size: 1.7rem;
`;
;
const Button = (props) => {
const {children, button, link, big, Hero} = props
if (button){
return (
<Buttona to={`${link}`} big={big}>
<Textcontainer big={big}>
{children}
{Hero && <Arrow />}
</Textcontainer>
</Buttona>
);
}
return (
<Link to={`${link}`} big={big}>
<Textcontainer big={big}>
{children}
{Hero && <Arrow />}
</Textcontainer>
</Link>
);
}
export default Button
|
var dialingCodes = [
{ Country: "Afghanistan", code: "+93" },
{ Country: "Albania", code: "+355" },
{ Country: "Algeria", code: "+213" },
{ Country: "American Samoa", code: "+1684" },
{ Country: "Andorra", code: "+376" },
{ Country: "Angola", code: "+244" },
{ Country: "Anguilla", code: "+1264" },
{ Country: "Antarctica", code: "+672" },
{ Country: "Antigua & Barbuda", code: "+1268" },
{ Country: "Argentina", code: "+54" },
{ Country: "Armenia", code: "+374" },
{ Country: "Aruba", code: "+297" },
{ Country: "Australia", code: "+61" },
{ Country: "Austria", code: "+43" },
{ Country: "Azerbaijan", code: "+994" },
{ Country: "Bahamas", code: "+1242" },
{ Country: "Bahrain", code: "+973" },
{ Country: "Bangladesh", code: "+880" },
{ Country: "Barbados", code: "+1246" },
{ Country: "Belarus", code: "+375" },
{ Country: "Belgium", code: "+32" },
{ Country: "Belize", code: "+501" },
{ Country: "Benin", code: "+229" },
{ Country: "Bermuda", code: "+1441" },
{ Country: "Bhutan", code: "+975" },
{ Country: "Bolivia", code: "+591" },
{ Country: "Bosnia", code: "+387" },
{ Country: "Botswana", code: "+267" },
{ Country: "Bouvet Island", code: "+47" },
{ Country: "Brazil", code: "+55" },
{ Country: "British Indian Ocean Territory", code: "+246" },
{ Country: "British Virgin Islands", code: "+1284" },
{ Country: "Brunei", code: "+673" },
{ Country: "Bulgaria", code: "+359" },
{ Country: "Burkina Faso", code: "+226" },
{ Country: "Burundi", code: "+257" },
{ Country: "Cambodia", code: "+855" },
{ Country: "Cameroon", code: "+237" },
{ Country: "Canada", code: "+1" },
{ Country: "Cape Verde", code: "+238" },
{ Country: "Caribbean Netherlands", code: "+599" },
{ Country: "Cayman Islands", code: "+1345" },
{ Country: "Central African Republic", code: "+236" },
{ Country: "Chad", code: "+235" },
{ Country: "Chile", code: "+56" },
{ Country: "China", code: "+86" },
{ Country: "Christmas Island", code: "+61" },
{ Country: "Cocos (Keeling) Islands", code: "+61" },
{ Country: "Colombia", code: "+57" },
{ Country: "Comoros", code: "+269" },
{ Country: "Congo - Brazzaville", code: "+242" },
{ Country: "Congo - Kinshasa", code: "+243" },
{ Country: "Cook Islands", code: "+682" },
{ Country: "Costa Rica", code: "+506" },
{ Country: "Croatia", code: "+385" },
{ Country: "Cuba", code: "+53" },
{ Country: "Curaçao", code: "+599" },
{ Country: "Cyprus", code: "+357" },
{ Country: "Czech Republic", code: "+420" },
{ Country: "Côte d'Ivoire", code: "+225" },
{ Country: "Denmark", code: "+45" },
{ Country: "Djibouti", code: "+253" },
{ Country: "Dominica", code: "+1767" },
{ Country: "Dominican Republic", code: "+1809" },
{ Country: "Dominican Republic", code: "+1829" },
{ Country: "Dominican Republic", code: "+1849" },
{ Country: "Ecuador", code: "+593" },
{ Country: "Egypt", code: "+20" },
{ Country: "El Salvador", code: "+503" },
{ Country: "Equatorial Guinea", code: "+240" },
{ Country: "Eritrea", code: "+291" },
{ Country: "Estonia", code: "+372" },
{ Country: "Ethiopia", code: "+251" },
{ Country: "Falkland Islands", code: "+500" },
{ Country: "Faroe Islands", code: "+298" },
{ Country: "Fiji", code: "+679" },
{ Country: "Finland", code: "+358" },
{ Country: "France", code: "+33" },
{ Country: "French Guiana", code: "+594" },
{ Country: "French Polynesia", code: "+689" },
{ Country: "French Southern Territories", code: "+262" },
{ Country: "Gabon", code: "+241" },
{ Country: "Gambia", code: "+220" },
{ Country: "Georgia", code: "+995" },
{ Country: "Germany", code: "+49" },
{ Country: "Ghana", code: "+233" },
{ Country: "Gibraltar", code: "+350" },
{ Country: "Greece", code: "+30" },
{ Country: "Greenland", code: "+299" },
{ Country: "Grenada", code: "+1473" },
{ Country: "Guadeloupe", code: "+590" },
{ Country: "Guam", code: "+1671" },
{ Country: "Guatemala", code: "+502" },
{ Country: "Guernsey", code: "+44" },
{ Country: "Guinea", code: "+224" },
{ Country: "Guinea-Bissau", code: "+245" },
{ Country: "Guyana", code: "+592" },
{ Country: "Haiti", code: "+509" },
{ Country: "Heard & McDonald Islands", code: "+672" },
{ Country: "Honduras", code: "+504" },
{ Country: "Hong Kong", code: "+852" },
{ Country: "Hungary", code: "+36" },
{ Country: "Iceland", code: "+354" },
{ Country: "India", code: "+91" },
{ Country: "Indonesia", code: "+62" },
{ Country: "Iran", code: "+98" },
{ Country: "Iraq", code: "+964" },
{ Country: "Ireland", code: "+353" },
{ Country: "Isle of Man", code: "+44" },
{ Country: "Israel", code: "+972" },
{ Country: "Italy", code: "+39" },
{ Country: "Jamaica", code: "+1876" },
{ Country: "Japan", code: "+81" },
{ Country: "Jersey", code: "+44" },
{ Country: "Jordan", code: "+962" },
{ Country: "Kazakhstan", code: "+7" },
{ Country: "Kenya", code: "+254" },
{ Country: "Kiribati", code: "+686" },
{ Country: "Kuwait", code: "+965" },
{ Country: "Kyrgyzstan", code: "+996" },
{ Country: "Laos", code: "+856" },
{ Country: "Latvia", code: "+371" },
{ Country: "Lebanon", code: "+961" },
{ Country: "Lesotho", code: "+266" },
{ Country: "Liberia", code: "+231" },
{ Country: "Libya", code: "+218" },
{ Country: "Liechtenstein", code: "+423" },
{ Country: "Lithuania", code: "+370" },
{ Country: "Luxembourg", code: "+352" },
{ Country: "Macau", code: "+853" },
{ Country: "Macedonia", code: "+389" },
{ Country: "Madagascar", code: "+261" },
{ Country: "Malawi", code: "+265" },
{ Country: "Malaysia", code: "+60" },
{ Country: "Maldives", code: "+960" },
{ Country: "Mali", code: "+223" },
{ Country: "Malta", code: "+356" },
{ Country: "Marshall Islands", code: "+692" },
{ Country: "Martinique", code: "+596" },
{ Country: "Mauritania", code: "+222" },
{ Country: "Mauritius", code: "+230" },
{ Country: "Mayotte", code: "+262" },
{ Country: "Mexico", code: "+52" },
{ Country: "Micronesia", code: "+691" },
{ Country: "Moldova", code: "+373" },
{ Country: "Monaco", code: "+377" },
{ Country: "Mongolia", code: "+976" },
{ Country: "Montenegro", code: "+382" },
{ Country: "Montserrat", code: "+1664" },
{ Country: "Morocco", code: "+212" },
{ Country: "Mozambique", code: "+258" },
{ Country: "Myanmar", code: "+95" },
{ Country: "Namibia", code: "+264" },
{ Country: "Nauru", code: "+674" },
{ Country: "Nepal", code: "+977" },
{ Country: "Netherlands", code: "+31" },
{ Country: "New Caledonia", code: "+687" },
{ Country: "New Zealand", code: "+64" },
{ Country: "Nicaragua", code: "+505" },
{ Country: "Niger", code: "+227" },
{ Country: "Nigeria", code: "+234" },
{ Country: "Niue", code: "+683" },
{ Country: "Norfolk Island", code: "+672" },
{ Country: "North Korea", code: "+850" },
{ Country: "Northern Mariana Islands", code: "+1670" },
{ Country: "Norway", code: "+47" },
{ Country: "Oman", code: "+968" },
{ Country: "Pakistan", code: "+92" },
{ Country: "Palau", code: "+680" },
{ Country: "Palestine", code: "+970" },
{ Country: "Panama", code: "+507" },
{ Country: "Papua New Guinea", code: "+675" },
{ Country: "Paraguay", code: "+595" },
{ Country: "Peru", code: "+51" },
{ Country: "Philippines", code: "+63" },
{ Country: "Pitcairn Islands", code: "+870" },
{ Country: "Poland", code: "+48" },
{ Country: "Portugal", code: "+351" },
{ Country: "Puerto Rico", code: "+1" },
{ Country: "Qatar", code: "+974" },
{ Country: "Romania", code: "+40" },
{ Country: "Russia", code: "+7" },
{ Country: "Rwanda", code: "+250" },
{ Country: "Réunion", code: "+262" },
{ Country: "Samoa", code: "+685" },
{ Country: "San Marino", code: "+378" },
{ Country: "Saudi Arabia", code: "+966" },
{ Country: "Senegal", code: "+221" },
{ Country: "Serbia", code: "+381" },
{ Country: "Seychelles", code: "+248" },
{ Country: "Sierra Leone", code: "+232" },
{ Country: "Singapore", code: "+65" },
{ Country: "Sint Maarten", code: "+1721" },
{ Country: "Slovakia", code: "+421" },
{ Country: "Slovenia", code: "+386" },
{ Country: "Solomon Islands", code: "+677" },
{ Country: "Somalia", code: "+252" },
{ Country: "South Africa", code: "+27" },
{ Country: "South Georgia & South Sandwich Islands", code: "+500" },
{ Country: "South Korea", code: "+82" },
{ Country: "South Sudan", code: "+211" },
{ Country: "Spain", code: "+34" },
{ Country: "Sri Lanka", code: "+94" },
{ Country: "Saint Barthélemy", code: "+590" },
{ Country: "St. Helena", code: "+290" },
{ Country: "St. Kitts & Nevis", code: "+1869" },
{ Country: "St. Lucia", code: "+1758" },
{ Country: "St. Martin", code: "+590" },
{ Country: "St. Pierre & Miquelon", code: "+508" },
{ Country: "St. Vincent & Grenadines", code: "+1784" },
{ Country: "Sudan", code: "+249" },
{ Country: "Suriname", code: "+597" },
{ Country: "Svalbard & Jan Mayen", code: "+47" },
{ Country: "Swaziland", code: "+268" },
{ Country: "Sweden", code: "+46" },
{ Country: "Switzerland", code: "+41" },
{ Country: "Syria", code: "+963" },
{ Country: "Sao Tome and Principe", code: "+239" },
{ Country: "Taiwan", code: "+886" },
{ Country: "Tajikistan", code: "+992" },
{ Country: "Tanzania", code: "+255" },
{ Country: "Thailand", code: "+66" },
{ Country: "Timor-Leste", code: "+670" },
{ Country: "Togo", code: "+228" },
{ Country: "Tokelau", code: "+690" },
{ Country: "Tonga", code: "+676" },
{ Country: "Trinidad & Tobago", code: "+1868" },
{ Country: "Tunisia", code: "+216" },
{ Country: "Turkey", code: "+90" },
{ Country: "Turkmenistan", code: "+993" },
{ Country: "Turks & Caicos Islands", code: "+1649" },
{ Country: "Tuvalu", code: "+688" },
{ Country: "U.S. Virgin Islands", code: "+1340" },
{ Country: "UK", code: "+44" },
{ Country: "US", code: "+1" },
{ Country: "Uganda", code: "+256" },
{ Country: "Ukraine", code: "+380" },
{ Country: "United Arab Emirates", code: "+971" },
{ Country: "Uruguay", code: "+598" },
{ Country: "Uzbekistan", code: "+998" },
{ Country: "Vanuatu", code: "+678" },
{ Country: "Vatican City", code: "+3906" },
{ Country: "Venezuela", code: "+58" },
{ Country: "Vietnam", code: "+84" },
{ Country: "Wallis & Futuna", code: "+681" },
{ Country: "Western Sahara", code: "+212" },
{ Country: "Yemen", code: "+967" },
{ Country: "Zambia", code: "+260" },
{ Country: "Zimbabwe", code: "+263" },
{ Country: "Ãland Islands", code: "+358" }
];
|
import './css/editor.css';
import './css/master-content.css';
import './css/animate.css';
import './css/style.css';
let styleMsg = [0, 1, 2].map(function(i) {
return require('raw-loader!./src/txt/style' + i + '.txt');
});
import mastercontent from 'raw-loader!./src/txt/master-content.txt';
import styleeditor from 'raw-loader!./src/txt/styleEditor.txt';
import mastereditor from 'raw-loader!./src/txt/masterEditor.txt';
import trickeditor from 'raw-loader!./src/txt/trickEditor.txt';
import itemMsg from 'raw-loader!./src/txt/item.txt';
import { sleep } from './lib/sleep';
import {
default as writeChar,
writeSimpleChar,
handleChar,
} from './lib/writeChar';
import { addClickListener, changeEditor } from './lib/click';
import { createItem, addSVGmousemoveListener } from './lib/item';
import 'jquery';
import 'jquery-ui-bundle';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { itemsmsg } from './src/item.json';
const style = document.createElement('style');
let interval = 16;
document.head.appendChild(style);
let animationSkipped = false;
let skipButton = document.querySelector('#skipButton');
skipButton.addEventListener('click', e => {
e.preventDefault();
animationSkipped = true;
document
.querySelector('body')
.removeChild(document.getElementById('skipButton'));
});
async function start() {
try {
await createEditor('desktop', styleeditor);
createEditor('desktop', mastereditor);
createEditor('desktop', trickeditor);
let styleText = document.getElementById('style-text');
await writeTo(
styleText,
styleMsg[0].replace(/[\n]/gi, ''),
true,
interval,
0,
1,
);
let styleBox = document.getElementById('style-box'),
masterBox = document.getElementById('master-box'),
gameBox = document.getElementById('game-box'),
trickBox = document.getElementById('trick-box');
let Boxs = [masterBox, styleBox, gameBox, trickBox];
changeEditor(masterBox, styleBox);
addmasterContent();
await changeEditor(styleBox, masterBox);
await writeTo(
styleText,
styleMsg[1].replace(/[\n]/gi, ''),
true,
interval,
0,
1,
);
await await createItem(itemsmsg, itemMsg);
await sleep(1000);
showGameAndTrick();
await writeTo(
styleText,
styleMsg[2].replace(/[\n]/gi, ''),
true,
interval,
0,
1,
);
await clearTransition();
addDraggable(Boxs);
addSVGmousemoveListener();
addClickListener(Boxs);
styleText.addEventListener('input', function() {
style.textContent = styleText.textContent;
});
document.querySelector('.inner-container').style.display = 'block';
await document
.getElementById('skipButton')
.classList.add('animated', 'slideOutLeft');
document
.querySelector('body')
.removeChild(document.getElementById('skipButton'));
console.log('实时Coding参考了http://strml.net/的源代码');
console.log('谢谢浏览!!');
} catch (err) {
if (err.message === 'SKIP IT') {
skipAnimation();
} else {
console.log(err);
throw err;
}
}
}
start();
async function skipAnimation() {
let styleText = document.getElementById('style-text');
style.textContent = styleMsg[0].replace(/[\n]/gi, '');
let styleBox = document.getElementById('style-box'),
masterBox = document.getElementById('master-box'),
gameBox = document.getElementById('game-box'),
trickBox = document.getElementById('trick-box');
let styleHtml = '';
for (let i = 0; i < styleMsg.length; i++) {
styleMsg[i] = styleMsg[i].replace(/[\n]/gi, '');
}
let stylemsgAll = styleMsg.join('\n');
for (let i = 0; i < stylemsgAll.length; i++) {
styleHtml = handleChar(styleHtml, stylemsgAll[i]);
}
styleText.innerHTML = styleHtml;
let Boxs = [masterBox, styleBox, gameBox, trickBox];
changeEditor(masterBox, styleBox);
addmasterContent();
await changeEditor(styleBox, masterBox);
style.textContent += styleMsg[1].replace(/[\n]/gi, '');
await await createItem(itemsmsg, itemMsg);
await sleep(1000);
showGameAndTrick();
style.textContent += styleMsg[2].replace(/[\n]/gi, '');
await clearTransition();
addDraggable(Boxs);
addSVGmousemoveListener();
addClickListener(Boxs);
styleText.addEventListener('input', function() {
style.textContent = styleText.textContent;
});
document.querySelector('.inner-container').style.display = 'block';
styleText.scrollTop = styleText.scrollHeight;
console.log('实时Coding参考了http://strml.net/的源代码');
console.log('谢谢浏览!!');
}
NProgress.configure({
minimum: 0.2,
});
(function() {
document.onreadystatechange = function() {
NProgress.start();
if (document.readyState == 'Uninitialized') {
NProgress.set(1);
}
if (document.readyState == 'Interactive') {
NProgress.set(0.6);
}
if (document.readyState == 'complete') {
(async function() {
await sleep(700);
NProgress.done();
})();
}
};
})();
const endOfSentence = /[\.\?\!]\s$/;
const comma = /\D[\,]\s$/;
const endOfBlock = /[^\/]\n\n$/;
async function writeTo(
el,
msg,
mirrortostyle,
interval,
index,
charsPerInterval,
) {
if (animationSkipped) {
throw new Error('SKIP IT');
}
let chars = msg.slice(index, index + charsPerInterval);
index += charsPerInterval;
el.scrollTop = el.scrollHeight;
if (mirrortostyle) {
writeChar(el, chars, style);
} else {
writeSimpleChar(el, chars);
}
if (index < msg.length) {
let thisInterval = interval;
let thisSlice = msg.slice(index - 2, index + 1);
if (comma.test(thisSlice)) thisInterval = interval * 30;
if (endOfBlock.test(thisSlice)) thisInterval = interval * 50;
if (endOfSentence.test(thisSlice)) thisInterval = interval * 70;
try {
await sleep(thisInterval);
} catch (err) {
console.log(err);
}
return writeTo(el, msg, mirrortostyle, interval, index, charsPerInterval);
}
}
function createEditor(elid, htmlmsg) {
let el = document.getElementById('desktop');
el.innerHTML += htmlmsg;
}
function clearTransition() {
$('*').css('transition', 'all 0s');
}
function showGameAndTrick() {
document.getElementById('sprite').src = './src/image/resource.png';
document.getElementById('catgif').src = './src/image/cat.gif';
document.getElementById('game-title').innerHTML =
'Run as far as you can by using ↑ & ↓';
document.getElementById('trick-title').innerHTML = 'Thanks!';
document.getElementById('game-box').style.display = 'block';
document.getElementById('trick-box').style.display = 'block';
}
function addDraggable(els) {
let length = els.length;
for (let i = 0; i < length; i++) {
$(els[i]).draggable({
handle: $(els[i])
.children('.header')
.first(),
});
}
}
function addmasterContent() {
let masterText = document.getElementById('master-text');
masterText.innerHTML = mastercontent;
}
|
/**
* Created by kras on 09.09.16.
*/
'use strict';
const { di } = require('@iondv/core');
const onError = require('./error');
module.exports = function (required, worker, res) {
var scope = di.context('app');
if (!scope) {
return onError(scope, new Error('app DI-container not found'), res, true);
}
if (Array.isArray(required)) {
for (var i = 0; i < required.length; i++) {
if (typeof scope[required[i]] === 'undefined' || !scope[required[i]]) {
return onError(scope, new Error('Required component not set up ' + required[i]), res, true);
}
}
}
worker(scope);
};
|
const express = require('express');
const path = require('path');
const postsDB = require('../model/posts');
const usersDB = require('../model/users');
const router = express.Router();
const multer = require('multer');
router.get('/', (req, res) => {
res.render('admin/index.html');
});
router.get('/blog/push', (req, res) => {
res.render('admin/blogEdit.html', {posts: {}});
});
router.post('/blog/push', (req, res) => {
//校验
if (!req.body.title) return res.json({msg: '请输文章标题'});
if (!req.body.brief) return res.json({msg: '请输文章摘要'});
if (!req.body.content) return res.json({msg: '请输文章内容'});
//默认数据
req.body.uid = req.session.users.id;
req.body.status = 0;
req.body.time = new Date();
postsDB.save(req.body, (err) => {
if (!err) return res.json({success: true});
res.json(err);
});
});
router.get('/blog/list', (req, res) => {
postsDB.findAllForAdmin({
uid: req.session.users.id,
title: req.query.title || ''
}, (err, rows) => {
if (!err) return res.render('admin/blogManage.html', {rows, title: req.query.title});
res.send(err.msg);
});
});
router.get('/blog/edit', (req, res) => {
postsDB.findPosts(req.query.id, (err, posts) => {
res.render('admin/blogEdit.html', {posts});
});
});
router.post('/blog/edit', (req, res) => {
//校验
if (!req.body.title) return res.json({msg: '请输文章标题'});
if (!req.body.brief) return res.json({msg: '请输文章摘要'});
if (!req.body.content) return res.json({msg: '请输文章内容'});
//更新时间
req.body.time = new Date();
postsDB.update(req.body, (err) => {
if (!err) return res.json({success: true});
res.json(err);
});
});
router.get('/blog/del', (req, res) => {
postsDB.delete(req.query.id, (err) => {
if (!err) return res.redirect('/admin/blog/list');
res.send(err.msg);
});
});
router.get('/settings', (req, res) => {
res.render('admin/settings.html', {users: req.session.users});
});
router.post('/settings', (req, res) => {
req.body.id = req.session.users.id;
usersDB.update(req.body, (err) => {
if (!err){
global.users = req.session.users = req.body;
return res.json({success: true});
}
res.json(err);
});
});
router.get('/repass', (req, res) => {
res.render('admin/repass.html');
});
router.post('/repass', (req, res) => {
res.send('/admin');
});
/*配置磁盘的存储信息*/
const storage = multer.diskStorage({
/*目录*/
destination: function (req, file, cb) {
cb(null, path.join(__dirname, '../public/uploads/avatar'));
},
/*名称*/
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
});
/*返回上传对象*/
const upload = multer({storage});
router.post('/upload', upload.single('avatar'), (req, res) => {
res.send('/public/uploads/avatar/' + req.file.filename);
});
module.exports = router;
|
function clearColor () {
return new Promise (
function(resolve, reject) {
const color = document.getElementsByClassName("color")
for(var i=0; i<color.length; i++){
color[i].classList.remove('color')
}
resolve(true)
}
)
}
module.exports = clearColor;
|
import React from 'react';
export default class ListItem extends React.PureComponent {
render() {
return (
<span>{this.props.value}</span>
);
}
}
|
(function () {
'use strict';
define(
function () {
var model = function (options) {
this.shortenedUrl = options.shortenedUrl;
this.inflateUrl = options.inflateUrl;
};
return model;
});
})();
|
(function ($) {
$('document').ready(function() {
var layer_div = $('<div>');
layer_div.attr('id', 'precaution-layer');
layer_div.css({
backgroundColor: '#EEE',
opacity: '0.7',
zIndex: '1000',
position: 'absolute',
top: '0px',
left: '0px'
});
$('body').append(layer_div);
$('#precaution-popup, #footer-popup').click(function() {
$(this).blur();
var width = $(window).width();
var height = $(document).height();
var scroll = $(document).scrollTop();
var window_height = $(window).height();
$('#precaution-layer').css('width', width);
$('#precaution-layer').css('height', height);
$('#precaution-layer').css('visibility', 'visible');
var template = Drupal.settings.ecatalog_precaution.template;
var return_button_wrap_div = $('<div class="precaution-button-back"></div>');
return_button_wrap_div.css('textAlign', 'center');
var return_button = $('<input type="button" value="' + Drupal.t('Back') + '">');
return_button_wrap_div.append(return_button);
var overlay_div = $('<div>');
overlay_div.attr('id', 'precaution-overlay');
overlay_div.css('backgroundColor', '#FFF');
overlay_div.css('position', 'absolute');
overlay_div.css('top', scroll + window_height * 0.1);
overlay_div.css('left', width * 0.5 - width * 0.4);
overlay_div.css('width', width * 0.8);
overlay_div.css('zIndex', '2000');
overlay_div.css('max-height', window_height * 0.8);
overlay_div.css('overflow', 'auto');
overlay_div.append(template);
overlay_div.append(return_button_wrap_div);
$('body').append(overlay_div);
return_button.click(function() {
$('#precaution-layer').css('visibility', 'hidden');
$('#precaution-overlay').remove();
});
$(window).scroll(function() {
var scroll = $(window).scrollTop();
var window_height = $(window).height();
$('#precaution-overlay').css('top', scroll + window_height * 0.1);
});
$(window).resize(function() {
var width = $(document).width();
var height = $(document).height();
var scroll = $(document).scrollTop();
var window_width = $(window).width();
var window_height = $(window).height();
$('#precaution-layer').css('width', width);
$('#precaution-layer').css('height', height);
$('#precaution-overlay').css('top', scroll + window_height * 0.1);
$('#precaution-overlay').css('left', window_width * 0.5 - window_width * 0.4);
$('#precaution-overlay').css('width', window_width * 0.8);
$('#precaution-overlay').css('overflow', 'auto');
$('#precaution-overlay').css('max-height', window_height * 0.8);
});
return false;
});
});
})(jQuery);
|
mainApp.run(['$rootScope', '$q','$window', 'authorizationService', 'invokeServerService', 'leftSideMenuFactory'
, function ($rootScope, $q, $window, authorizationService, invokeServerService, leftSideMenuFactory) {
$rootScope.GetFormPermission = function () {
var deferred = $q.defer();
invokeServerService.Post('/Authentication/GetMenuPermission', {}).success(function (response) {
deferred.resolve(response);
}).error(function () {
deferred.reject('error');
});
return deferred.promise;
}
$rootScope.routeForUnauthorizedAccess = '/Error/Index';
$rootScope.$on('$stateChangeSuccess',
function (event, current, prev) {
leftSideMenuFactory.hideMenu();
var screenWidth = $window.innerWidth;
if (screenWidth <= 800) {
$rootScope.isMobileSize = true;
} else {
$rootScope.isMobileSize = false;
}
});
//$rootScope.$on('$stateChangeStart',
// function (event, toState, toStateParams) {
// $rootScope.toState = toState;
// $rootScope.toStateParams = toStateParams;
// authorizationService.permissionCheck(toState.formName).then(function () {
// }, function () {
// //window.location = $rootScope.routeForUnauthorizedAccess
// });
// });
}]);
|
function Contact(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
this.addresses = [];
}
Contact.prototype.fullName = function() {
return this.firstName + " " + this.lastName;
};
function Address(street, city, state) {
this.street = street;
this.city = city;
this.state = state;
}
Address.prototype.fullAddress = function() {
return this.street + ", " + this.city + ", " + this.state;
}
function resetFields() {
$("input#firstName").val("");
$("input#lastName").val("");
$("input.address").val("");
$("input.city").val("");
$("input.state").val("");
$("input.zip").val("");
}
$(function() {
$("#add-address").click(function() {
$(".new-address").append('<div class="new-address">' +
'<div class="form-group">' +
'<input type="text" placeholder="Address" class="form-control address"' +
'</div>' +
'<div class="form-group">' +
'<input type="text" placeholder="City" class="form-control city"' +
'</div>' +
'<div class="form-group">' +
'<input type="text" placeholder="State" class="form-control state"' +
'</div>' +
'<div class="form-group">' +
'<input type="text" placeholder="Zip" class="form-control zip"' +
'</div>' +
'</div>');
});
$("form#new_address").submit(function(event) {
event.preventDefault();
var inputtedFirstName = $("input#firstName").val();
var inputtedLastName = $("input#lastName").val();
var newContact = new Contact(inputtedFirstName, inputtedLastName);
$(".new-address").each(function() {
var inputtedAddress = $(this).find("input.address").val();
var inputtedCity = $(this).find("input.city").val();
var inputtedState = $(this).find("input.state").val();
var inputtedZip = parseInt($(this).find("input.zip").val());
newAddress = { address: inputtedAddress, city: inputtedCity, state: inputtedState, zip: inputtedZip };
newContact.addresses.push(newAddress);
});
resetFields();
$("ul#contacts").append("<li><span class='contact'>" + newContact.fullName() + "</span></li>");
$("#result").show();
$(".contact").last().click(function() {
$("#show-contact").show();
$("#show-contact h2").text(newContact.firstName);
$(".first-name").text(newContact.firstName);
$(".last-name").text(newContact.lastName);
$("ul#addresses").text("");
newContact.addresses.forEach(function(address) {
$("ul#addresses").append("<li>" + address.address + ", " + address.city + ", " + address.state + ", " + address.zip + "</li>");
});
});
});
});
|
import React from 'react'
import {
Col,
Input,
Label,
FormGroup
}from 'reactstrap'
const Uppic = () =>(
<FormGroup row>
<Col xs={2} />
<Col xs={2}><Label >商品图片</Label></Col>
<Col xs={6}><Input name="uppic" type="file" value="商品图片"/></Col>
</FormGroup>
)
export default Uppic
|
'use strict'
const fs = require('fs');
const path = require('path');
const GitHubApi = require("github");
let config;
try{
config = fs.readFileSync(path.join(__dirname, '..', '..', '..', 'config', 'githubAPIConfig.json'));
}catch(err){
config = {debug: true};
}
exports.auth = function(authInfo){
let github = new GitHubApi(config);
try{
github.authenticate({
type: "basic",
username: authInfo.userName,
password: authInfo.password
});
}catch(err){
let error;
switch(err.code){
case 401:
switch(err.status){
case 'Unauthorized':
error = new Error('github 인증 실패');
error.code = 'E101';
error.inputId = authInfo.userName;
error.inputPassword = authInfo.password;
break;
}
break;
default:
error = new Error('github api 에러 (?)'.replace('?', err.message));
error.code = 'E100';
}
throw error;
}
return github;
};
|
function initGoogleService() {
var self = {};
var geocoder = new google.maps.Geocoder();
var usersCurrentLatLon = null;
self.askForLocation = function (callback) {
var geoSuccess = function (position) {
var lat = position.coords.latitude;
var lon = position.coords.longitude;
var latLon = new google.maps.LatLng(lat, lon);
usersCurrentLatLon = latLon;
callback();
};
var geoError = function (error) {
console.log(error);
};
navigator.geolocation.getCurrentPosition(geoSuccess, geoError);
};
self.processZipCode = function (zip, callback) {
if (zip === undefined || zip === null || zip === "") {
return;
}
geocoder.geocode( {'address': zip }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
lat = results[0].geometry.location.lat();
lon = results[0].geometry.location.lng(); console.log(results);
var latLon = new google.maps.LatLng(lat, lon);
usersCurrentLatLon = latLon;
callback();
} else {
alert("Zip Code was not successful for the following reason: " + status);
}
});
};
self.displayPosition = function (mapId, lat, lon, title) {
if (title === undefined) {
title = "Pin";
}
var location = new google.maps.LatLng(lat, lon);
var map = new google.maps.Map(document.getElementById(mapId), {
center: location,
zoom: 15
});
new google.maps.Marker({
map: map,
title: title,
position: location
});
};
self.searchAndDisplay = function (mapId, request) {
if (!self.exists(mapId)) {
throw "Required map element ID not provided";
}
if (!self.exists(request)) {
request = {};
}
if (!self.exists(request.location)) {
if (self.exists(usersCurrentLatLon)) {
request.location = usersCurrentLatLon;
} else {
alert("No location specified. Please allow location to be used or enter a zip code manually.");
return;
}
}
if (!self.exists(request.radius)) {
request.radius = 5000;
}
if (!self.exists(request.type)) {
request.type = ['car_repair'];
}
var map = new google.maps.Map(document.getElementById(mapId), {
center: request.location,
zoom: 15
});
var placesService = new google.maps.places.PlacesService(map);
placesService.nearbySearch(request, function (results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
createMarkers(map, results);
} else {
alert(status);
}
});
};
self.getCurrentLatLon = function () {
return usersCurrentLatLon;
};
self.exists = function (obj) {
if (obj !== undefined && obj !== null) {
return true;
}
return false;
};
var createMarkers = function (map, places) {
var bounds = new google.maps.LatLngBounds();
//var placesList = document.getElementById('places');
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
//placesList.innerHTML += '<li>' + place.name + '</li>';
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
};
window.GoogleService = self;
};
//init();
|
import React from 'react'
import logo from './logo.svg'
import getAllFromCollection from './helpers/getAllFromCollection'
import sample from './helpers/sample'
import './App.css'
export default class App extends React.Component {
state = {
goal: '',
tech: '',
limitation: '',
availableGoals: [],
availableTechs: [],
availableLimitations: [],
}
componentDidMount() {
Promise.all([
getAllFromCollection('goals'),
getAllFromCollection('techs'),
getAllFromCollection('limitations'),
])
.then(([availableGoals, availableTechs, availableLimitations]) => {
this.setState({
availableGoals,
availableTechs,
availableLimitations,
})
})
}
randomizeGoal = () => this.setState(state => ({
goal: sample(state.availableGoals).name,
}))
randomizeLimitation = () => this.setState(state => ({
limitation: sample(state.availableLimitations).name,
}))
randomizeTech = () => this.setState(state => ({
tech: sample(state.availableTechs).name,
}))
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<main className="App-intro">
<section className="goal">
<button
type="button"
onClick={this.randomizeGoal}
>
Create Goal
</button>
{this.state.goal}
</section>
<section className="limitation">
<button
type="button"
onClick={this.randomizeLimitation}
>
Create Limitation
</button>
{this.state.limitation}
</section>
<section className="tech">
<button
type="button"
onClick={this.randomizeTech}
>
Create Tech
</button>
{this.state.tech}
</section>
</main>
</div>
)
}
}
|
import {StyleSheet, Dimensions} from 'react-native';
import {Constants} from 'expo';
export const TAMANHO_PADRAO = 14;
export const VERDE = "#04B486";
export const BRANCO = "#fff";
export const FUNDO = "#fff";
export const FUNDO_ESCURO = "#666"
export const FUNDO_CINZA_CLARO = "#ddd"
export const DESMARCADO = "#f00";
export const MARCADO = "#00f";
export const PRETO = "#000";
export const COLOR_RATING = "yellow";
export const COR_SEPARADOR = "#000";
const EstilosComuns = StyleSheet.create({
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
flexDirection: 'column',
backgroundColor: FUNDO,
padding: 4
},
containerListening: {
flex: 1,
paddingTop: Constants.statusBarHeight,
flexDirection: 'column',
backgroundColor: VERDE,
},
backgroundToolbar: {
backgroundColor: VERDE,
},
backgroundPadrao: {
backgroundColor: FUNDO //FUNDO
},
sombra: {
shadowColor: VERDE,
shadowOpacity: 0.3,
shadowRadius:30
},
fontePadrao: {
fontFamily:'Roboto',
fontSize: TAMANHO_PADRAO
},
fonteBotao: {
fontFamily:'Roboto',
color: BRANCO,
fontSize: TAMANHO_PADRAO
},
centralizar: {
justifyContent: 'center',
alignItems: 'center',
},
corVerde: {
color: VERDE,
},
corBranca: {
color: BRANCO,
},
botao: {
backgroundColor: VERDE,
height: 40,
marginTop: 8,
justifyContent: 'center',
alignItems: 'center',
shadowColor: FUNDO_ESCURO,
},
negrito: {
fontWeight: 'bold'
},
sublinhado: {
textDecorationLine: 'underline',
},
inputText: {
borderBottomWidth: 1,
borderColor: "#A4A4A4",
fontSize: 16,
padding: 8,
},
textoTamanhoPadrao: {
fontSize: TAMANHO_PADRAO
},
textoJustificado: {
textAlign: 'justify'
},
textoCentralizado: {
textAlign: 'center'
} ,
tituloJanelas: {
fontSize: 20,
fontWeight: 'bold',
marginBottom: 5,
color: FUNDO_ESCURO,
padding: 10
},
bodyTitulo: {
flex: 1,
padding: 3
},
bodyMain : {
flex: 8,
flexDirection: 'column',
padding: 5,
},
rodape: {
flex: 1
},
rodapeDuplo:{
flex: 2
},
italico:{
fontStyle: 'italic'
},
bordaSeparacaoBlocos: {
borderBottomWidth: 1,
borderBottomColor: FUNDO_CINZA_CLARO
},
card: {
borderWidth: 1,
borderRadius: 2,
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop: 10,
padding: 10
},
});
export default EstilosComuns;
//elevation resolve o espaço da tab bar...
|
import React from 'react';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import Icon from 'react-native-vector-icons/FontAwesome';
import Search from '../component/searchComponent';
import UserProfile from '../component/userProfileCompoent';
import Notification from '../component/notificationComponent';
import msg_Stack from './messageStack';
import Friends_Top_Tab from './friendTopTab';
import search_Stack from './serachStack';
const rootTab = createBottomTabNavigator();
export function root_Tab() {
return (
<rootTab.Navigator
screenOptions={
({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
if (route.name === 'Message') {
iconName = 'align-center'
} else if (route.name === 'Friends') {
iconName = 'users'
//iconName = focused ? 'at' : 'facebook';
} else if (route.name === 'Profile') {
iconName = 'user-circle'
}
else if (route.name === 'Search') {
iconName = 'search'
}
else if (route.name === 'Notification') {
iconName = 'bell'
}
return <Icon name={iconName} size={size} color={color} />;
},
})
}
tabBarOptions={{
activeTintColor: 'white',
inactiveTintColor: 'grey',
showLabel: false,
showIcon: true,
// labelStyle: {
// fontSize: 15,
// },
style: {
backgroundColor: '#252623',
height: 50
}
}}
>
<rootTab.Screen name="Message" component={msg_Stack} options={{ tabBarBadge: 3 }} />
<rootTab.Screen name="Friends" component={Friends_Top_Tab} />
<rootTab.Screen name="Profile" component={UserProfile} />
<rootTab.Screen name="Search" component={search_Stack} />
<rootTab.Screen name="Notification" component={Notification} options={{ tabBarBadge: 6 }} />
</rootTab.Navigator>
);
}
|
var searchData=
[
['useobjstomeshfromtexbaker',['useObjsToMeshFromTexBaker',['../class_m_b3___mesh_baker_common.html#a439e2e6cbe654f7c5c859b7f0be0d261',1,'MB3_MeshBakerCommon']]]
];
|
/**
* Created by like on 2016/8/17.
*/
var createXhrObject = function () {
var methods =
[function () {
return new XMLHttpRequest();
}, function () {
return new ActiveXObject("Msxml2.XMLHTTP");
}, function () {
return new ActiveXObject("Microsoft.XMLHTTP");
}];
for (var i = 0, len = methods.length; i < len; i++) {
try {
methods[i].call(this, null);
}
catch (e) {
continue;
}
this.createXhr = methods[i];
return methods[i];
}
};
var simpleHandler = function () {
};
simpleHandler.prototype = {
constructor: simpleHandler,
request: function (method, url, callback, postVal) {
var xhr = this.createXhrObject();
xhr.onreadystatechange = function () {
if(xhr.readyState!==4){
return ;
}
if(xhr.status===200){
callback.success(xhr.responseText,xhr.responseXML);
callback.fail(xhr.status);
}
xhr.open(method,url,true);
if(method.toLowerCase()!=='POST'){
postVal = null;
}
xhr.send(postVal);
}
}
};
var myHandler = new simpleHandler();
var callcack = {
success: function (responseText,responseXML) {
console.log(responseText,responseXML);
},
fail: function (status) {
console.log(status);
}
}
myHandler.request(method,url,callcack,postVal);
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(['exports'], factory);
} else if (typeof exports !== "undefined") {
factory(exports);
} else {
var mod = {
exports: {}
};
factory(mod.exports);
global.polyfills = mod.exports;
}
})(this, function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.polyfill = polyfill;
// Just the polyfills we need; not the entire monster that is babel-polyfill
function polyfill() {
// Array polyfills
if (!Array.from) {
Array.prototype.from = function (object) {
return [].slice.call(object);
};
}
if (!Array.prototype.includes) {
Array.prototype.includes = function (searchElement /*, fromIndex*/) {
var k,
currentElement,
O = Object(this),
len = parseInt(O.length, 10) || 0,
n = parseInt(arguments[1], 10) || 0;
if (len === 0) {
return false;
}
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement || searchElement !== searchElement && currentElement !== currentElement) {
// NaN !== NaN
return true;
}
k++;
}
return false;
};
}
// String polyfills
if (!String.prototype.includes) {
String.prototype.includes = function (search, start) {
if (typeof start !== 'number') {
start = 0;
}
if (start + search.length > this.length) {
return false;
} else {
return this.indexOf(search, start) !== -1;
}
};
}
if (!String.prototype.endsWith) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
if (!String.prototype.startsWith) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
};
});
|
var questions = [
"Who let the dogs out?",
"Whats for dinner?",
"what is the color of darkness?",
"what is the meaning of life?",
"Why is the sky blue?",
"Who has the meats?",
]
var answers = [
["Baha Men","Shaggy","Scooby","Obama"],
["Beef","Turkey","Mashed Grapes","Pachirisu"],
["Sanguine, My Brother","Death","Talos","The Deepest Black"],
["42","Eat, Sh*t and Die","Glory To The Highest","Subversion Of Death"],
["Rayleigh Scattering", "Wizard Magic", "Blue Sunlight", "Colorblindness"],
["Arbys","Burger King","WackArnolds","The Mighty Ducks"]
];
// initialize question row which will hold questions
var qrow = 0;
// initialize child of question row which will hold answeres
var qrowchild = 0;
// initialize variable to = <input type='radio'.../> to wrap answers in radio groups
var buildRadio = 0;
// initialize random integer to randomizes answer order with rando()
var randint = 0;
// potentially randomizes output to mix up answers each time quiz is run
// may extend to randomize questions as well
function rando() {
return Math.floor((Math.random() * 100) + 1);
}
// Builds question/answer body field
function buildMain() {
// iterates to create and build one div.row with a div.answers-iterative child
for (var i = 0; i < questions.length; i++) {
qrow = $("<div>");
qrow.addClass("row" + "question" + i);
qrow.text(i + " " + questions[i]);
qrowchild = $("<div>");
qrowchild.addClass("answers" + i);
// iterates to create and build in-line spans of <input type='radio'.../> with answers
for (j=0; j<answers[i].length; j++) {
// normal typed with "string"+var+"string"
//buildRadio = "<input type='radio' value="+j+" name='opt"+i+"'>" + answers[i][j] + "</input>"
// https://campushippo.com/lessons/how-to-do-string-interpolation-with-javascript-7854ef9d
// string interpolated with `text ${variable}`
buildRadio = `<span><input type='radio' class='answ' value=${j} name='opt${i}' id=${answers[i][j]} >${answers[i][j]}</input></span>`
qrowchild.html(`${qrowchild.html()}Q:${i}A:${j} ${buildRadio}`);
}
// appends question row with children to #bodyactual
$("#bodyactual").append(qrow).append(qrowchild);
// =====================================================================
// dead call used to wrap answers in <input type='radio'.../>
// however it returned [objects] instead of [strings] and did not
// work with qrowchild.html(qrowchild.html()+buildOpt(answers[i][j]))
// expected output = <div...><input...>'arbys'</input></div>
// actual output = <div...>[object][object]</div>
//buildOpt(answers[i]);
// =====================================================================
};
};
$(document).ready(function() {
console.log( "ready!" );
// This did not work, how do I find out if a button is selected or not?
// Used as reference https://www.w3schools.com/jsref/prop_radio_checked.asp
// add 3rd value in array for Right v Wrong
//if ($('input[name='+opt0+']:checked').val()) {
// console.log('works')
//}
//$('input[name=name_of_your_radiobutton]:checked').val();
});
$('.answ').on('click',function() {
if ($(this).attr('checked') == true) {
console.log($(this).attr('class') + "is checked")
}
if ($(this).attr('checked') == false) {
console.log($(this).attr('class') + " its not checked")
};
});
// calls build main to fill #bodyactual with iterated content
buildMain();
//console.log(qrow + "\n" + qrowchild + "\n" + questions);
|
import React from 'react'
import { FormRowStyle } from './style'
import { TimeFilter } from '@/Utils/filter'
import CardStatus from '../FormCard/CardStatus'
import Start from '../start'
export default function FormRow({ card, HandleTapAction }){
return (
<FormRowStyle onClick={ () => HandleTapAction() }>
<td><Start/></td>
<td>{card.productCategory}</td>
<td>{card.prjCategory}</td>
<td>{card.guid}</td>
<td>{card.prjName}</td>
<td><CardStatus projectStatus={card.projectStatus} /></td>
<td>{card.prjManager}</td>
<td>{card.department}</td>
<td>{TimeFilter(card.prjStartDate)} ~ {TimeFilter(card.prjEndDate)}</td>
</FormRowStyle>
)
}
|
import React from "react";
import {
BrowserRouter as Router,
Route,
Switch,
Redirect
} from "react-router-dom";
// Components
const Header = React.lazy(() => import("./components/Header"));
// Pages
const Home = React.lazy(() => import("./components/Home"));
/*const Menu2 = React.lazy(() => import("./Menu2"));
<Route path="/menu2" render={props => <Menu2 {...props} />} />*/
export default function App() {
return (
<Router>
<React.Suspense fallback={<p className="loader">Loading...</p>}>
{/* ----- Header ----- */}
<Header />
{/* ----- Wrapper / Main ----- */}
<section id="main">
<Switch>
<Route path="/home" render={props => <Home {...props} />} />
{/* Redirect */}
<Route exact path="/">
<Redirect to="/home" />
</Route>
</Switch>
</section>
</React.Suspense>
</Router>
);
}
|
"use strict";
/**** priv API ****/
(function () {
function ItemClose(selector) {
this.selector = selector;
this.close = this.selector.addEventListener('click', remove)
}
function remove() {
this.parentElement.remove();
}
const el = document.querySelectorAll('.item-close');
for (let i = 0; i < el.length; i++) {
const us = new ItemClose(el[i]);
}
})();
/**** public API ****/
/* Menu constructor */
function Menu(selector, options) {
this.selector = selector;
/* Default values */
this.properties = {
effect: 'noEffect',
changeIcon: true
}
this.properties = Object.assign(this.properties, options);
this.navList = document.querySelector(this.selector + ' .navbar-list');
this.button = document.querySelector(this.selector + ' .hamburger');
this.hamburgerEvent(); // run hamburgerEvent() method
this.effect();
}
/* Proto methods */
Menu.prototype.hamburgerEvent = function () {
const el = this.navList.classList;
this.button.addEventListener('click', () => {
el.toggle('active');
if (!el.contains('active')) {
el.add('unactive');
} else if (el.contains('unactive')) {
el.remove('unactive')
}
this.changeIcon();
});
}
Menu.prototype.effect = function () {
if (this.properties.effect === 'slideDown') {
this.navList.classList.add('slideDown')
} else if (this.properties.effect === 'slideLeft') {
this.navList.classList.add('slideLeft')
}
if (this.properties.effect === 'noEffect') {
this.navList.classList.add('noEffect')
}
};
Menu.prototype.changeIcon = function () {
if (this.properties.changeIcon === true) {
this.button.firstElementChild.classList.toggle('fa-times');
} else if (this.properties.changeIcon === false) {
return false;
};
};
/* Button constructor */
function Button(selector, options) {
this.selector = document.querySelector(selector);
this.properties = {
background: 'green'
};
this.properties = Object.assign(this.properties, options);
this.background();
this.hover();
}
Button.prototype.background = function () {
const el = this.selector;
const value = this.properties.background;
switch (value) {
case 'green':
el.classList.add('btn-green');
break;
case 'blue':
el.classList.add('btn-blue');
break;
case 'red':
el.classList.add('btn-red');
break;
case 'orange':
el.classList.add('btn-orange');
break;
case 'gray':
el.classList.add('btn-gray');
break;
case 'black':
el.classList.add('btn-black');
break;
}
if (value.bgColor === undefined) {
return false;
} else {
el.style.backgroundColor = value.bgColor;
el.style.borderColor = value.bgColor;
}
if (value.fontColor === undefined) {
return false;
} else {
el.style.color = value.fontColor;
}
}
Button.prototype.hover = function () {
const value = this.properties.hover;
if (value === undefined) {
return false;
} else {
this.selector.addEventListener('mouseover', function () {
this.style.backgroundColor = value.bgColor;
this.style.borderColor = value.bgColor;
});
this.selector.addEventListener('mouseout', () => {
this.selector.style.backgroundColor = this.properties.background.bgColor;
this.selector.style.borderColor = this.properties.background.bgColor;
});
}
}
/* test */
const btn = new Button('.przycisk', {
background: 'green'
});
const bt = new Button('.przycisk2', {
background: {
bgColor: '#333333',
fontColor: '#ffffff'
},
hover: {
bgColor: '#444444',
fontColor: '#eeeeee'
}
});
|
import React from 'react'
import "../App.css"
import { Col,Navbar, Card, Row,Dropdown} from 'react-bootstrap';
import styled from 'styled-components';
import {CometChat} from '@cometchat-pro/chat'
const Styles = styled.div `
.display-name{
background: black;
color: white;
width: 30px;
height: 30px;
border-radius: 50%;
text-align: center;
padding: 5px;
}
.chat-sec{
height: 500px;
padding-bottom: 20px;
}
.msg{
position: absolute;
bottom: 0;
margin: 6px;
padding: 5px;
}
input[type=text]{
width: 330px;
padding: 5px;
border: none;
border-bottom: 1px solid gray;
}
button{
background-color: white;
border: none;
color: gray;
padding: 4px;
cursor: pointer;
}
.main-chat{
height:300px;
overflow: scroll;
}
`
export const Live_event = ({match}) => {
const [event,setEvents] = React.useState([])
const [messages,setMessages] = React.useState([])
const [message,setMessage]= React.useState('')
const [user,setUser] = React.useState([])
const getEvent = async ()=>{
const response = await fetch(`http://localhost:5000/events/event/${match.params.id}`, {
method: 'GET',
mode: 'cors',
credentials: 'same-origin',
headers: {
'Content-Type': 'application/json'
},
});
const datas = await response.json()
setEvents(datas);
var GUID = datas.title;
var password = "";
var groupType = CometChat.GROUP_TYPE.PUBLIC;
CometChat.joinGroup(GUID, groupType, password).then(
group => {
console.log("Group join")
},
error => {
console.log("Group joining failed with exception:", error);
})
var limit = 100;
var messagesRequest = new CometChat.MessagesRequestBuilder()
.setLimit(limit)
.setGUID(GUID)
.build();
messagesRequest.fetchPrevious().then(
messages => {
console.log("Message list fetched:", messages);
setMessages(messages)
},
error => {
console.log("Message fetching failed with error:", error);
}
);
CometChat.getLoggedinUser().then(
user => {
setUser(user.name.split(""))
console.log(user.name.split(""))
},
error => {
console.log("error getting details:", { error });
}
);
}
CometChat.addMessageListener(
"UNIQUE_LISTENER_ID",
new CometChat.MessageListener({
onTextMessageReceived: textMessage => {
console.log("Text message received successfully", textMessage);
const data = {
'name':textMessage.sender.name,
'text':textMessage.text
}
setMessages(messages.concat(data))
}
})
);
const sendMessage = (e)=>{
e.preventDefault()
var receiverID = event.title;
var messageText = message;
var receiverType = CometChat.RECEIVER_TYPE.GROUP;
var textMessage = new CometChat.TextMessage(
receiverID,
messageText,
receiverType
);
CometChat.sendMessage(textMessage).then(
message => {
console.log("Message sent successfully:", message);
setMessage('')
const data = {
'name':message.sender.name,
'text':message.text
}
setMessages(messages.concat(data))
})
}
const logout = () => {
CometChat.logout().then(() => {
window.location.href = '/';
});
}
React.useEffect(()=>{
getEvent()
},[])
return (
<Styles>
<Navbar sticky="top" bg="light" variant="light">
<Navbar.Brand href="#home">Live section</Navbar.Brand>
<Navbar.Toggle />
<Navbar.Collapse className="justify-content-end">
<Dropdown>
<Dropdown.Toggle variant="success" id="dropdown-basic">
<h6 className="display-name"> {user[0]}</h6>
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item href="#"> <p onClick={logout}>logout</p></Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</Navbar.Collapse>
</Navbar>
<Row className="m-3">
<Col sm={8}>
<iframe
title={event.title}
width="100%"
height="500px"
src={event !== undefined ? event.stream :null}>
</iframe>
<h5> <strong>{event !== undefined ? event.title :null}</strong> </h5>
</Col>
<Col sm={4}>
<Card className="chat-sec">
<Card.Header as="h5">Chat section</Card.Header>
<Card.Body className="main-chat">
<div className="">
{messages.map((message,i)=>(
<div className="" key={i}>
<p><span><b>{message.sender ? message.sender.name:message.name}:</b></span> {message.text}</p>
</div>
))}
</div>
</Card.Body>
<div className="msg">
<form onSubmit={sendMessage}>
<input type="text" placeholder="Say something" value={message} onChange={(e)=> setMessage(e.target.value)} />
<button type="submit"> <i className="fa fa-send"></i> </button>
</form>
</div>
</Card>
</Col>
</Row>
</Styles>
)
}
|
import React, { PropTypes } from 'react'
import picker from '../commentJs/picker'
export default (...mon) => {
class NewComponent extends React.PureComponent {
weekDateTab() {
let datePickerTab = [];
picker(...mon).forEach(function(val, index) {
let weekDateArr = [];
for(let key in val) {
weekDateArr.push(
<td key={key} target={val[key][1]}>
<a style={{
color: val[key][1] ? '#939393' : val[key][2] === 't' ? '#FFFFFF' : '#333333',
backgroundColor: val[key][2] === 't' ? '#1890FF' : '',
borderColor: val[key][3] === 'opt' ? '#1890FF' : 'transparent'
}} target={val[key][1]}>{ val[key][0] }</a>
</td>
);
}
datePickerTab.push(
<tr key={index}>
{ weekDateArr }
</tr>
);
});
return datePickerTab
}
weekTitleTab() {
let weekName = ['Mo','Tu','We','Th','Fr','Sa','Su']
let weekTitle = []
weekName.forEach(function(val, index) {
weekTitle.push(
<th key={index} className="dh">{val}</th>
);
});
return weekTitle;
}
render () {
return (
<div className="picker-tab">
<div className="dh picker-date">
<table>
<thead>
<tr>
{ this.weekTitleTab() }
</tr>
</thead>
<tbody>
{ this.weekDateTab() }
</tbody>
</table>
</div>
<div className="today-opts"><a>today</a></div>
</div>
);
}
}
NewComponent.PropTypes = {};
return NewComponent;
}
|
/*
This file defines the card object, its properties and methods.
*/
define(function() {
function Card(data, faction) {
this.base_stat;
this.stat;
this.faction = faction;
this.data = data;
this.view;
this.skill = 1;
this.active = false;
this.primary = false;
if (faction === "offense") {
this.base_stat = this.data.atk;
this.stat = this.base_stat;
} else {
this.base_stat = this.data.def;
this.stat = this.base_stat;
}
}
Card.prototype = {
constructor: Card,
// determine if this card is offensive or defensive, or both.
role: function() {
var scope = this.data.scope;
var ability = this.ability();
var role;
if (scope === "ATKDEF") {
role = "Dual";
} else if (scope === "ATK") {
role = (ability > 1) ? "offense" : "defense";
} else {
role = (ability > 1) ? "defense" : "offense";
}
return role;
},
// update the stats of the card (after receiving boost/degrade)
update: function(data) {
this.data = data;
if (this.faction === "offense") {
this.stat = data.atk;
this.base_stat = data.atk;
} else {
this.stat = data.def;
this.base_stat = data.def;
}
return this.data.id;
},
// switches data, effectively switching cards.
swap: function(data) {
var oldData = this.data;
this.data = data;
return oldData;
},
// return card to base stats
reboot: function() {
this.stat = this.base_stat;
},
// determine if the card's ability will proc
proc: function() {
var chance = parseInt(this.data.frequency);
if (this.primary) {
chance *= 1.275;
}
if (this.skill > 1) {
chance += (this.skill-1);
}
if ((Math.random() * 100) <= chance) {
return true;
}
return false;
},
// determine the card ability's strength based on level and type.
ability: function() {
var ability = parseInt(this.data.ability);
if (ability != 0) {
if (parseInt(this.skill) === 10) {
ability += (this.data.modifier * 10);
} else {
ability += (this.data.modifier * (this.skill-1));
}
ability /= 100;
ability += 1;
if (this.data.type === "Degrade") {
ability -= 2;
ability = Math.abs(ability);
}
return ability.toFixed(2);
}
return 1;
},
// self boost is its own beast
boostSelf: function() {
var stat = this.stat;
this.stat *= this.ability();
return (Math.round(this.stat - stat));
}
}
return {
create: function(d, f) {
return new Card(d, f);
}
}
});
|
//
module.exports = {
options: {
urls: [
'http://socialite.ungryfox.com'
]
}
};
|
let express = require("express"),
app = express(),
cors = require('cors'),
bodyParser = require("body-parser");
var exports = module.exports = {};
app.use(bodyParser.json({extended: true}));
app.use(cors());
exports.getRandomArbitrary = (max) => {
return Math.floor(Math.random() * max);
};
let data = [
{id: 1, value: 2, weight: 9},
{id: 2, value: 12, weight: 2},
{id: 3, value: 8, weight: 3},
{id: 4, value: 22, weight: 99},
{id: 5, value: 2, weight: 22},
{id: 6, value: 66, weight: 34},
{id: 7, value: 45, weight: 54},
{id: 8, value: 11, weight: 23},
{id: 9, value: 64, weight: 45},
{id: 10, value: 34, weight: 23}
];
exports.knapsack = ()=> {
let aa = 50;
let sortedWeght = [];
for (let i=0; i <= data.length-1 ; i++){
if(data[i].weight <= aa){
sortedWeght.push(data[i]);
}
}
let combinations[];
};
app.get("/knapsack", function (req, res) {
res.send(exports.knapsack())
});
const port = process.env.PORT || 7001;
app.listen(port);
console.log(`Knapsack Server listening on ${port}`);
module.exports.app = app;
|
$(function(){
$('.realised-projects-slider').slick({
arrows: false,
speed: 500,
autoplay: false,
autoplaySpeed: 3500,
pauseOnHover: false,
dots: true
});
})
|
var searchData=
[
['operator_5b_5d_6',['operator[]',['../structLineData.html#ad80505a7ef9baa083bd78ed05f0704da',1,'LineData']]]
];
|
(function() {
var QuickSettings = {
_topZ: 1,
_panel: null,
_titleBar: null,
_content: null,
_startX: 0,
_startY: 0,
_hidden: false,
_collapsed: false,
_controls: null,
_keyCode: -1,
_draggable: true,
_collapsible: true,
_globalChangeHandler: null,
create: function(x, y, title) {
var obj = Object.create(this);
obj._init(x, y, title);
return obj;
},
_init: function(x, y, title) {
this._bindHandlers();
this._createPanel(x, y);
this._createTitleBar(title || "QuickSettings");
this._createContent();
document.body.appendChild(this._panel);
},
_bindHandlers: function() {
this._startDrag = this._startDrag.bind(this);
this._drag = this._drag.bind(this);
this._endDrag = this._endDrag.bind(this);
this._doubleClickTitle = this._doubleClickTitle.bind(this);
this._onKeyUp = this._onKeyUp.bind(this);
},
_createPanel: function(x, y) {
this._panel = document.createElement("div");
this._panel.className = "msettings_main";
this.setPosition(x || 0, y || 0);
this._controls = {};
},
_createTitleBar: function(text) {
this._titleBar = document.createElement("div");
this._titleBar.textContent = text;
this._titleBar.className = "msettings_title_bar";
this._titleBar.addEventListener("mousedown", this._startDrag);
this._titleBar.addEventListener("dblclick", this._doubleClickTitle);
this._panel.appendChild(this._titleBar);
},
_createContent: function() {
this._content = document.createElement("div");
this._content.className = "msettings_content";
this._panel.appendChild(this._content);
},
setPosition: function(x, y) {
this._panel.style.left = x + "px";
this._panel.style.top = y + "px";
},
setSize: function(w, h) {
this._panel.style.width = w + "px";
this._content.style.width = w + "px";
this._content.style.height = (h - this._titleBar.offsetHeight) + "px";
},
setDraggable: function(draggable) {
this._draggable = draggable;
if(this._draggable || this._collapsible) {
this._titleBar.style.cursor = "pointer";
}
else {
this._titleBar.style.cursor = "default";
}
},
setCollapsible: function(collapsible) {
this._collapsible = collapsible;
if(this._draggable || this._collapsible) {
this._titleBar.style.cursor = "pointer";
}
else {
this._titleBar.style.cursor = "default";
}
},
_startDrag: function(event) {
this._panel.style.zIndex = ++QuickSettings._topZ;
if(this._draggable) {
document.addEventListener("mousemove", this._drag);
document.addEventListener("mouseup", this._endDrag);
this._startX = event.clientX;
this._startY = event.clientY;
}
event.preventDefault();
},
_drag: function(event) {
var x = parseInt(this._panel.style.left),
y = parseInt(this._panel.style.top),
mouseX = event.clientX,
mouseY = event.clientY;
this.setPosition(x + mouseX - this._startX, y + mouseY - this._startY);
this._startX = mouseX;
this._startY = mouseY;
event.preventDefault();
},
_endDrag: function(event) {
document.removeEventListener("mousemove", this._drag);
document.removeEventListener("mouseup", this._endDrag);
event.preventDefault();
},
_doubleClickTitle: function() {
if(this._collapsible) {
this.toggleCollapsed();
}
},
setGlobalChangeHandler: function(handler) {
this._globalChangeHandler = handler;
},
toggleCollapsed: function() {
if(this._collapsed) {
this.expand();
}
else {
this.collapse();
}
},
collapse: function() {
this._panel.removeChild(this._content);
this._collapsed = true;
},
expand: function() {
this._panel.appendChild(this._content);
this._collapsed = false;
},
hide: function() {
this._panel.style.visibility = "hidden";
this._hidden = true;
},
show: function() {
this._panel.style.visibility = "visible";
this._hidden = false;
},
_createContainer: function() {
var container = document.createElement("div");
container.className = "msettings_container";
return container;
},
_createLabel: function(title) {
var label = document.createElement("div");
label.innerHTML = title;
label.className = "msettings_label";
return label;
},
setKey: function(char) {
this._keyCode = char.toUpperCase().charCodeAt(0);
document.body.addEventListener("keyup", this.onKeyUp);
},
_onKeyUp: function(event) {
if(event.keyCode === this._keyCode) {
this.toggleVisibility();
}
},
toggleVisibility: function() {
if(this._hidden) {
this.show();
}
else {
this.hide();
}
},
bindRange: function(title, min, max, value, step, object) {
this.addRange(title, min, max, value, step, function(value) {
object[title] = value;
});
},
addRange: function(title, min, max, value, step, callback) {
var container = this._createContainer();
var range = document.createElement("input");
range.type = "range";
range.id = title;
range.min = min || 0;
range.max = max || 100;
range.step = step || 1;
range.value = value || 0;
range.className = "msettings_range";
var label = this._createLabel("<b>" + title + ":</b> " + range.value);
container.appendChild(label);
container.appendChild(range);
this._content.appendChild(container);
this._controls[title] = {
container: container,
range: range,
label: label,
callback: callback
};
var eventName = "input";
if(this._isIE()) {
eventName = "change";
}
var gch = this._globalChangeHandler;
range.addEventListener(eventName, function() {
label.innerHTML = "<b>" + title + ":</b> " + range.value;
if(callback) {
callback(parseFloat(range.value));
}
if(gch) {
gch();
}
});
},
_isIE: function() {
if(navigator.userAgent.indexOf("rv:11") != -1) {
return true;
}
if(navigator.userAgent.indexOf("MSIE") != -1) {
return true;
}
return false;
},
getRangeValue: function(title) {
return this._controls[title].range.value;
},
setRangeValue: function(title, value) {
var control = this._controls[title];
control.range.value = value;
control.label.innerHTML = "<b>" + title + ":</b> " + control.range.value;
if(control.callback) {
control.callback(control.range.value);
}
if(this._globalChangeHandler) {
this._globalChangeHandler();
}
},
setRangeParameters: function(title, min, max, step) {
var control = this._controls[title];
control.range.min = min;
control.range.max = max;
control.range.step = step;
},
bindBoolean: function(title, value, object) {
this.addBoolean(title, value, function(value) {
object[title] = value;
});
},
addBoolean: function(title, value, callback) {
var container = this._createContainer();
var label = document.createElement("span");
label.className = "msettings_checkbox_label";
label.textContent = title;
var checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.id = title;
checkbox.checked = value;
checkbox.className = "msettings_checkbox";
container.appendChild(checkbox);
container.appendChild(label);
this._content.appendChild(container);
this._controls[title] = {
container: container,
checkbox: checkbox,
callback: callback
};
var gch = this._globalChangeHandler;
checkbox.addEventListener("change", function() {
if(callback) {
callback(checkbox.checked);
}
if(gch) {
gch();
}
});
label.addEventListener("click", function() {
checkbox.checked = !checkbox.checked;
if(callback) {
callback(checkbox.checked);
}
if(gch) {
gch();
}
});
},
getBoolean: function(title) {
return this._controls[title].checkbox.checked;
},
setBoolean: function(title, value) {
this._controls[title].checkbox.checked = value;
if(control.callback) {
this._controls[title].callback(value);
}
if(this._globalChangeHandler) {
this._globalChangeHandler();
}
},
addButton: function(title, callback) {
var container = this._createContainer();
var button = document.createElement("input");
button.type = "button";
button.id = title;
button.value = title;
button.className = "msettings_button";
container.appendChild(button);
this._content.appendChild(container);
this._controls[title] = {
container: container,
button: button
}
var gch = this._globalChangeHandler;
button.addEventListener("click", function() {
if(callback) {
callback(button);
}
if(gch) {
gch();
}
});
},
bindColor: function(title, color, object) {
this.addColor(title, color, function(value) {
object[title] = value;
});
},
addColor: function(title, color, callback) {
var container = this._createContainer();
var label = this._createLabel("<b>" + title + ":</b> " + color);
var colorInput = document.createElement("input");
try {
colorInput.type = "color";
}
catch(e) {
colorInput.type = "text";
}
colorInput.id = title;
colorInput.value = color || "#ff0000";
colorInput.className = "msettings_color";
container.appendChild(label);
container.appendChild(colorInput);
this._content.appendChild(container);
this._controls[title] = {
container: container,
colorInput: colorInput,
label: label,
callback: callback
};
var gch = this._globalChangeHandler;
colorInput.addEventListener("input", function() {
label.innerHTML = "<b>" + title + ":</b> " + colorInput.value;
if(callback) {
callback(colorInput.value);
}
if(gch) {
gch();
}
});
},
getColor: function(title) {
return this._controls[title].colorInput.value;
},
setColor: function(title, value) {
var control = this._controls[title];
control.colorInput.value = value;
control.label.innerHTML = "<b>" + title + ":</b> " + control.colorInput.value;
if(control.callback) {
control.callback(control.colorInput.value);
}
if(this._globalChangeHandler) {
this._globalChangeHandler();
}
},
bindText: function(title, text, object) {
this.addText(title, text, function(value) {
object[title] = value;
});
},
addText: function(title, text, callback) {
var container = this._createContainer();
var label = this._createLabel("<b>" + title + "</b>");
var textInput = document.createElement("input");
textInput.type = "text";
textInput.id = title;
textInput.value = text || "";
textInput.className = "msettings_text_input";
container.appendChild(label);
container.appendChild(textInput);
this._content.appendChild(container);
this._controls[title] = {
container: container,
textInput: textInput,
label: label,
callback: callback
}
var gch = this._globalChangeHandler;
textInput.addEventListener("input", function() {
if(callback) {
callback(textInput.value);
}
if(gch) {
gch();
}
});
},
getText: function(title) {
return this._controls[title].textInput.value;
},
setText: function(title, text) {
var control = this._controls[title];
control.textInput.value = text;
if(control.callback) {
control.callback(text);
}
if(this._globalChangeHandler) {
this._globalChangeHandler();
}
},
addInfo: function(title, info) {
var container = this._createContainer();
container.innerHTML = info;
this._controls[title] = {
container: container
};
this._content.appendChild(container);
},
bindDropDown: function(title, items, object) {
this.addDropDown(title, items, function(value) {
object[title] = value.value;
});
},
addDropDown: function(title, items, callback) {
var container = this._createContainer();
var label = this._createLabel("<b>" + title + "<b>");
var select = document.createElement("select");
for(var i = 0; i < items.length; i++) {
var option = document.createElement("option");
option.label = items[i];
select.add(option);
};
var gch = this._globalChangeHandler;
select.addEventListener("change", function() {
var index = select.selectedIndex,
options = select.options;
if(callback) {
callback({
index: index,
value: options[index].label
});
}
if(gch) {
gch();
}
});
select.className = "msettings_select";
container.appendChild(label);
container.appendChild(select);
this._content.appendChild(container);
this._controls[title] = {
container: container,
select: select,
label: label,
callback: callback
};
},
getDropDownValue: function(title) {
var control = this._controls[title],
select = control.select,
index = select.selectedIndex,
options = select.options;
return {
index: index,
value: options[index].label
}
},
setDropDownIndex: function(title, index) {
var control = this._controls[title],
options = control.select.options;
control.select.selectedIndex = index;
if(control.callback) {
control.callback({
index: index,
value: options[index].label
});
}
if(this._globalChangeHandler) {
this._globalChangeHandler();
}
},
getInfo: function(title) {
return this._controls[title].container.innerHTML;
},
setInfo: function(title, info) {
this._controls[title].container.innerHTML = info;
},
removeControl: function(title) {
var container = this._controls[title].container;
if(container.parentElement) {
container.parentElement.removeChild(container);
}
this._controls[title] = null;
}
};
if (typeof define === "function" && define.amd) {
define(QuickSettings);
} else {
window.QuickSettings = QuickSettings;
}
}());
|
import React from "react";
import classes from "./Header.module.css";
import Logo from "./Logo";
import HeaderButton from "./HeaderButton";
const MAIN_TITLE = "Cadorisi";
const OFERTE_DE_SEZON = "Oferte de sezon";
const ARANJAMENTE_FLORALE = "Aranjamente florale";
const ACASA = "Acasa";
const CONTACT = "Contact";
const Header = () => {
const onOferteDeSezonHandler = () => {};
const onAranjamenteFloraleHandler = () => {};
const onHomeHandler = () => {};
const onContactHandler = () => {};
const onMainTitleHandler = () => {};
return (
<React.Fragment>
<header className={classes.header}>
<Logo></Logo>
<HeaderButton
className={"buttonOferte"}
onButtonClick={onOferteDeSezonHandler}
text={OFERTE_DE_SEZON}
></HeaderButton>
<HeaderButton
className={"buttonAranjamente"}
onButtonClick={onAranjamenteFloraleHandler}
text={ARANJAMENTE_FLORALE}
></HeaderButton>
<HeaderButton
className={"mainTitle"}
onButtonClick={onMainTitleHandler}
text={MAIN_TITLE}
></HeaderButton>
<HeaderButton
className={"buttonHome"}
onButtonClick={onHomeHandler}
text={ACASA}
></HeaderButton>
<HeaderButton
className={"buttonContact"}
onButtonClick={onContactHandler}
text={CONTACT}
></HeaderButton>
</header>
</React.Fragment>
);
};
export default Header;
|
const { Rules } = require('./rules/const');
module.exports = {
extends: [
require.resolve('./essential'),
'plugin:vue/recommended'
],
rules: {
'vue/require-default-prop': Rules.OFF,
'vue/html-self-closing': Rules.OFF,
'vue/attribute-hyphenation': Rules.ERROR
}
};
|
/*弹窗框下拉列表*/
$("#operation-infosel-modal p").bind("click", function() {
var ul = $("#operation-infosel-modal ul");
$("#operation-infosel-modal p i").addClass("current");
if (ul.css("display") == "none") {
ul.slideDown("fast");
} else {
ul.slideUp("fast");
};
});
$("#operation-infosel-modal ul li a").on("click", function() {
var txt = $(this).text();
$("#operation-infosel-modal p").html(txt + "<i></i>");
$("#operation-infosel-modal ul").hide();
$(".option").empty();
flage = 0 /*序号归0*/
});
/* end 下拉列表*/
var questTable = new tableDataOperation();
/*查询条件保存*/
var searchTrime = {}; /*查询的条件 (对象)*/
/*搜索查询事件*/
$("#question_search_btn").on("click",searchFn);
function searchFn(){
/*题目*/
var topicVal = $.trim($("#topic").val());
var status;
if($("#status").text()=='已处理'){
status=1;
}else if($("#status").text()=='未处理'){
status=0;
}else {
status='';
}
searchTrime.status = status;
searchTrime.content = topicVal;
$.ajax({
type:"post",
url:contextPath+"/feedback/listByPage",
data:searchTrime,
dataType:"json",
success:function(data){
if (data.code==1) {
laypage({
cont:'giveFeedBack_page',
pages:Math.ceil(data.data.total/data.data.pageSize),/*总页数*/
curr:data.data.currentPage||1,/*当前页*/
jump:pageCallback
})
}
}
})
}
/*分页回调函数*/
function pageCallback(obj,first){
var currentPage= obj.curr;
var dataPageSize=10;
searchTrime.currentPage=currentPage;
searchTrime.pageSize=dataPageSize;
$.ajax({
type:"post",
url:contextPath+"/feedback/listByPage",
data:searchTrime,
dataType:"json",
success:function(data){
sccFunction(data);
$("#table-dataallcheck").removeClass("check-current");
$("#table-dataallcheck").attr("data-check","");
}
});
}
function sccFunction(data) {
$("tbody").empty();
/*显示数据的ID*/
var tableList = ["type","askContent","mobilePhone","email","status","askTime"];
/*隐藏数据的ID*/
var tableListNone = ["id"];
/*表格展示数据的List*/
var dataList = data.data.data?data.data.data:[];
var sun_page=data.data.total;
$("#sum_page span").text(sun_page);
for(var i=0;i<dataList.length;i++){
if(dataList[i].type==0){
dataList[i].type="意见";
}else if(dataList[i].type==1){
dataList[i].type="建议";
}else if(dataList[i].type==2){
dataList[i].type="投诉";
}else if(dataList[i].type==3){
dataList[i].type="其他";
}
if(dataList[i].status==0){
dataList[i].status="未处理";
}else{
dataList[i].status="已处理";
}
}
/*添加数据*/
var operation=["table-edit"]
var title=["详细"]
questTable.dataAdd(dataList, "table_id", "itm", tableList, tableListNone,operation,title);
/*全选*/
tableEditFn();
}
searchFn()
function tableEditFn() {
$(".table-edit").on('click',function(e){
e.stopPropagation();
var self = this;
var getId = singleId(self, "id"); /*编辑某一个返回的这行的标识ID*/
$.ajax({
type: "post",
url:basecontextPath+"/feedback/detail",
data: {
id:getId
},
dataType: "json",
success: function(data) {
if (data.code == 1) {
modal("详情")
if(data.data.type==0){
$("#typeShow").text("意见");
}else if(data.data.type==1){
$("#typeShow").text("建议");
}else if(data.data.type==2){
$("#typeShow").text("投诉");
}else if(data.data.type==3){
$("#typeShow").text("其他");
}
$("#askConten").val(data.data.askContent);//反馈的内容
$("#Email").text(data.data.email);//反馈人员的email
$("#Tel").text(data.data.mobilePhone);//反馈人员的电话
$("#ids").val(data.data.id);//这是标志反馈人员的ID
if(data.data.status==1){
$("input[name='course_elaborate']").eq(0).attr("checked","ture");
}else{
$("input[name='course_elaborate']").eq(1).attr("checked","ture");
}
}
}
})
})
};
questTable.checkBoxAll("table-dataallcheck");
$("#status_add").on("click", function () {
var idArray = questTable.allDel("table_id", "id");
var ids = {};
if (idArray.length <= 0) {
layer.msg('请选择要处理的列表!');
return;
}
for (var i = 0; i < idArray.length; i++) {
ids[i] = idArray[i];
}
layer.confirm('确定要批量编辑吗?', {
btn: ['确定', '取消'],
cancel: function () {
$("#table_id tbody tr").removeClass('chlickColor').find('input').prop('checked', false);
}
}, function () {
$.ajax({
type: "post",
url: contextPath + "/feedback/markMulti",
data: {
ids: ids,
status:1
},
dataType: "json",
success: function (data) {
if (data.code == 1) {
$("#question_search_btn").click()
layer.msg('已编辑为已处理', {
icon: 1,
time: 800
})
}
}
});
},
function () {
$("#table_id tbody tr").removeClass('chlickColor').find('input').prop('checked', false);
})
});
$("#status_del").on("click", function () {
var idArray = questTable.allDel("table_id", "id");
var ids = {};
if (idArray.length <= 0) {
layer.msg('请选择要处理的列表!');
return;
}
for (var i = 0; i < idArray.length; i++) {
ids[i] = idArray[i];
}
layer.confirm('确定要批量编辑吗?', {
btn: ['确定', '取消'],
cancel: function () {
$("#table_id tbody tr").removeClass('chlickColor').find('input').prop('checked', false);
}
}, function () {
$.ajax({
type: "post",
url: contextPath + "/feedback/markMulti",
data: {
ids: ids,
status:0
},
dataType: "json",
success: function (data) {
if (data.code == 1) {
$("#question_search_btn").click()
layer.msg('已编辑为未处理', {
icon: 1,
time: 800
})
}
}
});
},
function () {
$("#table_id tbody tr").removeClass('chlickColor').find('input').prop('checked', false);
})
});
/*弹窗窗口*/
/*弹窗方法*/
function modal() {
layer.open({
type: 1,
skin: 'layui-layer-molv', //皮肤
title: ['反馈详情', "font-size:18px"],
area: ['700px', '450px'],
shadeClose: true,
content: $('#feedback_modal'),
cancel:function(){
$("#table_id tbody tr").removeClass('chlickColor').find('input').prop('checked', false);
}
});
};
$("#sign_update").on('click',function(){
var status;
if($("input[name='course_elaborate']"&&"input[value='1']").prop('checked')){
status=0;
}else {
status=1;
}
$.ajax({
type: "post",
url: contextPath + "/feedback/update",
data: {
id: $("#ids").val(),
status:status
},
dataType: "json",
success: function (data) {
if (data.code == 1) {
$("#question_search_btn").click()
layer.msg('提交成功', {
icon: 1,
time: 800
});
layer.closeAll();
}
}
});
})
|
import zookeeper from 'node-zookeeper-client';
import logger from 'winston';
export function createContext() {
return {
client: null,
path: '/',
masterUrl: null,
};
}
export function setPath(context, path) {
context.path = path;
}
export function parseToUrl(data) {
if (data.length === 0) {
return false;
}
const json = JSON.parse(data);
return 'http://' + json.address.ip + ':' + json.address.port;
}
function getData(context, child) {
context.client.getData(
context.path + '/' + child,
(error, data) => {
if (error) {
return;
}
context.masterUrl = parseToUrl(data.toString('utf8'));
logger.info('Master URL is now %s', context.masterUrl);
}
);
}
function watchNode(context) {
logger.info('Got new ZNode event');
context.client.getChildren(
context.path,
() => {
watchNode(context);
},
(error, children) => {
if (error) {
return;
}
if (children.length > 0) {
getData(context, children[0]);
}
}
);
}
export function connect(context, address) {
context.client = zookeeper.createClient(address);
context.client.connect();
context.client.once('connected', () => {
logger.info('Connected to ZooKeeper');
watchNode(context);
});
}
|
// INVOCA BOTBUILDER REQUIRIENDO EL PAQUETE
var builder = require('botbuilder');
// une la consola con el bot
var conector = new builder.ConsoleConnector().listen();
//instancia de un bot de tipo universal
var bot = new builder.UniversalBot(conector);
bot.dialog('/',[
//primer dialogo que se conoce como dialogo raiz
function(session){// creacion de objeto llamado sesion
builder.Prompts.text(session,'¿como te llamas?');
},
function(session,results){
let msj = results.response;
session.send(`Hola ${msj} `);//este objeto es la manera de conectar con los usuarios
}
])
|
//$(document).click(function( event ) {
//event.preventDefault();
$(document).ready(function() {
$('.pagination a').on("click", function (event) {
event.preventDefault();
$('.pagination').html('Data is loading...');
$.get(this.href, null, null, 'script');
return false;
});
});
//});
|
import Vue from 'vue'
import firebase from 'firebase'
import 'firebase/auth'
import {router} from './router';
import {checkIsAdmin, checkIsUser} from './firebase-helpers';
const FIREBASE_CONFIG = {
// Config object
};
firebase.initializeApp(FIREBASE_CONFIG);
const initVue = () => {
new Vue({
el: '#app',
template: '<router-view></router-view>',
router,
});
}
const STAGING_SITE = 'https://example.com';
firebase.auth().onAuthStateChanged((user) => {
if (user) {
if (location.origin === STAGING_SITE) {
checkIsAdmin().then(isAdmin => {
if (isAdmin) initVue()
else document.querySelector('#app').innerHTML = 'Admin only!';
}).catch(console.error);
}
else {
checkIsUser().then(isUser => {
if (isUser) initVue()
else document.querySelector('#app').innerHTML = 'No access permission!';
}).catch(console.error);
}
} else {
firebase.auth().getRedirectResult().then((result) => {
if (result.user){
return result.user;
}
else {
firebase.auth().signInWithRedirect(new firebase.auth.GoogleAuthProvider());
}
}).catch(console.error);
}
});
|
var searchData=
[
['init_383',['INIT',['../group__mouse.html#ggadc6e5733fc3c22f0a7b2914188c49c90a0cb1b2c6a7db1f1084886c98909a3f36',1,'mouse.h']]]
];
|
// function practise
const calcSum = function (x) {
return x + 15;
}
const d = function (x, y) {
const z = calcSum(x);
const t = z - 15;
if (t < 50) {
return `very small value ${t}`
} else {
return `sufficient value to perform task ${t}`
}
}
console.log(d(10, 20));
console.log(d(30, 40));
|
var jformat = /* 简单考虑封装 */(function () {
// --------- 模板引擎( 处理对象参数 ) ----------
// 模板引擎边界符号( 可配置 )
var options = {
left: '\\{\\{',
right: '\\}\\}',
__left__: '\\{\\{',
__right__: '\\}\\}'
};
// 用于处理模板引擎的正则表达式
var reg = new RegExp( options.left + '\\s*(.+?)\\s*' + options.right, 'g' );
// 可缓存
function getRegExpObj() {
if ( options.left !== options.__left__ || options.right !== options.__right__ ) {
options.__left__ = options.left;
options.__right__ = options.right;
reg = new RegExp( options.left + '\\s*(.+?)\\s*' + options.right, 'g' );
}
return reg;
}
function formatWithObject( format, target ) {
var r = getRegExpObj();
return format.replace( r, function ( _, attrName ) {
return target[ attrName ];
});
}
// --------- 模板引擎( 处理数组参数 ) ----------
function getRHole( index ) {
return new RegExp( '\\{\\s*(' + index + ')\\s*\\}', 'g' );
}
function formatWithArray( format ) {
var args = Array.prototype.slice.call( arguments, 1 ), len = args.length;
var i = 0, tmp_format = format;
for ( ; i < len; i++ ) {
tmp_format = tmp_format.replace( getRHole( i ), function ( _, index ) {
return args[ index ];
});
}
return tmp_format;
}
function formatFn ( format, obj ) {
if ( typeof obj === 'object' ) {
return formatWithObject( format, obj );
} else {
return formatWithArray.apply( null, arguments );
}
};
formatFn.options = options;
return formatFn;
})();
|
import Cookies from 'js-cookie'
export function getAccessToken() {
return Cookies.get('access')
}
export function getRefreshToken() {
return sessionStorage.getItem('refresh')
}
export function setAccessToken(access) {
return Cookies.set('access', access)
}
export function setRefreshToken(refresh) {
sessionStorage.setItem('refresh', refresh)
}
export function removeToken() {
sessionStorage.removeItem('refresh')
return Cookies.remove('access')
}
export function updateLastTime() {
const now = new Date()
sessionStorage.setItem('lastUpdateTime', now)
}
export function removeLastTime() {
sessionStorage.removeItem('lastUpdateTime')
}
const expireTime = 10 // 分钟
export function inExpiration() {
const now = new Date()
const lastTime = new Date(sessionStorage.getItem('lastUpdateTime'))
if (!lastTime) {
return false
} else {
return (now - lastTime) / (60 * 1000) < expireTime
}
}
|
import React, { Component } from 'react';
import Project from 'views/Project';
import { projects } from 'views/App';
export default class Projects extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className='Projects'>
<h1>Projects</h1>
{ projects.map(project => <Project project={ project } key={ project.name } />) }
</div>
);
}
}
|
/**
* instaneof
* 原理:沿着原型链,网上找,如果找得到,就返回true,如果找不到就返回false
*/
function myInstanceOf(sub, sup) {
let current = sub;
while(true) {
if(current === null) {
return false;
}
if(current.__proto__ === sup.prototype) {
return true;
}
current = current.__proto__;
}
}
// 测试代码
class Person {
constructor(name) {
this.name = name;
}
};
class Man extends Person {
constructor(name) {
super(name);
this.sex = 'male';
}
}
const man = new Man('mike');
console.log(myInstanceOf(man, Man)); //true
console.log(myInstanceOf(man, Person)); //true
console.log(myInstanceOf(man, Function)); //false
|
/* Engine.js
* 这个文件提供了游戏循环玩耍的功能(更新敌人和渲染)
* 在屏幕上画出出事的游戏面板,然后调用玩家和敌人对象的 update / render 函数(在 app.js 中定义的)
*
* 一个游戏引擎的工作过程就是不停的绘制整个游戏屏幕,和小时候你们做的 flipbook 有点像。当
* 玩家在屏幕上移动的时候,看上去就是图片在移动或者被重绘。但这都是表面现象。实际上是整个屏幕
* 被重绘导致这样的动画产生的假象
* 这个引擎是可以通过 Engine 变量公开访问的,而且它也让 canvas context (ctx) 对象也可以
* 公开访问,以此使编写app.js的时候更加容易
*/
var Engine = (function(global) {
/**
* 实现定义我们会在这个作用于用到的变量
* 创建 canvas 元素,拿到对应的 2D 上下文
* 设置 canvas 元素的高/宽 然后添加到dom中
*/
var doc = global.document,
win = global.window,
canvas = doc.createElement('canvas'),
ctx = canvas.getContext('2d'),
running = true, // 保存游戏状态
requestId,
lastTime;
canvas.width = 606;
canvas.height = 606;
doc.body.appendChild(canvas);
/**
* 这个函数调用一些初始化工作,特别是设置游戏必须的 lastTime 变量,这些工作只用
* 做一次就够了
*/
function init() {
running = true;
lastTime = Date.now();
main();
}
/**
* 这个函数是整个游戏的主入口,负责适当的调用 update / render 函数
*/
function main() {
/**
* 如果你想要更平滑的动画过度就需要获取时间间隙。因为每个人的电脑处理指令的
* 速度是不一样的,我们需要一个对每个人都一样的常数(而不管他们的电脑有多快)
*/
var now = Date.now(),
dt = (now - lastTime) / 1000.0;
// 调用我们的 update / render 函数, 传递事件间隙给 update 函数因为这样可以使动画更加顺畅。
update(dt);
render();
// 设置我们的 lastTime 变量,它会被用来决定 main 函数下次被调用的事件。
lastTime = now;
// 在浏览准备好调用重绘下一个帧的时候,用浏览器的 requestAnimationFrame 函数来调用这个函数
if (running) {
requestId = win.requestAnimationFrame(main);
}
}
/**
* 这个函数被 main 函数(我们的游戏主循环)调用,它本身调用所有的需要更新游戏角色
* 数据的函数,取决于你怎样实现碰撞检测(意思是如何检测两个角色占据了同一个位置,
* 比如你的角色死的时候),你可能需要在这里调用一个额外的函数。现在我们已经把这里
* 注释了,你可以在这里实现,也可以在 app.js 对应的角色类里面实现。
*/
function update(dt) {
updateEntities(dt);
// 检查 hero 实体是否遇到 enemy
checkCollisions();
}
/**
* 这个函数会遍历在 app.js 定义的存放所有敌人实例的数组,并且调用他们的 update()
* 函数,然后,它会调用玩家对象的 update 方法,最后这个函数被 update 函数调用。
* 这些更新函数应该只聚焦于更新和对象相关的数据/属性。把重绘的工作交给 render 函数。
*/
function updateEntities(dt) {
allEnemies.forEach(enemy => {
enemy.update(dt);
});
hero.update();
}
/**
* 这个函数做了一些游戏的初始渲染,然后调用 renderEntities 函数。记住,这个函数
* 在每个游戏的时间间隙都会被调用一次(或者说游戏引擎的每个循环),因为这就是游戏
* 怎么工作的,他们就像是那种每一页上都画着不同画儿的书,快速翻动的时候就会出现是
* 动画的幻觉,但是实际上,他们只是不停的在重绘整个屏幕。
*/
function render() {
// 这个数组保存着游戏关卡的特有的行对应的图片相对路径
var rowImages = [
'images/grass-block.png', // 草地
'images/stone-block.png', // 石头
'images/stone-block.png', // 石头
'images/stone-block.png', // 石头
'images/grass-block.png', // 草地
'images/grass-block.png' // 草地
],
numRows = 6,
numCols = 6,
row,
col;
// 便利我们上面定义的行和列,用 rowImages 数组,在各自的各个位置绘制正确的图片
for (row = 0; row < numRows; row++) {
for (col = 0; col < numCols; col++) {
/* 这个 canvas 上下文的 drawImage 函数需要三个参数,第一个是需要绘制的图片
* 第二个和第三个分别是起始点的x和y坐标。我们用我们事先写好的资源管理工具来获取
* 我们需要的图片,这样我们可以享受缓存图片的好处,因为我们会反复的用到这些图片
*/
ctx.drawImage(Resources.get(rowImages[row]), col * 101, row * 83);
}
}
renderEntities();
}
/**
* 这个函数会在每个时间间隙被 render 函数调用。他的目的是分别调用你在 enemy 和 hero
* 对象中定义的 render 方法。
*/
function renderEntities() {
// 渲染障碍物实体
rock.render(101, 160);
// 渲染所有宝石奖励实体
allGems.forEach(gem => {
gem.render(100, 140);
});
// 渲染所有敌人实体
allEnemies.forEach(enemy => {
enemy.render();
});
// 渲染英雄实体
hero.render();
// 渲染公主实体
princess.render();
}
/**
* 检查英雄实体是否与敌人实体相遇,若相遇,重置游戏状态
*/
function checkCollisions() {
let { x: hx, y: hy } = hero.position;
let metEnemy = allEnemies.some(enemy => {
let { x: ex, y: ey } = enemy.position;
// -20 微调小碰撞半径
return hy === ey && (hx > ex ? hx < ex + 101 - 20 : hx + 101 - 20 > ex);
});
if (metEnemy) {
running = false;
win.cancelAnimationFrame(requestId);
reset();
}
}
/**
* 这个函数现在没干任何事,但是这会是一个好地方让你来处理游戏重置的逻辑。可能是一个
* 从新开始游戏的按钮,也可以是一个游戏结束的画面,或者其它类似的设计。它只会被 init()
* 函数调用一次。
*/
function reset() {
resetEntity();
init();
}
/**
* 紧接着我们来加载我们知道的需要来绘制我们游戏关卡的图片。然后把 init 方法设置为回调函数。
* 那么党这些图片都已经加载完毕的时候游戏就会开始。
*/
Resources.load([
'images/stone-block.png',
'images/grass-block.png',
'images/enemy-bug-l.png',
'images/enemy-bug-r.png',
'images/char-boy.png',
'images/Gem Blue.png',
'images/Gem Green.png',
'images/Rock.png',
'images/char-princess-girl.png'
]);
Resources.onReady(init);
/**
* 把 canvas 上下文对象、重置游戏状态函数 绑定在 global 全局变量上(在浏览器运行的时候就是 window
* 对象),从而开发者就可以在他们的app.js文件里面更容易的使用它。
*/
global.ctx = ctx;
global.resetGame = reset;
})(this);
|
import React from 'react'
import PropTypes from 'prop-types'
const HeaderComponent = props => {
return <div>{props.children}</div>
}
HeaderComponent.propTypes = {
children: PropTypes.node
}
export default HeaderComponent
|
const express = require('express');
const mongoose = require('mongoose');
const config = require('./helpers/config');
const cors = require("cors");
const dotenv = require("dotenv")
const auth = require('./routes/auth')
// Mongoose Connection
mongoose.connect(config.MONGODB_URI, config.MONGOOSE_OPTIONS)
.then(()=> {
console.log(`MONGODB Connection successful`)
}).catch(exception=>{
console.log("MONGODB Connection failed/n", exception)
})
const app = express();
app.use(cors());
app.use(express.json());
app.use('/api/auth',auth);
const PORT = process.env.PORT || 1200;
app.listen(PORT, ()=> {
console.log(`Server started on PORT: ${PORT}`)
})
|
const express = require('express');
const router = express.Router();
const passport = require('passport');
const { ensureAuthenticated, forwardAuthenticated } = require('../config/auth');
/* GET home page. */
router.get('/',forwardAuthenticated, function(req, res, next) {
const user = req.user;
res.render('index', { title: 'Express', user });
});
module.exports = router;
|
import {
CLICK_CELL,
CHECK_WIN,
NEXT_PLAYER,
EXPAND_BOUNDS,
RESET
} from "./actionTypes";
export const clickCell = (row, column, player) => ({
type: CLICK_CELL,
payload: { row, column, player }
});
export const checkPlayerWin = (player, row, column) => ({
type: CHECK_WIN,
payload: { row, column, player }
});
export const nextPlayer = (player) => ({
type: NEXT_PLAYER,
payload: { player }
});
export const expandBounds = (point) => ({
type: EXPAND_BOUNDS,
payload: point
});
export const reset = () => ({
type: RESET,
payload: {}
});
|
angular.module('ngApp.quotationTools').controller('ukTNTInfoController', function ($uibModal, $scope, TNTInfo, TNTInfo1, LogisticCompany) {
$scope.UKTNTInfo = TNTInfo;
$scope.UKTNTInfo1 = TNTInfo1;
$scope.LogisticCompany = LogisticCompany;
});
|
/**
* Creates a 2d array with elements initialized using the given generator function.
*
* The inner arrays are the rows (constant y).
*
* @param {!int} width
* @param {!int} height
* @param {!function(x: !int, y: !int): T} generator
* @returns {!Array.<!Array.<T>>}
* @template T
*/
import {seq, Seq} from "src/base/Seq.js";
function makeArrayGrid(width, height, generator) {
let result = [];
for (let y = 0; y < height; y++) {
let rowEntries = [];
for (let x = 0; x < width; x++) {
rowEntries.push(generator(x, y));
}
result.push(rowEntries);
}
return result;
}
/**
* Forces a set to contain or not contain an item, based on a boolean parameter.
* @param {!Set.<T>|!GeneralSet.<T>} set The set the caller wants to contain (or not contain) the given item.
* @param {T} item The item that the caller wants to be in (or not in) the given set.
* @param {!boolean} membership Whether or not to include the item in the set.
* @template T
*/
function setMembershipInOfTo(set, item, membership) {
if (membership) {
set.add(item);
} else {
set.delete(item);
}
}
/**
* Flips whether or not a set contains an item.
* @param {!Set.<T>|!GeneralSet.<T>} set The set to update.
* @param {T} item The item to add xor remove from the set.
* @template T
*/
function toggleMembership(set, item) {
setMembershipInOfTo(set, item, !set.has(item));
}
/**
* @param {!Set.<T>|!!GeneralSet.<T>} src
* @param {!Set.<T>|!!GeneralSet.<T>} dst
* @template T
*/
function xorSetInto(src, dst) {
for (let e of src) {
toggleMembership(dst, e);
}
}
/**
* @param {!int} minRow
* @param {!int} maxRow
* @param {!int} minCol
* @param {!int} maxCol
* @param {!function(row: !int, col: !int): !string} func
* @returns {!string}
*/
function gridRangeToString(minRow, maxRow, minCol, maxCol, func) {
let w = maxCol - minCol + 1;
let rail = Seq.repeat('#', w + 2).join('');
let rows = [rail];
for (let row = minRow; row <= maxRow; row++) {
let cells = [];
for (let col = minCol; col <= maxCol; col++) {
let r = func(row, col);
cells.push(r === undefined ? ' ' : r);
}
rows.push('#' + cells.join('') + '#');
}
rows.push(rail);
return rows.join('\n');
}
/**
* @param {!Array.<!string>} planes
* @param {!int} maxWidth
* @returns {!string}
*/
function mergeGridRangeStrings(planes, maxWidth) {
let p = planes[0].split('\n');
let cellWidth = p[0].length;
let cellHeight = p.length;
let done = [];
let cur = [];
let w = 0;
for (let plane of planes) {
let planeRows = plane.split('\n');
let d = planeRows[0].length;
if (w + d + 3 <= maxWidth) {
w += d + 3;
cur.push(planeRows);
} else {
done.push(cur);
cur = [];
}
w += d;
}
if (cur.length > 0) {
done.push(cur);
}
return done.map(rowCells => {
let rows = [];
for (let i = 0; i < cellHeight; i++) {
rows.push(rowCells.map(e => e[i]).join(' '));
}
return rows.join('\n');
}).join('\n\n');
}
export {
setMembershipInOfTo,
toggleMembership,
xorSetInto,
makeArrayGrid,
gridRangeToString,
mergeGridRangeStrings
}
|
require("../common/vendor.js"), (global.webpackJsonp = global.webpackJsonp || []).push([ [ "pages/activity_a/720/_search" ], {
"0449": function(e, n, t) {
Object.defineProperty(n, "__esModule", {
value: !0
}), n.default = void 0;
var o = (0, t("80d6").getSystemInfo)().windowWidth / 750, r = 330 * o, i = 174 * o, c = {
props: {
decoration: [ String, Number ],
zone_ids: [ String, Number ],
zone_section_ids: [ String, Number ],
area: [ String, Number ],
total_price: [ String, Number ],
price: [ String, Number ],
layout: [ String, Number ],
metro: [ String, Number ],
keyword: String
},
components: {
TopFilter: function() {
t.e("components/buildings_top_filter/index").then(function() {
return resolve(t("71eb"));
}.bind(null, t)).catch(t.oe);
}
},
data: function() {
return {
fixed: !1
};
},
mounted: function() {
this.checkPosition();
},
methods: {
toggleFilter: function(e) {
e && wx.pageScrollTo({
scrollTop: r
});
},
changeFilter: function(e) {
console.error(e), this.$emit("changeFilter", e);
},
checkPosition: function() {
var e = this;
this.$mp.component.createIntersectionObserver().relativeToViewport({
top: -i
}).observe("#search-wrap", function(n) {
e.fixed = 0 === n.intersectionRatio;
});
},
changeKeyword: function(e) {
this.$emit("changeKeyword", e.target.value);
},
search: function() {
this.$emit("search");
}
}
};
n.default = c;
},
"3cfa": function(e, n, t) {
t.d(n, "b", function() {
return o;
}), t.d(n, "c", function() {
return r;
}), t.d(n, "a", function() {});
var o = function() {
var e = this;
e.$createElement;
e._self._c;
}, r = [];
},
4752: function(e, n, t) {
var o = t("61e1");
t.n(o).a;
},
"50d3": function(e, n, t) {
t.r(n);
var o = t("3cfa"), r = t("7333");
for (var i in r) [ "default" ].indexOf(i) < 0 && function(e) {
t.d(n, e, function() {
return r[e];
});
}(i);
t("4752");
var c = t("f0c5"), a = Object(c.a)(r.default, o.b, o.c, !1, null, "597c835c", null, !1, o.a, void 0);
n.default = a.exports;
},
"61e1": function(e, n, t) {},
7333: function(e, n, t) {
t.r(n);
var o = t("0449"), r = t.n(o);
for (var i in o) [ "default" ].indexOf(i) < 0 && function(e) {
t.d(n, e, function() {
return o[e];
});
}(i);
n.default = r.a;
}
} ]), (global.webpackJsonp = global.webpackJsonp || []).push([ "pages/activity_a/720/_search-create-component", {
"pages/activity_a/720/_search-create-component": function(e, n, t) {
t("543d").createComponent(t("50d3"));
}
}, [ [ "pages/activity_a/720/_search-create-component" ] ] ]);
|
const express = require("express");
const controller = require("../controllers/userController");
const passport = require("passport");
// Import middleware
const auth = require("../middleware/auth");
const currentUser = require("../middleware/setCurrentUser");
const router = express.Router();
router.use(currentUser.setCurrentUser);
router.get("/logout", controller.logout);
router.use(auth.checkNotAuthenticate);
router.get("/login", controller.login);
router.get("/register", controller.register);
router.post("/register", controller.registerUser);
router.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/user/login",
failureFlash: true,
})
);
module.exports = router;
|
var $ = jQuery;
if (document.domain.split('.')[1] === "google") {
$(document).ready(function() {
console.log('started');
// Page pre-modifications
$('style').remove();
//$('li > .action-menu-button').each(function () {$(this)[0].parentNode.remove()});
var results = $('#search #ires li.g');
$('body').append('<div class="new_list always_show"></div>');
results.each(function () {
$('body .new_list').append($(this));
});
console.log('finished');
});
$(document).ready(function() { // Load jquery for testing us
var jq = document.createElement("script");
jq.type = 'text/javascript';
jq.src = '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js'
document.head.appendChild(jq);
});
}
|
import React, { useState, useEffect, useRef } from "react";
import io from "socket.io-client";
import moment from "moment";
import LoadingSpinner from "../../components/LoadingSpinner";
import { useProfile } from "../../contexts/profile";
import { v4 as uuid } from "uuid";
import { Redirect, Link } from "react-router-dom";
import {
Container,
ChatContainer,
ChatFooter,
MessagesContainer,
FooterSpan,
} from "../Chat/styles";
import Message from "../../components/Message";
import { ReactComponent as SendIcon } from "../../assets/icons/paper-plane-regular.svg";
import { ChatHeader } from "./styles";
function ChatAdmin() {
const [socket, setSocket] = useState();
const [messages, setMessages] = useState([]);
const [filtered, setFiltered] = useState(null);
const [reversed, setReversed] = useState([]);
const [connected, setConnected] = useState(false);
const [deleting, setDeleting] = useState(null);
const [order, setOrder] = useState("asc");
const [usernameFilter, setUsernameFilter] = useState(null);
const [dateFilter, setDateFilter] = useState(null);
const { profile, setProfile } = useProfile();
const contentRef = useRef();
const messagesContainerRef = useRef();
useEffect(() => {
const socket = io("http://localhost:8080", {
query: {
access_token: profile?.access_token,
},
});
setSocket(socket);
}, []); // eslint-disable-line
useEffect(() => {
if (!socket) return;
socket.on("connected", (data) => {
setMessages(data.history);
let reversedHistory = [...data.history];
reversedHistory.reverse();
setReversed(reversedHistory);
setProfile({
...profile,
username: data.payload.username,
user_id: data.payload.id,
admin: data.payload.admin,
});
setConnected(true);
});
socket.on("chat.new_message", (data) => {
setMessages((cur_messages) => [...cur_messages, data]);
});
socket.on("chat.delete_message", (uuid) => {
setDeleting(uuid);
});
}, [socket]); // eslint-disable-line
useEffect(() => {
if (usernameFilter) return filter();
if (dateFilter) return filter();
return setFiltered(null);
}, [messages, usernameFilter, dateFilter]); // eslint-disable-line
useEffect(() => {
let reversedMessages = [];
if (filtered) reversedMessages = [...filtered];
else reversedMessages = [...messages];
reversedMessages.reverse();
setReversed(reversedMessages);
}, [messages, filtered]);
useEffect(() => {
if (connected)
messagesContainerRef.current.scrollTop =
messagesContainerRef.current.scrollHeight;
}, [connected]);
useEffect(() => {
if (!deleting) return;
deleteMessage(deleting);
setDeleting(null);
}, [deleting]); // eslint-disable-line
if (!socket)
return (
<div style={{ height: "100vh" }}>
<LoadingSpinner />
</div>
);
function handleSubmit(e) {
e.preventDefault();
const content = contentRef.current.value;
const id = uuid();
if (!content) return;
socket.emit("chat.new_message", {
uuid: id,
content,
});
let cur_messages = [...messages];
cur_messages.push({
uuid: id,
username: profile.username,
content,
createdAt: new Date(),
});
setMessages(cur_messages);
contentRef.current.value = "";
if (order === "asc")
messagesContainerRef.current.scrollTop =
messagesContainerRef.current.scrollHeight + 100;
}
if (profile.admin === false) return <Redirect to="/" />;
function handleUsernameFilter(e) {
setUsernameFilter(e.target.value);
}
function handleDateFilter(e) {
setDateFilter(e.target.value);
}
function handleChangeOrder(e) {
setOrder(e.target.value);
}
function filter() {
let filteredMessages = [];
filteredMessages = messages.filter((message) => {
if (usernameFilter && dateFilter)
return (
message.username.startsWith(usernameFilter) &&
moment(message.date).format("DD/MM/YY") ===
moment(dateFilter).format("DD/MM/YY")
);
if (usernameFilter && !dateFilter)
return message.username.startsWith(usernameFilter);
if (dateFilter && !usernameFilter)
return (
moment(message.date).format("DD/MM/YY") ===
moment(dateFilter).format("DD/MM/YY")
);
return null;
});
setFiltered(filteredMessages);
}
function deleteMessage(uuid) {
let cur_messages = [...messages];
let deleting_index;
cur_messages.forEach((message, index) => {
if (message.uuid === uuid) deleting_index = index;
});
cur_messages.splice(deleting_index, 1);
setMessages(cur_messages);
}
function handleDelete(uuid) {
deleteMessage(uuid);
socket.emit("chat.delete_message", uuid);
}
return (
<Container>
<ChatContainer>
<ChatHeader>
<span>Filtrar</span>
<div>
<input
onChange={handleUsernameFilter}
type="text"
placeholder="Nome de usuário"
/>
<input onChange={handleDateFilter} type="date" placeholder="Data" />
<select onChange={handleChangeOrder} value={order}>
<option value="asc">Mais recentes</option>
<option value="desc">Mais antigas</option>
</select>
</div>
</ChatHeader>
<MessagesContainer ref={messagesContainerRef}>
{order === "desc" ? (
<div>
{reversed?.map((entry, index) => (
<Message key={index} data={entry} onDelete={handleDelete} />
))}
</div>
) : filtered ? (
<div>
{filtered.map((entry, index) => (
<Message key={index} data={entry} onDelete={handleDelete} />
))}
</div>
) : (
<div>
{messages?.map((entry, index) => (
<Message key={index} data={entry} onDelete={handleDelete} />
))}
</div>
)}
</MessagesContainer>
<ChatFooter>
<form onSubmit={handleSubmit}>
<input
autoComplete="off"
type="text"
name="content"
ref={contentRef}
/>
<button type="submit">
<SendIcon />
</button>
</form>
<form>
<FooterSpan>
Conectado como <b>{profile?.username} (Administrador)</b> <br />{" "}
<b>
<Link to="/logout">Sair</Link>
</b>
</FooterSpan>
</form>
</ChatFooter>
</ChatContainer>
</Container>
);
}
export default ChatAdmin;
|
/*Fetching the id so that we will add the event listener to it*/
const searchBox = document.getElementById("search-box");
const searchList = document.getElementById("instant-search__list");
const heroDetails = document.getElementById("hero-details");
/*Adding Event Listener To that search box on keyup event*/
let delay;
searchBox.addEventListener("keyup", (event) => {
clearTimeout(delay);
delay = setTimeout(() => {
const str = searchBox.value;
while (searchList.firstChild) {
searchList.removeChild(searchList.firstChild);
}
if (str.length >= 1) {
const xhr = new XMLHttpRequest();
xhr.open(
"GET",
`https://www.superheroapi.com/api.php/3105140062907191/search/${str}`,
true
);
xhr.onload = () => {
var heroes = JSON.parse(xhr.response);
var results = heroes.results;
// if (!searchList.firstChild) {
for (var result of results) {
const item = `<li class="instant-search__result" ><span id="${result.id}">${result.name} </span></li>`;
const position = "beforeend";
searchList.insertAdjacentHTML(position, item);
}
// }
};
xhr.send();
}
}, 500);
});
/*Function when any search list is clicked*/
searchList.addEventListener("click", (event) => {
var heroId = event.target.id;
window.location.href = `./superhero.html?${heroId}`;
});
|
import emailjs from 'emailjs-com';
import { useEffect, useState } from 'react';
import * as yup from 'yup';
import contactFormSchema from '../utils/contactFormSchema';
import Footer from './Footer';
const initialValues = {
from_name: '',
from_email: '',
subject: '',
message: '',
};
const initialErrors = {
from_name: '',
from_email: '',
subject: '',
message: '',
};
const Contact = () => {
const [successSend, setSuccessSend] = useState(false);
const [emailError, setEmailError] = useState(false);
const [formValues, setFormValues] = useState(initialValues);
const [errors, setErrors] = useState(initialErrors);
const [buttonDisabled, setButtonDisabled] = useState(true);
const validate = (inputName, inputValue) => {
yup
.reach(contactFormSchema, inputName)
.validate(inputValue)
.then(() => {
setErrors({ ...errors, [inputName]: '' });
})
.catch((err) => {
setErrors({ ...errors, [inputName]: err.errors[0] });
});
};
const onChange = (evt) => {
const { name, value } = evt.target;
setSuccessSend(false);
validate(name, value);
setFormValues({
...formValues,
[name]: value,
});
};
useEffect(() => {
contactFormSchema.isValid(formValues).then((valid) => {
setButtonDisabled(!valid);
});
}, [formValues]);
const sendEmail = (evt) => {
evt.preventDefault();
const serviceId = process.env.REACT_APP_EMAIL_SERVICE_ID;
const templateId = process.env.REACT_APP_EMAIL_TEMPLATE_ID;
const emailUserId = process.env.REACT_APP_EMAIL_USER_ID;
emailjs.sendForm(serviceId, templateId, evt.target, emailUserId).then(
(result) => {
console.log('Email Sent', result.text);
setSuccessSend(true);
},
(error) => {
console.log('Email Error', error.text);
setEmailError(true);
}
);
evt.target.reset();
setButtonDisabled(true);
};
return (
<div className="contact">
<h2>Contact me</h2>
<form className="contact-form" onSubmit={sendEmail}>
<input
onChange={onChange}
type="text"
name="from_name"
placeholder="Name"
className="from-name"
/>
<input
onChange={onChange}
type="email"
name="from_email"
placeholder="Email Address"
/>
<input onChange={onChange} type="text" name="subject" placeholder="Subject" />
<textarea onChange={onChange} placeholder="Your message" name="message" />
{successSend && <p>Your message was successful.</p>}
{emailError && <p>There was an error sending your message.</p>}
{errors.from_name && <span className="error">{errors.from_name}</span>}
{errors.from_email && <span className="error">{errors.from_email}</span>}
{errors.subject && <span className="error">{errors.subject}</span>}
{errors.message && <span className="error">{errors.message}</span>}
<button
disabled={buttonDisabled}
className={!buttonDisabled ? 'enabled' : undefined}
type="submit"
value="Send">
Send Message
</button>
</form>
<Footer />
</div>
);
};
export default Contact;
|
webpackJsonp([1],[
/* 0 */
/***/ function(module, exports, __webpack_require__) {
__webpack_require__(2); //加载初始化样式
__webpack_require__(6); //加载组件样式
var $ = __webpack_require__(1);
alert("111")
$(".main").click(function(){
alert("222")
})
/***/ }
]);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.