text
stringlengths 7
3.69M
|
|---|
/*
**带checkbox的树形控件使用说明
**@url:此url应该返回一个json串,用于生成树
**@id: 将树渲染到页面的某个div上,此div的id
**@checkId:需要默认勾选的数节点id;1.checkId="all",表示勾选所有节点 2.checkId=[1,2]表示勾选id为1,2的节点
**节点的id号由url传入json串中的id决定
*/
loadedTreefag = false;
function showCheckboxTree(url,id,checkId){
if(loadedTreefag){
initTree(id,checkId);
}
var menuTree = jQuery("#"+id).bind("loaded.jstree",function(e,data){
loadedTreefag = true;
initTree(id,checkId);
}).jstree({
"core" : {
"data":{
"url":url,
"dataType":"json",
"cache":false
},
"attr":{
"class":"jstree-checked"
}
},
"types" : {
"default" : {
"valid_children" : ["default","file"]
},
"file" : {
"icon" : "glyphicon glyphicon-file",
"valid_children" : []
}
},
"checkbox" : {
"keep_selected_style" : false,
"real_checkboxes" : true
},
"plugins" : [
"contextmenu", "dnd", "search",
"types", "wholerow","checkbox"
],
"contextmenu":{
"items":{
"create":null,
"rename":null,
"remove":null,
"ccp":null
}
}
});
}
function getCheckboxTreeSelNode(treeid){
var ids = Array();
jQuery("#"+treeid).find("li").each(function(){
var liid = jQuery(this).attr("id");
if(jQuery("#"+liid+">a").hasClass("jstree-clicked") || jQuery("#"+liid+">a>i").hasClass("jstree-undetermined")){
ids.push(liid);
}
});
return ids;
}
function initTree(id,checkId){
jQuery("#"+id).jstree("open_all");
jQuery("#"+id).find("li").each(function(){
jQuery("#"+id).jstree("uncheck_node",jQuery(this));
if(checkId == 'all'){
jQuery("#"+id).jstree("check_node",jQuery(this));
}else if(checkId instanceof Array){
for(var i=0;i<checkId.length;i++){
if(jQuery(this).attr("id") == checkId[i]){
jQuery("#"+id).jstree("check_node",jQuery(this));
}
}
}
});
}
|
import {
StyleSheet,
View,
Text,
TouchableOpacity,
TouchableOpacityBase,
Dimensions,
FlatList,
} from 'react-native';
import {color} from 'react-native-reanimated';
import {colors} from '../../const/colors';
export default style = StyleSheet.create({
wrapper: {
flex: 1,
},
row: {
flexDirection: 'row',
},
titleWrapper: {
justifyContent: 'center',
},
title: {
fontFamily: 'Nunito-Light',
fontSize: 35,
justifyContent: 'flex-start',
color: colors.main,
},
stickyHeaderWrapper: {
zIndex: 10,
justifyContent: 'space-between',
alignItems: 'flex-start',
paddingHorizontal: 15,
paddingVertical: 10,
backgroundColor: '#F2F6FF',
},
stickyHeaderText: {
flex: 1,
fontSize: 20,
fontFamily: 'Nunito-SemiBold',
color: colors.blueDark,
},
stickyHeaderIcon: {
paddingHorizontal: 5,
},
itemListWrapper: {
marginBottom: 20,
marginHorizontal: 10,
},
});
|
import { calculateFee } from './fee'
describe('calculateFee()', () => {
const specs = [
{
input: [[{ hrs: 1, cost: 10 }], 1],
output: 10,
},
{
input: [[{ hrs: 1, cost: 10 }], 2],
output: 20,
},
{
input: [[{ hrs: 2, cost: 10 }], 1],
output: 10,
},
{
input: [[{ hrs: 2, cost: 10 }], 2],
output: 10,
},
{
input: [[{ hrs: 4, cost: 10 }], 2],
output: 10,
},
{
input: [
[
{ hrs: 2, cost: 10 },
{ hrs: 1, cost: 20 },
],
3,
],
output: 30,
},
{
input: [
[
{ hrs: 2, cost: 10 },
{ hrs: 1, cost: 20 },
],
4,
],
output: 50,
},
{
input: [
[
{ hrs: 4, cost: 10 },
{ hrs: 1, cost: 20 },
],
4,
],
output: 10,
},
{
input: [
[
{ hrs: 0.5, cost: 0 },
{ hrs: 1, cost: 20 },
],
0.5,
],
output: 0,
},
{
input: [
[
{ hrs: 0.5, cost: 0 },
{ hrs: 1, cost: 20 },
],
1,
],
output: 20,
},
{
input: [
[
{ hrs: 0.5, cost: 0 },
{ hrs: 4, cost: 10 },
{ hrs: 1, cost: 20 },
],
4,
],
output: 10,
},
{
input: [
[
{ hrs: 0.5, cost: 0 },
{ hrs: 4, cost: 10 },
{ hrs: 1, cost: 20 },
],
4.5,
],
output: 10,
},
{
input: [
[
{ hrs: 0.5, cost: 0 },
{ hrs: 4, cost: 10 },
{ hrs: 1, cost: 20 },
],
5,
],
output: 30,
},
]
specs.forEach(({ input, output }) => {
it(`should return ${JSON.stringify(output)}, when receive (${JSON.stringify(
input[0]
)}, ${JSON.stringify(input[1])})`, () => {
expect(calculateFee(...input)).toBe(output)
})
})
const throwSpecs = [[], [null], [{}], [''], [1]]
throwSpecs.forEach((input) => {
it(`should throw when receives ${JSON.stringify(input)}`, () => {
expect(() => calculateFee(...input)).toThrow()
})
})
})
|
import React from 'react'
import { storiesOf } from '@storybook/react'
import * as typography from './index'
storiesOf('Atoms/Typography', module)
.add('General', () => (
<div>
<typography.CardBody>CardBody</typography.CardBody>
<typography.CardBodyBold>CardBodyBold</typography.CardBodyBold>
<typography.CardHeader>CardHeader</typography.CardHeader>
<typography.HyperLinkedText>HyperLinkedText</typography.HyperLinkedText>
<typography.NavHeader>NavHeader</typography.NavHeader>
<typography.ParagraphDescriptions>ParagraphDescriptions</typography.ParagraphDescriptions>
</div>
))
|
import {homeLoad, pageLoad} from "./pageLoad";
import menuLoad from "./menuLoad";
import contactLoad from "./contactLoad";
import removeContent from "./removeContent";
const headerTag = document.querySelector("header");
const mainDiv = document.querySelector("#content");
const headers = ["home" , "menu", "contact"];
function toggle(header, headers){
toggleClass(header, headers);
toggleEventListeners(header, headers);
}
function toggleClass(header, headers){
headers.forEach(header => document.querySelector(`#${header}-nav`).classList.remove("active"));
document.querySelector(`#${header}-nav`).classList.add("active");
}
function toggleEventListeners(activeHeader, headers){
headers.forEach(header => document.querySelector(`#${header}-nav`).removeEventListener("click", load));
const headersAdj = headers.filter(header => header !== activeHeader);
headersAdj.forEach(header => document.querySelector(`#${header}-nav`).addEventListener("click", load));
}
function load(e){
const headerId = e.target.id;
const header = headerId.substring(0, headerId.indexOf("-"));
removeContent(mainDiv);
if (header === "home") homeLoad(mainDiv, toggle, headers);
else if (header === "menu") menuLoad(mainDiv, toggle, headers);
else if (header === "contact") contactLoad(mainDiv, toggle, headers);
}
pageLoad(headerTag, mainDiv, toggle, headers);
|
require('dotenv').config()
const express = require('express');
const bodyParser = require('body-parser');
const massive = require('massive');
const con = require('./controller');
const app = express();
const { SERVER_PORT, CONNECTION_STRING } = process.env;
app.use(bodyParser.json());
massive(CONNECTION_STRING)
.then(db => {
app.set('db', db);
})
app.get(`/api/houses`, con.getAll);
app.post(`/api/houses`, con.addHouse);
app.delete(`/api/houses/:id`, con.removeHouse);
app.listen(SERVER_PORT, () => {
console.log(`can you hear me? I'm on ${SERVER_PORT}`)
})
|
let $ = window.jQuery.noConflict();
class DataTableClass {
constructor(options) {
if(typeof options === "undefined") {
options = {};
}
let actions = {
edit: '<i class="show fas fa-edit on-edit row"></i>',
save: '<i class="hidden hidden fas fa-save on-save row"></i>',
delete: '<i class="show fas fa-minus-circle on-delete row"></i>',
cancel: '<i class="hidden fas fa-window-close on-cancel row"></i>',
};
options.tableID = options.tableID ?? undefined;
options.edit = '.on-edit.row';
options.save = '.on-save.row';
options.deletes = '.on-delete.row';
options.cancel = '.on-cancel.row';
options.onSave = options.onSave ?? false;
options.table = options.tableID ?? document.querySelector('table');
// Storage Old Values
options.oldValues = [] ?? undefined;
// Storage Post Values
options.postData = [] ?? undefined;
if(typeof options.table !== "undefined") {
$(options.table).find('thead tr th').last().after('<th scope="col">Actions</th>');
$.each($(options.table).find('tbody tr'), function (e, index) {
$(index).find('td').attr('on-editable', 'true');
$(index).eq(0).removeAttr('on-editable', 'true');
$(index).append('<td class="actions">'+ actions.edit +' '+ actions.delete +' '+ actions.save +' '+ actions.cancel +'</td>');
});
// Create an editable form
$(options.edit, options.table).on('click', function (e) {
e.preventDefault();
let parent = this.parentNode.parentNode;
let editable = $('td', parent);
if(editable.not('.actions')) {
$.each(editable.not('.actions'), function (e, index) {
options.oldValues[e] = $(index, e).html();
$(index).html('<input type="text" class="form-control" name="'+ e +'" value="'+ $(index).html() +'" />');
});
}
if(editable.hasClass('actions')) {
editable.find('.show').hide();
editable.find('.hidden').show();
}
});
// Unset the changes
$(options.cancel, options.table).on('click', function (e) {
e.preventDefault();
let parent = this.parentNode.parentNode;
let editable = $('td', parent);
console.log(options.oldValues);
if(editable.not('.actions')) {
$.each(options.oldValues, function (key, value) {
console.log(key + value);
editable.not('.actions').eq(key).html(value);
});
}
if(editable.hasClass('actions')) {
editable.find('.show').show();
editable.find('.hidden').hide();
}
});
// Save the changes on table
$(options.save, options.table).on('click', function (e) {
e.preventDefault();
let parent = this.parentNode.parentNode;
let editable = $('td', parent);
if(editable.not('.actions')) {
$.each(editable.not('.actions'), function (key, value) {
let newValues = $(value, key).find('input').val();
options.postData[key] = $(value, key).find('input').val();
$(value, key).html(newValues);
});
}
if(editable.hasClass('actions')) {
editable.find('.show').show();
editable.find('.hidden').hide();
}
});
// Delete an row from table
$(options.deletes, options.table).on('click', function (e) {
e.preventDefault();
let parent = this.parentNode.parentNode;
parent.remove();
});
}
console.log(options);
}
saveAsync(params) {
if(typeof params === "undefined") {
console.log("No params has defined");
return false;
}
params.type = "POST" ?? params.type;
params.dataPost = params.dataPost ?? {};
params.dataPost.save = true;
$.ajax({
url: params.url,
type: params.type,
dataType: 'json',
data: params.dataPost
}).done(function (XMLHttpRequest, textStatus) {
console.log(XMLHttpRequest);
console.log('save with ajax' + textStatus);
}).fail(function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
});
}
}
|
import React,{Component} from 'react';
import two from "./2.png"
import ReactDOM from 'react-dom'
import Login from './login'
import appLogo from './appLogo.png'
import DropdownNavBar from './dropdown';
require('./home.css');
require('./navbar.css');
require('./responsive_navbar.css');
export default class Navbar extends Component
{
render()
{
function login()
{
ReactDOM.render(<Login />,document.getElementById('main'));
}
return(
<div>
<div className='head fluid row' style={{font:'fluid'}}>
<div id="navImg" className='logo fluid'>
<a href='/'>
<img src={two} alt={"cannot load"} id="pcImg"/>
<img src={appLogo} alt={"cannot Load"} id="mobileImg"/>
</a>
</div>
{/*
<div className='fluid' style={{width:"2%"}}></div>
<div className='fluid topbar'>
<a src= "www.google.com"> Our Menu</a>
</div>
<div className='fluid whiteBar '> | </div>
<div className='fluid topbar'>
<a src="google.com"> Offers</a> </div>
<div className='fluid whiteBar '> | </div>
<div className='fluid topbar'>
<a src="google.com"> Contact</a> </div>
<div className='fluid whiteBar '> | </div>
*/}
<div>
<div className='row'>
<div className='col topbarTextItems'><a>Our <span id="comeDownInNavbar">Menu</span></a></div>
<div className='col topbarTextItems'><a>Special <span id="comeDownInNavbar">Offers</span></a></div>
<div className='col topbarTextItems'><a>Store <span id="comeDownInNavbar">Finder</span></a></div>
<div className='col topbarTextItems removeFromMobile'><a>Inside Dominos</a></div>
<div className='col topbarTextItems removeFromMobile'><a>Gift Card</a></div>
<div className='col topbarTextItems removeFromMobile'><a>Contact</a></div>
</div>
</div>
<div id="orderButtonDesktop" className='fluid order col'><button onClick={login} className='btn orders'>Order Online Now ►</button></div>
<div id="orderButtonMobile" className='fluid order col'><button onClick={login} className='btn orders'>Order Online Now ►</button></div>
<div id="userInfo" style={{display:"none"}}className='fluid order col'>
{/*<button onClick={login} className='btn orders dropbtn'>Welcome <span id='userName'>Guest</span> ▼</button>*/}
{/*<DropdownNavBar />*/}
</div>
</div>
</div>
);
}
}
|
import React from "react";
import { HashRouter as Router, Route } from "react-router-dom";
import "./index.css";
import About from "./pages/About";
import Portfolio from "./pages/Portfolio";
import Contact from "./components/Contact";
import MobileNav from "./components/Navbar/MobileNav";
import TechnicalSkills from "./pages/TechnicalSkills";
function App() {
return (
<Router>
<Route exact path="/" component={About} />
<Route path="/about" component={About} />
<Route path="/portfolio" component={Portfolio} />
<Route exact path="/skills" component={TechnicalSkills} />
<MobileNav />
<Contact />
</Router>
);
}
export default App;
|
/**
* Created by Lee on 1/29/2016.
*/
Ext.define('AdvUtils.view.main.insight.InsightController', {
extend: 'Ext.app.ViewController',
alias: 'controller.insight',
/**
* Called when the view is created
*/
init: function() {
}
,
onInsightClick: function(btn) {
var lookupVal = btn.up('panel').down('textfield').value;
var grid = this.lookupReference('insightgrid');
console.log("Insight...%s", lookupVal);
grid.store.getProxy().url = "/rest/insight/promoStatus/" + lookupVal;
grid.store.load();
}
});
|
var assert = require('assert');
// EXERCISE: implement a string map that avoid the typical pitfalls
var StringMap = require('../impl/StringMap');
var sm = new StringMap();
// Should not invoke hasOwnProperty() on data object
sm.set('hasOwnProperty', 123);
assert.strictEqual(sm.get('hasOwnProperty'), 123);
// Must escape the key '__proto__'
sm.set('__proto__', 'abc');
assert.strictEqual(sm.get('__proto__'), 'abc');
// Do inherited properties bleed in?
assert.strictEqual(sm.get('toString'), undefined);
assert.ok(!sm.hasKey('toString'));
// Test delete() and hasKey()
assert.ok(!sm.hasKey('foo'));
sm.set('foo', 3);
assert.ok(sm.hasKey('foo'));
sm.delete('foo');
assert.ok(!sm.hasKey('foo'));
|
const bbHelada = require("../../Models/Bebidas/BebidaHelada");
function guardarBH(req, res) {
console.log('Endpoint de agregar Bebidas heladas ejecutada');
const newBH = new bbHelada();
const { codigo, nombre, ingrediente, precio, restaurante, descripcion, foto } = req.body;
newBH.codigo = codigo;
newBH.nombre = nombre;
newBH.ingrediente = ingrediente;
newBH.precio = precio;
newBH.restaurante = restaurante;
newBH.descripcion = descripcion;
newBH.foto = foto;
if (codigo === '') {
res.status(404).send({ message: 'Codigo Necesario' })
} else {
if (nombre === '') {
res.status(404).send({ message: "Nombre necesario" })
} else {
if (ingrediente === '') {
res.status(404).send({ message: "Ingredientes necesarios" })
} else {
if (precio === '') {
res.status(404).send({ message: "Precio necesario" })
} else {
if (restaurante === '') {
res.status(404).send({ message: "Restaurante necesario" })
} else {
if (descripcion === '') {
res.status(404).send({ message: "Descripcion necesaria" })
} else {
newBH.save((err, bbHStored) => {
if (err) {
res.status(500).send({ message: "Error del servidor" })
} else {
if (!bbHStored) {
res.status(404).send({ message: "Error al guardar bebida helada" });
} else {
console.log('Bebida Helada Guardada');
res.status(200).send({ bbH: bbHStored });
}
}
});
}
}
}
}
}
}
}
function getBebHel(req, res) {
bbHelada.find().then(bebHel => {
if (!bebHel) {
res.status(404).send({ message: "No se ha encontrado ninguna Bebida Caliente" });
} else {
res.status(200).send({ bebHel });
}
})
}
function updateBebHel(req, res) {
const especiData = req.body;
const params = req.params;
bbHelada.findByIdAndUpdate({ _id: params.id }, especiData, (err, espUpdate) => {
if (err) {
res.status(500).send({ code: 500, message: "Error del servidor" });
} else {
if (!espUpdate) {
res.status(404).send({ code: 404, message: "No se ha encontrado el Bebida Helada" });
} else {
res.status(200).send({ code: 200, message: "Bebida Helada actualizada correctamente" });
}
}
})
}
function deleteBebHel(req, res) {
const { id } = req.params;
bbHelada.findByIdAndRemove(id, (err, espeDeleted) => {
if (err) {
res.status(500).send({ cod: 500, message: "Error del servidor" });
} else {
if (!espeDeleted) {
res.status(404).send({ code: 404, message: "No se ha encontrado el Bebida Helada" });
} else {
res.status(200).send({ code: 200, message: "Bebida Helada eliminada correctamente" });
}
}
})
}
module.exports = {
guardarBH,
getBebHel,
updateBebHel,
deleteBebHel
};
|
import React from "react"
import styled from "styled-components"
import { ElementContainer } from "../../../../styles/Containers"
import { Header3 } from "../../../../styles/Headlines"
const Headline1 = () => {
return (
<ExtendElementContainer column>
<Header3 primary mobileMedium tabletLarge>
Take The Quiz
</Header3>
<Header3 upper tertiary mobileSmall setMLineHeight={2}>
Setup a Fit Chat
</Header3>
</ExtendElementContainer>
)
}
export default Headline1
const ExtendElementContainer = styled(ElementContainer)`
align-items: center;
`
|
exports.up = function(knex) {
return knex.schema.createTable("courseexercisesreplies", t => {
t.string('id').primary()
t.text('text_feedback')
t.text('text_answer')
t.string("choice_answer")
t.integer("achieved_points")
t.boolean("closed").default(false)
t.boolean("solved").default(false)
t.string('user_id').references("id").inTable("users");
t.string('exercise_id').references("id").inTable("courseexercises");
t.timestamp('created_at').notNullable().defaultTo(knex.fn.now());
t.timestamp('updated_at').notNullable().defaultTo(knex.fn.now());
})
};
exports.down = function(knex) {
return knex.schema.dropTable('courseexercisesreplies')
};
|
import React from "react";
import { SelectDate, Hour, Minute, Timezone, Container } from "../Input";
// import API from "../utils/API";
// import PropTypes from 'prop-types'
import { Row, Col, Button, Toast, Divider } from "react-materialize";
// import SearchFlight from "../components/SearchFlight";
export default function (props) {
//This for the not flying
const { firstDepDate, firstarrivalDate } = props;
const { seconddepDate, secondarrivalDate } = props;
const { handleInputChange } = props;
return (
<div>
<Row>
<Col s={6} >
<h4>Starting Trip</h4>
<SelectDate
name="firstDepDate"
onChange={handleInputChange}
value={firstDepDate}
label="Pick a Date" />
</Col>
<Col s={6}>
<h4>Arrival Date</h4>
<SelectDate
name="firstarrivalDate"
onChange={handleInputChange}
value={firstarrivalDate}
label="Pick a Date" />
</Col>
</Row>
{/* <div className="divider"></div> */}
<Row>
<Col s={6}>
<h4>Leaving</h4>
<SelectDate
name="seconddepDate"
onChange={handleInputChange}
value={seconddepDate}
placeholder="Pick a Date" />
</Col>
<Col s={6}>
<h4>Getting Back Home</h4>
<SelectDate
name="secondarrivalDate"
onChange={handleInputChange}
value={secondarrivalDate}
placeholder="Pick a Date" />
</Col>
</Row>
</div>
)
}
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardContent from '@material-ui/core/CardContent';
import CardActions from '@material-ui/core/CardActions';
import Typography from '@material-ui/core/Typography';
import Button from '@material-ui/core/Button';
const styles = theme => ({
root: {
padding: theme.spacing.unit,
},
});
class RandomCatFacts extends Component {
state = {
index: 0,
};
incrementIndex = () => {
const { facts } = this.props;
this.setState(prevState => {
if (prevState.index + 1 === facts.length) {
return { index: 0 };
}
return { index: prevState.index + 1 };
});
};
render() {
const { classes, facts } = this.props;
const { index } = this.state;
const fact = facts[index].text;
return (
<Card className={classes.card}>
<CardHeader title="Random Cat Facts" />
<CardContent>
<Typography component="p">{fact}</Typography>
</CardContent>
<CardActions>
<Button variat="contained" size="small" onClick={this.incrementIndex}>
Another Random Cat Fact
</Button>
</CardActions>
</Card>
);
}
}
RandomCatFacts.propTypes = {
classes: PropTypes.object.isRequired,
facts: PropTypes.array.isRequired,
};
export default withStyles(styles)(RandomCatFacts);
|
const { Entity, validatorAdapter } = require('speck-entity')
const Joi = require('joi')
const adapter = validatorAdapter('joi', require('joi'))
const uuidv4 = require('uuid/v4')
class Message extends Entity {}
Message.SCHEMA = {
id: {
validator: adapter(Joi.string().guid()),
builder: (value) => {
if (!value) {
return uuidv4()
}
return value
}
},
recipient: adapter(Joi.number()),
originator: adapter(Joi.number()),
body: adapter(Joi.string()),
created: {
validator: adapter(Joi.object().type(Date)),
type: Date,
builder: (value) => {
if (typeof value === 'number') {
return new Date(value)
}
return value
}
},
sended: {
validator: adapter(Joi.object().type(Date)),
type: Date,
builder: (value) => {
if (typeof value === 'number') {
return new Date(value)
}
return value
}
}
}
module.exports = Message
|
samson.controller('KubernetesReleasesCtrl', function($scope, $stateParams, kubernetesService, kubernetesReleaseFactory) {
$scope.project_id = $stateParams.project_id;
function loadKubernetesReleases() {
kubernetesService.loadKubernetesReleases($scope.project_id).then(function(data) {
$scope.releases = data.map(function(item) {
return kubernetesReleaseFactory.build(item);
});
}
);
}
loadKubernetesReleases();
});
|
let currentDayElement = document.getElementById('currentDay');
let today = (moment().format('LLLL'));
currentDayElement.textContent = today;
$('.col-md-2').css('color', 'red')
$('.display-3').css('color', 'blue')
// creating the color of the blocks depending on the time of the day
function callTime(hour) {
if (hour < today) {
return "past";
} else if (hour > today) {
return "future";
} else if (hour === today) {
return "present";
}
}
$(".row").each(function (index) {
var timeIndex = index + 9;
var savedData = localStorage.getItem("num" + timeIndex);
var time = callTime(timeIndex);
$(this).children("input").val(savedData);
$(this).children("input").addClass(time);
});
// Click Event handler
$(".saveBtn").click(function () {
console.log(this, "this");
let inputUser = $(this).siblings(".user-input").val();
let timeBlock = $(this).siblings(".user-input").attr("id");
localStorage.setItem(inputUser, timeBlock);
});
|
var Q = require('q');
var config = require('../config');
var cheerio = require('cheerio');
var request = require('request');
var htmlMiner = require('./text')
function Article() {
this.url = null;
this.$ = null;
this.date = new Date();
};
Article.prototype.init = function (url, date) {
var deferred = Q.defer();
this.url = url;
this.date = date;
var obj = this;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
obj.$ = cheerio.load(body);
deferred.resolve(true);
}
});
return deferred.promise;
};
// is the page an article or an "open list" ?
Article.prototype.isArticle = function() {
return !this.$('body').hasClass('single-open-list-post');
};
Article.prototype.getAuthor = function() {
return this.$('.post-info-block .author-time a').attr('href');
};
Article.prototype.getArticleMetrics = function() {
var views = this.$('.post-stats .post-views span').html();
if(views.indexOf('K') != -1) {
views = views.replace('K', '');
views = views * 1000;
} else if(views.indexOf('M') != -1) {
views = views.replace('M', '');
views = views * 1000000;
}
var share = this.$('.post-stats .post-shares span').html();
if(share.indexOf('K') != -1) {
share = share.replace('K', '');
share = share * 1000;
} else if(share.indexOf('M') != -1) {
share = share.replace('M', '');
share = share * 1000000;
}
var vote = this.$('.socialbar .vote-panel .points').attr('data-points');
return {
views: parseInt(views),
share: parseInt(share),
vote: parseInt(vote)
};
};
Article.prototype.getFormMetrics = function() {
var views = this.$('header p.views-count').last().html();
views = views.match(/([0-9]+[MK])/)[1];
if(views.indexOf('K') != -1) {
views = views.replace('K', '');
views = parseInt(views * 1000);
} else if(views.indexOf('M') != -1) {
views = views.replace('M', '');
views = views * 1000000;
}
var vote = this.$('.socialbar .vote-panel .points').attr('data-points');
return {
views: parseInt(views),
vote: parseInt(vote)
};
};
Article.prototype.commentsInfo = function() {
var result = {};
result['has_comments'] = this.$('.comment-author-image').length != 0;
return result;
};
Article.prototype.getTitleInfo = function() {
var withStopWords = htmlMiner.getText(this.$('.post-title').html()).split(" ").length;
var withoutStopWords = htmlMiner.getTextWithoutStopWords(this.$('.post-title').html()).split(" ").length;
var num = 1 - withoutStopWords / withStopWords;
return {
words: withoutStopWords,
ratio: Math.round(num * 1000) / 1000
}
};
Article.prototype.getContentInfo = function() {
var txt = htmlMiner.removeHtml(this.$('.post-content').html());
var withStopWords = htmlMiner.getText(txt).split(" ").length;
var withoutStopWords = htmlMiner.getTextWithoutStopWords(txt).split(" ").length;
var num = 1 - withoutStopWords / withStopWords;
return {
words: withoutStopWords,
ratio: Math.round(num * 1000) / 1000
}
};
Article.prototype.getMediaInfo = function() {
var horizontal = 0;
var vertical = 0;
var square = 0;
var obj = this;
this.$('.post-content .attachment-link-container').each(function (i, e) {
var tmp = parseInt(obj.$(e).find('a img').attr('width')) > parseInt(obj.$(e).find('a img').attr('height'));
if(tmp > 0) {
horizontal++;
} else if(tmp < 0) {
vertical++;
} else {
square++;
}
});
var cmp = horizontal + square + vertical;
var video = 0;
this.$('.post-content .fb-video').each(function(i, e) {
video++;
});
return {
pictures: cmp,
horizontal: horizontal,
vertical: vertical,
square: square,
ratioHorizontal: cmp == 0 ? 0 : Math.round(horizontal * 1000 / cmp) / 1000,
ratioVertical: cmp == 0 ? 0 : Math.round(vertical * 1000 / cmp) / 1000,
ratioSquare: cmp == 0 ? 0 : Math.round(square * 1000 / cmp) / 1000,
video: video
}
};
Article.prototype.getTagsInfo = function() {
var obj = this;
var tags = [];
this.$('.post-tags ul li').each(function (i, e) {
tags.push(htmlMiner.clean(obj.$(e).find('a').html()));
});
var cmp = tags.length;
var str = 0;
tags.forEach(function(item) {
str += item.length;
});
return {
nbTags: cmp,
tagLength: Math.round(str * 1000 / cmp) / 1000
}
};
Article.prototype.getDescriptionInfo = function() {
var withStopWords = htmlMiner.getText(this.$('meta[name="description"]').attr('content')).split(" ").length;
var withoutStopWords = htmlMiner.getTextWithoutStopWords(this.$('meta[name="description"]').attr('content')).split(" ").length;
var num = 1 - withoutStopWords / withStopWords;
return {
words: withoutStopWords,
ratio: Math.round(num * 1000) / 1000
}
};
Article.prototype.getDateInfo = function() {
var day = new Date(this.date).getDay();
var result = {};
var date = '';
switch(day) {
case 1: date = 'Monday'; break;
case 2: date = 'Tuesday'; break;
case 3: date = 'Wednesday'; break;
case 4: date = 'Thursday'; break;
case 5: date = 'Friday'; break;
case 6: date = 'Saturday'; break;
case 0: date = 'Sunday'; break;
}
result['day'] = date;
result["weekend"] = day == 0 || day == 6 ? 'Yes' : 'No';
return result;
};
Article.prototype.getCategoryInfo = function() {
var category = config.category;
var origin = category;
category = category.map(function(item) {
return htmlMiner.stem(item);
});
var result = {};
var obj = this;
this.$('.post-tags ul li').each(function (i, e) {
var tags = htmlMiner.stem(obj.$(e).find('a').html());
for(var i in category) {
if(!result.hasOwnProperty(origin[i])) {
result[origin[i]] = false;
}
if(tags.indexOf(category[i]) != -1) {
result[origin[i]] = true;
}
}
});
return result;
};
Article.prototype.getH = function() {
return {
h1: this.$('.post-content h1').length,
h2: this.$('.post-content h2').length,
h3: this.$('.post-content h3').length,
h4: this.$('.post-content h4').length,
p: this.$('.post-content p').length
}
};
Article.prototype.getMoreInfo = function() {
var obj = this;
var result = {
facebook: false,
etsy: false,
instagram: false,
flickr: false,
tumblr: false,
imgur: false,
twitter: false,
site: false
};
this.$('.post-content p').each(function (i, e) {
if(obj.$(e).html().indexOf('More info: ') == 0) {
obj.$(e).find('a').each(function(j, f) {
var link = obj.$(f).attr('href');
if(link.indexOf('instagram') != -1) {
result.instagram = true;
return;
}
if(link.indexOf('etsy') != -1) {
result.etsy = true;
return;
}
if(link.indexOf('facebook') != -1) {
result.facebook = true;
return;
}
if(link.indexOf('flicker') != -1) {
result.flickr = true;
return;
}
if(link.indexOf('twitter') != -1) {
result.twitter = true;
return;
}
if(link.indexOf('tumblr') != -1) {
result.tumblr = true;
return;
}
if(link.indexOf('imgur') != -1) {
result.imgur = true;
return;
}
result.site = true;
});
}
});
return result;
};
module.exports = Article;
|
var env = [];
var x = 273.15;
function CallAjax(city) {
var key = "21ec46344d981a5c9b3ecb0f2f68c0c4"
var url = `https://api.openweathermap.org/data/2.5/weather?q=${city} &appid=${key}`
var http = new XMLHttpRequest();
http.open("GET", url);
http.send()
http.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.response))
env = JSON.parse(this.response)
// console.log(JSON.parse(this.response))
// document.querySelector(".weather").innerHTML = this.response
switch (env.weather[0].main) {
case 'Clear':
document.body.style.backgroundImage = "url('clearPicture.jpg')";
break;
case 'Clouds':
document.body.style.backgroundImage = "url('cloudyPicture.jpg')";
break;
case 'Rain':
case 'Drizzle':
document.body.style.backgroundImage = "url('rainPicture.jpg')";
break;
case 'Mist':
document.body.style.backgroundImage = "url('mistPicture.jpg')";
break;
case 'Thunderstorm':
document.body.style.backgroundImage = "url('stormPicture.jpg')";
break;
case 'Snow':
document.body.style.backgroundImage = "url('snowPicture.jpg')";
break;
default:
break;
}
document.querySelector(".weather").innerHTML = `
<h2>${env.name}</h5>
<h4>Max Temp. ${env.main.temp_max - x}</h4>
<h4>Min Temp. ${env.main.temp_min - x}</h6>
<p>Weather description : ${env.weather[0].description}</p>
`;
document.querySelector('#IconImg').src =
'http://openweathermap.org/img/w/' + env.weather[0].icon + '.png';
}
}
}
var data1 =[]
function CallAjax1(country){
var key = "dc9f64f8456f4f9a8f7e67b0e7b0e453"
// var url = `http://api.openweathermap.org/data/2.5/weather?q=delhi&appid=${key}`
var url = `https://newsapi.org/v2/top-headlines?country=${country}&apiKey=${key}`
var http = new XMLHttpRequest();
http.open("GET", url);
http.send()
http.onreadystatechange = function(){
if(this.readyState==4 && this.status==200)
{
console.log(JSON.parse(this.response))
var data = JSON.parse(this.response)
console.log(typeof(data))
// data1.push(data)
// BindItem(data)
document.querySelector(".news").innerHTML = this.response
document.querySelector(".news").innerHTML = `
<h2>Author : ${data.articles[0].author}</h5>
<h4>Title : ${data.articles[0].content}</h4>
<h4>Description : ${data.articles[0].description}</h6>`
}
}
}
function BindItem(arr){
var temp=``
arr.forEach((e)=>{
temp = `
<h2>Author : ${data.articles[0].author}</h5>
<h4>Title : ${data.articles[0].content}</h4>
<h4>Description : ${data.articles[0].description}</h6>`
})
document.querySelector(".news").innerHTML=temp;
}
|
function generateMarkdown (data) {
return `
#${data.Title}
'
## Table of contents
*[Description][#description]
*[Instalation][#instalation]
*[Usage Information][#usage]
}
|
// // add to cart
let productsCountEl= document.getElementById("producrts-count");
let addToCart = document.querySelectorAll(".add-too-cart");
for (let i=0; i < addToCart.length; i++) {
addToCart[i].addEventListener ("click",function() {
productsCountEl.textContent = +productsCountEl.textContent + 1;
});
};
// like button
let BtnLike = document.querySelectorAll(".my-like");
console.log(BtnLike);
BtnLike.forEach(btn => {
btn.addEventListener("click", function() {
// if (btn.classList.contains("liked")) {
// btn.classList.remove("liked");
// } else {
// btn.classList.add("liked");
// }
btn.classList.toggle("liked");
})
});
let moreDetBtn = document.querySelectorAll(".more-det");
let modal = document.querySelector(".modal");
let btnClose =document.querySelector(".btn-close")
console.log(btnClose);
moreDetBtn.forEach(btn => {
btn.addEventListener("click",openModal)
});
btnClose.addEventListener("click",hideModal)
function openModal() {
modal.classList.add("show");
modal.classList.remove("hide");
}
function hideModal() {
modal.classList.add("hide");
modal.classList.remove("show");
}
modal.addEventListener("click",function(e) {
if(e.target === modal) {
hideModal()
}
});
function showModalByScroll () {
if (window.pageYOffset > document.body.scrollHeight/2){
openModal ();
window.removeEventListener("scroll", showModalByScroll)
}
}
window.addEventListener("scroll", showModalByScroll)
|
import Helper from '@ember/component/helper';
import CountryCodes from '@upfluence/ember-upf-utils/resources/country-codes';
export function countryName(countryCode) {
let country = CountryCodes.find((item) => item.id === countryCode[0]);
if (country) {
return country.name;
}
return countryCode || '-';
}
export default Helper.helper(countryName);
|
import personService from "../services/personService.js"
export default class DetailView {
constructor() {
// this.data = [];
// this.initData();
// this.data = personService.persons;
this.template();
}
// async initData() {
// // let persons = await personService.loadPersons();
// // console.log(await this.data)
// this.data = await personService.loadPersons();
// }
template() {
document.querySelector('#detailView').innerHTML += /*html*/ `<article>
<div class="line">
<button type="button" onclick="goback()">Go back</button> </div>
<div id="theDetailView">
</div>
</article>
`
}
goToDetailView(id) {
let template = "";
let theId = id.slice(2, id.length);
personService.getPerson(theId)
console.log(personService.getPerson(theId))
for (const person of personService.persons) {
if (person.login.uuid === theId) {
template += /*html*/ `
<img src="${person.picture.medium}" alt="medium">
<br>
<h2>${person.name.first}
${person.name.last} </h2>
<div class="textCollection">
<p><b>Username: </b>${person.login.username}</p>
<p><b>Gender: </b>${person.gender}</p>
</div>
<div class="textCollection">
<p><b>Adress: </b>${person.location.street.name} ${person.location.street.number}</p>
<p><b>Timezone: </b>${person.location.timezone.offset}</p>
</div>
<div class="textCollection">
<p><b>Email: </b><a href="mailto:${person.email}">${person.email}</a></p>
<p><b>Cell number: </b><a href="tel:${person.cell}">${person.cell}</a></p>
</div>
`;
}
}
document.querySelector('#theDetailView').innerHTML = template;
document.querySelector('#profile').style.display = 'none'
document.querySelector('#detailView').style.display = 'block'
}
goback() {
document.querySelector('#detailView').style.display = 'none';
document.querySelector('#profile').style.display = 'block';
}
}
|
import React, {Component} from 'react'
import {
MDBBox,
MDBNav,
MDBModal,
MDBModalHeader,
MDBModalBody,
MDBModalFooter,
MDBRow,
MDBCol,
MDBBtn
} from "mdbreact"
import {ToastContainer, Slide} from "react-toastify"
import LeadSummary from "./summaryBar/LeadSummary"
import LeadDetail from "./detailTab/LeadDetail"
import CallBar from "./callBar/CallBar"
import {connect} from "react-redux"
import LoadingScreen from '../LoadingScreen'
import SideNavItem from "../ui/SideNavItem"
import {
faBars,
faCalendarCheck,
faEdit, faFile,
faPoll, faStream, faFileSignature
} from "@fortawesome/pro-regular-svg-icons"
import LeadTabs from "./LeadTabs"
import {faChevronRight, faUser, faGift} from "@fortawesome/pro-solid-svg-icons"
import moment from "moment"
import EndInteraction from "./EndInteraction"
import "react-toastify/dist/ReactToastify.css";
import {TwilioDevice} from "../../twilio/TwilioDevice";
class Interaction extends Component {
constructor(props) {
super(props);
this.toggleNav = this.toggleNav.bind(this)
this.toggleEndInteraction = this.toggleEndInteraction.bind(this)
this.toggleDetails = this.toggleDetails.bind(this)
this.state = {
endInteractionVisible : false,
unsavedNoteModalVisible: false,
slim : false,
details : true,
activeItem : "surveys",
date: moment(),
time: moment().hour(0).minute(0)
};
}
earlyCloseWarning = (ev) => {
ev.preventDefault()
const confirmationMessage = this.props.localization.interaction.earlyCloseWarning
ev.returnValue = confirmationMessage // Gecko, Trident, Chrome 34+
return confirmationMessage // Gecko, WebKit, Chrome <34
}
componentDidMount() {
window.addEventListener("beforeunload", this.earlyCloseWarning)
}
componentWillUnmount() {
window.removeEventListener("beforeunload", this.earlyCloseWarning)
}
componentDidUpdate(prevProps) {
// we can start or stop the incoming audio ring based on changes in the incomingCallQueue length
if (prevProps.twilio.interactionIncomingCallSID === "" && this.props.twilio.interactionIncomingCallSID !== "") {
// incoming call has come in, fire up the audio if we haven't already
if (this.ringAudio === undefined) {
let src = 'https://83b-audio.s3.amazonaws.com/agent/iphone_ring.wav';
this.ringAudio = new Audio(src)
this.ringAudio.loop = true;
}
// get it playing
this.ringAudio.play();
} else if (prevProps.twilio.interactionIncomingCallSID !== "" && this.props.twilio.interactionIncomingCallSID === "") {
// other way around, stop the music
if (this.ringAudio !== undefined) {
this.ringAudio.pause();
}
}
}
answerIncoming = () => {
if (this.props.twilio.conferenceOID === "") {
TwilioDevice.openAgentConnection(true)
} else {
TwilioDevice.connectIncoming(this.props.twilio.interactionIncomingCallSID, this.props.twilio.conferenceOID)
}
}
toggleEndInteraction() {
// do nothing if twilio connection is still active
if (this.props.twilio.callbarVisible) return
// pop a warning if there is unsaved note content
if (this.props.interaction.hasUnsavedNote) {
this.setState({ unsavedNoteModalVisible: true})
return
}
// otherwise pop the endInteraction modal
this.setState({endInteractionVisible : !this.state.endInteractionVisible})
}
closeUnsavedNoteModal = () => {
this.setState({ unsavedNoteModalVisible: false })
}
ignoreUnsavedNote = () => {
this.props.dispatch({type: "INTERACTION.CLEAR_UNSAVED_NOTE"})
this.setState({ unsavedNoteModalVisible: false, endInteractionVisible: true })
}
toggleNav()
{
this.setState({slim : !this.state.slim})
}
toggleDetails() {
this.setState({details : !this.state.details})
}
toggleTab = tab => () => {
if (this.state.activeItem !== tab) {
this.setState({
activeItem: tab
});
}
}
render() {
if (this.props.lead === undefined || this.props.lead.id === undefined) {
return <LoadingScreen />
}
let slim = this.state.slim
let localization = this.props.localization.interaction
// determine if the docusign tab is appropriate
const docusignVisible = this.props.shift.docusign_templates.some( template => {
return template.client_id === this.props.lead.client_id
})
// determine if the questions tab is appropriate
const questionsVisible = this.props.lead.client.questions.length > 0
// determine if the rewards tab is appropriate
const rewardsVisible = this.props.lead.rewards.length > 0
return(
<MDBBox className="d-flex w-100 skin-secondary-color">
<MDBBox className="m-0 my-2 ml-2 border rounded skin-secondary-background-color" style={{flex: slim ? "0 0 50px" : "0 0 100px", order : 0, fontSize:"14px"}}>
<MDBNav>
<SideNavItem active={false} toggle icon={faBars} label={""} slim={false} onClick={this.toggleNav}/>
<SideNavItem active={this.state.details} toggle toggleIcon={faChevronRight} icon={faUser} label={localization.details.tabTitle} slim={slim} onClick={this.toggleDetails}/>
<SideNavItem active={this.state.activeItem === "surveys"} icon={faPoll} label={localization.survey.tabTitle} rotation={90} slim={slim} onClick={this.toggleTab("surveys")}/>
{questionsVisible && <SideNavItem active={this.state.activeItem === "questions"} icon={faPoll} label={localization.questions.tabTitle} rotation={90} slim={slim} onClick={this.toggleTab("questions")}/>}
<SideNavItem active={this.state.activeItem === "timeline"} icon={faStream} label={localization.timeline.tabTitle} slim={slim} onClick={this.toggleTab("timeline")}/>
<SideNavItem active={this.state.activeItem === "appointments"} icon={faCalendarCheck} label={localization.appointment.tabTitle} slim={slim} onClick={this.toggleTab("appointments")}/>
<SideNavItem active={this.state.activeItem === "notes"} icon={faEdit} label={localization.notes.tabTitle} slim={slim} onClick={this.toggleTab("notes")}/>
<SideNavItem active={this.state.activeItem === "documents"} icon={faFile} label={localization.documents.tabTitle} slim={slim} onClick={this.toggleTab("documents")}/>
{docusignVisible && <SideNavItem active={this.state.activeItem === "esignatures"} icon={faFileSignature} label={localization.docusign.tabTitle} slim={slim} onClick={this.toggleTab("esignatures")}/>}
{rewardsVisible && <SideNavItem active={this.state.activeItem === "rewards"} icon={faGift} label={localization.rewards.tabTitle} slim={slim} onClick={this.toggleTab("rewards")}/>}
</MDBNav>
</MDBBox>
<MDBBox className="d-flex m-2" style={{flex: 1, overflow:"auto", flexDirection:"column"}}>
<LeadSummary toggleEndInteraction={this.toggleEndInteraction} className=""/>
<MDBBox className="d-flex" style={{flex: 1, overflow:"auto", flexDirection:"row"}}>
<MDBBox className="d-flex mt-2 mr-2" style={{flex: 1, overflow:"auto", flexDirection:"column"}}>
{this.state.details && <LeadDetail />}
<LeadTabs activeTab={this.state.activeItem}/>
</MDBBox>
<CallBar />
</MDBBox>
</MDBBox>
{this.state.endInteractionVisible && <EndInteraction history={this.props.history} toggle={this.toggleEndInteraction}/>}
<MDBModal isOpen={this.state.unsavedNoteModalVisible} toggle={this.closeUnsavedNoteModal}>
<MDBModalHeader>{localization.endInteraction.unsavedNoteModalHeader}</MDBModalHeader>
<MDBModalBody>
<MDBRow className="p-2">
{localization.endInteraction.unsavedNoteModalBody}
</MDBRow>
<MDBModalFooter className="p-1"/>
<MDBRow>
<MDBCol size={"12"}>
<MDBBtn
color="primary"
rounded
outline
className="float-left"
onClick={this.closeUnsavedNoteModal}
>
{this.props.localization.buttonLabels.cancel}
</MDBBtn>
<MDBBtn
color="primary"
rounded
className="float-right"
onClick={this.ignoreUnsavedNote}
>
{localization.endInteraction.endWithoutSavingNoteButton}
</MDBBtn>
</MDBCol>
</MDBRow>
</MDBModalBody>
</MDBModal>
<MDBModal isOpen={this.props.twilio.interactionIncomingCallSID !== ""} centered toggle={() => {}} keyboard={false}>
<MDBModalBody className="p-4 d-flex flex-column align-items-center">
<h3>{localization.answerInteractionIncomingTitle.replace("$", this.props.lead.details.first_name)}</h3>
<MDBBtn className="button danger p-1 m-3" onClick={this.answerIncoming}>{localization.answerInteractionIncomingLabel}</MDBBtn>
</MDBModalBody>
</MDBModal>
<ToastContainer
position="bottom-left"
hideProgressBar={false}
newestOnTop={true}
autoClose={5000}
pauseOnHover={false}
transition={Slide}
/>
</MDBBox>
)
}
}
const mapStateToProps = state => {
return {
localization: state.localization,
lead : state.lead,
twilio: state.twilio,
interaction: state.interaction,
shift: state.shift
}
}
export default connect(mapStateToProps)(Interaction);
|
const AppError = require('../../../../../shared/errors/AppError');
const usersRepository = require('../../repositories/UsersRepository')
class IsUserMemberOfService {
constructor() {}
async execute(user, group) {
const isUserMemberOf = await usersRepository.isUserMemberOf(user, group)
if (!isUserMemberOf) {
throw new AppError(204, `The user ${user} is not a member of ${group} group`);
};
return isUserMemberOf
}
}
module.exports = new IsUserMemberOfService;
|
const path = require('path')
const fs = require('fs')
let nodeModules = fs.readdirSync('./node_modules')
.filter((module) => {
return module !== '.bin';
})
.reduce((prev, module) => {
return Object.assign(prev, {[module]: 'commonjs ' + module});
}, {})
module.exports = {
entry: {
app: './gatekeeper-electron/application.js',
fork: './gatekeeper-electron/subprocess-wrapper.js'
},
output: {
path: path.resolve(__dirname, './webpack-build'),
filename: '[name].bundle.js'
},
module: {
rules: [
{ test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ },
{ test: /\.jsx$/, loader: 'babel-loader', exclude: /node_modules/ },
]
},
target: 'electron',
node: {
/* http://webpack.github.io/docs/configuration.html#node */
__dirname: false,
__filename: false
},
externals: nodeModules
}
|
import { byArray, bySearchString } from '../../utils/filters';
const initialState = {
searchFilter: '',
categoryFilter: [],
movies: [],
categories: [],
selectedMovieDetails: null
};
export default function moviesPage(state = initialState, action) {
switch (action.type) {
case 'SET_SEARCH_FILTER':
return { ...state, searchFilter: action.filter };
case 'SET_CATEGORY_FILTER':
return { ...state, categoryFilter: action.filter };
case 'RECEIVE_MOVIES':
return { ...state, movies: action.result };
case 'RECEIVE_CATEGORIES':
return { ...state, categories: action.result };
case 'RECEIVE_MOVIE_DETAILS':
return { ...state, selectedMovieDetails: action.result };
default:
return state;
}
}
export function filterMovies(state) {
const { movies, categoryFilter, searchFilter } = state;
return movies.filter(byArray(movie => movie.category, categoryFilter))
.filter(bySearchString(movie => movie.title, searchFilter));
}
|
app.controller('ng-app-controller-template1', ['$scope', '$http', function ($scope,
$http)
{
console.log('1')
$scope.mensaje = 'Texto cargado desde el controlador Pagina1Controller';
$http.post('/test',
{
text: 'hello'
})
.then(function (response)
{
console.log(response.data)
});
}]);
|
/*
* ProGade API
* Copyright 2012, Hans-Peter Wandura (ProGade)
* Last changes of this file: Aug 22 2012
*/
var PG_BROWSER_CHROME = 'Chrome';
var PG_BROWSER_OPERA = 'Opera';
var PG_BROWSER_INTERNET_EXPLORER = 'Internet Explorer';
var PG_BROWSER_FIREFOX = 'Firefox';
var PG_BROWSER_PHOENIX = 'Phoenix';
var PG_BROWSER_MOZILLA = 'Mozilla';
var PG_BROWSER_NETSCAPE = 'Netscape';
var PG_BROWSER_SAFARI = 'Safari';
var PG_BROWSER_ANDROID = 'Android';
var PG_BROWSER_IPHONE = 'iPhone';
var PG_BROWSER_GOOGLEBOT = 'Google Bot';
var PG_BROWSER_YAHOOBOT = 'Yahoo! Bot';
var PG_BROWSER_ICHIROBOT = 'Ichiro Bot';
var PG_BROWSER_YANDEXBOT = 'YandexBot';
var PG_BROWSER_BINGBOT = 'Bing Bot';
var PG_BROWSER_FACEBOOKBOT = 'Facebook Bot';
var PG_BROWSER_PROVIDER_MSNBOT = 'MSN Bot';
var PG_BROWSER_PROVIDER_GOOGLEBOT = 'Google Bot';
var PG_BROWSER_PROVIDER_YAHOOBOT = 'Yahoo! Bot';
var PG_BROWSER_PROVIDER_SUPERGOOBOT = 'SuperGoo Ichiro Bot';
var PG_BROWSER_PROVIDER_YANDEXBOT = 'Yandex Bot';
var PG_BROWSER_PROVIDER_AOL = 'AOL';
var PG_BROWSER_PROVIDER_ALICEDSL = 'Alice DSL';
var PG_BROWSER_PROVIDER_ARCOR = 'Arcor';
var PG_BROWSER_PROVIDER_VODAFONE = 'Vodafone';
var PG_BROWSER_PROVIDER_TONLINE = 'T-Online';
var PG_BROWSER_PROVIDER_1UND1 = '1&1 Internet AG';
var PG_BROWSER_PROVIDER_1UND1_SERVER = '1&1 Internet AG Server';
var PG_BROWSER_PROVIDER_SERVER4YOU = 'Server 4 You';
var PG_BROWSER_PROVIDER_KABELDEUTSCHLAND = 'Kabel Deutschland';
var PG_BROWSER_PROVIDER_BADGMBH = 'BAD GmbH';
var PG_BROWSER_PROVIDER_FACEBOOK = 'Facebook';
var PG_BROWSER_PROVIDER_MEDIAWAYS = 'mediaWays GmbH Internet Services';
var PG_BROWSER_PROVIDER_BWL = 'Baden-W�rttemberg';
/*
@start class
@param extends classPG_ClassBasics
*/
function classPG_Browser()
{
// Declarations...
this.fOnSelectStart = null;
this.fOnMouseDown = null;
this.fOnClick = null;
this.oFocusedElement = null;
this.bRunOnceOnLoad = true;
this.iScreenSizeX = 0;
this.iScreenSizeY = 0;
this.oTitleTimeout = null;
this.iOrientation = (typeof(window.orientation) != 'undefined') ? window.orientation : 0;
this.fOnOrientationChange = null;
/*
this.getIframeWindow = function(_sIframeID)
{
var _oWindow = null;
var _oIframe = window.getElementById(_sIframeID);
if (_oIframe) {_oWindow = (_oIframe.contentWindow || _oIframe.window);}
return _oWindow;
}
this.getIframeDocument = function(_sIframeID)
{
var _oDocument = null;
var _oIframe = window.getElementById(_sIframeID);
if (_oIframe)
{
_oDocument = (_oIframe.contentWindow || _oIframe.contentDocument);
if (_oDocument.document) {_oDocument = _oDocument.document;}
}
return _oDocument;
}
this.overwriteFrame = function(_sWindow, _sFrameToOverwrite, _sTargetFrame)
{
if (typeof(window.defineGetter) != 'undefined')
{
alert(_sWindow+'.defineGetter("'+_sFrameToOverwrite+'", function() {return '+_sTargetFrame+'});');
eval(_sWindow+'.defineGetter("'+_sFrameToOverwrite+'", function() {return '+_sTargetFrame+'});');
return;
}
if (window.HTMLElement)
{
if (typeof(window.HTMLElement.prototype.__defineGetter__) != 'undefined')
{
alert(_sWindow+'.prototype.HTMLElement.__defineGetter__("'+_sFrameToOverwrite+'",function() {return '+_sTargetFrame+';});');
eval(_sWindow+'.prototype.HTMLElement.__defineGetter__("'+_sFrameToOverwrite+'",function() {return '+_sTargetFrame+';});');
return;
}
}
if (typeof(window.prototype) != 'undefined')
{
alert(_sWindow+'.prototype.'+_sFrameToOverwrite+' = '+_sTargetFrame+';');
eval(_sWindow+'.prototype.'+_sFrameToOverwrite+' = '+_sTargetFrame+';');
return;
}
alert(_sWindow+'.'+_sFrameToOverwrite+' = '+_sTargetFrame+';');
// eval(_sWindow+'.'+_sFrameToOverwrite+' = window.self;');
eval('top = self;');
}
*/
this.axBrowserVersionParser = new Array(
{'Search': "/.*\ Googlebot\/([0-9\.\,]+).*/gi", 'Replace': '\\1'},
{'Search': "/.*\ Yahoo\!\ (.*).*/gi", 'Replace': '\\1'},
{'Search': "/.*\ ichiro\/(.*).*/gi", 'Replace': '\\1'},
{'Search': "/.*\ YandexBot\/([0-9\.\,]+).*/gi", 'Replace': '\\1'},
{'Search': "/.*\ bingbot\/([0-9\.\,]+).*/gi", 'Replace': '\\1'},
{'Search': "/(^|.*\ )facebook.*(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\3'},
{'Search': "/.*(\ |\/)Android(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\3'},
{'Search': "/.*(\ |\/)Chrome(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\3'},
{'Search': "/(.*\ |^)Opera(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\3'},
{'Search': "/.*\ Windows Phone\ ([0-9\.\,]+).*)/gi", 'Replace': '\\1'},
{'Search': "/.*(\ |\/)MSIE(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\3'},
{'Search': "/.*\ iPhone\ OS\ ([0-9\.\,\_]+).*/gi", 'Replace': '\\1'},
{'Search': "/.*Version(\ |\/)([0-9\.\,]+)\ Safari\/.*/gi", 'Replace': '\\2'},
{'Search': "/.*(\ |\/)Navigator(\ |\/)([0-9\.\,]+)/gi", 'Replace': '\\3'},
{'Search': "!.*(\ |\/)Firefox(\ |\/)([0-9\.\,]+).*!gi", 'Replace': '\\3'},
{'Search': "/.*(\ |\/)Mozilla(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\3'},
{'Search': "/.*(\ |\/)IE(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\3'},
{'Search': "/.*(\ |\/)Explorer(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\3'}
);
this.axBrowserNameParser = new Array(
{'Search': "Googlebot", 'Replace': PG_BROWSER_GOOGLEBOT},
{'Search': "Yahoo!", 'Replace': PG_BROWSER_YAHOOBOT},
{'Search': "ichiro", 'Replace': PG_BROWSER_ICHIROBOT},
{'Search': "YandexBot", 'Replace': PG_BROWSER_YANDEXBOT},
{'Search': "bingbot", 'Replace': PG_BROWSER_BINGBOT},
{'Search': "facebook", 'Replace': PG_BROWSER_FACEBOOKBOT},
{'Search': "Android", 'Replace': PG_BROWSER_ANDROID},
{'Search': "iPhone", 'Replace': PG_BROWSER_IPHONE},
{'Search': "Chrome", 'Replace': PG_BROWSER_CHROME},
{'Search': "Opera", 'Replace': PG_BROWSER_OPERA},
{'Search': "Msie", 'Replace': PG_BROWSER_INTERNET_EXPLORER},
{'Search': "Safari", 'Replace': PG_BROWSER_SAFARI},
{'Search': "Navigator", 'Replace': PG_BROWSER_NETSCAPE},
{'Search': "Netscape", 'Replace': PG_BROWSER_NETSCAPE},
{'Search': "Firefox", 'Replace': PG_BROWSER_FIREFOX},
{'Search': "Phoenix", 'Replace': PG_BROWSER_PHOENIX},
{'Search': "Mozilla", 'Replace': PG_BROWSER_MOZILLA},
{'Search': "IE", 'Replace': PG_BROWSER_INTERNET_EXPLORER},
{'Search': "Explorer", 'Replace': PG_BROWSER_INTERNET_EXPLORER}
);
this.axProviderParser = new Array(
{'Search': "msnbot", 'Replace': PG_BROWSER_PROVIDER_MSNBOT, 'Website': 'www.msn.de'},
{'Search': "googlebot", 'Replace': PG_BROWSER_PROVIDER_GOOGLEBOT, 'Website': 'www.google.de'},
{'Search': "crawl.yahoo", 'Replace': PG_BROWSER_PROVIDER_YAHOOBOT, 'Website': 'www.yahoo.de'},
{'Search': "super-goo", 'Replace': PG_BROWSER_PROVIDER_SUPERGOOBOT, 'Website': ''},
{'Search': "yandex", 'Replace': PG_BROWSER_PROVIDER_YANDEXBOT, 'Website': ''},
{'Search': "aol", 'Replace': PG_BROWSER_PROVIDER_AOL, 'Website': ''},
{'Search': "alicedsl", 'Replace': PG_BROWSER_PROVIDER_ALICEDSL, 'Website': ''},
{'Search': "arcor", 'Replace': PG_BROWSER_PROVIDER_ARCOR, 'Website': ''},
{'Search': "vodafone", 'Replace': PG_BROWSER_PROVIDER_VODAFONE, 'Website': ''},
{'Search': "t-online", 'Replace': PG_BROWSER_PROVIDER_TONLINE, 'Website': ''},
{'Search': "server4you.de", 'Replace': PG_BROWSER_PROVIDER_SERVER4YOU, 'Website': ''},
{'Search': "onlinehome-server.info", 'Replace': PG_BROWSER_PROVIDER_1UND1_SERVER, 'Website': ''},
{'Search': "bad-gmbh", 'Replace': PG_BROWSER_PROVIDER_BADGMBH, 'Website': 'www.bad-gmbh.de'},
{'Search': "tfbnw.net", 'Replace': PG_BROWSER_PROVIDER_FACEBOOK, 'Website': 'www.facebook.com'},
{'Search': "mediaWays", 'Replace': PG_BROWSER_PROVIDER_MEDIAWAYS, 'Website': 'www.mediaways.de'},
{'Search': ".bwl.de", 'Replace': PG_BROWSER_PROVIDER_BWL, 'Website': 'www.bwl.de'},
{'Search': "superkabel.de", 'Replace': PG_BROWSER_PROVIDER_KABELDEUTSCHLAND, 'Website': 'www.superkabel.de'}, // 188-194-200-212-dynip.superkabel.de
{'Search': "pD9E0FAFA.dip0.t-ipconnect.de", 'Replace': PG_BROWSER_PROVIDER_1UND1, 'Website': ''},
{'Search': "p54AE905A.dip0.t-ipconnect.de", 'Replace': PG_BROWSER_PROVIDER_1UND1, 'Website': ''},
{'Search': "pd95b47de.dip0.t-ipconnect.de", 'Replace': PG_BROWSER_PROVIDER_TONLINE, 'Website': ''},
{'Search': "p5DE67C1C.dip.t-dialin.net", 'Replace': '?', 'Website': ''},
{'Search': "p54AED96E.dip.t-dialin.net", 'Replace': '?', 'Website': ''},
{'Search': "p5DF3E04B.dip.t-dialin.net", 'Replace': '?', 'Website': ''},
{'Search': "p5DF3B5F8.dip.t-dialin.net", 'Replace': '?', 'Website': ''},
{'Search': "p54B1C704.dip.t-dialin.net", 'Replace': '?', 'Website': ''}
);
this.axOperatingSystemVersionParser = new Array(
{'Search': "/.*\ Windows Phone(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\2'}, // Windows Phone 8.0
{'Search': "/.*\ Windows(\ |\/)(NT\ [0-9\.\,]+).*/gi", 'Replace': '\\2'}, // Windows NT 5.1
{'Search': "/.*\ Android(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\2'}, // Android 2.1
{'Search': "/.*\ Ubuntu(\ |\/)([0-9\.\,]+).*/gi", 'Replace': '\\2'}, // Ubuntu/10.04
{'Search': "/.*\ Linux(\ |\/)(i[0-9\.\,]+).*/gi", 'Replace': '\\2'}, // Linux i686
{'Search': "/.*\ iPhone\ OS(\ |\/)([0-9\.\,\_]+).*/gi", 'Replace': '\\2'}, // iPhone OS 4_2_1
{'Search': "/.*\ iPod\ OS(\ |\/)([0-9\.\,\_]+).*/gi", 'Replace': '\\2'}, // iPod OS 4_2_1
{'Search': "/.*\ iPad\ OS(\ |\/)([0-9\.\,\_]+).*/gi", 'Replace': '\\2'}, // iPad OS 4_2_1
{'Search': "/.*\ Mac\ OS\ X(\ |\/)([0-9\.\,\_]+).*/gi", 'Replace': '\\2'} // Mac OS X 10_6_6
);
this.axOperatingSystemParser = new Array(
{'Search': "Windows Phone", 'Replace': 'Windows Phone'},
{'Search': "Windows", 'Replace': 'Windows'},
{'Search': "BlackBerry", 'Replace': 'Black Berry'},
{'Search': "Android", 'Replace': 'Android'},
{'Search': "Symbian", 'Replace': 'Symbian'},
{'Search': "Linux", 'Replace': 'Linux'},
{'Search': "iPhone", 'Replace': 'iOS'},
{'Search': "iPad", 'Replace': 'iOS'},
{'Search': "iPod", 'Replace': 'iOS'},
{'Search': "Mac OS", 'Replace': 'Mac OS'}
);
// Construct...
// Methods...
/*
@start method
@group Mobile
@return bMobile [type]bool[/type]
[en]...[/en]
*/
this.isMobile = function()
{
switch (this.getOSName())
{
case 'Windows Phone':
case 'Black Berry':
case 'Android':
case 'Symbian':
case 'iOS':
return true;
}
// if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT']))) {return true;}
// if(strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false) {return true;}
// if(strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false) {return true;}
return false;
}
/* @end method */
/*
@start method
@group Detection
@return sInfo [type]string[/type]
[en]...[/en]
*/
this.getBrowserInfo = function() {return navigator.userAgent;}
/* @end method */
this.getInfo = this.getBrowserInfo;
/*
@start method
@group Browser
@return sBrowserVersion [type]string[/type]
[en]...[/en]
@param sBrowserInfo [type]string[/type]
[en]...[/en]
*/
this.getBrowserVersion = function(_sBrowserInfo)
{
if (typeof(_sBrowserInfo) == 'undefined') {var _sBrowserInfo = null;}
_sBrowserInfo = this.getRealParameter({'oParameters': _sBrowserInfo, 'sName': 'sBrowserInfo', 'xParameter': _sBrowserInfo});
var _sBrowserVersion = '';
if (_sBrowserInfo == null) {_sBrowserInfo = this.getBrowserInfo();}
for (var i=0; i<this.axBrowserVersionParser.length; i++)
{
if ((_sBrowserVersion == _sBrowserInfo) || (_sBrowserVersion == ''))
{
_sBrowserVersion = _sBrowserInfo.replace(this.axBrowserVersionParser[i]['Search'], this.axBrowserVersionParser[i]['Replace']);
}
}
if (_sBrowserVersion == _sBrowserInfo) {_sBrowserVersion = '[unknown version]';}
_sBrowserVersion = _sBrowserVersion.replace(/_/g, '.');
_sBrowserVersion = _sBrowserVersion.replace(/,/g, '.');
return _sBrowserVersion;
}
/* @end method */
this.getVersion = this.getBrowserVersion;
/*
@start method
@group Browser
@return sBrowserName [type]string[/type]
[en]...[/en]
@param sBrowserInfo [type]string[/type]
[en]...[/en]
*/
this.getBrowserName = function(_sBrowserInfo)
{
if (typeof(_sBrowserInfo) == 'undefined') {var _sBrowserInfo = null;}
_sBrowserInfo = this.getRealParameter({'oParameters': _sBrowserInfo, 'sName': 'sBrowserInfo', 'xParameter': _sBrowserInfo});
if (_sBrowserInfo == null) {_sBrowserInfo = this.getBrowserInfo();}
for (var i=0; i<this.axBrowserNameParser.length; i++)
{
if (_sBrowserInfo.indexOf(this.axBrowserNameParser[i]['Search']) != -1) {return this.axBrowserNameParser[i]['Replace'];}
}
return '[unknown browser]';
}
/* @end method */
this.getName = this.getBrowserName;
/*
@start method
@group Browser
@return sLanguage [type]string[/type]
[en]...[/en]
*/
this.getBrowserLanguage = function()
{
var _sLanguage = 'en';
if (typeof(navigator.userLanguage) != 'undefined') {_sLanguage = navigator.userLanguage;}
else if (typeof(navigator.systemLanguage) != 'undefined') {_sLanguage = navigator.systemLanguage;}
else if (typeof(navigator.browserLanguage) != 'undefined') {_sLanguage = navigator.browserLanguage;}
else if (typeof(navigator.language) != 'undefined') {_sLanguage = navigator.language;}
_sLanguage = _sLanguage.replace(/([A-Za-z]{2}).*/gi, '$1');
return _sLanguage;
}
/* @end method */
this.getLanguage = this.getBrowserLanguage;
/* TODO...
public function getProviderInfo() {return gethostbyaddr($_SERVER["REMOTE_ADDR"]);}
public function getProviderName($_sProviderInfo = NULL)
{
if ($_sProviderInfo == NULL) {$_sProviderInfo = $this->getProviderInfo();}
for ($i=0; $i<count($this->axProviderParser); $i++)
{
if (stristr($_sProviderInfo, $this->axProviderParser[$i]['Search'])) {return $this->axProviderParser[$i]['Replace'];}
}
return '[unknown provider]';
}
*/
/*
@start method
@group OS
@return sOsName [type]string[/type]
[en]...[/en]
@param sBrowserInfo [type]string[/type]
[en]...[/en]
*/
this.getOperatingSystemName = function(_sBrowserInfo)
{
if (typeof(_sBrowserInfo) == 'undefined') {var _sBrowserInfo = null;}
_sBrowserInfo = this.getRealParameter({'oParameters': _sBrowserInfo, 'sName': 'sBrowserInfo', 'xParameter': _sBrowserInfo});
if (_sBrowserInfo == null) {_sBrowserInfo = this.getBrowserInfo();}
for (var i=0; i<this.axOperatingSystemParser.length; i++)
{
if (_sBrowserInfo.indexOf(this.axOperatingSystemParser[i]['Search']) != -1) {return this.axOperatingSystemParser[i]['Replace'];}
}
return '[unknown operating system]';
}
/* @end method */
this.getOperatingSystem = this.getOperatingSystemName;
this.getOSName = this.getOperatingSystemName;
this.getOS = this.getOperatingSystemName;
/*
@start method
@group OS
@return sOsVersion [type]string[/type]
[en]...[/en]
@param sBrowserInfo [type]string[/type]
[en]...[/en]
*/
this.getOperatingSystemVersion = function(_sBrowserInfo)
{
if (typeof(_sBrowserInfo) == 'undefined') {var _sBrowserInfo = null;}
_sBrowserInfo = this.getRealParameter({'oParameters': _sBrowserInfo, 'sName': 'sBrowserInfo', 'xParameter': _sBrowserInfo});
_sBrowserVersion = '';
if (_sBrowserInfo == null) {_sBrowserInfo = this.getBrowserInfo();}
for (var i=0; i<this.axOperatingSystemVersionParser.length; i++)
{
if ((_sBrowserVersion == _sBrowserInfo) || (_sBrowserVersion == ''))
{
_sBrowserVersion = _sBrowserInfo.replace(this.axOperatingSystemVersionParser[i]['Search'], this.axOperatingSystemVersionParser[i]['Replace']);
}
}
if (_sBrowserVersion == _sBrowserInfo) {_sBrowserVersion = '[unknown version]';}
_sBrowserVersion = _sBrowserVersion.replace(/_/g, '.');
_sBrowserVersion = _sBrowserVersion.replace(/,/g, '.');
return _sBrowserVersion;
}
/* @end method */
this.getOSVersion = this.getOperatingSystemVersion;
/*
@start method
@group Setup
*/
this.disableOnSelectStart = function(_eEvent) {return false;}
/* @end method */
/*
@start method
@group Setup
*/
this.disableOnMouseDown = function(_eEvent) {return false;}
/* @end method */
/*
@start method
@group Setup
*/
this.enableOnClick = function(_eEvent) {return true;}
/* @end method */
/*
@start method
@group Setup
*/
this.initSelect = function()
{
if (typeof(this.oDocument.onselectstart) != 'undefined') {this.fOnSelectStart = this.oDocument.onselectstart;}
if (typeof(this.oDocument.onmousedown) != 'undefined') {this.fOnMouseDown = this.oDocument.onmousedown;}
if (typeof(this.oDocument.onclick) != 'undefined') {this.fOnClick = this.oDocument.onclick;}
/*
if (this.oWindow.sidebar)
{
// alert(this.oWindow.sidebar);
this.fOnMouseDown = this.oDocument.onmousedown;
this.fOnClick = this.oDocument.onclick;
}
*/
// alert(this.fOnSelectStart+" ; "+this.fOnMouseDown+" ; "+this.fOnClick);
}
/* @end method */
/*
@start method
@group Setup
*/
this.enableSelect = function()
{
/*
if (this.oWindow.sidebar)
{
this.oDocument.onmousedown = this.fOnMouseDown;
this.oDocument.onclick = this.fOnClick;
}
*/
if (typeof(this.oDocument.onselectstart) != 'undefined') {this.oDocument.onselectstart = this.fOnSelectStart;}
if (typeof(this.oDocument.onmousedown) != 'undefined') {this.oDocument.onmousedown = this.fOnMouseDown;}
if (typeof(this.oDocument.onclick) != 'undefined') {this.oDocument.onclick = this.fOnClick;}
if (typeof(event) != "undefined")
{
if (event.preventDefault)
{
}
else
{
event.returnValue = true;
event.cancelBubble = false;
}
}
}
/* @end method */
/*
@start method
@group Setup
*/
this.disableSelect = function()
{
/*
if (this.oWindow.sidebar)
{
this.oDocument.onmousedown = this.disableOnMouseDown;
this.oDocument.onclick = this.enableOnClick;
}
*/
if (typeof(this.oDocument.onselectstart) != 'undefined') {this.oDocument.onselectstart = this.disableOnSelectStart;}
if (typeof(this.oDocument.onmousedown) != 'undefined') {this.oDocument.onmousedown = this.disableOnMouseDown;}
if (typeof(this.oDocument.onclick) != 'undefined') {this.oDocument.onclick = this.enableOnClick;}
if (typeof(event) != "undefined")
{
if (event.preventDefault)
{
event.preventDefault();
event.stopPropagation();
}
else
{
event.returnValue = false;
event.cancelBubble = true;
}
}
}
/* @end method */
/*
@start method
@group Desktop
@return iSizeX [type]int[/type]
[en]...[/en]
*/
this.getDesktopSizeX = function() {return screen.availWidth;}
/* @end method */
/*
@start method
@group Desktop
@return iSizeY [type]int[/type]
[en]...[/en]
*/
this.getDesktopSizeY = function() {return screen.availHeight;}
/* @end method */
/*
@start method
@group Screen
@return oSize [type]object[/type]
[en]...[/en]
*/
this.getScreenSize = function()
{
if ((this.oWindow) && (this.oDocument))
{
var _bIsNetscape = (navigator.appName.indexOf("Netscape") != -1);
var _oSize = new Object();
if (typeof(this.oDocument.documentElement) != 'undefined')
{
_oSize.x = _bIsNetscape ? this.oWindow.innerWidth : this.oDocument.documentElement.clientWidth;
_oSize.y = _bIsNetscape ? this.oWindow.innerHeight : this.oDocument.documentElement.clientHeight;
}
else
{
_oSize.x = _bIsNetscape ? this.oWindow.innerWidth : this.oDocument.body.clientWidth;
_oSize.y = _bIsNetscape ? this.oWindow.innerHeight : this.oDocument.body.clientHeight;
}
return _oSize;
}
return null;
}
/* @end method */
/*
@start method
@group Screen
@return iSizeX [type]int[/type]
[en]...[/en]
*/
this.getScreenSizeX = function()
{
var _iSizeX = 0;
if ((this.oWindow) && (this.oDocument))
{
if (typeof(this.oDocument.documentElement) != 'undefined')
{
if (typeof(this.oDocument.documentElement.clientWidth) != 'undefined')
{
_iSizeX = this.oDocument.documentElement.clientWidth;
}
}
if ((typeof(this.oWindow.innerWidth) != 'undefined') && (_iSizeX == 0)) {_iSizeX = this.oWindow.innerWidth;}
if ((typeof(this.oDocument.body.clientWidth) != 'undefined') && (_iSizeX == 0)) {_iSizeX = this.oDocument.body.clientWidth;}
if ((typeof(this.oDocument.body.offsetWidth) != 'undefined') && (_iSizeX == 0)) {_iSizeX = this.oDocument.body.offsetWidth;}
}
return _iSizeX;
}
/* @end method */
/*
@start method
@group Screen
@return iSizeY [type]int[/type]
[en]...[/en]
*/
this.getScreenSizeY = function()
{
var _iSizeY = 0;
if ((this.oWindow) && (this.oDocument))
{
if (typeof(this.oDocument.documentElement) != 'undefined')
{
if (typeof(this.oDocument.documentElement.clientHeight) != 'undefined')
{
_iSizeY = this.oDocument.documentElement.clientHeight;
}
}
if ((typeof(this.oWindow.innerHeight) != 'undefined') && (_iSizeY == 0)) {_iSizeY = this.oWindow.innerHeight;}
if ((typeof(this.oDocument.body.clientHeight) != 'undefined') && (_iSizeY == 0)) {_iSizeY = this.oDocument.body.clientHeight;}
if ((typeof(this.oDocument.body.offsetHeight) != 'undefined') && (_iSizeY == 0)) {_iSizeY = this.oDocument.body.offsetHeight;}
}
return _iSizeY;
}
/* @end method */
/*
@start method
@group Other
@return bResized [type]bool[/type]
[en]...[/en]
*/
this.onResizeTest = function()
{
var _iScreenSizeX = this.getScreenSizeX();
var _iScreenSizeY = this.getScreenSizeY();
if ((_iScreenSizeX != this.iScreenSizeX) || (_iScreenSizeY != this.iScreenSizeY))
{
this.iScreenSizeX = _iScreenSizeX;
this.iScreenSizeY = _iScreenSizeY;
return true;
}
return false;
}
/* @end method */
this.isRealResized = this.onResizeTest;
this.isResized = this.onResizeTest;
/*
@start method
@group Detection
@return bMinimized [type]bool[/type]
[en]...[/en]
*/
this.isMinimized = function()
{
var _iScreenPosX = 0;
if (typeof(this.oWindow.screenLeft) != 'undefined') {_iScreenPosX = this.oWindow.screenLeft;}
else if (typeof(this.oWindow.screenX) != 'undefined') {_iScreenPosX = this.oWindow.screenX;}
if (_iScreenPosX == -32000) {return true;}
return false;
}
/* @end method */
/*
@start method
@group Detection
@return bMaximized [type]bool[/type]
[en]...[/en]
*/
this.isMaximized = function()
{
if ((this.oWindow.outerWidth >= this.getDesktopSizeX())
&& (this.oWindow.outerHeight >= this.getDesktopSizeY()))
{
return true;
}
return false;
}
/* @end method */
/*
@start method
@group Setup
@param sMessage [needed][type]string[/type]
[en]...[/en]
*/
this.setStatus = function(_sMessage) {this.oWindow.status = _sMessage;}
/* @end method */
/*
@start method
@group Setup
@param sTitle [needed][type]string[/type]
[en]...[/en]
@param iTimeout [type]int[/type]
[en]...[/en]
@param iScrollCharSteps [type]int[/type]
[en]...[/en]
@param sBlinkTitle [type]string[/type]
[en]...[/en]
*/
this.setTitle = function(_sTitle, _iTimeout, _iScrollCharSteps, _sBlinkTitle)
{
if (typeof(_sTitle) == 'undefined') {var _sTitle = null;}
if (typeof(_iTimeout) == 'undefined') {var _iTimeout = null;}
if (typeof(_iScrollCharSteps) == 'undefined') {var _iScrollCharSteps = null;}
if (typeof(_sBlinkTitle) == 'undefined') {var _sBlinkTitle = null;}
_iTimeout = this.getRealParameter({'oParameters': _sTitle, 'sName': 'iTimeout', 'xParameter': _iTimeout});
_iScrollCharSteps = this.getRealParameter({'oParameters': _sTitle, 'sName': 'iScrollCharSteps', 'xParameter': _iScrollCharSteps});
_sBlinkTitle = this.getRealParameter({'oParameters': _sTitle, 'sName': 'sBlinkTitle', 'xParameter': _sBlinkTitle});
_sTitle = this.getRealParameter({'oParameters': _sTitle, 'sName': 'sTitle', 'xParameter': _sTitle});
if (_iTimeout == null) {_iTimeout = 0;}
if (_sBlinkTitle == null) {_sBlinkTitle = '';}
if (_sBlinkTitle != '')
{
var _sTitle2 = _sTitle;
_sTitle = _sBlinkTitle;
_sBlinkTitle = _sTitle2;
}
this.oDocument.title = _sTitle;
if ((_iScrollCharSteps != null) && (_iScrollCharSteps != 0))
{
if (typeof(oPGStrings))
{
_sTitle = oPGStrings.moveChars({'sString': _sTitle, 'iCharSteps': _iScrollCharSteps});
if (_sBlinkTitle != '') {_sBlinkTitle = oPGStrings.moveChars({'sString': _sBlinkTitle, 'iCharSteps': _iScrollCharSteps});}
}
}
if (this.oTitleTimeout != null) {this.oWindow.clearTimeout(this.oTitleTimeout); this.oTitleTimeout = null;}
if (_iTimeout > 0) {this.oTitleTimeout = this.oWindow.setTimeout("oPGBrowser.setTitle({'sTitle': '"+_sTitle+"', 'iTimeout': "+_iTimeout+", 'iScrollCharSteps': "+_iScrollCharSteps+", 'sBlinkTitle': '"+_sBlinkTitle+"'})", _iTimeout);}
}
/* @end method */
/*
@start method
@group Setup
@param sTitle [needed][type]string[/type]
[en]...[/en]
@param iTimeout [type]int[/type]
[en]...[/en]
@param iCurrentUpperChar [type]int[/type]
[en]...[/en]
@param sDefaultChar [type]string[/type]
[en]...[/en]
@param iUpperCharsCount [type]int[/type]
[en]...[/en]
@param bPong [type]bool[/type]
[en]...[/en]
@param iDirection [type]int[/type]
[en]...[/en]
@param bChangeUpperAndLower [type]bool[/type]
[en]...[/en]
*/
this.setTitleWave = function(_sTitle, _iTimeout, _iCurrentUpperChar, _sDefaultChar, _iUpperCharsCount, _bPong, _iDirection, _bChangeUpperAndLower)
{
if (typeof(_sTitle) == 'undefined') {var _sTitle = null;}
if (typeof(_iTimeout) == 'undefined') {var _iTimeout = null;}
if (typeof(_iCurrentUpperChar) == 'undefined') {var _iCurrentUpperChar = null;}
if (typeof(_bPong) == 'undefined') {var _bPong = null;}
if (typeof(_sDefaultChar) == 'undefined') {var _sDefaultChar = null;}
if (typeof(_iUpperCharsCount) == 'undefined') {var _iUpperCharsCount = null;}
if (typeof(_iDirection) == 'undefined') {var _iDirection = null;}
_iTimeout = this.getRealParameter({'oParameters': _sTitle, 'sName': 'iTimeout', 'xParameter': _iTimeout});
_iCurrentUpperChar = this.getRealParameter({'oParameters': _sTitle, 'sName': 'iCurrentUpperChar', 'xParameter': _iCurrentUpperChar});
_sDefaultChar = this.getRealParameter({'oParameters': _sTitle, 'sName': 'sDefaultChar', 'xParameter': _sDefaultChar});
_iUpperCharsCount = this.getRealParameter({'oParameters': _sTitle, 'sName': 'iUpperCharsCount', 'xParameter': _iUpperCharsCount});
_bPong = this.getRealParameter({'oParameters': _sTitle, 'sName': 'bPong', 'xParameter': _bPong});
_iDirection = this.getRealParameter({'oParameters': _sTitle, 'sName': 'iDirection', 'xParameter': _iDirection});
_bChangeUpperAndLower = this.getRealParameter({'oParameters': _sTitle, 'sName': 'bChangeUpperAndLower', 'xParameter': _bChangeUpperAndLower});
_sTitle = this.getRealParameter({'oParameters': _sTitle, 'sName': 'sTitle', 'xParameter': _sTitle});
if (_iTimeout == null) {_iTimeout = 0;}
if (_iCurrentUpperChar == null) {_iCurrentUpperChar = 0;}
if (_sDefaultChar == null) {_sDefaultChar = '.';}
if (_iUpperCharsCount == null) {_iUpperCharsCount = 1;}
if (_iDirection == null) {_iDirection = 1;}
if (typeof(oPGStrings))
{
this.oDocument.title = oPGStrings.toWave({'sString': _sTitle, 'iCurrentUpperChar': _iCurrentUpperChar, 'sDefaultChar': _sDefaultChar, 'iUpperCharsCount': _iUpperCharsCount, 'bChangeUpperAndLower': _bChangeUpperAndLower});
_iCurrentUpperChar += _iDirection;
if (_iCurrentUpperChar >= _sTitle.length)
{
if (_bPong == true) {_iDirection = -1;}
else {_iCurrentUpperChar = -_iUpperCharsCount;}
}
else if (_iCurrentUpperChar < -_iUpperCharsCount)
{
if (_bPong == true)
{
_iCurrentUpperChar = -_iUpperCharsCount;
_iDirection = 1;
}
else {_iCurrentUpperChar = _sTitle.length;}
}
}
if (this.oTitleTimeout != null) {this.oWindow.clearTimeout(this.oTitleTimeout); this.oTitleTimeout = null;}
if (_iTimeout > 0) {this.oTitleTimeout = this.oWindow.setTimeout("oPGBrowser.setTitleWave({'sTitle': '"+_sTitle+"', 'iTimeout': "+_iTimeout+", 'iCurrentUpperChar': "+_iCurrentUpperChar+", 'sDefaultChar': '"+_sDefaultChar+"', 'iUpperCharsCount': "+_iUpperCharsCount+", 'bPong': "+_bPong.toString()+", 'iDirection': "+_iDirection+", 'bChangeUpperAndLower': "+_bChangeUpperAndLower.toString()+"})", _iTimeout);}
}
/* @end method */
/*
@start method
@group Other
@return oScrollPos [type]object[/type]
[en]...[/en]
*/
this.getScrollPos = function()
{
if ((this.oWindow) && (this.oDocument))
{
var _oScrollPos = new Object();
/*
var _bIsNetscape = (navigator.appName.indexOf("Netscape") != -1);
_oScrollPos.x = _bIsNetscape ? pageXOffset : this.oDocument.body.scrollLeft;
_oScrollPos.y = _bIsNetscape ? pageYOffset : this.oDocument.body.scrollTop;
*/
if (this.oDocument.documentElement && this.oDocument.documentElement.scrollTop) // Explorer 6 Strict
{
_oScrollPos.x = this.oDocument.documentElement.scrollLeft;
_oScrollPos.y = this.oDocument.documentElement.scrollTop;
}
else if (this.oDocument.body) // all other Explorers
{
_oScrollPos.x = this.oDocument.body.scrollLeft;
_oScrollPos.y = this.oDocument.body.scrollTop;
}
else if (self.pageXOffset) // all except Explorer
{
_oScrollPos.x = self.pageXOffset;
_oScrollPos.y = self.pageYOffset;
}
return _oScrollPos;
}
return null;
}
/* @end method */
/*
@start method
@group Popup
@return oPopupWindow [type]object[/type]
[en]...[/en]
@param sUrl [needed][type]string[/type]
[en]...[/en]
@param iSizeX [needed][type]int[/type]
[en]...[/en]
@param iSizeY [needed][type]int[/type]
[en]...[/en]
@param sWinName [type]string[/type]
[en]...[/en]
@param bScrollbars [type]bool[/type]
[en]...[/en]
@param bResizable [type]bool[/type]
[en]...[/en]
@param iPosX [type]int[/type]
[en]...[/en]
@param iPosY [type]int[/type]
[en]...[/en]
*/
this.popup = function(_sUrl, _iSizeX, _iSizeY, _sWinName, _bScrollbars, _bResizable, _iPosX, _iPosY)
{
if (typeof(_iSizeX) == 'undefined') {var _iSizeX = 750;}
if (typeof(_iSizeY) == 'undefined') {var _iSizeY = 500;}
if (typeof(_sWinName) == 'undefined') {var _sWinName = '';}
if (typeof(_bScrollbars) == 'undefined') {var _bScrollbars = true;}
if (typeof(_bResizable) == 'undefined') {var _bResizable = true;}
if (typeof(_iPosX) == 'undefined') {var _iPosX = null;}
if (typeof(_iPosY) == 'undefined') {var _iPosY = null;}
_iSizeX = this.getRealParameter({'oParameters': _sUrl, 'sName': 'iSizeX', 'xParameter': _iSizeX});
_iSizeY = this.getRealParameter({'oParameters': _sUrl, 'sName': 'iSizeY', 'xParameter': _iSizeY});
_sWinName = this.getRealParameter({'oParameters': _sUrl, 'sName': 'sWinName', 'xParameter': _sWinName});
_bScrollbars = this.getRealParameter({'oParameters': _sUrl, 'sName': 'bScrollbars', 'xParameter': _bScrollbars});
_bResizable = this.getRealParameter({'oParameters': _sUrl, 'sName': 'bResizable', 'xParameter': _bResizable});
_iPosX = this.getRealParameter({'oParameters': _sUrl, 'sName': 'iPosX', 'xParameter': _iPosX});
_iPosY = this.getRealParameter({'oParameters': _sUrl, 'sName': 'iPosY', 'xParameter': _iPosY});
_sUrl = this.getRealParameter({'oParameters': _sUrl, 'sName': 'sUrl', 'xParameter': _sUrl});
if (_iSizeX > screen.width) {_iSizeX = screen.width;}
if (_iSizeY > screen.height) {_iSizeX = screen.height;}
if (_iPosX == null) {_iPosX = Math.floor((screen.width-_iSizeX)/2);}
if (_iPosY == null) {_iPosY = Math.floor((screen.height-_iSizeY)/2);}
var _sProperties = "scrollbars=";
if (_bScrollbars == true) {_sProperties += "yes";} else {_sProperties += "no";}
_sProperties += ",resizable=";
if (_bResizable == true) {_sProperties += "yes";} else {_sProperties += "no";}
_sProperties = "top="+_iPosY+",left="+_iPosX+",width="+_iSizeX+",height="+_iSizeY+",location=no,toolbar=no,menubar=no,status=no,"+_sProperties;
return this.oWindow.open(_sUrl, _sWinName, _sProperties);
}
/* @end method */
/*
@start method
@group Element
@return oElement [type]object[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getElementObject = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
switch (typeof(_xElement))
{
case 'string': return this.oDocument.getElementById(_xElement);
case 'object': return _xElement;
}
return null;
}
/* @end method */
/*
@start method
@group Element
@return iPosX [type]int[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getDocumentOffsetX = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = this.getElementObject({'xElement': _xElement});
var _iPosX = 0;
if (_oElement)
{
while ((typeof(_oElement) == 'object') && (typeof(_oElement.tagName) != 'undefined'))
{
_iPosX += parseInt(_oElement.offsetLeft);
if (_oElement.tagName.toUpperCase() == 'BODY') {_oElement = 0; return _iPosX;}
else if (_oElement.tagName.toUpperCase() == 'DIV') {_iPosX -= _oElement.scrollLeft;}
if (typeof(_oElement) == 'object') {if (typeof(_oElement.offsetParent) == 'object') {_oElement = _oElement.offsetParent;}}
if (_oElement == null) {return _iPosX;}
}
}
return _iPosX;
}
/* @end method */
/*
@start method
@group Element
@return iPosY [type]int[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getDocumentOffsetY = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = this.getElementObject({'xElement': _xElement});
var _iPosY = 0;
if (_oElement)
{
while ((typeof(_oElement) == 'object') && (typeof(_oElement.tagName) != 'undefined'))
{
_iPosY += parseInt(_oElement.offsetTop);
if (_oElement.tagName.toUpperCase() == 'BODY') {_oElement = 0; return _iPosY;}
else if (_oElement.tagName.toUpperCase() == 'DIV') {_iPosY -= _oElement.scrollTop;}
if (typeof(_oElement) == 'object') {if (typeof(_oElement.offsetParent) == 'object') {_oElement = _oElement.offsetParent;}}
if (_oElement == null) {return _iPosY;}
}
}
return _iPosY;
}
/* @end method */
/*
@start method
@group Element
@return iSizeX [type]int[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getSizeX = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = this.getElementObject({'xElement': _xElement});
var _iSizeX = 0;
if (_oElement)
{
_iSizeX = parseInt(_oElement.offsetWidth);
if (isNaN(_iSizeX))
{
_iSizeX = 0;
if ((_iSizeX < 1) && (typeof(_oElement.style.width) != 'undefined')) {_iSizeX = parseInt(_oElement.style.width);}
if (isNaN(_iSizeX)) {_iSizeX = 0;}
if ((_iSizeX < 1) && (typeof(_oElement.width) != 'undefined')) {_iSizeX = parseInt(_oElement.width);}
if (isNaN(_iSizeX)) {_iSizeX = 0;}
var _iPaddingLeft = parseInt(oPGCss.getProperty({'xElement': _oElement, 'sName': 'PaddingLeft'}));
var _iPaddingRight = parseInt(oPGCss.getProperty({'xElement': _oElement, 'sName': 'PaddingRight'}));
if (_iPaddingLeft > 0) {_iSizeX += _iPaddingLeft;}
if (_iPaddingRight > 0) {_iSizeX += _iPaddingRight;}
}
}
return _iSizeX;
}
/* @end method */
/*
@start method
@group Element
@return iSizeY [type]int[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getSizeY = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = this.getElementObject({'xElement': _xElement});
var _iSizeY = 0;
if (_oElement)
{
_iSizeY = parseInt(_oElement.offsetHeight);
if (isNaN(_iSizeY))
{
_iSizeY = 0;
if ((_iSizeY < 1) && (typeof(_oElement.style.height) != 'undefined')) {_iSizeY = parseInt(_oElement.style.height);}
if (isNaN(_iSizeY)) {_iSizeY = 0;}
if ((_iSizeY < 1) && (typeof(_oElement.height) != 'undefined')) {_iSizeY = parseInt(_oElement.height);}
if (isNaN(_iSizeY)) {_iSizeY = 0;}
var _iPaddingTop = parseInt(oPGCss.getProperty({'xElement': _oElement, 'sName': 'PaddingTop'}));
var _iPaddingBottom = parseInt(oPGCss.getProperty({'xElement': _oElement, 'sName': 'PaddingBottom'}));
if (_iPaddingTop > 0) {_iSizeY += _iPaddingTop;}
if (_iPaddingBottom > 0) {_iSizeY += _iPaddingBottom;}
}
}
return _iSizeY;
}
/* @end method */
/*
@start method
@description
[en]...[/en]
@return bContains [type]bool[/type]
[en]...[/en]
@param iPosX [needed][type]int[/type]
[en]...[/en]
@param iPosY [needed][type]int[/type]
[en]...[/en]
@param xElement [type]mixed[/type]
[en]...[/en]
@param iRectPosX [type]int[/type]
[en]...[/en]
@param iRectPosY [type]int[/type]
[en]...[/en]
@param iRectSizeX [type]int[/type]
[en]...[/en]
@param iRectSizeY [type]int[/type]
[en]...[/en]
*/
this.rectContains = function(_iPosX, _iPosY, _xElement, _iRectPosX, _iRectPosY, _iRectSizeX, _iRectSizeY)
{
_iPosY = this.getRealParameter({'oParameters': _iPosX, 'sName': 'iPosY', 'xParameter': _iPosY});
_xElement = this.getRealParameter({'oParameters': _iPosX, 'sName': 'xElement', 'xParameter': _xElement});
_iRectPosX = this.getRealParameter({'oParameters': _iPosX, 'sName': 'iRectPosX', 'xParameter': _iRectPosX});
_iRectPosY = this.getRealParameter({'oParameters': _iPosX, 'sName': 'iRectPosY', 'xParameter': _iRectPosY});
_iRectSizeX = this.getRealParameter({'oParameters': _iPosX, 'sName': 'iRectSizeX', 'xParameter': _iRectSizeX});
_iRectSizeY = this.getRealParameter({'oParameters': _iPosX, 'sName': 'iRectSizeY', 'xParameter': _iRectSizeY});
_iPosX = this.getRealParameter({'oParameters': _iPosX, 'sName': 'iPosX', 'xParameter': _iPosX});
if (_xElement != null)
{
var _oElement = this.getElementObject({'xElement': _xElement});
if (_oElement)
{
_iRectPosX = this.getDocumentOffsetX({'xElement': _oElement});
_iRectPosY = this.getDocumentOffsetY({'xElement': _oElement});
_iRectSizeX = this.getSizeX({'xElement': _oElement});
_iRectSizeY = this.getSizeY({'xElement': _oElement});
}
}
if (
(_iPosX > _iRectPosX) && (_iPosX <= _iRectPosX+_iRectSizeX)
&& (_iPosY > _iRectPosY) && (_iPosY <= _iRectPosY+_iRectSizeY)
)
{
return true;
}
return false;
}
/* @end method */
/*
this.setHTML = function(_sContainerID, _sHTML, _sJsToExecuteOnLoading, _sJsToExecuteOnDone)
{
var _oContainer = this.oDocument.getElementById(_sContainerID);
if ((_oContainer) && (typeof(oPGStrings) != 'undefined'))
{
_oContainer.innerHTML = _sHTML;
alert(oPGStrings.addSlashes(_sHTML));
this.checkHTMLIsSet(_sContainerID, oPGStrings.stringToUtf8(_sHTML), oPGStrings.stringToUtf8(_sJsToExecuteOnLoading), oPGStrings.stringToUtf8(_sJsToExecuteOnDone));
}
}
this.checkHTMLIsSet = function(_sContainerID, _sHTML, _sJsToExecuteOnLoading, _sJsToExecuteOnDone)
{
var _oContainer = this.oDocument.getElementById(_sContainerID);
if (_oContainer)
{
alert(_oContainer.innerHTML+" != "+oPGStrings.stripSlashes(oPGStrings.utf8ToString(_sHTML)));
if (_oContainer.innerHTML != oPGStrings.stripSlashes(oPGStrings.utf8ToString(_sHTML)))
{
if ((typeof(oPGStrings) != 'undefined') && (_sJsToExecuteOnLoading != '')) {eval(oPGStrings.utf8ToString(oPGStrings.stripSlashes(_sJsToExecuteOnLoading)));}
this.oWindow.setTimeout("oPGBrowser.checkHTMLIsSet('"+_sContainerID+"', '"+oPGStrings.addSlashes(_sHTML)+"', '"+oPGStrings.addSlashes(_sJsToExecuteOnLoading)+"', '"+oPGStrings.addSlashes(_sJsToExecuteOnDone)+"')", 100);
}
else
{
if ((typeof(oPGStrings) != 'undefined') && (_sJsToExecuteOnDone != '')) {eval(oPGStrings.utf8ToString(oPGStrings.stripSlashes(_sJsToExecuteOnDone)));}
}
}
}
*/
/*
this.getFocusedElement = function() {return this.oFocusedElement;}
this.onFocus = function(_eEvent)
{
if (!_eEvent) {_eEvent = window.event;} // For IE.
this.oFocusedElement = arguments[0].target || _eEvent.srcElement;
}
*/
/*
@start method
@group Element
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sHtml [needed][type]string[/type]
[en]...[/en]
*/
this.setOuterHtml = function(_xElement, _sHtml)
{
_sHtml = this.getRealParameter({'oParameters': _oElement, 'sName': 'sHtml', 'xParameter': _sHtml});
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = null;
if (typeof(_xElement) == 'string') {_oElement = this.oDocument.getElementById(_xElement);} else {_oElement = _xElement;}
var _oRange = _oElement.ownerDocument.createRange();
_oRange.setStartBefore(_oElement);
var _oFragment = _oRange.createContextualFragment(_sHtml);
_oElement.parentNode.replaceChild(_oFragment, _oElement);
}
/* @end method */
/*
@start method
@group Element
@return sHtml [type]string[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getOuterHtml = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = null;
if (typeof(_xElement) == 'string') {_oElement = this.oDocument.getElementById(_xElement);} else {_oElement = _xElement;}
var _oElement = this.oDocument.createElement("div");
_oElement.appendChild(_oElement.cloneNode(true));
return _oElement.innerHTML;
}
/* @end method */
/*
@start method
@group Element
@param xElement [needed][type]mixed[/type]
[en]...[/en]
@param sHtml [needed][type]mixed[/type]
[en]...[/en]
*/
this.setInnerHtml = function(_xElement, _sHtml)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = null;
if (typeof(_xElement) == 'string') {_oElement = this.oDocument.getElementById(_xElement);} else {_oElement = _xElement;}
if (_oElement == null) {return null;}
_oElement.innerHTML = _sHtml;
}
/* @end method */
/*
@start method
@group Element
@return sHtml [type]string[/type]
[en]...[/en]
@param xElement [needed][type]mixed[/type]
[en]...[/en]
*/
this.getInnerHtml = function(_xElement)
{
_xElement = this.getRealParameter({'oParameters': _xElement, 'sName': 'xElement', 'xParameter': _xElement, 'bNotNull': true});
var _oElement = null;
if (typeof(_xElement) == 'string') {_oElement = this.oDocument.getElementById(_xElement);} else {_oElement = _xElement;}
if (_oElement == null) {return null;}
return _oElement.innerHTML;
}
/* @end method */
/*
this.initLandscapeListener = function()
{
if (typeof(window.matchMedia) != 'undefined')
{
alert('matchMedia is supported!');
this.oLandscapeOrientation = window.matchMedia("(orientation:landscape)");
this.oLandscapeOrientation.addListener(oPGBrowser.onLandscapeOrientationChange);
}
else {alert('matchMedia is not supported!');}
}
this.onLandscapeOrientationChange = function(_onLandscapeOrientation)
{
if (_onLandscapeOrientation.matches) {oPGBrowser.bIsLandscape = true;}
else {oPGBrowser.bIsLandscape = false;}
if (oPGBrowser.fOnLandscapeOrientationChange != null) {oPGBrowser.fOnLandscapeOrientationChange(oPGBrowser.bIsLandscape);}
}
this.setLandscapeOrientationChangeFunction = function(_fFunction)
{
this.fOnLandscapeOrientationChange = _fFunction;
}
*/
/*
@start method
@group Mobile
@param fFunction [needed][type]function[/type]
[en]...[/en]
*/
this.setOnOrientationChangeFunction = function(_fFunction)
{
_fFunction = this.getRealParameter({'oParameters': _fFunction, 'sName': 'fFunction', 'xParameter': _fFunction});
this.fOnOrientationChange = _fFunction;
}
/* @end method */
/*
@start method
@group Mobile
*/
this.onResize = function()
{
if (oPGBrowser.isResized())
{
if (oPGBrowser.isOrientationChanged())
{
if (oPGBrowser.fOnOrientationChange != null) {oPGBrowser.fOnOrientationChange();}
}
}
}
/* @end method */
/*
@start method
@group Mobile
@return bIsChanged [type]bool[/type]
[en]...[/en]
*/
this.isOrientationChanged = function()
{
if (typeof(window.orientation) != "undefined")
{
var _iOrientation = window.orientation;
if (oPGBrowser.iOrientation != _iOrientation)
{
oPGBrowser.iOrientation = _iOrientation;
return true;
}
}
return false;
}
/* @end method */
/*
@start method
@group Mobile
@return iOrientation [type]int[/type]
[en]...[/en]
*/
this.getOrientation = function() {return oPGBrowser.iOrientation;}
/* @end method */
/*
@start method
@group Other
@param eEvent [needed][type]object[/type]
[en]...[/en]
*/
this.onLoad = function(_eEvent)
{
if (this.bRunOnceOnLoad == true)
{
this.initSelect();
// this.initLandscapeListener();
this.bRunOnceOnLoad = false;
}
}
/* @end method */
this.init = this.onLoad;
}
/* @end class */
classPG_Browser.prototype = new classPG_ClassBasics();
var oPGBrowser = new classPG_Browser();
|
'use strict';
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
bump: {
options: {
files: ['bower.json', 'package.json'],
commit: true,
commitMessage: 'Release v%VERSION%',
commitFiles: ['bower.json', 'package.json'],
createTag: true,
tagName: 'v%VERSION%',
tagMessage: 'Version %VERSION%',
push: true,
pushTo: 'origin'
}
},
browserify: {
dist: {
files: {'dist/bc-countries-plus.js': ['src.js']},
options: {
browserifyOptions: {bundleExternal: false, standalone: 'bcCountries'}
}
}
},
uglify: {
main: {
files: {'dist/bc-countries-plus.min.js': 'dist/bc-countries-plus.js'}
}
},
karma: {
options: {configFile: 'karma.conf.js'},
unit: {
browsers: ['PhantomJS']
},
e2e: {
browsers: ['Chrome']
}
}
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-browserify');
grunt.loadNpmTasks('grunt-karma');
grunt.loadNpmTasks('grunt-bump');
grunt.registerTask('build', ['browserify', 'uglify']);
grunt.registerTask('test', 'karma:unit');
grunt.registerTask('default', ['browserify', 'uglify', 'test']);
};
|
var mongoose = require('mongoose');
var schema = new mongoose.Schema({
name: {
first: {
type: String,
required: true
},
last: {
type: String,
required: true
}
},
photo: {
url: {
type: String,
required: false
}
},
email: {
type: String,
required: true,
index: {
unique: true
}
},
friends: [
{ type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}],
posts: [
{ type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}],
createdOn: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('User', schema);
|
import { LOGIN_SUCCESS, LOGIN_FAILED, SIGNUP_SUCCESS, SIGNUP_FAILED } from '../constants/constants'
const initialState = {
};
const loginReducer = (state = initialState , action) => {
const {type, userData, error} = action;
switch (type) {
case LOGIN_SUCCESS:
console.log("LOGIN_SUCCESS in reducer",{...state,...userData})
console.log("LOGIN_SUCCESS and modal in reducer",state)
return {
...state,
authenticated:true,
...userData
}
case LOGIN_FAILED:
console.log("LOGIN_FAILED in reducer",{...state,error})
return {...state, authenticated:false, error}
case SIGNUP_SUCCESS:
console.log("SIGNUP_SUCCESS in reducer",{...state,...userData})
console.log("SIGNUP_SUCCESS and modal in reducer",state)
return {
...state,
registered:true
}
case SIGNUP_FAILED:
console.log("SIGNUP_FAILED in reducer",{...state,error})
return {...state, registered:false, error}
default:
return state
}
}
export default loginReducer;
|
import {html} from '../../node_modules/lit-html/lit-html.js';
import {getMyFurniture} from '../api/data.js';
import {furnitureTemplate} from "./common/furnitureTemplate.js";
const myTemplate = (data) => html`
<div class="row space-top">
<div class="col-md-12">
<h1>My Furniture</h1>
<p>This is a list of your publications.</p>
</div>
</div>
<div class="row space-top">
${data.map(furnitureTemplate)}
</div>`;
export async function myFurniturePage(context) {
const data = await getMyFurniture();
context.render(myTemplate(data));
}
|
/**
* @author Ryan Fernandes
*/
const express = require("express");
const bodyParser = require("body-parser");
const userRequestRouter = express.Router();
const mongoose = require("mongoose");
const donor = require("../models/userModel");
userRequestRouter.use(bodyParser.json());
userRequestRouter.route("/:status").put((req, res, next) => {
if (req.params.status == "Approve") {
donor.findByIdAndUpdate(
{ _id: req.body.id },
{ active: "active" },
function (err, d) {
if (err) {
return res.send(err);
} else {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.send({ message: "Success" });
}
}
);
} else if (req.params.status === "complete") {
donor.findByIdAndUpdate(
{ _id: req.body.id },
{ active: "complete", reqemail: req.body.reqemail },
{ new: true },
function (err, d) {
if (err) {
return res.send(err);
} else {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.send(d);
}
}
);
} else {
donor.findByIdAndUpdate(
{ _id: req.body.id },
{ active: "inactive" },
function (err, d) {
if (err) {
return res.send(err);
} else {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.send({ message: "Success" });
}
}
);
}
});
userRequestRouter.route("/").get((req, res, next) => {
donor.find({ active: "pending" }, function (err, d) {
if (err) {
return res.send(err);
} else {
res.statusCode = 200;
res.setHeader("Content-Type", "application/json");
res.json(d);
}
});
});
module.exports = userRequestRouter;
|
import React, {Component} from 'react';
import {View, Text, TextInput, FlatList, TouchableOpacity} from 'react-native';
import {Spiner} from './'
import {DEVICE_OS, iOS} from '../../actions/constants';
// var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
let listHeight = 0;
class Autocomplete extends Component {
constructor(props) {
super(props);
this.state = {
query: '',
searchedItems: []
};
};
renderItem = (item) => {
return (
<View style={{
height: 25,
alignItems: 'flex-start',
justifyContent: 'center'
}}>
<TouchableOpacity
onPress={
() => {
this.props.onSelect(item)
this.setState({searchedItems: []});
}
}
>
<Text
numberOfLines={1}
style={[styles.labelStyle,{
flexWrap: 'wrap',
textDecorationLine: 'underline'
}]}
>
{item.title}
</Text>
</TouchableOpacity>
</View>
);
};
renderList() {
let listHeight = 0;
if (this.props.data.length >= 1) {
const renderedList = this.props.data.slice(0, 30)
listHeight = renderedList.length <= 10 ? renderedList.length * 30 : 200;
return (
<View style={{
flex:1,
alignSelf: 'stretch',
maxHeight: 200,
height: listHeight
}}
>
<FlatList
style={{
height: listHeight,
flex: 1
}}
data={this.props.data}
renderItem={this.renderItem}
/>
</View>
)
}
}
render() {
const {inputStyle, labelStyle, containerStyle} = styles;
const {label, placeholder, value} = this.props;
return (
<View style={[containerStyle]}>
<Text style={[labelStyle, this.props.labelStyle]}>
{label}
</Text>
<View style={{
minHeight: 43,
height: 40,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center'
}}
>
<TextInput
{...this.props}
placeholderTextColor='#b6b9bf'
multiline={false}
onSubmitEditing={() => {console.log('enter pressed')}}
placeholder={placeholder}
value={value}
onChangeText={this.props.onChangeText}
onFocus={this.props.onFocus}
style={inputStyle}/>
</View>
{
this.renderList()
}
</View>
)
}
}
const styles = {
containerStyle: {
marginLeft: 45,
marginRight: 45,
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-start',
alignItems: 'flex-start',
// position: 'absolute',
zIndex: 999
},
inputStyle: {
// placeholderTextColor: '#b6b9bf',
fontFamily:'SFUIText-Regular',
color: '#111',
fontSize: 15,
lineHeight: 25,
flex:1,
borderBottomWidth: DEVICE_OS == iOS ? 1 : 0,
borderBottomColor: '#000'
},
labelStyle: {
marginLeft: 4,
marginBottom: 2,
paddingTop:0,
height: 20,
fontFamily: 'SFUIText-Medium',
fontSize: 14,
color: '#423486',
alignSelf:'stretch',
},
}
export {Autocomplete};
|
var form1 = document.getElementById('form1')
var form2 = document.getElementById('form2')
var form3 = document.getElementById('form3')
function print(output, id) {
document.getElementById(id).innerHTML = output;
}
form1.addEventListener("submit", function(event) {
event.preventDefault();
var sum = +this.firstNumber.value + +this.secondNumber.value;
print(sum, "sum");
})
form2.addEventListener("submit", function(event) {
event.preventDefault();
var difference = +this.firstNumber.value - +this.secondNumber.value;
print(difference, "difference");
})
form3.addEventListener("submit", function(event) {
event.preventDefault();
var product = +this.firstNumber.value * +this.secondNumber.value;
print(product, "product");
})
|
function testClosure() {
for (var i = 0; i < 4; i++) {
setTimeout(() => {
console.log(`i as var is ${i}`)
}, 0);
}
}
function testClosureWithBlockScopeUsingLet(){
for (let i = 0; i < 4; i++) {
setTimeout(() => {
console.log(`i as let is ${i}`)
}, 0);
}
}
testClosure();
testClosureWithBlockScopeUsingLet();
|
import { auth0Client } from "../auth0/auth0"
import { firebaseClient } from "../firebase/firebase"
const auth0ToFirebase = async() => {
const authToken = await auth0Client.handleCallback();
return authToken;
}
const firebaseCustomToken = async function setFirebaseCustomToken(tokenFromAuth) {
const firebaseTokenRequest = await fetch('http://localhost:3001/firebase', {
headers: {
'Authorization': `Bearer ${tokenFromAuth}`,
},
}).then(token => token.json());
const token = await firebaseTokenRequest.firebaseToken;
await firebaseClient.setToken(token);
}
export const authTokenFirebAuth0 = () => auth0ToFirebase().then(token => {
firebaseCustomToken(token)
})
|
'use strict';
var scroller = {
data: [],
// cache section offsets
setData: function() {
var _this = this;
$('section').each(function(k) {
(function($this, data) {
var sectionData = {
offset: Math.round($this.offset().top),
title: $this.data('title'),
hash: '#' + $this.attr('id'),
number: k
};
data.push(sectionData);
})($(this), _this.data)
});
}
};
var setHash = function(hash) {
window.history.pushState({page: hash}, '',hash);
}
/**
* [resolution description] check window resolution / position
* @type {Object}
*/
var resolution = {
isTablet: function() {
return (document.documentElement.clientWidth <= 1024 && document.documentElement.clientWidth >= 768);
},
isPhone: function() {
return document.documentElement.clientWidth < 768;
},
isLandscape: function() {
return document.documentElement.clientWidth > document.documentElement.clientHeight;
}
};
/**
* [imagePreview description] Image Preview on hover module
* @param {[type]} $imgSet [images to perform action on]
* @return {[type]} [description]
*/
var imagePreview = {
render: function($imgSet) {
var xOffset = 10;
var yOffset = 30;
var div = document.createElement('div');
div.className = 'preview';
var img = document.createElement('img');
div.appendChild(img);
var p = document.createElement('p');
div.appendChild(p);
/* END CONFIG */
$imgSet.hover(function(e) {
var url = $(this).parents('a').attr('href');
if (!url || url === undefined) {
url = $(this).attr('src');
}
img.src = url;
img.alt = this.alt;
p.innerHTML = this.alt;
$('body').append(div);
$(div).css({
"top": (e.pageY - xOffset) + "px",
"left": (e.pageX + yOffset) + "px"
}).fadeIn(450);
},
function() {
$(div).fadeOut(150);
}).mousemove(function(e) {
$(div).css({
"top": (e.pageY - xOffset) + "px",
"left": (e.pageX + yOffset) + "px"
});
});
}
};
jQuery.fn.resetFlexslider = function() {
var width = document.documentElement.clientWidth;
$(this).find('.slides').css({
'-webkit-transform': 'translate3d(-' + width + ', 0px, 0px)',
'transform': 'translate3d(-' + width + ', 0px, 0px)',
});
};
jQuery.fn.resetMetaSlider = function() {
var $this = $(this);
var width = document.documentElement.clientWidth;
var height = 0;
if (resolution.isTablet() && !resolution.isLandscape()) {
height = document.documentElement.clientHeight * 0.6;
$this.find('.caption-wrap').css('bottom', document.documentElement.clientHeight - height);
$this.find('.flex-direction-nav').css('bottom', document.documentElement.clientHeight - height - 25);
} else if (resolution.isPhone()) {
height = document.documentElement.clientHeight * 0.45;
$this.find('.caption-wrap').css('bottom', document.documentElement.clientHeight - height);
$this.find('.flex-direction-nav').css('bottom', document.documentElement.clientHeight - height - 55);
} else {
height = document.documentElement.clientHeight;
$this.find('.caption-wrap, .flex-direction-nav').css('bottom', '');
}
$this.find('li img').css({
'min-height': height
}).find('.slides').css({
'-webkit-transform': 'translate3d(-' + width + ', 0px, 0px)',
transform: 'translate3d(-' + width + ', 0px, 0px)'
});
slider.setSliderHeight($(this));
}
var slider = {
setSliderHeight: function($slider) {
var height = null;
if (resolution.isTablet()) {
if (resolution.isLandscape()) {
height = this.getSliderHeight();
}
else {
height = document.documentElement.clientHeight * 0.6;
}
} else if (resolution.isPhone()) {
height = document.documentElement.clientHeight * 0.5;
}
else {
height = document.documentElement.clientHeight - jQuery('.header').height();
}
$slider.find('.slides li').each(function() {
$(this).height(height);
});
},
getSliderHeight: function() {
return document.documentElement.clientHeight - jQuery('.header-wrap').height() + 'px';
},
flexsliderConfig: function(childElements) {
var carouselElementsOnSlide = 3;
var carouselElementsinItem = 2;
var carouselElementsWidth = 390;
var carouselElementsGutter = 0;
if (resolution.isTablet()) {
if (resolution.isLandscape()) {
carouselElementsinItem = 1;
carouselElementsOnSlide = 3;
carouselElementsWidth = 290;
carouselElementsGutter = 0;
} else {
carouselElementsinItem = 2;
carouselElementsOnSlide = 1;
carouselElementsWidth = 125;
carouselElementsGutter = 0;
}
}
else if (resolution.isPhone()) {
carouselElementsOnSlide = 1;
carouselElementsinItem = 1;
carouselElementsWidth = 250;
carouselElementsGutter = 0;
}
else {
if (childElements <= 4) {
carouselElementsinItem = 1;
}
}
return {
carouselElementsGutter:carouselElementsGutter,
carouselElementsWidth: carouselElementsWidth,
carouselElementsinItem: carouselElementsinItem,
carouselElementsOnSlide: carouselElementsOnSlide,
carouselElements: childElements
};
}
};
/**
* [loadGallery description] Loads certain portfolio gallery, and restarts the carousel for each one
* @param {[type]} url [description]
* @return {[type]} [description]
*/
var loadGallery = function(url) {
var galleryDataPromise = jQuery.get(url);
galleryDataPromise.done(function(response) {
var theContent = jQuery(response).find('.Portfolio').html();
$('#portfolioLoadContainer .flexslider').html(theContent);
var childElements = jQuery(theContent).find('.Portfolio-item').length;
loadCarousel(slider.flexsliderConfig(childElements));
});
};
var isCarouselLoaded = false;
var loadCarousel = function(config) {
var $ = jQuery;
// format the carousel
$('.flexslider-carousel').carousel({
itemsInList: config.carouselElementsinItem
});
// if the carousel is already loaded, first remove current data
if (isCarouselLoaded) {
$('.flexslider-carousel').removeData("flexslider");
};
// carousel init
$('.flexslider-carousel').flexslider({
animation: 'slide',
animationLoop: false,
slideshow: true,
touch: true,
minItems: 1,
maxItems: config.carouselElementsOnSlide,
prevText: '',
nextText: '',
itemWidth: config.carouselElementsWidth,
itemMargin: config.carouselElementsGutter,
start: function() {
$(document).trigger('galleryLoaded');
if (!$('.flex-control-nav li').length) {
$('.flexslider-carousel').find('.flex-direction-nav').hide();
}
}
});
};
jQuery(document).on('galleryLoaded', function() {
isCarouselLoaded = true;
$('#portfolioLoadContainer').find('.flexslider').animate({
opacity: 1
}, 150);
$('.loader').hide();
});
jQuery(document).ready(function($) {
// init metaslider
$(window).load(function() {
$('.metaslider').resetMetaSlider();
scroller.setData();
});
var headerHeight = document.querySelector('header').clientHeight;
$(window).on('load scroll', function(e) {
var scrollTop = window.scrollY + headerHeight;
// menu state
$('.header-wrap').toggleClass('fixed', scrollTop >= 0);
// mobile menu title
for (var i = 0; i < scroller.data.length; i++) {
if (Math.ceil(scrollTop) >= scroller.data[i].offset) {
$('.hook-menu-navigate > .menu-item a').removeClass('active');
$('.hook-menu-navigate > .menu-item').eq(scroller.data[i].number).find('> a').addClass('active');
$('.js-current-page').text(scroller.data[i].title);
}
}
if (scrollTop > document.clientHeight * 0.5) {
scrollToTop.showGoTopButton();
}
// set hash last
setTimeout(function() {
var hash = $('.hook-menu-navigate > li > a.active').attr('href');
setHash(hash);
}, 0);
});
// init image preview for single portfolio items
imagePreview.render($('.Portfolio-item-single img'));
// reset flexslider and scrolling offset on window resize or orientation change
$(window).on('resize', function() {
$('.flexslider-carousel').resetFlexslider();
$('.metaslider').resetMetaSlider();
});
if (resolution.isPhone()) {
// set menu to fixed
$('.header-wrap').addClass('fixed');
// update slider section height
slider.setSliderHeight($('.metaslider'));
}
/**
* [scrollBtn description] Scroll To Top Of page
* @type {[type]}
*/
var scrollToTop = {
$scrollBtn: $('.hook-goToTop'),
scrollPos: $(window).scrollTop(),
showGoTopButton: function() {
if (this.scrollPos >= document.body.scrollHeight * 0.35) {
this.$scrollBtn.fadeIn(500);
} else {
this.$scrollBtn.fadeOut(500);
}
}
};
scrollToTop.$scrollBtn.on('click', function() {
$('.hook-menu-navigate li:first-child a').click();
});
/**
* Image uploader module
*/
var $uploadInput = $("input[type=file].upload");
var fileUploaded = [];
var imagesUploaded = [];
function FileManager(file, input) {
var $parent = $(input).parents('.imageUpload');
this.file = file;
this.input = input;
this.fileData = file.name.concat(file.size);
this.$descriptionInput = $parent.find("input[id^='uploadFile']");
this.$imageInput = $parent.find("img");
this.imageData = {};
this.imageData.title = this.$imageInput.attr("title");
this.imageData.src = this.$imageInput.attr("src");
this.$removeImageBtn = $parent.find(".action");
}
FileManager.prototype.prepImageUpload = function() {
if (/image/.test(this.file.type)) {
if (this.file.size > 5000000) {
alert('File is too large. Please upload images smaller than 5 MB');
this.uploadImg.pop();
return;
} else {
this.uploadImage();
}
} else {
alert('Only png, jpg, jpeg and gif image file types allowed!');
this.uploadImg.pop();
return;
}
}
FileManager.prototype.uploadImage = function() {
var _this = this;
var fileName = this.input.value.split("fakepath\\")[1];
var reader = new FileReader();
reader.onloadend = function() {
_this.$imageInput.attr({
src: reader.result,
alt: _this.file.name.split(".", 1)
});
imagePreview.render(_this.$imageInput);
}
reader.readAsDataURL(this.file);
this.$descriptionInput.val(fileName);
this.$removeImageBtn.text("Remove").addClass("remove");
};
FileManager.prototype.removeImage = function(){
var _this = this;
// restore DOM to image upload state
this.$imageInput.attr({
"src": this.imageData.src,
"title": this.imageData.title
});
this.$removeImageBtn.text("Upload").removeClass("remove");
this.input.value = "";
// remove image from array
imagesUploaded.filter(function(value) {
if (value === _this.fileData) {
var pos = imagesUploaded.indexOf(value);
imagesUploaded.splice(pos, 1);
}
});
updateValues(imagesUploaded.length);
this.$removeImageBtn.text("Upload");
this.$descriptionInput.val("Upload File");
};
/**
* when i click the upload button, either upload a new picture or remove the existing one
* @return {[type]} [description]
*/
$uploadInput.parent().find('.action').on("click", function(e) {
e.preventDefault();
var fileName = $(this).parents('.imageUpload').data('title');
if ($(this).hasClass('remove')) {
fileUploaded[fileName].removeImage();
}
else {
$(this).parent().find('.upload').click();
}
});
$uploadInput.on("change", function(e) {
var file = this.files[0];
var fileData = file.name.concat(file.size);
var fileName = $(this).parents('.imageUpload').data('title');
if (imagesUploaded.indexOf(fileData) < 0) {
imagesUploaded.push(fileData);
var newUpload = new FileManager(file, this);
newUpload.prepImageUpload();
fileUploaded[fileName] = newUpload;
} else {
alert("You already uploaded this image. Please upload another one");
return;
}
updateValues(imagesUploaded.length);
});
/**
* Switch Payment Processor
*/
var $paymentMethods = $(".choosePaymentMethod");
var $paymentContainer = $("[data-id]");
$paymentMethods.click(function(e) {
e.preventDefault();
$('.hook-orderForm input[name=payment_method]').val($(this).attr('id'));
$paymentMethods.removeClass('selected');
$(this).addClass('selected');
var id = $(this).attr('id');
$paymentContainer.hide();
$paymentContainer.filter(function() {
if ($(this).data('id') === id) {
$(this).show();
}
})
});
/**
* Form Validation Module
*/
var $orderForm = $(".hook-orderForm");
var $formInputs = $orderForm.find("input[required], textarea");
var $formImagesUploaded = $orderForm.find("input[id^=uploadFile]");
var $formInputErrors = $orderForm.find("span.error");
var $romcardForm = $("[data-id=romcard]");
var captchaUrl = config.baseUrl + '/includes/order/include/check-captcha.php';
var tagBody = '(?:[^"\'>]|"[^"]*"|\'[^\']*\')*';
var tagOrComment = new RegExp('<(?:' //start expresion
// Comment body.
+ '!--(?:(?:-*[^->])*--+|-?)'
// Special "raw text" elements whose content should be elided.
+ '|script\\b' + tagBody + '>[\\s\\S]*?</script\\s*' + '|style\\b' + tagBody + '>[\\s\\S]*?</style\\s*'
// Regular name
+ '|/?[a-z]' + tagBody + ')>',
'gi');
var removeTags = function(html) {
var oldHtml;
do {
oldHtml = html;
html = html.replace(tagOrComment, '');
} while (html !== oldHtml);
return html.replace(/</g, '<');
};
$('.hook-paymentSecondStep form').find('[name=submit], [type=submit]').click(function(event) {
event.preventDefault();
var orderFormValidated = validateOrderForm();
var $form = $(this).parents('form');
$orderForm.find('.response').removeClass('success fail').text('');
orderFormValidated.then(function(valid) {
if (valid) {
/**
* [orderCaptchaPromise description] captcha validation
* @type {[type]} return a promise
*/
var orderCaptchaPromise = captchaValidation($orderForm);
orderCaptchaPromise.then(function(data) {
var data = JSON.parse(data);
if (!data.success) {
$orderForm.find('.error-captcha').text("Captcha failed");
grecaptcha.reset();
}
else {
$orderForm.ajaxSubmit({
url: config.baseUrl + '/includes/contact.php',
contentType: 'multipart/form-data',
success: function(message) {
$orderForm.find('.error').text('');
$('.hook-paymentSecondStep .response').addClass('success').text(message);
setTimeout(function() {
$form.submit();
}, 1500);
},
fail: function(message) {
$('.hook-paymentSecondStep .response').addClass('fail').text(message);
}
});
}
});
};
});
});
/**
* [captchaValidation description] validates captcha for desired form
* @param {[type]} $form [form to validate captcha for]
* @return {[type]} [description]
*/
var captchaValidation = function($form) {
var captchaPOSTResponse = $form.find('.g-recaptcha-response').val();
return $.ajax({
url: captchaUrl,
type: "POST",
headers: "application/json",
data: {
"secret": config.captchaSecret,
"response": captchaPOSTResponse
}
});
};
var validateOrderForm = function() {
//emptyes all errors
$orderForm.find('.error').text('');
var dfd = $.Deferred();
var validated = true;
$formInputErrors.html('');
if (!imagesUploaded.length) {
validated = false;
$('.error-images').text("Please upload at least 1 image");
}
$formInputs.each(function(k, v) {
if (!$(this).val()) {
validated = false;
switch ($(this).attr('name')) {
case "name":
$('.error-name').text('Please provide your name');
break;
case "email":
$('.error-email').text('Please provide your email address');
break;
case "message":
$('.error-message').text('Please tell us what you expect from the graphic simulation');
break;
case "terms":
$('.error-terms').text('You have to accept the terms and conditions');
break;
case "scaptcha":
$('.error-captcha').text('Please enter the code in the image above');
break;
}
} else {
if ($(this).attr('name') === "name" && !/^[\w\s]+$/.test($(this).val())) {
$('.error-name').text('Name should only contain characters');
validated = false;
} else if ($(this).attr('name') === "email" && !/(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|”(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*”)@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/.test($(this).val())) {
$('.error-email').text('Please provide a valid email address');
validated = false;
} else if ($(this).attr('name') === "message") {
$(this).val(removeTags($(this).val()));
if (!/^[\w\s]+$/.test($(this).val())) {
$('.error-message').text("Message should only contain characters");
validated = false;
}
if ($(this).val().length > 1500) {
$('.error-message').text("The message is too long!");
validated = false;
} else if ($(this).val().length < 25) {
$('.error-message').text("The message is too short! Minimum 25 chars");
validated = false;
}
} else if ($(this).attr('name') === 'terms' && !this.checked) {
$('.error-terms').text("You must agree with the terms and conditions");
validated = false;
}
}
});
if (validated === true) {
var userName = $orderForm.find('input[name=name]').val();
var userEmail = $orderForm.find('input[name=email]').val();
$romcardForm.find('input[name=name]').val(userName);
$romcardForm.find('input[name=email]').val(userEmail);
selectOrderItems(imagesUploaded.length);
}
return dfd.resolve(validated);
};
/**
* Order form select dropdown filtering / updating
*/
var selectorOptions = [];
var priceSelector = document.getElementsByTagName("select");
var romcardForm = document.getElementById("rc");
var payPalForm = document.getElementById('ppal');
for (var i = 0; i < priceSelector.length; i++) {
selectorOptions.push(priceSelector[i].querySelectorAll("option"));
}
var selectOrderItems = function(imgLen) {
for (var j = 0; j < selectorOptions.length; j++) {
(function(selectorOptions){
$(selectorOptions).each(function() {
if ($(this).data('qty') !== imgLen) {
$(this).hide();
$(this).attr('disabled', true);
}
});
})(selectorOptions[j]);
}
};
var updateValues = function(qty) {
$(selectorOptions).each(function() {
$(this).attr({
"selected": false,
"disabled": true
}).hide();
$(this).filter(function() {
var $this = $(this);
if ($this.data("qty") === qty) {
$this.attr({
"selected": true,
"disabled": false
}).show();
}
});
});
$(priceSelector).change();
};
$(priceSelector).on('change', function() {
var qty = $(this).find('option[selected]').data('qty');
var fullname = this.value;
var shortname;
var reg = RegExp(fullname);
$('.hook-orderForm input[name=order]').val($(this).val());
$(this).find('option[selected]').each(function() {
if (reg.test(this.value)) {
shortname = $(this).data('value');
}
});
// updates romcard form
romcardForm.querySelector('input[name=name]').value = fullname;
romcardForm.querySelector('input[name=value]').value = shortname + '-' + qty;
// updates paypal form
payPalForm.querySelector('input[name=item_name]').value = fullname;
payPalForm.querySelector('input[name=os0]').value = fullname;
payPalForm.querySelector('input[name=quantity]').value = qty;
});
/**
* Contact Form Handling
* Validate all contact forms (make it real and contact us)
* Order form has manual validation
*/
$('.contactForm').each(function() {
var $this = $(this);
$this.submit(function(event) {
event.preventDefault();
$this.find('.response').removeClass('success fail').text('');
}).validate({
debug: true, //debug mode, remove from prod
submitHandler: function(form) {
$(form).ajaxSubmit({
url: config.baseUrl + '/includes/contact.php',
success: function(message) {
$this.find('.msg').remove();
$this.find('.response').addClass('success').text(message);
},
fail: function(message) {
$this.find('.response').addClass('fail').text(message);
}
});
}
});
});
/**
* [firstGallery description] activate fist portfolio gallery menu item
* @type {[type]}
*/
var firstGallery = $('#portfolioMenu li:first-child a');
firstGallery.parents('li').addClass('active');
loadGallery(firstGallery.attr('href'));
/**
* [flexslider]
* @return {[type]} [description]
*/
$('.flexslider').each(function() {
var $this = $(this);
if ($this.find('li').length > 1) {
$this.flexslider({
allowOneSlide: false,
animation: 'slide',
slideshow: true,
prevText: '',
nextText: ''
});
}
});
$('.js-mobile-menu').on('click', function() {
$('body').toggleClass('menu-open');
});
/**
* [firstGallery description] activate fist portfolio gallery menu item
* @type {[type]}
*/
var firstGallery = $('#portfolioMenu li:first-child a');
firstGallery.parents('li').addClass('active');
loadGallery(firstGallery.attr('href'));
/**
* [flexslider]
* @return {[type]} [description]
*/
$('.flexslider').each(function() {
var $this = $(this);
if ($this.find('li').length > 1) {
$this.flexslider({
allowOneSlide: false,
animation: 'slide',
slideshow: true,
prevText: '',
nextText: ''
});
}
});
$('.js-mobile-menu').on('click', function() {
$('body').toggleClass('menu-open');
});
// go to page sections
$('.hook-menu-navigate > li > a').each(function() {
var navHref = this.attributes.href.value.replace(/(.*)\//, '$1');
navHref = navHref.substring(navHref.lastIndexOf('/') + 1);
$(this).attr({
'href': navHref,
'data-scroll': navHref
});
// on click, close mobile menu if open
$(this).on('click', function(e) {
var scrollLink = $(this).data('scroll').replace('#','');
var scrollTo = $('section#'+scrollLink);
var $this = $(this);
var distance = Math.abs(window.scrollY - scrollTo.offset().top);
var pixelSpeed = 5;
var animationSpeed = distance / pixelSpeed;
e.preventDefault();
$('body').removeClass('menu-open');
$('html body').animate({
scrollTop: scrollTo.offset().top - $('header').height()
}, animationSpeed, 'linear', function() {
setTimeout(function() {
$this.parents('.hook-menu-navigate').find('a').removeClass('active');
$this.addClass('active');
setHash($this.attr('href'));
}, animationSpeed);
});
});
});
/**
* [$loadContainer description] Changes gallery on flexslider portfolio
* @type {[type]}
*/
var $loadContainer = $('#portfolioLoadContainer');
var $loader = $loadContainer.find('.loader');
// Load Gallery Pages To Flexslider
$('.js-hook-load .menu-item a').on('click', function(e) {
// e.preventDefault();
var $this = $(this),
$menuItem = $this.parent(),
isActive = $menuItem.hasClass('active'),
$parent = $this.parents('.js-hook-load');
$parent.find('li').removeClass('active');
$menuItem.addClass('active');
// already active
if (isActive) {
return;
}
$loadContainer.find('.flexslider').animate({
opacity: 0.25
}, 250);
$loader.fadeIn(150);
loadGallery($this.attr('href'));
});
});
|
import React from 'react'
export const Deleta = ({task, handleClick, text }) =>{
return <button onClick={() => handleClick(task)}>{text}</button>
}
|
let timeFormat = d3.timeFormat("%Y/%m/%d");
let margin = {top: 20, right: 0, bottom: 30, left: 40};
let ratio_width_length = 4.0;
let timelapseSpeeds = [0.1, 0.15, 0.225, 0.3, 0.45, 0.6, 0.9, 1.2];
function getTranslation(transform) {
// Create a dummy g for calculation purposes only. This will never
// be appended to the DOM and will be discarded once this function
// returns.
var g = document.createElementNS("http://www.w3.org/2000/svg", "g");
// Set the transform attribute to the provided string value.
g.setAttributeNS(null, "transform", transform);
// consolidate the SVGTransformList containing all transformations
// to a single SVGTransform of type SVG_TRANSFORM_MATRIX and get
// its SVGMatrix.
var matrix = g.transform.baseVal.consolidate().matrix;
// As per definition values e and f are the ones for the translation.
return [matrix.e, matrix.f];
}
function stackMax(layer) {
return d3.max(layer, function(d) { return d[1]; });
}
class StreamGraph {
constructor(width, height, data, svg, listener, colorrange = null, color = "blue", keys) {
this.week = 0;
this.keys = keys;
this.speed_idx = 3;
this.timelapseSpeed = timelapseSpeeds[this.speed_idx];
this.listener = listener;
this.colorrange = [];
if(colorrange) {
this.colorrange = colorrange
}
else {
if(color == "palette") {
this.colorrange = ["#3366cc", "#dc3912", "#ff9900", "#109618", "#990099", "#0099c6"];
}
else if (color == "blue") {
this.colorrange = ["#045A8D", "#2B8CBE", "#54A9CF", "#86BDDB", "#A0D1E6", "#D1EEF6"];
}
else if (color == "spotify_green") {
this.colorrange = ["#0A4820", "#0E6429", "#1A893F", "#1DB954", "#2BD974", "#5DFFA4"];
}
else if (color == "pink") {
this.colorrange = ["#980043", "#DD1C77", "#DF65B0", "#C994C7", "#D4B9DA", "#F1EEF6"];
}
else if (color == "orange") {
this.colorrange = ["#B30000", "#E34A33", "#FC8D59", "#FDBB84", "#FDD49E", "#FEF0D9"];
}
}
this.z = d3.scaleOrdinal()
.range(this.colorrange);
let z = this.z
this.setDimension(width, height);
this.tooltip = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("max-width", "350px")
.style("line-height", 1.5)
.style("opacity", 0);
this.streamGraph = svg.append("g")
.attr("width", this.graph_width + margin.left + margin.right)
.attr("height", this.height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
this.createLayers(data);
this.streamGraph.selectAll("layers")
.data(this.layers)
.enter().append("path")
.attr("class", "layer")
.attr("d", this.area)
.attr("fill", function(d,i) { return z(i); });
this.axishandler = this.streamGraph.append("g")
.attr("class", "axishandler")
// .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
let xAxis = this.xAxis;
let yAxis = this.yAxis;
height = this.height;
this.axishandler.append("g")
.attr("class", "xaxis")
.attr("transform", "translate(0," + (height-10) + ")")
.call(xAxis);
this.axishandler.append("g")
.attr("class", "yaxis")
.call(yAxis);
// text label for the y axis
this.streamGraph.append("text")
.attr("transform", "rotate(0)")
.attr("y", -10)
.attr("x",0)
.attr("dy", "0em")
.style("fill", "white")
.style("text-anchor", "middle")
.style("font-size", "14px")
.text("Streams/week");
this.applyNewData();
this.drawPlayButton();
this.playing = false;
this.resize(width, height);
}
drawPlayButton(delay = 0) {
/*
this.streamGraph.select(".pausebutton").remove();
this.streamGraph.select(".fastbutton").remove();
this.streamGraph.select(".slowbutton").remove();
*/
let buttonSize = this.height/3;
this.streamGraph.select(".playbutton").remove();
if(this.pauseButton) {
this.pauseButton.on("click", null);
this.pauseButton.transition()
.duration(delay)
.attr("opacity", 0)
}
if(this.fastButton) {
this.fastButton.on("click", null);
this.fastButton.transition()
.duration(delay)
.attr("x", (this.width/2 - buttonSize))
.attr("opacity", 0)
}
if(this.slowButton) {
this.slowButton.on("click", null);
this.slowButton.transition()
.duration(delay)
.attr("x", (this.width/2 - this.height/3))
.attr("opacity", 0)
}
this.playButton = this.streamGraph.append("image")
.attr("class", "playbutton")
.attr("xlink:href","img/play2.svg")
.attr("width", buttonSize)
.attr("height", buttonSize)
.attr("x", (this.width - margin.left)/2 - buttonSize/2)
.attr("y", this.height + buttonSize/2)
.attr("opacity", 0);
this.playButton.transition()
.duration(delay)
.attr("opacity", 1)
let _this = this;
this.playButton.on("click", function() {
_this.playing = true;
_this.listener.buttonPressed(true, _this.week);
_this.drawPauseButton(250);
});
}
drawPauseButton(delay) {
let buttonSize = this.height/3;
/*
this.streamGraph.select(".playbutton").remove();*/
this.streamGraph.select(".pausebutton").remove();
this.streamGraph.select(".fastbutton").remove();
this.streamGraph.select(".slowbutton").remove();
if(this.playButton) {
this.playButton.on("click", null);
this.playButton.transition()
.duration(delay)
.attr("opacity", 0)
}
this.pauseButton = this.streamGraph.append("image")
.attr("class", "pausebutton")
.attr("xlink:href","img/pause2.svg")
.attr("width", buttonSize)
.attr("height", buttonSize)
.attr("x", (this.width - margin.left)/2 - buttonSize/2)
.attr("y", this.height + buttonSize/2)
.attr("opacity", 0);
this.pauseButton.transition()
.duration(delay)
.attr("opacity", 1)
let _this = this;
this.pauseButton.on("click", function() {
_this.playing = false;
_this.listener.buttonPressed(false);
_this.drawPlayButton(250);
});
this.fastButton = this.streamGraph.append("image")
.attr("class", "fastbutton")
.attr("xlink:href","img/forward.svg")
.attr("width", buttonSize)
.attr("height", buttonSize)
.attr("x", (this.width - margin.left)/2 - buttonSize/2)
.attr("y", this.height + buttonSize/2)
.attr("opacity", 0);
this.fastButton.transition()
.duration(delay)
.attr("x", (this.width - margin.left)/2 + buttonSize)
.attr("opacity", 1)
this.fastButton.on("click", function() {
_this.changeSpeed(1)
});
this.slowButton = this.streamGraph.append("image")
.attr("class", "slowbutton")
.attr("xlink:href","img/backward.svg")
.attr("width", buttonSize)
.attr("height", buttonSize)
.attr("x", (this.width - margin.left)/2 - buttonSize/2)
.attr("y", this.height + buttonSize/2)
.attr("opacity", 0);
this.slowButton.transition()
.duration(delay)
.attr("x", (this.width - margin.left)/2 - 2 * buttonSize)
.attr("opacity", 1)
this.slowButton.on("click", function() {
_this.changeSpeed(-1)
});
}
changeSpeed(increment) {
let buttonSize = this.height/3;
this.speed_idx = Math.min(this.speed_idx + increment, timelapseSpeeds.length - 1);
this.speed_idx = Math.max(this.speed_idx, 0);
this.timelapseSpeed = timelapseSpeeds[this.speed_idx];
let speed = (timelapseSpeeds[this.speed_idx] / timelapseSpeeds[3]).toPrecision(2);
this.streamGraph.select(".speedtext").remove();
this.speedText = this.streamGraph.append("text")
.attr("class", "speedtext")
.attr("x", (this.width - margin.left)/2 + (5*buttonSize)/2)
.attr("y", this.height + buttonSize/2)
.style("fill", "white")
.style("font-size", "18px")
.attr("dy", "1em")
.attr("opacity", 1)
.text("x" + speed);
this.speedText
.transition()
.attr("opacity", 0)
.delay(1000)
.duration(800);
}
setData(data) {
this.week = 0;
this.speed_idx = 3;
this.timelapseSpeed = timelapseSpeeds[this.speed_idx];
this.setTimeStamp(0);
this.createLayers(data);
this.changeGraph();
this.applyNewData();
}
setDimension(width, height) {
if(width/height > ratio_width_length) {
this.width = height * ratio_width_length;
this.height = height;
} else {
this.width = width;
this.height = width / ratio_width_length;
}
this.graph_width = this.width - margin.left - margin.right;
}
createLayers(data) {
let height = this.height
let width = this.width
this.data = data
this.datearray = [];
this.stack = d3.stack()
.keys(this.keys)
.order(d3.stackOrderNone)
//.offset(d3.stackOffsetSilhouette);
.offset(d3.stackOffsetNone);
this.layers = this.stack(this.data)
this.x = d3.scaleTime()
.range([0, this.graph_width])
.domain(d3.extent(this.data, function(d) { return d.date; }));
this.y = d3.scaleLinear()
.range([height-10, 0])
.domain([0, d3.max(this.layers, stackMax)]);
let x = this.x
let y = this.y
this.xAxis = d3.axisBottom()
.scale(this.x);
this.yAxis = d3.axisLeft()
.scale(this.y)
.ticks(6)
.tickFormat(x => nFormatter(x, 3));
this.area = d3.area()
.curve(d3.curveBasis)
.x(function(d, i) { return x(data[i].date); })
.y0(function(d) { return y(d[0]); })
.y1(function(d) { return y(d[1]); });
}
changeGraph() {
let area = this.area;
this.streamGraph.selectAll("path")
.data(this.layers)
.transition()
.duration(1500)
.attr("d", area);
}
applyNewData() {
let _this = this;
let data = this.data
let x = this.x
let y = this.y
let xAxis = this.xAxis;
let yAxis = this.yAxis;
this.axishandler.select(".xaxis")
.transition()
.duration(2500)
.call(xAxis);
this.axishandler.select(".yaxis")
.transition()
.duration(2500)
.call(yAxis);
let tooltip = this.tooltip;
let streamGraph = this.streamGraph;
let datearray = this.datearray;
let layers = this.layers;
this.streamGraph.selectAll(".layer")
.attr("opacity", 1)
.on("mouseover", function(d, i) {
tooltip.transition()
.duration(200)
.style("opacity", 1);
streamGraph.selectAll(".layer").transition()
.duration(250)
.attr("opacity", function(d, j) {
return j != i ? 0.6 : 1;
})})
.on("mousemove", function(d, i) {
let mouse = d3.mouse(this);
let mousex = mouse[0];
let invertedx = x.invert(mousex);
for (let k = 0; k < data.length; k++) {
datearray[k] = data[k].date
// datearray[k] = datearray[k].getMonth() + datearray[k].getDate();
}
let mousedate = 0
let diff = Math.abs(invertedx.getTime() - datearray[0].getTime())
for(let j = 1; j < datearray.length; j++) {
if(Math.abs(invertedx.getTime() - datearray[mousedate].getTime()) > Math.abs(invertedx.getTime() - datearray[j].getTime())) {
mousedate = j;
}
}
let regionSum = d[mousedate][1] - d[mousedate][0];
let streamsSum = layers.map(x => x[mousedate][1] - x[mousedate][0]).reduce((a, v) => a + v, 0)
if(_this.keys.length > 1) {
tooltip.html(/*timeFormat(datearray[mousedate])*/ "Week " + (mousedate+1) + "<br>" + d.key + ": " + nFormatter(regionSum, 3) + "<br> " + "World: " + nFormatter(streamsSum, 3))
.style("visibility", "visible");
} else {
tooltip.html(/*timeFormat(datearray[mousedate])*/ "Week " + (mousedate+1) + "<br>" + "Total streams" + ": " + nFormatter(regionSum, 3))
.style("visibility", "visible");
}
tooltip
.style("left", (d3.event.pageX) + "px")
.style("top", (d3.event.pageY - tooltip.node().getBoundingClientRect().height) + "px");
})
.on("mouseout", function(d, i) {
tooltip.transition()
.duration(500)
.style("opacity", 0);
streamGraph.selectAll(".layer")
.transition()
.duration(250)
.attr("opacity", "1");
})
d3.select(".chart")
.on("mousemove", function(){
mousex = d3.mouse(this);
mousex = mousex[0] + 5;
})
.on("mouseover", function(){
mousex = d3.mouse(this);
mousex = mousex[0] + 5;
//vertical.style("left", mousex + "px")
});
}
setTimeStamp(week) {
this.week = week;
this.drawTimeLine();
}
resize(width, height) {
let data = this.data
this.setDimension(width, height)
height = this.height;
this.x = d3.scaleTime()
.range([0, this.graph_width])
.domain(d3.extent(data, function(d) { return d.date; }));
this.y = d3.scaleLinear()
.range([height-10, 0])
.domain([0, d3.max(this.layers, stackMax)]);
this.xAxis = d3.axisBottom()
.scale(this.x);
this.yAxis = d3.axisLeft()
.scale(this.y)
.ticks(4)
.tickFormat(x => nFormatter(x, 3));
let x = this.x
let y = this.y
let z = this.z
this.area = d3.area()
.curve(d3.curveBasis)
.x(function(d, i) { return x(data[i].date); })
.y0(function(d) { return y(d[0]); })
.y1(function(d) { return y(d[1]); });
this.streamGraph
.attr("width", this.graph_width + margin.left + margin.right)
.attr("height", this.height + margin.top + margin.bottom)
//.append("g")
//.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
this.streamGraph.selectAll(".layer")
.attr("d", this.area);
this.drawTimeLine();
this.axishandler.selectAll(".xAxis").remove()
this.axishandler.selectAll(".yAxis").remove()
this.axishandler.remove()
this.axishandler = this.streamGraph.append("g")
.attr("class", "axishandler")
// .attr("transform", "translate(" + margin.left + "," + margin.top + ")");
let xAxis = this.xAxis;
let yAxis = this.yAxis;
this.axishandler.append("g")
.attr("class", "xaxis")
.attr("transform", "translate(0," + (height-10) + ")")
.call(xAxis);
this.axishandler.append("g")
.attr("class", "yaxis")
.call(yAxis);
if(this.playing) {
this.drawPauseButton();
} else {
this.drawPlayButton();
}
}
drawTimeLine() {
this.streamGraph.select(".timeline").remove()
if(this.week) {
if(this.week >= this.data.length - 1) {
this.week = this.data.length - 1;
}
let date1 = this.data[Math.floor(this.week)].date
let date2 = this.data[Math.ceil(this.week)].date
let dateRate = this.week - Math.floor(this.week);
let date = new Date(date1.getTime() + dateRate * (date2.getTime() - date1.getTime()))
this.streamGraph.append("rect")
.attr("class", "timeline")
.attr("x", this.x(date))
.attr("y", -10)
.attr("width", 2)
.attr("height", this.height)
.attr("fill", "#ffffff");
}
}
pause() {
this.playing = false;
this.drawPlayButton();
}
remove() {
this.tooltip.remove();
this.streamGraph.remove();
}
}
|
const express = require('express');
const router = express.Router();
const pool = require('../modules/pool');
router.get('/', (req, res)=>{
const sqlQuery = `SELECT * FROM quote
ORDER BY random()
LIMIT 1;`;
pool.query(sqlQuery)
.then(result=>res.send(result.rows[0]))
.catch(error=>{
console.log('Error in / GET', error);
res.sendStatus(500);
});
});
module.exports = router;
|
/* 🤖 this file was generated by svg-to-ts*/
export const EOSIconsHorizontalSplit = {
name: 'horizontal_split',
data: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M3 19h18v-6H3v6zm0-8h18V9H3v2zm0-6v2h18V5H3z"/></svg>`
};
|
app.service('dialogService', function($http) {
this.showDialogById = function(dialogId, yesevent) {
var modalDialog = $(dialogId);
modalDialog.find('#yesbutton').one('click', function(event) {
console.log('yes button call!');
if(!yesevent(event)){
modalDialog.modal('hide');
}
});
modalDialog.modal('show');
return modalDialog;
}
this.showConfirmDialog = function(title, message, yesevent){
var modalDialog = this.showDialogById('#modal-from-dom', yesevent);
modalDialog.find('#warning_dialog_title').text(title);
modalDialog.find('#warning_dialog_message').text(message);
}
});
app.service('wordService', function($http) {
this.saveImgUrl = function(link,url,cb){
var dataContainer = {
url : url,
link : link
};
$http({
method: 'POST',
url: '/words/saveimgurl',
data: dataContainer}).
success(function(data, status, headers, config) {
console.log(data);
cb(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
this.updateWord = function(lang,link,word, record,cb){
var dataContainer = {
lang : lang,
link : link,
word: word,
record: record
};
$http({
method: 'POST',
url: '/words/update',
data: dataContainer}).
success(function(data, status, headers, config) {
console.log(data);
cb(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
this.deleteImg = function(link,cb){
var dataContainer = {
link : link
};
$http({
method: 'POST',
url: '/words/deleteimg',
data: dataContainer}).
success(function(data, status, headers, config) {
console.log(data);
cb(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
this.deleteLink = function(word){
$http({
method: 'POST',
url: '/words/deletelink',
data: {links:[word.link]}}).
success(function(data, status, headers, config) {
console.log(data);
data[0].some(function(dl){
if(dl.lid == word.link){
word.del = dl.del;
return true;
}
});
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
this.updateLinkDescription = function(word, description){
var url = '/words/updatelink/';
$http({
method: 'POST',
url: url,
data: {lid: word.link, description:description}}).
success(function(data, status, headers, config) {
data.some(function(link){
if(link.version === 0){
if(word.description){
word.description = link.description;
} else if(word.d){
word.d = link.description;
}
return true;
}
});
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
this.setQuestionState = function(word, state, message){
var url = '/question/setstate/' + word.link + '/' + word.n1 + '/' + word.n2 + '/' + state;
$http({
method: 'POST',
url: url,
data: {message:message}}).
success(function(data, status, headers, config) {
word.q_state = data.word.q_state;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
this.approve = function(linkId,flag,cb){
var dataContainer = {
flag : flag,
linkId : linkId
};
$http({
method: 'POST',
url: '/approveimages/approve',
data: dataContainer}).
success(function(data, status, headers, config) {
console.log(data);
cb(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
});
/***
* PLEASE NOTE!
* lang is comming from word
* the lang is gettet from first word in list!!!
*/
app.service('duplicityService', function($http, $timeout) {
var self = {};
var waitingList = []
var MAX_FROM_WAITING_LIST = 2000;
var timerRun = null;
var wordsByLink = null;
self.check = function(word){
waitingList.push(word);
}
self.loadDuplicityTimer = function(words){
if(words){
wordsByLink = words;
}
if(!timerRun){
timerRun = $timeout(loadDuplicity, 10);
}
}
var loadDuplicity = function() {
var workList = {}
var links = '';
var lang,lang2;
if(waitingList.length < 1){
if(timerRun){
//timerRun.stop();
}
timerRun = null;
return;
}
waitingList.some(function(word,idx){
if(!lang){
lang = word.n1;
}
if(!lang2){
lang2 = word.n2;
}
workList[word.link] = word;
links += ',' + word.link;
waitingList.splice(idx, 1);
return idx == MAX_FROM_WAITING_LIST;
})
// remove symbol ',' from front
links = links.substr(1);
requestGET($http, '/words/sentences/'+lang+'/'+lang2+'/?toLinks='+links, function(response, status){
response.toLinks.forEach(function(linkToIndex, sentenceIndex){
var sen = response.sentences[sentenceIndex];
linkToIndex.forEach(function(link){
sentenceToWord(wordsByLink[link], sen)
})
})
// proces next in list
timerRun = null;
self.loadDuplicityTimer();
});
}
function sentenceToWord(workWord, sen){
if(!workWord.sentences){
workWord.sentences = []
workWord.sentencesId = []
}
if(workWord.sentencesId.indexOf(sen.l) == -1){
workWord.sentences.push(sen);
workWord.sentencesId.push(sen.l);
}
}
return self;
});
app.service('lastVisitService', function($http) {
var lastVisitService = this;
lastVisitService.onChangeLastVisit = null;
lastVisitService.questionsCount = 1;
lastVisitService.questionsWhereIAMCount = 3;
lastVisitService.QUESTION_ALL = 1;
lastVisitService.QUESTION_WHERE_I_AM = 2;
lastVisitService.refreshCounts = function(type, cnt){
if(type == lastVisitService.QUESTION_ALL){
this.questionsCount = cnt;
} else if(type == lastVisitService.QUESTION_WHERE_I_AM){
this.questionsWhereIAMCount = cnt;
}
this.onChangeLastVisit(this.questionsCount, this.questionsWhereIAMCount);
}
lastVisitService.getLastVisit = function(type,cb){
lastVisitService.onChangeLastVisit = cb;
var dataContainer = {
type : type
};
$http({
method: 'POST',
url: '/question/getlastvisit',
data: dataContainer}).
success(function(data, status, headers, config) {
console.log(data);
lastVisitService.refreshCounts(type, data.cnt);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
lastVisitService.setLastVisit = function(type,cb){
//this.onChangeLastVisit = cb;
var dataContainer = {
type : type
};
$http({
method: 'POST',
url: '/question/setlastvisit',
data: dataContainer}).
success(function(data, status, headers, config) {
console.log(data);
lastVisitService.refreshCounts(type, 0);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}
});
|
// server.js 1
console.log('hello world')
// server.js http0
var express = require('express');
var app=express();
app.listen(3000, function (err) {
console.log('server running at port 3000');
})
// server.js http1
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('hello world');
}).listen(3000,"127.0.0.1");//http://localhost:3000/ 有区别,localhost 解析到127.0.0.1
console.log('server running at http://127.0.0.1:1337/');
// server.js http2
// var http = require('http');
// var server = http.createServer(function(request, response){
// try {
// var ret = require('.' + request.url);
// response.end(ret.output);
// } catch (err) {
// response.end(err.toString());
// }
// });
// server.listen(8080);
|
export default {
isURL(url){
return /^((https|http|ftp|rtsp|mms)?:\/\/)[^\s]+/.test(url);
},
//数组判断
isArray: Array.isArray || function (arr) {
return Array.prototype.toString.call(arr) === '[object Array]';
},
//判断数字
isNumber: function (val) {
//isFinite 检测是否为无穷大
//isNumber(parseInt(a)) // true
// 第一种写法
return typeof val === 'number' && isFinite(val);
//第二种写法
// return typeof val === 'number' && !isNaN(val)
},
//判断字符串
isString: function (str) {
return typeof str === 'string';
},
//判断布尔值
isBoolean: function (bool) {
return typeof bool === 'boolean';
},
//判断函数
isFun: function (fn) {
return typeof fn === 'function';
},
//判断对象
isObject: function (obj) {
//{},[],null 用typeof检测不出来
return Object.prototype.toString.call(obj) === '[object Object]';
},
//判断undefined
isUndefined: function (undefined) {
return typeof undefined === 'undefined';
},
isNull: function (n) {
//判断空值用 n === null
return n === null;
},
isNaN: function (val) {
return typeof val === 'number' && isNaN(val);
},
$(ele){
if(document.querySelector){
return document.querySelector(ele);
} else {
if (ele.indexOf('#') > -1){
return document.getElementById(ele.replace('#',''));
} else if (ele.indexOf('.') > -1){
return document.getElementsByClassName(ele.replace('.',''))[0];
} else {
return document.getElementsByTagName(ele)[0];
}
}
},
toggleClass(ele, cls){
ele.className.indexOf(cls) > -1 ? ele.classList.remove(cls) : ele.classList.add(cls);
},
addEvent(element, type, handler, useCapture) {
if(element.addEventListener) {
element.addEventListener(type, handler, useCapture ? true : false);
} else if(element.attachEvent) {
element.attachEvent('on' + type, handler);
} else if(element != window){
element['on' + type] = handler;
}
},
removeEvent(element, type, handler, useCapture) {
if(element.removeEventListener) {
element.removeEventListener(type, handler, useCapture ? true : false);
} else if(element.detachEvent) {
element.detachEvent('on' + type, handler);
} else if(element != window){
element['on' + type] = null;
}
},
cancelEvent(e) {
if(e.preventDefault){
e.preventDefault();
}
else{
e.returnValue = false;
}
if(e.stopPropagation){
e.stopPropagation();
}
else{
e.cancelBubble = true;
}
return false;
},
};
|
export const types = {
productAddNew: '[products] New product'
}
|
let IStore = require('./IStore.js');
if( window.require ){
var fs = window.require('fs');
var { remote:{app} } = window.require('electron');
var {webFrame} = window.require('electron');
webFrame.registerURLSchemeAsPrivileged('file', {});
}else{
fs = {
mkdir( path, cb ){ cb(); },
readFile( path, enc, cb ){
var data = localStorage.getItem( path );
if( typeof enc === "function" ){
cb = enc;
if( data === null )
return cb( "ENOENT" );
data = data.split(",");
var buffer = new Uint8Array( data.length );
for( var i=0, l=data.length; i<l; ++i )
buffer[i] = data[i] | 0;
data = buffer;
}else if( data === null )
return cb( "ENOENT" );
cb( undefined, data );
},
writeFile( path, data, cb ){
localStorage.setItem( path, data );
cb(true);
}
}
}
class NodeStore extends IStore {
constructor(){
super();
if( app )
this.root = app.getPath("userData") + "/";
else
this.root = "";
this.fs = fs;
}
}
module.exports = NodeStore;
|
import { StyleSheet, Platform } from 'react-native';
import { isX, paddingX } from 'kitsu/utils/isX';
import * as colors from 'kitsu/constants/colors';
export const styles = StyleSheet.create({
containerStyle: {
flex: 1,
backgroundColor: colors.listBackPurple,
paddingTop: Platform.select({ ios: 77, android: 72 }),
},
headerCoverImage: {
height: isX ? 100 + paddingX : 100,
justifyContent: 'center',
},
hintText: {
fontFamily: 'OpenSans',
fontSize: 10,
color: colors.grey,
},
valueText: {
// TODO: Find a better name for this and remove margin to generalize more.
fontFamily: 'OpenSans',
fontSize: 12,
marginTop: 4,
color: colors.softBlack,
},
linkText: {
fontFamily: 'OpenSans',
fontSize: 12,
color: colors.linkBlue,
},
emptyText: {
marginVertical: 4,
marginLeft: 13,
fontFamily: 'OpenSans',
fontSize: 12,
color: colors.white,
},
inputWrapper: {
backgroundColor: colors.white,
paddingHorizontal: 12,
paddingTop: 8,
paddingBottom: 4,
},
input: {
flex: 1,
height: 40,
fontFamily: 'OpenSans',
fontSize: 14,
},
selectMenu: {
backgroundColor: colors.white,
paddingVertical: 8,
paddingHorizontal: 12,
},
item: {
backgroundColor: colors.white,
paddingHorizontal: 12,
paddingVertical: 10,
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
},
itemImage: {
resizeMode: 'contain',
width: 16,
height: 16,
marginHorizontal: 4,
},
blockingWrapper: {
backgroundColor: colors.white,
padding: 2,
borderRadius: 2,
margin: 12,
},
privacySettingsWrapper: {
flexDirection: 'row',
backgroundColor: 'white',
paddingHorizontal: 12,
paddingVertical: 16,
alignItems: 'center',
justifyContent: 'space-between',
},
privacySettingsText: {
fontFamily: 'OpenSans',
color: colors.softBlack,
fontSize: 14,
},
privacyTipsWrapper: {
backgroundColor: 'white',
paddingHorizontal: 12,
paddingVertical: 8,
},
privacyTipsText: {
fontSize: 10,
color: 'grey',
},
logoutButton: {
marginTop: 20,
marginBottom: 40,
padding: 12,
backgroundColor: colors.white,
alignItems: 'center',
},
logoutButtonText: {
fontWeight: '500',
color: colors.activeRed,
},
userProfileButton: {
marginTop: 12,
marginHorizontal: 12,
padding: 8,
flexDirection: 'row',
alignItems: 'center',
},
userProfileImage: {
width: 40,
height: 40,
borderRadius: 20,
},
userProfileTextWrapper: {
marginLeft: 12,
backgroundColor: 'transparent',
},
userProfileName: {
fontFamily: 'OpenSans',
color: colors.white,
fontSize: 14,
fontWeight: '600',
},
userProfileDetailsText: {
fontFamily: 'OpenSans',
color: colors.white,
fontSize: 10,
},
});
export const flatten = (...additionalStyles) => {
const includedStyles = additionalStyles.map(style => styles[style]);
return StyleSheet.flatten(includedStyles);
};
|
/**
* Dependencies.
*/
var SupplierGroupController = require('../../controllers/supplierGroup');
module.exports = exports = function(server) {
console.log('Loading SupplierGroup routes');
exports.indexes(server);
exports.create(server);
exports.update(server);
exports.show(server);
exports.remove(server);
};
/**
* GET /events
* Gets all the SupplierGroup from MongoDb and returns them.
*
* @param server - The Hapi Server
*/
exports.indexes = function(server) {
// GET
server.route({
method: 'GET',
path: '/supplierGroup',
config: {
handler: SupplierGroupController.GetAll
}
});
};
/**
* POST /new
* Creates a new supplierGroup in the datastore.
*
* @param server - The Hapi Serve
*/
exports.create = function(server) {
// POST
server.route({
method: 'POST',
path: '/supplierGroup',
config: {
handler: SupplierGroupController.Create
}
});
};
/**
* Update /supplierGroup/{id}
* Update an SupplierGroup, based on the id in the path.
*
* @param server - The Hapi Server
*/
exports.update = function(server) {
server.route({
method: 'PUT',
path: '/supplierGroup/{id}',
config: {
handler: SupplierGroupController.UpdateSupplierGroup
}
})
};
/**
* GET /supplierGroup/{id}
* Gets the supplierGroup based upon the {id} parameter.
*
* @param server
*/
exports.show = function(server) {
server.route({
method: 'GET',
path: '/supplierGroup/{id}',
config: {
handler: SupplierGroupController.GetSupplierGroup
}
})
};
/**
* DELETE /supplierGroup/{id}
* Deletes an SupplierGroup, based on the id in the path.
*
* @param server - The Hapi Server
*/
exports.remove = function(server) {
server.route({
method: 'DELETE',
path: '/supplierGroup/{id}',
config: {
handler: SupplierGroupController.DeleteSupplierGroup
}
})
};
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Card, Row, Col, Table } from 'react-bootstrap'
import * as Chartjs from 'react-chartjs-2'
import { DonutChart } from '@hydrogenapi/react-components'
import Auth from '../auth';
import Initializer from '../Initializer';
import SpinnerComponent from '.././components/SpinnerComponent';
import Navbar from '../components/Navbar';
import { formatCurrency } from './helpers';
import {
getUser,
getAllSecurities,
getClientAnnualVolume,
getClientHoldings,
getClientCumulativeReturn,
getClientAssetSize,
logoutUser,
setAccount
} from '../store/actions/index'
import '../App.css'
class ClientPage extends Component {
constructor(props) {
super(props)
this.state = {
showModal: '',
price: null,
isDeleting: false,
currentBalance: null,
accountName: ''
}
}
componentDidUpdate(prevProps) {
const { onGetClientHoldings, onGetClientAssetSize, onGetClientCumulativeReturn, onGetClientAnnualVolume, user, clientAssetSize, accessToken } = this.props;
if (accessToken !== prevProps.accessToken) {
this.setState({ accessToken: accessToken });
}
if (user !== prevProps.user) {
onGetClientAssetSize(user.id);
onGetClientHoldings(user.id);
onGetClientCumulativeReturn(user.id)
onGetClientAnnualVolume(user.id)
}
if (clientAssetSize.length !== prevProps.clientAssetSize.length) {
this.setState({ currentBalance: clientAssetSize.slice(-1)[0].value });
}
}
handleShowAccountName = (name) => {
this.setState({ accountName: name })
}
onLogoutClick = () => {
const { onLogoutUser } = this.props;
Auth.signout(() => {
this.props.history.push('/');
onLogoutUser();
})
}
onResetClick = async () => {
this.setState({ isDeleting: true });
const { onLogoutUser, onSetAccount } = this.props;
const { clearAll } = Initializer;
const accessToken = localStorage.getItem('accessToken');
await clearAll(accessToken);
Auth.signout(() => {
onLogoutUser();
this.props.history.push('/')
})
this.setState({ isDeleting: false });
onSetAccount({});
}
componentDidMount = () => {
const { onGetUser, onGetAllSecurities } = this.props;
const username = localStorage.getItem('username')
onGetAllSecurities();
onGetUser({ username: username });
}
render() {
const { clientAssetSize, clientHoldings, clientAnnualVolume, clientCumulativeReturn, securities, user, history } = this.props;
const { currentBalance, isDeleting } = this.state;
let totalEarnings;
if (clientAssetSize.length > 0) {
const firstCashFlow = clientAssetSize[0];
const allAdditions = clientAssetSize.map(s => s.additions).reduce((prev, next) => prev + next);
totalEarnings = currentBalance - firstCashFlow.value - allAdditions;
}
const colors = ['#16D9F0', '#0D96A6', '#327fa8', '#133080', '#335fd6']
const data = (clientHoldings && clientHoldings.length > 0 && securities.length > 0) ? securities.map((s, index) => {
const clientHoldingsGroup = clientHoldings.filter(ch => s.id !== ch.security_id);
const weight = clientHoldingsGroup.map(item => item.weight).reduce((prev, next) => prev + next);
const amount = clientHoldingsGroup.map(item => item.amount).reduce((prev, next) => prev + next);
let securityType;
if (s.ticker === 'VTI') securityType = 'Stocks';
if (s.ticker === 'BND') securityType = 'Bonds';
return {
value: weight / 2,
label: securityType,
asset_class: s.asset_class,
color: colors[index],
amount: amount,
name: s.name,
ticker: s.ticker
}
}) : [];
return (
isDeleting ? <SpinnerComponent /> : <div className="dashboard-container">
<Navbar
handleShowAccountName={(name) => this.handleShowAccountName(name)}
onResetClick={this.onResetClick} user={user} routerHistory={history}
onLogoutClick={this.onLogoutClick}
/>
<div className="container">
<Row className="mt-3 mb-2 ml-2">
<h3 className="font-weight-light client-page-title">All accounts</h3>
</Row>
<Row>
<Card className="goal-card-dashboard m-2 float-left">
<Row>
<Col className="d-lg-block align-items-stretch">
<a href="#d" className="card-body media align-items-center text-body">
<i className="lnr lnr-checkmark-circle display-4 d-block text-primary"></i>
<span className="media-body d-block ml-4 mt-4">
<span className="goal-cards-text"><span className="font-weight-bolder">$ {currentBalance && formatCurrency(currentBalance.toFixed(2))}</span></span><br />
<small className="text-muted">Current balance</small>
</span>
</a>
<a href="#d" className="card-body media align-items-center text-body">
<i className="lnr lnr-checkmark-circle display-4 d-block text-primary"></i>
<span className="media-body d-block ml-4 mt-4">
<span className="goal-cards-text"><span className="font-weight-bolder">$ {totalEarnings && formatCurrency(totalEarnings.toFixed(2))}</span></span><br />
<small className="text-muted">Total earnings</small>
</span>
</a>
</Col>
<Col className="d-lg-block align-items-stretch">
<a href="#d" className="card-body media align-items-center text-body">
<i className="lnr lnr-checkmark-circle display-4 d-block text-primary"></i>
<span className="media-body d-block ml-4 mt-4">
<span className="goal-cards-text"><span className="font-weight-bolder">{clientCumulativeReturn.cum_return && clientCumulativeReturn.cum_return.toFixed(2)} %</span></span><br />
<small className="text-muted">Performance</small>
</span>
</a>
<a href="#d" className="card-body media align-items-center text-body">
<i className="lnr lnr-checkmark-circle display-4 d-block text-primary"></i>
<span className="media-body d-block ml-4 mt-4">
<span className="goal-cards-text"><span className="font-weight-bolder">{clientAnnualVolume.ann_vol && clientAnnualVolume.ann_vol.toFixed(2)} %</span></span><br />
<small className="text-muted">Volatility</small>
</span>
</a>
</Col>
</Row>
</Card>
<Card className="client-page-dashboard m-2 pt-4 flex-grow-1 float-right">
<DonutChart
legend="left"
width={280}
height={250}
data={data.map(d => { return { label: d.label, value: d.value / 100, color: d.color } })}
/>
<div className="client-page-table-dashboard">
<Table responsive className="card-table client-table-responsive">
<thead>
<tr>
<th>Name</th>
<th>Ticker</th>
<th>Weight</th>
<th>Balance</th>
</tr>
</thead>
<tbody>
{data.map((d, index) => {
return [
<tr key={index}>
<td>{d.label}</td>
<td>{d.ticker}</td>
<td>{d.value && d.value.toFixed(2)}%</td>
<td>${d.amount && formatCurrency(d.amount.toFixed(2))}</td>
</tr>
]
})}
</tbody>
</Table>
</div>
</Card>
</Row>
<Row>
<Card className="m-2 mt-3 w-100 client-chart">
<h5 style={{ paddingLeft: '5px', paddingTop: '10px', marginBottom: '-2px' }}>Account growth per month</h5>
<Chartjs.Line
height={210}
data={{
labels: clientAssetSize.map(ca => ca.date),
datasets: [{
label: 'Assets value growth',
data: clientAssetSize.map(ca => ca.value),
borderWidth: 1,
backgroundColor: 'rgba(28,180,255,.05)',
borderColor: 'rgba(28,180,255,1)'
}]
}}
options={{
scales: {
xAxes: [{
gridLines: {
display: false
},
ticks: {
fontColor: '#aaa'
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
fontColor: '#aaa',
stepSize: 2000
}
}]
},
responsive: true,
maintainAspectRatio: false
}}
/>
</Card>
</Row>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
accessToken: state.user.accessToken,
user: state.user.user,
securities: state.models.securities,
clientAssetSize: state.user.clientAssetSize,
clientCumulativeReturn: state.user.clientCumulativeReturn,
clientAnnualVolume: state.user.clientAnnualVolume,
clientHoldings: state.user.clientHoldings,
});
const mapDispatchToProps = dispatch => ({
onGetUser: payload => dispatch(getUser(payload)),
onGetAllSecurities: payload => dispatch(getAllSecurities(payload)),
onGetClientAssetSize: payload => dispatch(getClientAssetSize(payload)),
onGetClientAnnualVolume: payload => dispatch(getClientAnnualVolume(payload)),
onGetClientCumulativeReturn: payload => dispatch(getClientCumulativeReturn(payload)),
onGetClientHoldings: payload => dispatch(getClientHoldings(payload)),
onLogoutUser: payload => dispatch(logoutUser(payload)),
onSetAccount: payload => dispatch(setAccount(payload)),
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(ClientPage);
|
/**
* 申请售后 退款等待审核
*/
import React, { Component, PureComponent } from "react";
import {
StyleSheet,
Dimensions,
View,
Text,
Image,
ScrollView,
TouchableOpacity,
BackHandler,
} from "react-native";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import actions from "../../action/actions";
import * as requestApi from '../../config/requestApi'
import CountDown from '../../components/CountDown';
import moment from 'moment'
import math from "../../config/math";
import Header from "../../components/Header";
import CommonStyles from "../../common/Styles";
import { getPreviewImage, keepTwoDecimalFull } from "../../config/utils";
const { width, height } = Dimensions.get("window");
class SOMRefundMoneyScreen extends Component {
static navigationOptions = {
header: null
};
timer = null;
_didFocusSubscription;
_willBlurSubscription;
constructor(props) {
super(props);
this._didFocusSubscription = props.navigation.addListener('willFocus', payload =>{
this.getNavigaionParam();
BackHandler.addEventListener('hardwareBackPress', this.handleBackPress)
});
this.state = {
detail: {
goodsInfo: [{
refundCount:0,
}],
refundAmount: 0,
refundReason: ''
},
isGetData: false, // 防止闪百
isRefused: false,
countDown: '提交',
}
}
handleCountDown = (dealline) => {
let time = moment(dealline).diff(moment());
this.timer = setInterval(() => {
let t = null;
let d = null;
let h = null;
let m = null;
let s = null;
//js默认时间戳为毫秒,需要转化成秒
t = time / 1000;
d = Math.floor(t / (24 * 3600));
h = Math.floor((t - 24 * 3600 * d) / 3600);
m = Math.floor((t - 24 * 3600 * d - h * 3600) / 60);
s = Math.floor((t - 24 * 3600 * d - h * 3600 - m * 60));
time -= 1000;
if (time < 0) {
this.setState({
showSubmit: true,
countDown: '提交'
}, () => {
clearInterval(this.timer)
})
return
}
this.setState({
countDown: d + ((d === 0) ? '' : '天') + h + ((h === 0) ? '' : '小时') + m + '分钟' + s + '秒'
})
Loading.hide();
}, 1000)
}
componentDidMount() {
Loading.hide();
this._willBlurSubscription = this.props.navigation.addListener('willBlur', payload =>
BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress)
);
}
getNavigaionParam = () => {
Loading.show();
let refundId = this.props.navigation.getParam('refundId', '')
requestApi.mallOrderRefundDetail({
refundId,
}).then(res => {
// res.goodsInfo[0].refundCount = 2
let isRefused = false
// 如果进入平台退款流程
if (res.refundStatus === 'PRE_REFUND' || res.refundStatus === 'REFUNDING' || res.refundStatus === 'COMPLETE') {
this.props.navigation.navigate('SOMRefundProcess', { refundId: refundId, routerIn: 'SOMRefundMoney' })
} else if (res.refundStatus === 'APPLY') { // 如果是审核状态
this.handleCountDown(moment(res.refundTime * 1000).add(res.refundAutoAcceptTime, 's'))
} else { // 如果平台拒绝
isRefused = true
}
this.setState({
detail: res,
isRefused,
isGetData: true, // 防止闪百
}, () => {
this.props.actions.setRefundAmount(res.goodsInfo, res)
})
}).catch(err => {
console.log(err)
})
}
componentWillUnmount() {
this.timer && clearInterval(this.timer);
this._didFocusSubscription && this._didFocusSubscription.remove();
this._willBlurSubscription && this._willBlurSubscription.remove();
}
// 处理物理返回。返回到订单列表
handleBackPress = () => {
const { navigation } = this.props
let callback = navigation.getParam('callback', () => { })
let routerIn = navigation.getParam('routerIn', () => { })
callback()
let isFocused = this.props.navigation.isFocused()
console.log('isFocused', isFocused)
if (isFocused) {
if (routerIn === 'details') {
navigation.goBack()
return true;
}
this.props.navigation.navigate("SOMOrder");
return true
}
BackHandler.removeEventListener('hardwareBackPress', this.handleBackPress)
return false
}
handleChangeState = (key = '', value = '') => {
this.setState({
[key]: value
})
}
handleRefundAgain = () => {
const { detail } = this.state
const { navigation } = this.props
let _detail = JSON.parse(JSON.stringify(detail))
if (_detail.goodsInfo[0].refundCount >= 2) {
Toast.show('超出申请次数限制,暂不能申请!')
return
}
_detail.goodsInfo.map(item => {
item['num'] = item.buyCount
item['price'] = item.realPrice
item['goodsShowAttr'] = item.goodsAttr
item['goodsPic'] = item.goodsPic
})
// navigation.navigate("SOMRefund", {
// orderInfo: _detail,
// afterSaleGoods: _detail.goodsInfo,
// callback: this.getNavigaionParam
// });
navigation.navigate('SOMAfterSaleCategory', {
afterSaleGoods: _detail.goodsInfo,
orderInfo:_detail,
callback: this.getNavigaionParam
})
}
getRefundPrice = (data) => {
let allPice = 0;
data.goodsInfo.map(item => {
allPice += math.divide (item.realPrice , 100)
})
allPice +=math.divide (data.postFee , 100)
return allPice
}
render() {
const { navigation, store } = this.props;
const { detail,countDown,isRefused,isGetData } = this.state
let callback = navigation.getParam('callback', () => { })
let routerIn = navigation.getParam('routerIn', '')
let refundId = this.props.navigation.getParam('refundId', '')
let refundAmount = (store.mallReducer.refundAmount || 0)
console.log('detail',detail)
console.log("sd",moment(detail.refundTime * 1000).add(detail.refundAutoAcceptTime,'s'))
return (
<View style={styles.container}>
<Header
navigation={navigation}
goBack={true}
title={"退款申请"}
leftView={
<View>
<TouchableOpacity
style={[styles.headerItem, styles.left]}
onPress={() => {
if (routerIn === 'details') {
navigation.goBack()
}
if (routerIn === 'refundMoney') {
navigation.navigate('SOMOrder');
if (callback) { callback() }
}
}}
>
<Image source={require('../../images/mall/goback.png')} />
</TouchableOpacity>
</View>
}
/>
{
isGetData
? <ScrollView
showsHorizontalScrollIndicator={false}
showsVerticalScrollIndicator={false}
>
<View style={styles.goodsWrpa}>
{
detail.goodsInfo.length > 0 && detail.goodsInfo.map((item, index) => {
let price =math.divide (item.goodsPrice || 0, 100);
let borderBottom = index === detail.goodsInfo.length - 1 ? {} : styles.borderBottom
return (
<View style={[styles.goodsItem, styles.flex_1, styles.flex_start_noCenter, borderBottom]} key={index}>
<View style={[styles.flex_1, styles.flex_start]}>
<View style={[styles.imgWrap, styles.flex_center]}>
<Image defaultSource={require('../../images/default/default_100.png')} source={{ uri: getPreviewImage(item.goodsPic, '50p') }} style={styles.imgStyle} />
</View>
<View style={[styles.flex_1, styles.goodsInfo]}>
<Text numberOfLines={2} style={styles.goodsTitle}>{item.goodsName}</Text>
<Text style={styles.goodsAttr}>{(item.goodsAttr && item.goodsAttr) ? `${item.goodsAttr} x ${item.buyCount}`: ''}</Text>
<View style={[styles.flex_1, styles.flex_start_noCenter,{ marginTop: 5 }]}>
<Text style={styles.goodsPriceLabel}>价格:</Text>
<Text style={styles.goodsPriceValue}>¥{price}</Text>
</View>
</View>
</View>
</View>
)
})
}
</View>
<View style={styles.selectWrap}>
<View style={[styles.categoryItem, styles.flex_1, styles.flex_between]}>
<View>
<Text style={styles.labelText}>退货原因: {detail.refundReason}</Text>
</View>
</View>
<View style={[styles.categoryItem, styles.flex_1, styles.flex_between, styles.topBorder]}>
<View style={styles.flex_start}>
<Text style={styles.labelText}>退款金额:</Text>
<Text style={[styles.labelText, styles.labelValue]}>¥{keepTwoDecimalFull(math.divide(refundAmount , 100))}</Text>
</View>
</View>
</View>
{
!isRefused
? <View style={{paddingLeft: 10,paddingBottom: 10}}>
<Text style={styles.noticeInfoText}>* 若卖家在规定时间内未处理,系统将自动为您退款</Text>
</View>
: <View style={{paddingLeft: 10,paddingBottom: 10}}>
<Text style={styles.noticeInfoText}>* 审核未通过 { (detail.goodsInfo[0].refundCount >= 2) ? ',如有疑问,请联系客服!': ''}</Text>
</View>
}
{
isRefused
? !(detail.goodsInfo[0].refundCount >= 2) ? // 拒绝了判断是否申请了两次
<TouchableOpacity
style={[styles.countDownWrap]}
onPress={() => {
Loading.show();
this.handleRefundAgain()
}}
>
<Text style={[styles.countDownText]}>再次申请</Text>
</TouchableOpacity>
: null
: (countDown !== '提交' && detail.refundAutoAcceptTime !== 0)
? // 没有被拒绝并且时间未到
<View style={styles.countDownWrap}>
<CountDown
date={moment(detail.refundTime * 1000).add(detail.refundAutoAcceptTime,'s')}
days={{ plural: ' ', singular: ' ' }}
hours=':'
mins=':'
segs=' '
type='orderApply'
label='等待卖家同意'
daysStyle={styles.countDownText}
hoursStyle={styles.countDownText}
minsStyle={styles.countDownText}
secsStyle={styles.countDownText}
firstColonStyle={styles.countDownText}
secondColonStyle={styles.countDownText}
onEnd={() => {
console.log('时间到')
// navigation.navigate('SOMRefundProcess', { refundId: refundId })
}}
/>
</View>
: <View style={styles.countDownWrap}>
<Text style={styles.countDownText}>等待卖家同意</Text>
</View>
}
</ScrollView>
: null
}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...CommonStyles.containerWithoutPadding
},
flex_center: {
justifyContent: 'center',
alignItems: 'center'
},
flex_start: {
justifyContent: 'flex-start',
flexDirection: 'row',
alignItems: 'center'
},
flex_start_noCenter: {
justifyContent: 'flex-start',
flexDirection: 'row',
},
flex_between: {
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center'
},
flex_1: {
flex: 1
},
goodsWrpa: {
borderRadius: 8,
backgroundColor: '#fff',
margin: 10,
borderWidth: 1,
borderColor: 'rgba(215,215,215,0.5)',
overflow: 'hidden',
// marginBottom: 60
},
goodsItem: {
padding: 15,
backgroundColor: '#fff',
},
selectedBtnWrap: {
marginRight: 10
},
unSelected: {
width: 15,
height: 15,
borderWidth: 1,
borderColor: '#979797',
borderRadius: 15,
},
goodsTitle: {
lineHeight: 17,
fontSize: 12,
color: '#222'
},
imgStyle: {
height: 69,
borderRadius: 6,
width: 69,
},
imgWrap: {
borderRadius: 6,
borderWidth: 1,
borderColor: '#E5E5E5',
backgroundColor: '#fff',
height: 69,
width: 69,
},
goodsInfo: {
paddingLeft: 10,
flex: 1
},
goodsAttr: {
fontSize: 10,
color: '#999',
marginTop: 5
},
goodsPriceLabel: {
fontSize: 10,
color: '#999',
},
goodsPriceValue: {
fontSize: 10,
color: '#101010',
paddingLeft: 7
},
selectWrap: {
margin: 10,
marginTop: 0,
borderRadius: 8,
backgroundColor: '#fff',
borderWidth: 1,
borderColor: 'rgba(215,215,215,0.5)',
},
categoryItem: {
padding: 15
},
labelText: {
fontSize: 14,
color: '#222',
},
labelSmallText: {
fontSize: 12,
color: '#777',
},
topBorder: {
borderTopColor: '#f1f1f1',
borderTopWidth: 1
},
selectReason: {
fontSize: 14,
color: '#999',
paddingRight: 4
},
labelValue: {
fontSize: 12,
color: '#222',
paddingLeft: 4
},
marginTop: {
marginTop: 5
},
borderBottom: {
borderBottomColor: '#f1f1f1',
borderBottomWidth: 1,
},
block: {
width,
height: 5,
backgroundColor: '#F1F1F1',
position: 'absolute',
top: 0,
left: 0
},
bottomBtn: {
margin: 10,
paddingVertical: 11,
backgroundColor: '#4A90FA',
borderRadius: 8
},
bottomBtnText: {
textAlign: 'center',
color: '#fff',
fontSize: 17
},
countDownText: {
fontSize: 17,
color: '#fff',
textAlign: 'center'
},
countDownWrap: {
marginHorizontal: 10,
marginBottom: 30,
borderRadius: 8,
backgroundColor: '#4A90FA',
height: 44,
justifyContent: 'center',
alignItems: 'center'
},
noticeInfoText: {
color: '#EE6161',
fontSize: 12,
},
headerItem: {
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
height: '100%',
// position: 'absolute'
},
left: {
width: 50
},
});
export default connect(
state => ({ store: state }),
dispatch => ({ actions: bindActionCreators(actions, dispatch) })
)(SOMRefundMoneyScreen);
|
// http://henriquat.re/modularizing-angularjs/modularizing-angular-applications/modularizing-angular-applications.html
// http://henriquat.re/
// https://www.safaribooksonline.com/blog/2014/03/27/13-step-guide-angularjs-modularization/
'use strict'
var angular = require('angular');
require('angular-route');
var app = angular.module('noteshareApp', ['ui.router', 'ngStorage', 'environment',
'ngFileUpload', , 'ui.bootstrap', 'ngAnimate',
'cfp.hotkeys', 'angular-confirm']).
config(function(envServiceProvider) {
// set the domains and variables for each environment
envServiceProvider.config({
domains: {
development: ['localhost', 'dev.local'],
production: ['herokuapp.com', 'herokuapp.com', "manuscripta.herokuapp.com"]
// anotherStage: ['domain1', 'domain2'],
// anotherStage: ['domain1', 'domain2']
},
vars: {
development: {
apiUrl: "http://jxxmbp.local:2300/v1",
clientUrl: "http://jxxmbp.local:3000"
// antoherCustomVar: 'lorem',
// antoherCustomVar: 'ipsum'
},
production: {
apiUrl: "http://xdoc-api.herokuapp.com/v1",
clientUrl: "http://manuscripta.herokuapp.com"
// antoherCustomVar: 'lorem',
// antoherCustomVar: 'ipsum'
}
// anotherStage: {
// customVar: 'lorem',
// customVar: 'ipsum'
// }
}
});
// run the environment check, so the comprobation is made
// before controllers and services are built
envServiceProvider.check();
});
angular.module('filters-module', [])
.filter('trustAsResourceUrl', ['$sce', function($sce) {
return function(val) {
return $sce.trustAsResourceUrl(val);
};
}])
require('./topLevel')
require('./services')
require('./directives')
require('./user')
require('./documents')
require('./images')
require('./search')
require('./site')
require('./admin')
|
import gql from 'graphql-tag';
export const GET_SEASONS = gql `
{
baseseasons {
strSeason
}
}
`;
export const GET_SEASON = gql `
query Season($year: String!){
season(year: $year) {
events {
strEvent
strHomeTeam
strAwayTeam
intHomeScore
intAwayScore
dateEvent
}
}
}
`;
|
import AdminService from "./../../../../services/Admin.Service";
import lodash from "lodash";
import ToastifyMessage from "./../../../../utilities/ToastifyMessage";
import history from "./../../../../history";
import { useEffect, useState } from "react";
import { Modal } from "react-responsive-modal";
import "react-responsive-modal/styles.css";
import ProfileChiTietKhachHang from "./ProfileChiTietKhachHang";
import React from "react";
function QuanLyKhachHang(props) {
const [khachHang, setKhachHang] = useState([]);
//const [data, setData] = useState([]);
//const [showCreateModal,hideCreateModal]= useModal()
const [open, setOpen] = useState(false);
//const onOpenModal = () => setOpen(true);
//const onCloseModal = () => setOpen(false);
const [openChiTiet, setOpenChiTiet] = useState(false);
const [selectSoDienThoai, setSelectSoDienThoai] = useState("");
const onOpenModalChiTiet = (SoDienThoai) => {
console.log(SoDienThoai);
setOpenChiTiet(true);
setSelectSoDienThoai(SoDienThoai);
};
const onCloseModalChiTiet = () => setOpenChiTiet(false);
useEffect(() => {
AdminService.GetKhachHang().then((response) => {
console.log(response);
setKhachHang(response.data.data);
});
}, []);
const TimKiemKhachHang=()=>{
let txtSoDienThoai= document.getElementById("txtSoDienThoaiTimKiem").value
if (!lodash.isEmpty(txtSoDienThoai.trim())){
AdminService.GetKhachHangBySDT(txtSoDienThoai).then((res)=>{
if (!res.data.data){
ToastifyMessage.ToastError("Không tìm thấy số điện thoại này")
} else{
setKhachHang([res.data.data])
}
})
}
if (lodash.isEmpty(txtSoDienThoai)){
AdminService.GetKhachHang().then((response) => {
console.log(response);
setKhachHang(response.data.data);
});
}
}
return (
<div className="flex justify-center pt-8">
<div>
<div>
<input
className="ml-96 border border-4 mb-2 px-3 py-1.5 mr-2"
type="text"
id="txtSoDienThoaiTimKiem"
placeholder="Tim bang so dien thoai"
//defaultValue={result}
/>
<button
onClick={TimKiemKhachHang}
className="bg-blue-300 text-white py-1 px-3 rounded-sm text-xl mb-2"
>
Tìm kiếm
</button>
</div>
<table className="border-collapse border border-green-800 shadow-lg bg-white ml-10">
<thead className="table-header-group">
<tr className="bg-blue-100 border text-left px-8 py-4">
<th className="w-1/8 bg-blue-100 border text-left px-8 py-4">
STT
</th>
<th className="w-1/8 bg-blue-100 border text-left px-8 py-4">
Họ tên
</th>
<th className="w-1/8 bg-blue-100 border text-left px-8 py-4">
Số điện thoại
</th>
<th className="w-1/8 bg-blue-100 border px-8 py-4 text-center">
Email
</th>
<th className="w-1/8 bg-blue-100 border text-left px-8 py-4"></th>
<th className="w-1/8 bg-blue-100 border text-left px-8 py-4">
Hoạt động
</th>
</tr>
</thead>
<tbody>
{khachHang.map(function (item, index) {
return (
<tr key={index} className="bg-white border px-8 py-4 text-center">
<td>{index + 1}</td>
<td>{item.HoTen}</td>
<td>{item.SoDienThoai}</td>
<td>{item.email}</td>
<td>
<button
className="underline text-blue-400"
onClick={onOpenModalChiTiet.bind(null, item.SoDienThoai)}
>
Chi tiết
</button>
</td>
</tr>
);
})}
</tbody>
</table>
<div></div>
<React.Fragment>
<Modal open={openChiTiet} onClose={onCloseModalChiTiet} center>
<ProfileChiTietKhachHang
SoDienThoai={selectSoDienThoai}
></ProfileChiTietKhachHang>
</Modal>
</React.Fragment>
</div>
</div>
);
}
export default QuanLyKhachHang;
|
!function(d, $) {
var stub = {
entries: [{
title: 'title 1',
link: 'link 1',
author: 'author 1',
publishedDate: 'publishedDate 1',
categories: ['category 11', 'category 12']
}, {
title: 'title 2',
link: 'link 2',
author: 'author 2',
publishedDate: 'publishedDate 2',
categories: ['category 21', 'category 22']
}]
};
// Aggregate string array to string
Handlebars.registerHelper('categoriesFormat', function(categories) {
if (!categories || categories.length === 0) return '';
if (categories.length === 1) return categories[0];
return categories.reduce(function(a, b) {
return a + b + ', ';
}, '');
});
// Format author data
Handlebars.registerHelper('authorFormat', function(author) {
return author ? '- ' + author : '- Unknown author';
});
var
templateSource = $('#template').html(),
template = Handlebars.compile(templateSource),
html = '',
// Json url
url = '//ajax.googleapis.com/ajax/services/feed/load?v=1.0';
url += '&num=10&q=http://news.google.com/news?output=rss';
// Get json data from Google
$.ajax({
url: url,
type: 'GET',
// avoid having no CORS policy issues by using jsonp
dataType: 'jsonp',
success: function(result) {
data = result; // save to global var for debugging
// If download was success, then apply rendering
if (result.responseStatus === 200) {
html = template(result.responseData.feed);
} else {
html = template(stub);
}
},
error: function(result) {
html = template(stub);
console.log(result);
$('body').append('ERROR - ' + JSON.stringify(result));
},
complete: function() {
$('#rendered').append(html);
}
});
}(document, jQuery);
|
export const flowLeft = {name: 'flowLeft', precedence: 3, syntax: '__ <- __'}
export const flowRight = {name: 'flowRight', precedence: 4, syntax: '__ -> __'}
export default {flowLeft, flowRight}
|
module.exports = require('glagol')(
require('path').resolve(__dirname, 'tasks'),
{ formats: { null: require('./parse.js') }});
|
import { STATES as S } from '../constants';
import deepFreeze from 'deep-freeze';
const dict = [];
dict['l^'] = [];
dict['l>'] = [];
dict['lv'] = [];
dict['l<'] = [];
let state = S.tf;
let act = 'l^';
dict[act][S.tf] = { state: '', ui: '' };
dict[act][S.tr] = { state: '', ui: '' };
act = 'l>';
dict[act][S.tf] = { state: S.tl, ui: 'y' };
dict[act][S.tl] = { state: S.tb, ui: 'y' };
dict[act][S.tb] = { state: S.tr, ui: 'y' };
dict[act][S.tr] = { state: S.tf, ui: 'y' };
act = 'l<';
dict[act][S.tf] = { state: S.tr, ui: '-y' };
dict[act][S.tr] = { state: S.tb, ui: '-y' };
dict[act][S.tb] = { state: S.tl, ui: '-y' };
dict[act][S.tl] = { state: S.tf, ui: '-y' };
act = 'lv';
dict[act][S.tf] = { state: '', ui: '' };
deepFreeze(dict);
export { dict as dictLeftAction };
|
var searchData=
[
['callmanually',['CallManually',['../class_object_pool.html#ad94dc76a38c1ce6273fe9a25590e2e7aad72789e168d08643de0b38c7f868303a',1,'ObjectPool']]]
];
|
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { Link } from "react-router-dom";
import Icon from "../components/Icon";
import GoogleMap from "../components/GoogleMap";
import { editByidUserMsg } from "../action/authAction";
import { v4 as uuidv4 } from "uuid";
const Contact = () => {
const dispatch = useDispatch();
const [msg, setMsg] = useState({ email: "", message: "", id: uuidv4() });
const handleChange = (e) => {
setMsg({ ...msg, [e.target.id]: e.target.value });
};
const handleSubmit = (e) => {
e.preventDefault();
dispatch(editByidUserMsg("601b15469986e23024e94219", msg));
setMsg({ email: "", message: "", id: uuidv4() });
alert("message envoyé");
};
return (
<div className="jumbotron">
<h1
className="font-weight-bold mx-auto text-center "
style={{ width: "400px" }}
>
<Link to="/" className="text-decoration-none">
FootStars <Icon />
</Link>
</h1>
<div className=" d-flex flex-wrap justify-content-center vh-100 ">
<form
onSubmit={handleSubmit}
className=" shadow-lg border p-4 m-3 h-75 alert-warning "
style={{ width: "400px" }}
>
<h5>
Envoyez nous un message{" "}
<i class="fas fa-comment-dots text-info"></i>
</h5>
<p style={{ fontSize: "12px", color: "green" }}>
*On Vous répondra le plus tôt possible
</p>
<hr />
<div className="form-group">
<label htmlFor="logTel">Votre Email SVP</label>
<input
style={{ width: "360px", height: "50px" }}
className=" form-control"
type="email"
id="email"
value={msg.email}
placeholder="ex: user@gmail.com"
onChange={handleChange}
required
/>
</div>
<div className="form-group">
<label htmlFor="message">Votre message:</label>
<textarea
value={msg.message}
className="p-2"
style={{ width: "360px", height: "200px" }}
id="message"
placeholder="Taper votre message"
onChange={handleChange}
required
></textarea>
</div>
<button
type="submit"
className="btn btn-outline-info rounded-pill p-2 float-right"
>
Envoyer
</button>
</form>
<div
className="shadow-lg p-4 m-3 h-75 border alert-light"
style={{ width: "530px" }}
>
<p>
<i className="fas fa-map-marker-alt text-warning"></i> Adresse:
Sousse, Aidi Bou Ali, code postale 4045
</p>
<p>
<i class="fas fa-envelope-open-text text-success"></i> Email:
footstars@gmail.com
</p>
<p>
<i className="fas fa-mobile-alt text-danger"></i> Phone: +216 73 698
254 / +216 54 332 335
</p>
<GoogleMap />
</div>
</div>
</div>
);
};
export default Contact;
////wawawawaawa
|
'use strict';
export default function EditTodoController($scope, todoService, categoryService, $state) {
'ngInject';
$scope.categories = categoryService.getCategories();
$scope.newTodo = {
name: '',
deadline: '',
category: '',
isDone: false
};
$scope.addTodo = function () {
todoService.tasks.push($scope.newTodo);
$scope.newTodo = {
name: '',
deadline: '',
category: '',
isDone: false
};
$state.go('tasks.all');
};
}
|
import React from 'react'
import App from './App'
import Todo from './Todo.js'
export default class Todolist extends React.Component {
state = {
todos:[],
todoshow:"all"
};
addTodo = (todo) => {
this.setState({
todos: [ todo, ...this.state.todos]
});
};
togglecomplete = (id) => {
this.setState({
todos : this.state.todos.map(todo => {
if(todo.id === id){
return{
...todo,
complete: !todo.complete
} ;
}else{
return todo;
}
})
})
}
render(){
let todos=[];
if(this.state.todoshow === "all"){
todos =this.state.todos;
}else if ( this.state.todoshow === "active" ) {
todos =this.state.todoshow.filter(todo => !todo.complete);
}
else if ( this.state.todoshow === "complete " ) {
todos =this.state.todoshow.filter(todo => todo.complete);
}
return (
<div>
<App onSubmit={this.addTodo}/>
{this.state.todos.map(todo => (
<Todo key={todo.id} togglecomplete={() =>
this.togglecomplete(todo.id)
}
todo={todo}
/>
))}
<div> todoleft: {
this.state.todos.filter(todo =>
!todo.complete ).length }
</div>
<div>
<button>all</button>
<button>active</button>
<button>complete</button>
</div>
</div>
);
}
}
|
var express = require("express");
var router_upload = require("./process_upload");
var router_file = require("./file_manage");
var router_get = require("./process_get");
var router_db = require("./db_get");
var app = express();
app.use("/upload", router_upload);
app.use("/", router_file);
app.use("/get", router_get);
app.use("/dbget", router_db.router_db_get);
var server = app.listen(3000, function() {
var host = server.address().address;
var port = server.address().port;
console.log("application instance http://%s:%s", host, port);
});
|
import React, { Component } from 'react'
import { connect } from 'react-redux'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import { withTheme } from '@material-ui/core/styles'
import { injectIntl, intlShape } from 'react-intl'
import { Activity } from 'rmw-shell'
import { setDialogIsOpen } from 'rmw-shell/lib/store/dialogs/actions'
import List from '@material-ui/core/List'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction'
import Divider from '@material-ui/core/Divider'
import Icon from '@material-ui/core/Icon'
import IconButton from '@material-ui/core/IconButton'
import TextField from '@material-ui/core/TextField'
import Avatar from '@material-ui/core/Avatar'
import { withRouter } from 'react-router-dom'
import Button from '@material-ui/core/Button'
import Dialog from '@material-ui/core/Dialog'
import DialogActions from '@material-ui/core/DialogActions'
import DialogContent from '@material-ui/core/DialogContent'
import DialogContentText from '@material-ui/core/DialogContentText'
import DialogTitle from '@material-ui/core/DialogTitle'
import { withFirebase } from 'firekit-provider'
import green from '@material-ui/core/colors/green'
import Scrollbar from 'rmw-shell/lib/components/Scrollbar'
import withWidth from '@material-ui/core/withWidth'
import moment from 'moment'
import { Card, CardBody, Row, Col } from 'reactstrap'
import '../../assets/paper-dashboard.css'
class Tasks extends Component {
constructor(props) {
super(props)
this.name = null
this.listEnd = null
this.new_task_title = null
this.state = { value: '' }
}
scrollToBottom = () => {
const node = ReactDOM.findDOMNode(this.listEnd)
if (node) {
node.scrollIntoView({ behavior: 'smooth' })
}
}
componentDidUpdate(prevProps, prevState) {
this.scrollToBottom()
}
componentDidMount() {
const { watchList, firebaseApp } = this.props
let tasksRef = firebaseApp
.database()
.ref('public_tasks')
.orderByKey()
.limitToLast(20)
watchList(tasksRef)
this.scrollToBottom()
}
handleKeyDown = (event, onSucces) => {
if (event.keyCode === 13) {
onSucces()
}
}
handleAddTask = () => {
const { auth, firebaseApp } = this.props
const newTask = {
title: this.state.value,
created: moment.now(),
userName: auth.displayName,
userPhotoURL: auth.photoURL,
userId: auth.uid,
completed: false
}
if (this.state.value.length > 0) {
firebaseApp
.database()
.ref('public_tasks')
.push(newTask)
.then(() => {
this.setState({ value: '' })
})
}
}
handleUpdateTask = (key, task) => {
const { firebaseApp } = this.props
firebaseApp
.database()
.ref(`public_tasks/${key}`)
.update(task)
}
userAvatar = (key, task) => {
if (task.completed) {
return (
<Avatar style={{ backgroundColor: green[500] }}>
{' '}
<Icon> done </Icon>{' '}
</Avatar>
)
}
return (
<div>
{task.userPhotoURL && <Avatar src={task.userPhotoURL} alt='person' />}
{!task.userPhotoURL && (
<Avatar>
{' '}
<Icon> person </Icon>{' '}
</Avatar>
)}
</div>
)
}
renderList(tasks) {
const { auth, intl, history, setDialogIsOpen } = this.props
if (tasks === undefined) {
return <div />
}
return tasks.map((row, i) => {
const task = row.val
const key = row.key
return (
<div key={key}>
<ListItem
id={key}
key={key}
onClick={
auth.uid === task.userId
? () => {
this.handleUpdateTask(key, {
...task,
completed: !task.completed
})
}
: undefined
}
>
{this.userAvatar(key, task)}
<ListItemText
primary={task.title}
secondary={`${task.userName} ${
task.created
? intl.formatRelative(new Date(task.created))
: undefined
}`}
/>
<ListItemSecondaryAction>
{task.userId === auth.uid ? (
<IconButton
color='primary'
onClick={
task.userId === auth.uid
? () => {
history.push(`/tasks/edit/${key}`)
}
: undefined
}
>
<Icon>{'edit'}</Icon>
</IconButton>
) : (
undefined
)}
{task.userId === auth.uid ? (
<IconButton
color='secondary'
//style={{ display: isWidthDown('md', width) ? 'none' : undefined }}
onClick={() => {
setDialogIsOpen('delete_task_from_list', key)
}}
>
<Icon>{'delete'}</Icon>
</IconButton>
) : (
undefined
)}
</ListItemSecondaryAction>
</ListItem>
<Divider inset={true} />
</div>
)
})
}
handleClose = () => {
const { setDialogIsOpen } = this.props
setDialogIsOpen('delete_task_from_list', undefined)
}
handleDelete = key => {
const { firebaseApp, dialogs, unwatchList, watchList } = this.props
unwatchList('public_tasks')
firebaseApp
.database()
.ref(`public_tasks/${dialogs.delete_task_from_list}`)
.remove()
let messagesRef = firebaseApp
.database()
.ref('public_tasks')
.orderByKey()
.limitToLast(20)
watchList(messagesRef)
this.handleClose()
}
render() {
const { intl, tasks, theme, dialogs } = this.props
let styles = { backgroundColor: theme.palette.background.paper }
return (
<Activity
isLoading={tasks === undefined}
containerStyle={{ overflow: 'hidden' }}
title={intl.formatMessage({ id: 'tasks' })}
>
<Scrollbar>
<div className={'main-panel'}>
<div className='content'>
<Row>
<Col xs={12} sm={12} md={12} lg={12}>
<Card className='card-stats' style={styles}>
<CardBody>
<div style={{ overflow: 'none', paddingBottom: 56 }}>
<List
id='test'
style={{ height: '100%' }}
ref={field => {
this.list = field
}}
>
{this.renderList(tasks)}
</List>
<div
style={{ float: 'left', clear: 'both' }}
ref={el => {
this.listEnd = el
}}
/>
</div>
</CardBody>
</Card>
</Col>
</Row>
{tasks && (
<Row>
<Col xs={12} sm={12} md={12} lg={12}>
<Card className='card-stats' style={styles}>
<CardBody>
<div
style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 15
}}
>
<TextField
id='public_task'
fullWidth={true}
value={this.state.value}
onKeyDown={event => {
this.handleKeyDown(event, this.handleAddTask)
}}
onChange={e =>
this.setState({ value: e.target.value })
}
type='Text'
/>
<IconButton
disabled={this.state.value === ''}
onClick={this.handleAddTask}
>
<Icon
className='material-icons'
color={theme.palette.primary1Color}
>
send
</Icon>
</IconButton>
</div>
</CardBody>
</Card>
</Col>
</Row>
)}
</div>
</div>
</Scrollbar>
<Dialog
open={dialogs.delete_task_from_list !== undefined}
onClose={this.handleClose}
aria-labelledby='alert-dialog-title'
aria-describedby='alert-dialog-description'
>
<DialogTitle id='alert-dialog-title'>
{intl.formatMessage({ id: 'delete_task_title' })}
</DialogTitle>
<DialogContent>
<DialogContentText id='alert-dialog-description'>
{intl.formatMessage({ id: 'delete_task_message' })}
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose} color='primary'>
{intl.formatMessage({ id: 'cancel' })}
</Button>
<Button onClick={this.handleDelete} color='secondary'>
{intl.formatMessage({ id: 'delete' })}
</Button>
</DialogActions>
</Dialog>
</Activity>
)
}
}
Tasks.propTypes = {
intl: intlShape.isRequired,
theme: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired
}
const mapStateToProps = state => {
const { lists, auth, dialogs } = state
return {
tasks: lists.public_tasks,
auth,
dialogs
}
}
export default connect(
mapStateToProps,
{ setDialogIsOpen }
)(injectIntl(withWidth()(withTheme()(withRouter(withFirebase(Tasks))))))
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
const fileUpload = require('express-fileupload');
const Jimp = require('jimp');
const mv = require('mv');
const fs = require('fs');
var showdown = require('showdown');
var converter = new showdown.Converter();
const xoffset = 4368
const yoffset = 5460
var wikitemplate = fs.readFileSync('wiki.html',{ encoding: 'utf8' });
var app = express();
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(fileUpload());
app.post('/upload', function(req, res) {
if (!req.files)
return res.status(400).send('No files were uploaded.');
// The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
let sampleFile = req.files.sampleFile;
// Use the mv() method to place the file somewhere on your server
sampleFile.mv('temp.jpg', function(err) {
if (err)
return res.status(500).send(err);
Jimp.read("temp.jpg", function(err, lenna) {
if (err) throw err;
x = parseInt(req.body.x) + xoffset
y = parseInt(req.body.y) + yoffset
Jimp.loadFont(Jimp.FONT_SANS_32_BLACK).then(function(font) {
mv('public/img/' + x + "-" + y + ".jpg", 'backup/' + new Date().getTime() + '-' + x + "-" + y + ".jpg", function(err) {
lenna.print(font, 10, 10, req.body.x + "," + req.body.y);
lenna.print(font, 800, 730, req.body.name);
lenna.crop(0, 0, 960, 768) // resize
.write('public/img/' + x + "-" + y + ".jpg"); // save
res.redirect('/upload.html');
});
}).catch(function(err) {
if (err) throw err;
});
});
});
})
app.get('/wiki/', function(req, res,next) {
fs.readdir(__dirname+'/wiki/', function(err, files) {
if (err) return;
console.log(files);
var output = ''
files.forEach(function(f) {
output += '<a href="/wiki/'+f+'">'+f+'</a><br>'
});
res.send(wikitemplate.replace('{{wiki}}',output));
});
})
app.get('/wiki/:dir', function(req, res,next) {
fs.readdir(__dirname+'/wiki/'+req.params.dir, function(err, files) {
if (err) return;
console.log(files);
var output = ''
files.forEach(function(f) {
output += '<a href="./'+req.params.dir +'/'+f+'">'+f+'</a><br>'
});
res.send(wikitemplate.replace('{{wiki}}',output));
});
})
app.get('/wiki/:dir/:file', function(req, res,next) {
console.log(req.params);
var path = __dirname + '/wiki/'+req.params.dir + '/' + req.params.file;
fs.readFile(path, 'utf8', function(err, data) {
if(err ) {
res.send(err);
}else{
var html = converter.makeHtml(data.toString())
var output = wikitemplate.replace('{{wiki}}',html)
output = output.replace('{{title}}',req.params.file)
res.send(output);
}
});
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// render the error page
res.status(err.status || 500);
res.send(err);
});
app.listen(3000, () => console.log('Example app listening on port 3000!'))
module.exports = app;
|
window.onload = function() {
var textbox = document.getElementById("InputTextBox").select();
}
|
/** @jsx React.DOM */
unit.def('Forum.View', function (app) {
var ThreadEntry = app.Thread.Entry;
var ThreadForm = app.Thread.Form;
return React.createClass({
displayName: 'Forum',
getInitialState: function () {
return {
threads: { data: [], ready: false }
};
},
componentWillMount: function () {
var self = this;
var model = this.props.model;
model.on('data.forum', function () {
self.setState(model.data());
});
this.refresh();
},
componentWillUnmount: function () {
var model = this.props.model;
model.off('data.forum');
},
refresh: function () {
var self = this;
var model = this.props.model;
this.setState(model.data());
model.threads().then(function (data) {
var threads = _.map(data, function (thread) {
return <ThreadEntry key={'thread'+thread.id()} model={thread} refreshListing={self.refresh} />;
});
self.setState({ threads: { data: threads, ready: true } });
});
},
render: function () {
var state = this.state;
var threadNodes;
if (this.state.threads.ready) {
threadNodes = _.map(this.state.threads.data, function (node) {
return <div><hr/>{node}</div>;
});
if (threadNodes.length === 0) {
threadNodes = <div className="empty-state">There are currently no threads.</div>;
}
}
else { // threads still loading
threadNodes = '';
}
// render template
return (
<div className="thread">
<h2>{state.title}</h2>
{threadNodes}
<ThreadForm forum={this.props.model} refreshListing={this.refresh} />
</div>
);
},
});
}).after([
'Thread.Entry',
'Thread.Form'
]);
|
"use strict";timer.renderTimeout(),timer.enableOrDisableControlButtons(),timer.setUserSettings();
|
import React, { useState, useEffect } from 'react'
import axios from 'axios'
import {Redirect} from 'react-router'
export default function OrderNew(props) {
// state of Order
const [order, setOrder] = useState({});
const [toNext, setToNext] = useState(false)
const handleChange = (e) => {
let name = e.target.name
let value = e.target.value
setOrder({ ...order, [name]: value })
}
const handleSubmit = (e) => {
e.preventDefault();
console.log(order)
axios.post('http://localhost:4000/api/v1/order/new',order)
.then((data) => {
console.log(data)
setToNext(true)
})
.catch(err => {
console.log(err.response)
})
}
return (
<div>
<form onSubmit={(e) => handleSubmit(e)}>
<h1>Create An Order</h1>
<label>Title</label>
<div><input
type='text'
placeholder="Enter a title of order "
name="title"
onChange={(e) => handleChange(e)}
/></div>
<label>DeviceType</label>
<br/>
<select name="deviceType" onChange={(e) => handleChange(e)}>
<option >Choose a device</option>
<option value="Computer">Computer</option>
<option value="Phone">Phone</option>
</select>
<br/>
<label>software Type</label>
<br/>
<select name="softwareType" onChange={(e) => handleChange(e)}>
<option >Choose a software</option>
<option value="IOS">IOS</option>
<option value="Android">Android </option>
<option value="IOS">MAC</option>
<option value="Android">Windows </option>
</select>
<br/>
<label>Description</label>
<div><input
type='text'
placeholder="Enter description of order "
name="description"
onChange={(e) => handleChange(e)}
/></div>
<label>Attachment</label>
<div><input
type='text'
placeholder="Upload Image or Video "
name="attachment"
onChange={(e) => handleChange(e)}
/></div>
<label>Phone Number</label>
<div><input
placeholder="Enter your Phone Number"
name="phoneNumber"
onChange={(e) => handleChange(e)}
/></div>
<button type="submit" > Submit </button>
</form>
{toNext ? <Redirect to="/Order" />: null}
</div>
)
}
|
var login = {
msg:$.trim($("#msg").val()),
bindEvent: function () {
var _this = this;
if(!!_this.msg){
_comment.showTips(_this.msg);
}
}
}
$(function () {
login.bindEvent();
});
|
/**
* Created by kras on 19.07.16.
*/
/* eslint global-require:off */
'use strict';
const clone = require('clone');
const { utils: { duration: parseDuration } } = require('@iondv/commons');
const session = require('express-session');
const storeAdapter = require('./connect-adapter');
const { t } = require('@iondv/i18n');
/**
* @param {{}} options
* @param {{}} options.session
* @param {{}} options.storage
* @param {{}} options.app
* @constructor
*/
function SessionHandler(options) {
if (!options || !options.storage) {
throw new Error(t('Settings for session storage are not specified.'));
}
const exclusions = [];
this.exclude = path => exclusions.push(path);
this.init = function () {
var sessOpts = clone(options.session || {});
if (sessOpts.cookie && sessOpts.cookie.maxAge) {
if (typeof sessOpts.cookie.maxAge === 'string') {
sessOpts.cookie.maxAge = parseDuration(sessOpts.cookie.maxAge, true);
}
}
return options.storage.dataSource.open()
.then(() => {
sessOpts.store = storeAdapter(session, options.storage.dataSource, options.storage.type, options.storage);
const smw = session(sessOpts);
if (options.app) {
options.app.use((req, res, next) => {
for (let i = 0; i < exclusions.length; i++) {
let tmp = exclusions[i];
if (tmp[0] !== '/') {
tmp = '/' + tmp;
}
tmp = '^' + tmp.replace(/\*\*/g, '.*').replace(/\\/g, '\\\\').replace(/\//g, '\\/') + '$';
if (new RegExp(tmp).test(req.path)) {
return next();
}
}
smw(req, res, next);
});
}
});
};
}
module.exports = SessionHandler;
|
/**
* @file
* Syntax check PHP files.
*/
/* eslint-env node */
/* eslint no-console:0 */
'use strict';
var gulp = require('gulp');
var phplint = require('phplint').lint;
var gutil = require('gulp-util');
gulp.task('phplint', function (cb) {
var extensions = '{php,module,inc,install,test,profile,theme}';
var sourcePatterns = [
'modules/**/*.' + extensions,
'themes/**/*.' + extensions,
'tests/behat/**/*.' + extensions,
'settings/**/*.' + extensions
];
var phpLintOptions = {
limit: 50
};
phplint(sourcePatterns, phpLintOptions, function (err, stdout, stderr) {
if (err) {
throw new gutil.PluginError({
plugin: 'phplint',
message: err
});
}
cb();
});
});
|
//Cargar tramites
function CargarTramites() {
var uriTramites = "http://40.85.92.66:1010/api/tramites?colaboradorId=" + localStorage.getItem("UserId");//Home
$.ajax({
type: "GET",
url: uriTramites,
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var concat = "";
if (msg.length > 0) {
for (var i = 0; i < msg.length; i++) {
//Novedades
var novedad = "";
for (var j = 0; j < msg[i].EstadosTramites.length; j++) {
if (msg[i].EstadosTramites[j].Novedad != null && msg[i].EstadosTramites[j].Novedad != "") {
novedad = msg[i].EstadosTramites[j].Novedad;
}
}
//Novedades
var fecha = msg[i].Priorizado ? "Priorizado" : msg[i].FechaString;
concat += "<div data-role='collapsible' id='set' data-collapsed='false'><h3>" + fecha + " - " + msg[i].LastEstado.Nombre + "</h3>";
concat += "<b>Estado: </b>" + msg[i].LastEstado.Nombre + "</br>";
concat += "<b>Fecha: </b>" + msg[i].FechaString + "</br>";
concat += "<b>Usuario: </b>" + msg[i].Usuario.Nombre + " " + msg[i].Usuario.Apellido + "</br>";
concat += "<b>Teléfono: </b>" + msg[i].Usuario.Celular + "</br>";
//Novedades
if (novedad != "") {
concat += "<b>Novedad: </b>" + novedad;
}
//Novedades
concat += "<hr />";
for (var j = 0; j < msg[i].DetalleTramites.length; j++) {
if (msg[i].DetalleTramites[j].Categoria.Id != 1) {
concat += "<b>Categoria: </b>" + msg[i].DetalleTramites[j].Categoria.Nombre + "</br>";
concat += "<b>Salida: </b>" + msg[i].DetalleTramites[j].Salida + "</br>";
//mapa salida
if (!(msg[i].DetalleTramites[j].LatitudSalida == '' || msg[i].DetalleTramites[j].LatitudSalida == null)) {
SetLocationIndex("salida" + i, j);
SetLocation("salida" + i, j, msg[i].DetalleTramites[j].LatitudSalida, msg[i].DetalleTramites[j].LongitudSalida);
concat += "<a href='#popupMap' class='ui-btn ui-icon-location' data-icon='location' data-rel='popup' data-shadow='false' data-iconshadow='false' data-position-to='window' data-transition='slidedown' style='-webkit-border-radius: .3125em; border-radius: .3125em;' onclick=\"SetLocationIndex('salida" + i + "'," + j + ");\">Ver mapa salida</a>"
}
concat += "<b>Llegada: </b>" + msg[i].DetalleTramites[j].Llegada + "</br>";
//mapa llegada
if (!(msg[i].DetalleTramites[j].LatitudLlegada == '' || msg[i].DetalleTramites[j].LatitudLlegada == null)) {
SetLocationIndex("llegada" + i, j);
SetLocation("llegada" + i, j, msg[i].DetalleTramites[j].LatitudLlegada, msg[i].DetalleTramites[j].LongitudLlegada);
concat += "<a href='#popupMap' class='ui-btn ui-icon-location' data-icon='location' data-rel='popup' data-shadow='false' data-iconshadow='false' data-position-to='window' data-transition='slidedown' style='-webkit-border-radius: .3125em; border-radius: .3125em;' onclick=\"SetLocationIndex('llegada" + i + "'," + j + ");\">Ver mapa llegada</a>"
}
concat += "<b>Descripción: </b>" + msg[i].DetalleTramites[j].Descripcion + "</br>";
concat += "<hr />";
}
}
if (msg[i].Comprobante == true) {
concat += "<b>Con Comprobante</b></br>";
concat += "<hr />";
}
concat += "<a href='#popupCambiarEstado' data-rel='popup' data-shadow='false' data-iconshadow='false' data-position-to='window' style='text-decoration: none;'><button type='button' data-icon='gear' data-iconpos='left' data-mini='false' data-inline='false' id='cambiarpass' onclick='SetTramiteId(" + msg[i].Id + ")'>Cambiar Estado</button></a>";
concat += "<a href='#popupTrasladar' data-rel='popup' data-shadow='false' data-iconshadow='false' data-position-to='window' style='text-decoration: none;'><button type='button' data-icon='forward' data-iconpos='left' data-mini='false' data-inline='false' id='cambiarpass' onclick='SetTramiteId(" + msg[i].Id + ")'>Trasladar</button></a>";
concat += "</div>";
}
}
else {
concat = "<center><h3>No se encontraron Trámites</h3></center>";
}
$("#set").html(concat).collapsibleset("refresh");
return false;
}
});
//Registra localización
navigator.geolocation.getCurrentPosition(onSuccess, onError);
}
function onSuccess(position) {
var localizacion = {
UsuarioId: localStorage.getItem("UserId"),
Longitud: position.coords.longitude,
Latitud: position.coords.latitude
};
var uriLocalizacionPost = "http://40.85.92.66:1010/api/Localizaciones";
$.ajax({
type: "POST",
data: JSON.stringify(localizacion),
url: uriLocalizacionPost,
contentType: "application/json"
});
}
function onError(error) {
//Mostrar algún mensaje de q no se ha podido registrar la localización
}
|
/**Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3 */
var isSymmetric = function(root) {
//if root is null, it is a mirror of itself
if (root === null) return true;
return rec(root.left, root.right);
};
function rec(left, right) {
//since this is binary tree if both null we have completed search
if (left === null && right === null) return true;
//if all true continue recursion
if (left && right && left.val === right.val)
return rec(left.left, right.right) && rec(left.right, right.left);
return false;
}
|
var searchData=
[
['write_5fcommand_5fbyte',['write_command_byte',['../group__keyboard.html#gab93137324dbf429632060d75313911ee',1,'write_command_byte(uint8_t cmd_byte): keyboard.c'],['../group__keyboard.html#gab93137324dbf429632060d75313911ee',1,'write_command_byte(uint8_t cmd_byte): keyboard.c']]]
];
|
const base64 = require("file-base64");
// const UploadController = require("../controllers/upload.controller.js");
const fs = require("fs");
const joinPath = require("path.join");
const dir = joinPath(__dirname, "../uploads/");
const Idea = require("../models/idea.model.js");
exports.downloadFile = async (ideaId, file) => {
const newDir = dir + ideaId + "/";
const filePath = newDir + file;
const fileExistCheck = "File Exist Check: " + fs.existsSync(filePath);
console.log(fileExistCheck);
let promise = new Promise((res, rej) => {
base64.encode(filePath, function(err, base64String) {
// console.log(base64String);
res(base64String);
if (err) {
rej("Error in base64: " + err);
}
});
});
const result = await promise;
// console.log(result, "result");
return result;
};
exports.deleteFile = async (ideaId, file) => {
console.log("Inside deleteFile...");
const newDir = dir + ideaId + "/";
const filePath = newDir + file;
const fileExistCheck = "File Exist Check: " + fs.existsSync(filePath);
console.log(fileExistCheck);
const data = await Idea.findById(ideaId)
.then(idea => {
if (!idea) {
return "Idea not found with id " + ideaId;
}
// console.log("idea.fileName: ", idea.fileName);
return idea.fileName;
})
.catch(err => {
if (err.kind === "ObjectId") {
return "Idea not found with id " + ideaId;
}
return "Error retrieving Idea with id " + ideaId;
});
const filtered = data.filter(function(value, index, arr) {
return value != file;
});
// console.log("filtered data: " + filtered);
let promise = new Promise((res, rej) => {
const ideaUpdate = {
fileName: filtered
};
Idea.findByIdAndUpdate(ideaId, ideaUpdate, { new: true })
.then(idea => {
if (!idea) {
rej("Idea not found with id status(404) " + ideaId);
}
try {
fs.unlinkSync(filePath);
// console.log("File deleted successfully.");
res("File deleted successfully !");
} catch (err) {
// handle the error
rej("Error occured while deleting file.");
}
})
.catch(err => {
if (err.kind === "ObjectId") {
// console.log("Idea not found with id status(404)");
return "Idea not found with id status(404)" + ideaId;
}
// console.log("Error updating Idea with id status(500)");
return "Error updating Idea with id status(500)" + ideaId;
});
});
const result = await promise;
// console.log(result, "result");
return result;
};
// if (fs.existsSync(filePath)) {
// console.log("inside existsSync...");
// let promise = new Promise((res, rej) => {
// base64.encode(filePath, function (err, base64String) {
// console.log(base64String);
// res(base64String);
// });
// // const files = [];
// // fs.readFile(filePath, function(err, data) {
// // if (err) throw err;
// // console.log(data, "<--data");
// // files.push(data);
// // console.log(files, "<--files");
// // res(files);
// // });
// });
|
var app = require('../app');
var supertest = require('supertest');
var request = supertest.agent(app); //supertest.(app); not recording cookie
var should = require('should');
testhp = function ( num, ans,done){
request.get('/fib').query({n: num})
.end(function(err,res){
res.text.should.equal(ans);
done(err);
});
};
testHp = function(info,num,ans){
it(info,function(done){
request.get('/fib').query({n: num})
.end(function(err,res){
res.text.should.equal(ans);
done(err);
});
});
}
describe('test/app.test.js',function(){
it('should return 55 when n is 10',function(done){
request.get('/fib').query({n: 10})
.end(function(err,res){
res.text.should.equal('55');
done(err);
});
});
it('should return 0 when n === 0',function(done){
testhp(0,'0',done);
});
testHp('should equal 1 when n === 1',1,'1');
testHp('should equal 55 when n === 10',10,'55');
testHp('should throw when n > 10',100,'n should <= 10');
testHp('should throw when n < 0',-1,'n should >= 0');
testHp('should throw when n is not Number', 'NonNumber','n should be a Number');
it('should return status 500 when error', function(done){
request.get('/fib').expect(500)
.end((err,res)=>{
done(err);
});
});
});
|
import PropTypes from "prop-types";
import { PureComponent } from "react";
import ListGroup from "react-bootstrap/ListGroup";
import ListGroupItem from "react-bootstrap/ListGroupItem";
import PanelWithTitle from "../../ui/components/PanelWithTitle";
export default class StepAttachments extends PureComponent {
static propTypes = {
scenarioId: PropTypes.string.isRequired,
attachments: PropTypes.array.isRequired
};
buildUrlForAttachment = (attachmentId) => {
const { scenarioId } = this.props;
return `/api/scenarii/${scenarioId}/attachments/${attachmentId}`;
};
render() {
const { attachments } = this.props;
const items = attachments.map((attachment, index) => {
return (
<ListGroupItem key={attachment.id}>
<a href={this.buildUrlForAttachment(attachment.id)} download>
Pièce-jointe #{index + 1}
</a>
</ListGroupItem>
);
});
return (
<PanelWithTitle title="Pièces jointes" className="mb-3">
<ListGroup variant="flush">{items}</ListGroup>
</PanelWithTitle>
);
}
}
|
var http = require("http");
var util = require("util");
var charts = require("./highchart-data.js");
var charts2 = require("./highchart-data-intraday.js");
var charts3 = require("./highchart-SG.js");
var db = require("./db.js");
charts.fetch_info();
charts2.fetch_info();
charts3.fetch_info();
var server = {}; //Server object. This object is use to stock everything owned by the server.
server.r = require("../nodejs/router.js"); server.port = 5000;
server.address = "127.0.0.1";
/**
* This method is called each times a request arrives on the server * @param req (Object) request object for this request
* @param resp (Object) response object for this request
*/
server.receive_request = function (req, resp) { server.r.router(req, resp);
};
http.createServer(server.receive_request).listen(server.port, "0.0.0.0");
util.log("INFO - Server started, listening " + server.address + ":" + server.port);
var prout = function(){
//util.log("okokookokokokookookokokokook");
db.check_all_cookies();
};
setInterval(prout,60000);
|
let fs=require("fs");
let f1kapromise=fs.promises.readFile("f1.txt");
f1kapromise.then(function(data)
{
console.log("I'm in f1 "+data);
let f2kapromise=fs.promises.readFile("f2.txt");
return f2kapromise;
})
.then(function(data)
{
console.log("I'm in f2 "+data);
let f3kapromise=fs.promises.readFile("f3.txt");
return f3kapromise;
})
.then(function(data)
{
console.log("I'm in f3 "+data);
})
|
var gulp = require('gulp');
var lr = require('gulp-livereload');
var jshint = require('gulp-jshint');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var paths = {
main: './index.js',
tests: './test/**/*.js',
lib: './lib/**/*.js'
};
paths.js = [paths.main, paths.tests, paths.lib];
gulp.task('lint', function(){
return gulp.src(paths.js)
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'));
});
var bundler = browserify(paths.main);
gulp.task('compile', function(){
return bundler.bundle({standalone: 'clumper'})
.pipe(source('clumper.js'))
.pipe(gulp.dest('./dist'))
.pipe(lr());
});
gulp.task('watch', function(){
gulp.watch(paths.js, ['lint']);
gulp.watch([paths.main, paths.lib], ['compile']);
gulp.watch(paths.tests, ['test']);
});
gulp.task('default', ['compile', 'watch']);
|
export const styles = theme => ({
participantSelect: {
position: 'absolute',
right: '0px',
horizontalAlign: 'right',
float: 'right',
},
participant: {
margin: '8px 0px',
height: '36px',
width: '100%',
borderBottom: `.75px solid ${theme.palette.common.lightGrey}`,
},
participantBar: {
width: '0.4rem',
height: '36px',
marginRight: '7%',
borderRadius: '16px',
},
});
export default styles;
|
const routeTitles = {
'/apps': 'apps',
'/apps/guides': 'Guides',
'/apps/reports': 'Reports',
'/apps/guide': 'Guide',
}
export const getRouteTitles = path =>
routeTitles[path]
|
var b,h,l1,l2;
h=prompt("Ingrese altura: ","6");
b=prompt("Ingrese base: ","6");
for(l1=0;l1<h;l1++)
{ for(l2=0;l2<b;l2++)
{
document.write("*");
}
document.write("<br>");
}
|
var MinerGame = MinerGame || {};
MinerGame.secrets = 0;
MinerGame.totalSecrets = 153;
MinerGame.startTime = MinerGame.startTime || 0;
MinerGame.totalTime = 0;
MinerGame.deaths = 0;
MinerGame.hardModeDeaths = 0;
// GAMEPLAY STATE //
MinerGame.playState = function(){};
MinerGame.playState.prototype = {
create: function() {
// fade camera in
this.game.camera.flash(0x000000, 250);
// play music
if (MinerGame.level === '6' && !MinerGame.drillEnabled) {
if (MinerGame.currentTrack) {
MinerGame.currentTrack.stop();
}
} else if (MinerGame.level === 'final' && MinerGame.newLevel) {
if (MinerGame.currentTrack) {
MinerGame.currentTrack.stop();
}
MinerGame.newLevel = false;
MinerGame.currentTrack = this.game.add.audio('final-level');
MinerGame.currentTrack.loopFull();
} else if (!MinerGame.currentTrack) {
var trackKey = 'field1';
if (MinerGame.hardMode) {
trackKey = 'hard-mode';
}
MinerGame.currentTrack = this.game.add.audio(trackKey);
MinerGame.currentTrack.volume -= .2;
MinerGame.currentTrack.loopFull();
}
// init sfx
this.playerDieSound = this.add.audio('player_die');
this.playerDieSound.volume -= .7;
this.portalSound = this.add.audio('start_game');
this.portalSound.volume -= .6;
this.secretSound = this.add.audio('secret');
this.secretSound.volume -= .85;
this.breakBlockSound = this.add.audio('dust');
this.breakBlockSound.volume -= .3;
this.springSound = this.add.audio('spring');
this.springSound.volume -= .5;
this.drillBurstSound = this.game.add.audio('drill-burst');
this.drillBurstSound.volume -= .65;
this.drillBurstSoundClock = 0;
this.powerupSound = this.game.add.audio('powerup');
this.powerupSound.volume -= 0.5;
this.blipSound = this.game.add.audio('blip');
this.blipSound.volume -= 0.6;
// init the tile map
this.map = this.game.add.tilemap(MinerGame.level);
if (MinerGame.hardMode) {
this.map.addTilesetImage('stageTiles', 'outside-tiles');
} else {
this.map.addTilesetImage('stageTiles', 'tiles');
}
// create tilemap layers
this.backgroundLayer = this.map.createLayer('backgroundLayer');
this.stageLayer = this.map.createLayer('stageLayer');
this.trapsLayer = this.map.createLayer('trapsLayer');
this.fragileLayer = this.map.createLayer('fragileLayer');
this.springLayer = this.map.createLayer('springLayer');
this.drillLayer = this.map.createLayer('drillLayer');
// set collisions on stageLayer, trapsLayer, fragileLayer and springLayer
this.map.setCollisionBetween(1, 2000, true, 'stageLayer');
this.map.setCollisionBetween(1, 2000, true, 'trapsLayer');
this.map.setCollisionBetween(1, 2000, true, 'fragileLayer');
this.map.setCollisionBetween(1, 2000, true, 'springLayer');
this.map.setCollisionBetween(1, 2000, true, 'drillLayer');
// resize game world to match layer dimensions
this.backgroundLayer.resizeWorld();
// create items on the stage
this.createPowerups(); // powerups
this.createPortal(); // end of level portal
this.createSecrets(); // collectibles
// actor/fx rendering layers
this.game.layers = {
player: this.game.add.group(),
foreground: this.game.add.group(),
effects: this.game.add.group(), // bullets and dust
ui: this.game.add.group()
};
// create block dust effects
this.blockDust = this.game.add.group();
this.game.layers.effects.add(this.blockDust); // add to rendering layer
var i;
for (i = 0; i < 250; i++) {
var dust = this.game.add.sprite(0, 0, 'block-dust');
dust.animations.add('burst');
dust.kill();
this.blockDust.add(dust);
}
// create drill burst effects
this.drillBurstGroup = this.game.add.group();
this.game.layers.effects.add(this.drillBurstGroup);
for (i = 0; i < 500; i++) {
var burst = this.game.add.sprite(0, 0, 'drill-particle');
this.game.physics.arcade.enable(burst);
// scale up
burst.scale.set(1.5);
burst.lifespan = 200;
burst.kill();
this.drillBurstGroup.add(burst);
}
// create crystal burst effects
this.crystalBurstGroup = this.game.add.group();
this.game.layers.effects.add(this.crystalBurstGroup);
for (i = 0; i < 500; i++) {
var shine = this.game.add.sprite(0, 0, 'secret-particle');
this.game.physics.arcade.enable(shine);
// scale up
// shine.scale.set(1.5);
shine.lifespan = 200;
shine.kill();
this.crystalBurstGroup.add(shine);
}
//create player
this.input = new MinerGame.Input(this.game);
var objects = this.findObjectsByType('playerStart', this.map, 'objectsLayer');
this.player = new MinerGame.Player(this.game, this.input, objects[0].x, objects[0].y);
// spawn robot if exists
var robots = this.findObjectsByType('robot', this.map, 'objectsLayer');
if (robots.length > 0) {
this.robot = this.game.add.sprite(robots[0].x, robots[0].y, 'robot');
this.robot.anchor.setTo(0.5, 0.5);
this.robot.animations.add('hover');
this.robot.animations.play('hover', 8, true);
this.game.physics.arcade.enable(this.robot);
this.robot.body.immovable = true;
} else {
this.robot = null;
}
//the camera will follow the player in the world
this.game.camera.follow(this.player);
// if outside, make clouds
var floatParticleKey = 'particle';
if (MinerGame.hardMode) {
this.clouds = this.game.add.tileSprite(0, 0, this.game.world.width, this.game.world.height, 'mist');
this.clouds.autoScroll(-8, 0);
this.game.layers.foreground.add(this.clouds);
floatParticleKey = 'cloud-particle';
}
// create floating lava/cloud particles
this.lavaParticles = this.game.add.emitter(this.game.world.centerX, this.game.world.height, 400);
this.lavaParticles.width = this.game.world.width;
this.lavaParticles.makeParticles(floatParticleKey);
this.lavaParticles.minParticleScale = 0.3;
this.lavaParticles.maxParticleScale = 1.2;
this.lavaParticles.alpha = 0.2;
this.lavaParticles.setYSpeed(-500, -325);
this.lavaParticles.gravity = 0;
this.lavaParticles.setXSpeed(-5, 5);
this.lavaParticles.minRotation = 0;
this.lavaParticles.maxRotation = 0;
this.lavaParticles.start(false, 2200, 5, 0);
this.game.layers.foreground.add(this.lavaParticles);
// make lava splash emitter (for player deaths)
this.lavaSplash = this.game.add.emitter(0, 0, 200);
this.lavaSplash.makeParticles('particle');
this.lavaSplash.minRotation = 0;
this.lavaSplash.maxRotation = 0;
this.lavaSplash.minParticleScale = 0.3;
this.lavaSplash.maxParticleScale = 1.5;
this.lavaSplash.setYSpeed(-280, -150);
this.lavaSplash.gravity = 500;
this.game.layers.foreground.add(this.lavaSplash);
// make the UI
// levels
this.levelText = this.game.add.bitmapText(this.game.camera.width / 2, 12, 'carrier_command', 'lv ' + MinerGame.level, 8);
this.levelText.anchor.setTo(0.5, 0);
// secrets %
var percentage = Math.floor(MinerGame.secrets / MinerGame.totalSecrets * 100).toString() + '%';
this.secretText = this.game.add.bitmapText(this.game.camera.width - 12, 30, 'carrier_command', 'Crystals: ' + percentage, 8);
this.secretText.anchor.x = 1;
if (MinerGame.hardMode) {
this.secretText.kill();
}
// timer
var time = Math.floor(this.game.time.totalElapsedSeconds() - MinerGame.startTime);
this.timerText = this.game.add.bitmapText(this.game.camera.width - 12, 12, 'carrier_command', 'time: ' + time, 8);
this.timerText.anchor.setTo(1, 0);
// keep HUD fixed to camera
this.game.layers.ui.add(this.levelText);
this.game.layers.ui.add(this.secretText);
this.game.layers.ui.add(this.timerText);
this.game.layers.ui.fixedToCamera = true;
// tutorial text
this.resetTutText();
this.skipBtn = this.game.input.keyboard.addKey(Phaser.Keyboard.SPACEBAR);
this.skipBtn.onDown.add(function() {
if (this.drawTutText) {
this.resetTutText();
}
}, this);
if (MinerGame.newLevel) {
MinerGame.newLevel = false;
if (MinerGame.level === '1') {
this.drawTutorialText(['WELCOME MINER!',
'My name is A5IM0V-pr1m3.', 'clearly, I am a robot.',
'I see that you are lost.',
'That was my doing...','You see, my plan is to\n\nlead you mindlessly from\n\nroom to room with those\n\ngreen portals until you\n\neither give up or die!', 'HAHAHAHAHA!!1!*!!!1!!\n\nso evil!!', '...', 'You *might* get out alive\n\nif you run with the arrow\n\nkeys and jump with \'x\'.', '...so fun...', 'Try not to die, you\n\nmiserable yellow\n\ncreature.', '<3']);
} else if (MinerGame.level === '1 hard') {
this.drawTutorialText(['Ugh! You disgust me, human.',
'But your tenacity is\n\nquite remarkable.', '...', 'I\'ve decided to keep\n\nyou as a pet!', 'A greasy, ugly,\n\nfascinating pet\n\nhuman.', 'Don\'t try to run\n\naway, biped.', 'You\'ll never make\n\nit out alive!!!1!', 'ahahahahaaha\n\nhahahahaheha\n\nshhnahf!!@!!\n\n@!@#!!#!', 'ha!']);
}
}
},
update: function() {
// stage collisions
this.game.physics.arcade.collide(this.player, this.stageLayer);
// traps collisions
this.game.physics.arcade.collide(this.player, this.trapsLayer, this.playerTrapHandler, null, this);
// collision with fragile blocks
this.game.physics.arcade.collide(this.player,
this.fragileLayer, this.playerFragileHandler, null, this);
// collision with spring blocks
this.game.physics.arcade.collide(this.player,
this.springLayer, this.playerSpringHandler, null, this);
// collision with drill blocks
this.game.physics.arcade.collide(this.player, this.drillLayer, this.drillBlockHandler, null, this);
// portal to next level
this.game.physics.arcade.collide(this.player, this.portals, this.playerPortalHandler, null, this);
// secret collectible
this.game.physics.arcade.overlap(this.player, this.secrets, this.playerSecretHandler, null, this);
// powerup
this.game.physics.arcade.overlap(this.player, this.powerups, this.playerPowerupHandler, null, this);
// robot
if (this.robot) {
this.game.physics.arcade.overlap(this.player, this.robot, this.playerRobotHandler, null, this);
}
// timer
this.updateTimerText();
// tutText
this.tutTextUpdate();
// shake death text
this.shakeText(this.tutText);
this.shakeText(this.skipText, this.game.world.centerX, this.game.height - 12);
}
// debugging
// render: function() {
// this.game.debug.body(this.player);
// }
};
// COLLISION HANDLERS //
MinerGame.playState.prototype.playerPortalHandler = function(player, portal) {
portal.body.velocity.x = 0;
portal.body.velocity.y = 0;
// flag to disable portalHandler (multiple portals)
if (this.transporting) {
return;
}
this.transporting = true;
// flag that the state is resetting because of a new level (for tut text)
MinerGame.newLevel = true;
// stop following player with camera
this.game.camera.unfollow();
// destroy player drill
player.drill.pendingDestroy = true;
// make green particles
this.drillBurst(portal.centerX, portal.centerY);
// destroy player and portal
portal.pendingDestroy = true;
player.pendingDestroy = true;
// save secrets collected
MinerGame.secrets += player.secrets;
// play warp sound
this.portalSound.play();
// add player warp sprite
var key = 'player-warp';
if (MinerGame.hardMode) {
key = 'player-speedo-warp';
}
var playerWarp = this.game.add.sprite(portal.centerX, portal.centerY, key);
playerWarp.anchor.setTo(0.5, 0.5);
playerWarp.animations.add('warp');
playerWarp.animations.play('warp', 25, false, true);
// start next level on warp animation end
playerWarp.events.onAnimationComplete.addOnce(function() {
this.game.camera.fade(0x000000, 100);
this.game.camera.onFadeComplete.addOnce(function() {
MinerGame.level = portal.targetTilemap;
this.lavaParticles = null;
this.lavaSplash = null;
this.transporting = false;
if (MinerGame.level === 'end') {
MinerGame.totalTime = Math.floor(this.game.time.totalElapsedSeconds() - MinerGame.startTime);
this.game.state.start('victory');
} else {
this.game.state.start(this.game.state.current);
}
}, this);
}, this);
};
MinerGame.playState.prototype.playerSecretHandler = function(player, secret) {
// crystal particles
this.crystalBurst(secret.centerX, secret.centerY);
// destroy secret
secret.pendingDestroy = true;
// increment secrets (saves at end of level, resets if player dies)
player.secrets++;
this.updateSecretText(MinerGame.secrets + player.secrets);
};
MinerGame.playState.prototype.playerTrapHandler = function(player, trap) {
// kill drill
player.drill.pendingDestroy = true;
//camera stops following player
this.game.camera.unfollow();
// player dies
player.pendingDestroy = true;
// increment death count
if (MinerGame.hardMode) {
MinerGame.hardModeDeaths++;
} else {
MinerGame.deaths++;
}
// shake camera
// this.startCameraShake();
// show some text, if not already showing any
if (!this.drawTutText) {
var text = '';
var rand = Math.random();
if (rand < 0.1) {
text = 'HAHAHAHA';
} else if (rand < 0.2) {
text = 'OUCHIE :[';
} else if (rand < 0.3) {
text = 'Try again T.T';
} else if (rand < 0.4){
text = 'You win! JK you died.';
} else if (rand < 0.5) {
text = '*burp*';
} else if (rand < 0.6) {
text = 'come on now :[';
} else if (rand < 0.7) {
text = 'What is... feeling?';
} else if (rand < 0.8) {
text = 'Juicy';
} else if (rand < 0.9) {
text = 'nice try, you got this <3';
} else {
text = 'You\'re breaking my <3';
}
this.deathText = this.game.add.bitmapText(this.game.camera.x + (this.game.camera.width / 2), this.game.camera.y + (this.game.camera.height / 2), 'carrier_command', text, 12);
this.deathText.anchor.setTo(0.5, 0.5);
}
// play death sound
this.playerDieSound.play();
// start lava splash
this.lavaSplash.x = player.x;
this.lavaSplash.y = player.bottom + 8;
this.lavaSplash.start(false, 5000, 20);
// shake the camera
this.game.camera.shake(0.004, 1200);
this.game.camera.onShakeComplete.addOnce(function() {
// restart level after camera shake
this.game.camera.fade(0x000000, 250);
this.game.camera.onFadeComplete.addOnce(function() {
this.game.state.start(this.game.state.current);
}, this);
}, this);
};
MinerGame.playState.prototype.playerFragileHandler = function(player, block) {
// block disappears after .25 seconds
this.game.time.events.add(250, function() {
// play block breaking sound
if (!this.breakBlockSound.isPlaying) {
this.breakBlockSound.play();
}
// make block dust
var dust = this.blockDust.getFirstDead();
dust.reset(block.worldX, block.worldY);
dust.animations.play('burst', 20, false, true);
// store block index so we can replace it later
var index = block.index;
this.map.removeTile(block.x, block.y, 'fragileLayer');
// replace block 1.5s after it disappears
this.game.time.events.add(1500, function() {
// make dust when block comes back
var dust = this.blockDust.getFirstDead();
dust.reset(block.worldX, block.worldY);
dust.animations.play('burst', 20, false, true);
// play dust sound again
if (!this.breakBlockSound.isPlaying) {
this.breakBlockSound.play();
}
// place the block
this.map.putTile(index, block.x, block.y, 'fragileLayer');
}, this);
}, this);
};
MinerGame.playState.prototype.drillBlockHandler = function(player, block) {
if(!player.drilling) {
return;
}
// recharge player's drill
player.drillCharge = player.maxDrillCharge;
// play breaking block sound
if (!this.breakBlockSound.isPlaying) {
this.breakBlockSound.play();
}
// make block dust
var dust = this.blockDust.getFirstDead();
dust.reset(block.worldX, block.worldY);
dust.animations.play('burst', 20, false, true);
// make drill particle effect
this.drillBurst(block.worldX + block.width / 2, block.worldY + block.height / 2);
// remove block
this.map.removeTile(block.x, block.y, 'drillLayer');
};
MinerGame.playState.prototype.playerSpringHandler = function(player, block) {
// player has to hit from the top of the block
if (player.bottom > block.top) {
return;
}
// player bounces high
player.body.velocity.y = -400;
player.spring = true; // disable player jump...
// play spring noise
if (!this.springSound.isPlaying) {
this.springSound.play();
}
};
MinerGame.playState.prototype.playerPowerupHandler = function(player, powerup) {
this.drillBurst(powerup.x, powerup.y);
powerup.pendingDestroy = true;
MinerGame.drillEnabled = true;
player.battery.revive();
// play powerup sound
this.powerupSound.play();
// change music
MinerGame.currentTrack = this.game.add.audio('field2');
MinerGame.currentTrack.volume -= .3;
MinerGame.currentTrack.loopFull();
// freeze player
this.player.paused = true;
// show drill tutorial
this.drawTutorialText(['wowee, You got the laser drill...', '>:[',
'I\'m so depresse--I mean happy\n\nyou made it this far.',
'OK, more advice.',
'Hold \'z\' to use the drill.\n\nBut be aware That it will \n\nrun out of charge if you\n\nuse it in air for too\n\nlong.',
'So touch the ground or drill\n\ngreen blocks to recharge it,\n\nand keep an eye on your\n\nbattery in the top-left, ok?',
'be careful! It has the\n\nworst battery invented...\n\nReally, though. It sucks.',
'...',
'>:D',
'So long, ugly humanoid!\n\nmay we never meet again!'
]);
};
MinerGame.playState.prototype.playerRobotHandler = function(player, robot) {
console.log('player robot collisions');
if (player.currentState != player.drillState) {
return;
}
MinerGame.hardModeTime = Math.floor(this.game.time.totalElapsedSeconds() - MinerGame.startTime);
this.game.state.start('finale');
};
// GAMEPLAY STATE UTILITIES //
/* map creation */
MinerGame.playState.prototype.findObjectsByType = function(type, map, layer) {
var result = new Array();
map.objects[layer].forEach(function(element){
if(element.type === type) {
//Phaser uses top left, Tiled bottom left so we have to adjust the y position
element.y -= map.tileHeight;
result.push(element);
}
});
return result;
};
MinerGame.playState.prototype.createFromTiledObject = function(element, group) {
var sprite = group.create(element.x, element.y, element.properties.sprite);
//copy all properties to the sprite
Object.keys(element.properties).forEach(function(key){
sprite[key] = element.properties[key];
});
// play animation
if (sprite.animated) {
sprite.animations.add('default');
sprite.animations.play('default', 10, true);
}
};
MinerGame.playState.prototype.createPowerups = function() {
// create items
if (MinerGame.drillEnabled) {
return;
}
this.powerups = this.game.add.group();
this.powerups.enableBody = true;
var result = this.findObjectsByType('powerup', this.map, 'objectsLayer');
result.forEach(function(element){
this.createFromTiledObject(element, this.powerups);
}, this);
};
MinerGame.playState.prototype.createPortal = function() {
// create end-of-level portal
this.portals = this.game.add.group();
this.portals.enableBody = true;
var result = this.findObjectsByType('portal', this.map, 'objectsLayer');
result.forEach(function(element){
this.createFromTiledObject(element, this.portals);
}, this);
};
MinerGame.playState.prototype.createSecrets = function() {
// create secret pickups for unlocking content
this.secrets = this.game.add.group();
this.secrets.enableBody = true;
var result = this.findObjectsByType('secret', this.map, 'objectsLayer');
result.forEach(function(element) {
this.createFromTiledObject(element, this.secrets);
}, this);
};
MinerGame.playState.prototype.updateSecretText = function(numSecrets) {
var percentage = Math.floor(numSecrets / MinerGame.totalSecrets * 100).toString() + '%';
// edge case
if (MinerGame.totalSecrets > numSecrets && percentage === '100%') {
percentage = '99%';
}
this.secretText.text = 'crystals: ' + percentage;
};
MinerGame.playState.prototype.updateTimerText = function() {
var time = Math.floor(this.game.time.totalElapsedSeconds() - MinerGame.startTime);
this.timerText.text = 'time: ' + time;
};
MinerGame.playState.prototype.drawTutorialText = function(lines) {
// pause player
this.player.currentState = this.player.pausedState;
// init tutorial text
this.tutText = this.game.add.bitmapText(this.game.camera.x + (this.game.camera.width / 2), this.game.camera.y + (this.game.camera.height / 2), 'carrier_command', '', 12);
this.tutText.anchor.setTo(0.5, 0.5);
// show skip text
this.skipText =
this.game.add.bitmapText(this.game.camera.x + (this.game.camera.width / 2),
this.game.camera.height - 12, 'carrier_command', 'press \'space\' to skip tutorial', 12);
this.skipText.anchor.setTo(0.5, 1);
// tutorial text vars and timers
this.charClock = 0;
this.charTimer = 0;
this.currCharIndex = 0;
this.lineClock = 0;
this.lineTimer = 0;
this.currLineIndex = 0;
this.lines = lines;
this.currLine = lines[0];
this.drawTutText = true; // flag for update loop
};
MinerGame.playState.prototype.tutTextUpdate = function() {
if (!this.drawTutText) {
return;
}
// increment by chars
this.charClock++;
// update every 3 frames
if (this.charClock > this.charTimer + 3 && !this.charsPaused) {
// advance to next char and reset timer
this.charTimer = this.charClock;
this.tutText.text += this.currLine[this.currCharIndex];
this.currCharIndex++;
this.blipSound.play();
}
// at the end of a line, pause reading chars and advance to next line
if (this.currCharIndex > this.currLine.length - 1) {
this.charsPaused = true;
// wait...
this.lineClock++;
if (this.lineClock > this.lineTimer + 80) { // 60 frames, 1 sec
this.currLineIndex++;
if (this.currLineIndex < this.lines.length) {
// reset timers, advance to next line, unpause char parsing
this.lineTimer = this.lineClock;
this.currLine = this.lines[this.currLineIndex];
this.charsPaused = false;
// reset tut text and char ind pointer
this.tutText.text = '';
this.currCharIndex = 0;
} else { // at end of lines, nothing more to read
this.resetTutText();
}
}
}
};
MinerGame.playState.prototype.resetTutText = function() {
if (this.tutText) {
this.tutText.pendingDestroy = true;
}
if (this.skipText) {
this.skipText.pendingDestroy = true;
}
this.player.currentState = this.player.groundState;
this.drawTutText = false;
this.charsPaused = false;
}
// shoot a radius of drill particles
MinerGame.playState.prototype.drillBurst = function(x, y) {
// play sound
if (this.game.time.time > this.drillBurstSoundClock + 50) {
this.drillBurstSound.play();
this.drillBurstSoundClock = this.game.time.time;
}
for (var i = 0; i < 8; i++) {
var part = this.drillBurstGroup.getFirstDead();
// revive and position
part.revive();
part.reset(x, y);
// shoot out
this.game.physics.arcade.velocityFromAngle(i*45, 300, part.body.velocity);
part.angle = i*45;
part.lifespan = 150;
}
};
MinerGame.playState.prototype.crystalBurst = function(x, y) {
// play sound
this.secretSound.play();
for (var i = 0; i < 8; i++) {
var part = this.crystalBurstGroup.getFirstDead();
// revive and position
part.revive();
part.reset(x, y);
// shoot out
this.game.physics.arcade.velocityFromAngle(i*45, 150, part.body.velocity);
part.angle = i*45;
part.lifespan = 50;
}
}
// update function for shaking text
MinerGame.playState.prototype.shakeText = function(text, x, y) {
if (text) {
var randX = Math.random();
var randY = Math.random();
if (this.game.time.time % 2) {
randX *= -1;
randY *= -1;
}
x = x || this.game.camera.x + (this.game.camera.width / 2);
y = y || this.game.camera.y + (this.game.camera.height / 2);
text.x = x + randX;
text.y = y + randY;
}
}
|
const TwingNodeExpressionConstant = require('../../../../../../../lib/twing/node/expression/constant').TwingNodeExpressionConstant;
const TwingTestMockCompiler = require('../../../../../../mock/compiler');
const TwingNodeExpressionUnaryNot = require('../../../../../../../lib/twing/node/expression/unary/not').TwingNodeExpressionUnaryNot;
const tap = require('tap');
tap.test('node/expression/unary/not', function (test) {
test.test('constructor', function (test) {
let expr = new TwingNodeExpressionConstant(1, 1);
let node = new TwingNodeExpressionUnaryNot(expr, 1);
test.same(node.getNode('node'), expr);
test.end();
});
test.test('compile', function (test) {
let compiler = new TwingTestMockCompiler();
let expr = new TwingNodeExpressionConstant(1, 1);
let node = new TwingNodeExpressionUnaryNot(expr, 1);
test.same(compiler.compile(node).getSource(), ' !1');
test.end();
});
test.end();
});
|
canvasSettings.downloadCanvas = function(link, canvasId, filename) {
//Downloads Image
link.href = document.getElementById(canvasId).toDataURL();
link.download = filename;
}
document.getElementById('download').addEventListener('click', function() {
canvasSettings.downloadCanvas(this, 'canvas-real', 'image.png');
}, false);
|
'use strict';
var mongoose = require('bluebird').promisifyAll(require('mongoose'));
var UserSchema = new mongoose.Schema({
nome: String,
email: String,
senha: String
});
export default mongoose.model('User', UserSchema);
|
import EpisodesList from "./components/header/episodes-list/EpisodesList";
import Header from "./components/header/Header";
function App() {
return (
<div className="App">
<Header/>
<main className="container mt-5">
<EpisodesList/>
</main>
</div>
);
}
export default App;
|
import React, { Component} from 'react';
import { Navbar, Nav, NavItem, NavLink, NavbarBrand } from 'reactstrap';
import { NavLink as TopNav, Link} from 'react-router-dom'
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux'
import * as sessionActions from '../actions/sessionActions'
import history from '../history'
class UserNavbar extends Component {
signOut = (event) => {
event.preventDefault()
this.props.actions.signOut()
history.push("/")
}
render() {
return(
<div>
<Navbar className="navbar navbar-expand-lg bg-dark" >
<NavbarBrand><Link to="#" onClick={(event) => this.signOut(event)}>Sign Out</Link></NavbarBrand>
<Nav navbar className="list-unstyled ml-auto" >
<NavItem>
<NavLink>
<TopNav to="/potlucks/new">New Potluck</TopNav>
</NavLink>
</NavItem>
<NavItem>
<NavLink>
<TopNav to="/potlucks">Your Potlucks</TopNav>
</NavLink>
</NavItem>
<NavItem>
<NavLink>
<TopNav to="/recipes/new">New Recipe</TopNav>
</NavLink>
</NavItem>
<NavItem>
<NavLink>
<TopNav to="/recipes">Your Recipes</TopNav>
</NavLink>
</NavItem>
<NavItem>
<NavLink>
<TopNav to="/friends">Friends</TopNav>
</NavLink>
</NavItem>
<NavItem>
<NavLink>
<TopNav to="/account">Account</TopNav>
</NavLink>
</NavItem>
</Nav>
</Navbar>
</div>
)}}
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(sessionActions, dispatch)
};
}
const mapStateToProps = (state) => {
return {
user: state
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UserNavbar)
|
/*
============================================
; Title: Discussion 3.1
; Author: Kimberly Pierce
; Date: 11 December 2019
; Modified By: Micah Connelly
; Description: Control statement with two errors
;===========================================
*/
var i = 1; //declare variable value to be used in loop
while (i < 11) { //condition for loop to continue
console.log(i + " " + "This loop will count to 10"); // the thing to do
//corrected console log: added missing "+" and ending quotation mark
i++; //increase var value by 1 each time
}
|
var _ = require('underscore')
var AV = require('leanengine');
var blc = require("broken-link-checker")
var mandrill = require('mandrill-api');
var mandrill_client = new mandrill.Mandrill('5-lEbzv4ZLUII78TutS5Yw');
var backupModule = function () {
};
var brokenlinkMsg="-1";
var checkbrokenlink1=function(checklinkarray,callback){
var html;
var htmlChecker;
var brokenlink=[];
var gcounter=-1;
var printOffset=10;
var i=1;
var totallink=checklinkarray.length;
if(gcounter==-2){
console.log("gcounter==-2 / msg:"+brokenlinkMsg);
}
else{
var temp = _(checklinkarray).map(function (value){return "<a href='"+value+"'></a>"});
html = temp.join();
htmlChecker = new blc.HtmlChecker({}, {
link: function(result) {
gcounter++;
if(result.broken){
brokenlinkMsg+=result.html.text+" is broken :"+result.url.resolved+"\n";
brokenlink.push(result.url.resolved);
// console.log(result.html.index, result.broken, result.html.text, result.url.resolved);
console.log(result.html.index, result.broken, result.html.text, result.url.resolved);
}
if(i%printOffset == 0){
i=1;
console.log(gcounter+" links have been checked . ......");
}else{
i++;
}
if(gcounter==totallink){
gcount =-2;
}
},
complete: function() {
console.log("done checking!");
gcounter=-2;
callback(brokenlink);
}
});
htmlChecker.scan(html, "https://mywebsite.com");
}
}
var getObjectFromClass = function(className,arr){
var promise = new AV.Promise();
var CLASS = AV.Object.extend(className);
var query = new AV.Query(CLASS);
query.exists('objectId');
query.limit(1000);
query.find().then(function(results) {
arr[className]=[]
_.each(results, function(item){
arr[className].push(item.toJSON())
} );
promise.resolve(results);
}, function(error) {
console.log('Error: ' + error.code + ' ' + error.message);
//return AV.Promise.error(error);
promise.reject(error);
});
return promise;
}
backupModule.hello = function(callback) {
// var links=["http://smallpdf.com/assets/img/ui/trophy.svg?h=1b05e9bc","http://smallpdf.com/assets/img/ui/trophy.svg?h=1b05e9bc2","www.abc.com2"];
var links=[];
var linkArr={};
var promise2 =getObjectFromClass("Products",linkArr);
var promise1 =getObjectFromClass("InteriorDesign",linkArr);
AV.Promise.when(
getObjectFromClass("Products",linkArr),
getObjectFromClass("InteriorDesign",linkArr)
).then(function (value) {
var links1= _.pluck(linkArr.Products, 'ios_object_url');
var links2= _.pluck(linkArr.Products, 'android_object_url');
var links3= _.flatten(_.pluck(linkArr.Products, 'images'));
var links4= _.pluck(linkArr.InteriorDesign, 'ios_object_url');
var links5= _.pluck(linkArr.InteriorDesign, 'android_object_url');
var links6= _.flatten(_.pluck(linkArr.InteriorDesign, 'images'));
links=[].concat(links1,links2,links3,links4,links5,links6);
// links=[].concat(links6);
console.log("going to check "+links.length+" links: ");
checkbrokenlink1(links,function(brokenlinkarr){
callback.success(JSON.stringify({result: brokenlinkarr}));
// res.render('brokenlink', { title: 'Express',result: brokenlinkarr });
});
});
}
backupModule.sendemail = function(msg,callback) {
// console.log(msg);
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
// console.log(year+"/"+month+"/"+day);
var title = year+"/"+month+"/"+day+" istagingHome report";
msg="<h1>iStaging Home </h1><small>Leancloud Report "+year+"/"+month+"/"+day+"</small>"+msg;
var params = {
"message": {
"from_email":"peter@staging.com.tw",
"from_name": "leancloud-istagingHome",
"to":[{"email":"peter@staging.com.tw",
"name": "Peter"
}],
"subject": title,
"html": msg
}
};
mandrill_client.messages.send(params, function(res) {
console.log("email sent");
callback.success((res));
// console.log(res);
// callback.success(res);
}, function(err) {
console.log(err);
callback.error(err);
});
}
module.exports = backupModule;
|
class BinaryTreeNode<A> {
left: BinaryTree<A>;
right: BinaryTree<A>;
constructor(left: BinaryTree<A>, right: BinaryTree<A>) {
this.left = left;
this.right = right;
}
}
class BinaryTreeLeaf<A> {
value: A;
constructor(value: A) {
this.value = value;
}
}
type BinaryTree<A> = BinaryTreeNode<A> | BinaryTreeLeaf<A>;
|
import React, {Component} from 'react';
import SinglePirate from '../../components/pirates/SinglePirate.js';
import Request from '../../helpers/request.js';
class SinglePirateContainer extends Component {
constructor(props){
super(props);
}
render(){
return (
<p>I am a SinglePirateContainer</p>
)
}
}
export default SinglePirateContainer;
|
var searchData=
[
['pos_34',['pos',['../class_x_ray_values.html#ac2ad0053dfd6cbe6596776578cfdaca5',1,'XRayValues']]],
['position_35',['position',['../class_clipping_cyllinder.html#af3a9b1c74987b6e0866a4ffb3cebf72b',1,'ClippingCyllinder']]]
];
|
angular.module("mobileControllers")
.controller("LoginController", function ($filter, $location, $rootScope, $scope, $state, Popup, $ionicViewSwitcher, $ionicLoading, MobileService) {
$scope.next = function (form) {
$ionicLoading.show({template: '<ion-spinner></ion-spinner>'});
MobileService.regGetCode(form).then(function (data) {
$ionicLoading.hide();
if (data.code == -1) {
Popup.alert(data.message);
return;
}
var params = {
phone: $scope.form.phone,
redirectUrl: $location.search().redirect_url,
appMarket: $location.search().appMarket,
invite_code: $location.search().inviteCode
}
$scope.form = null;
//1000已注册用户
if (data.data === 1) {
$state.go('login-next', params)
return
}
//0未注册用户
if (data.data === 0) {
/*
if (data.data.item) {
params.codeImg = $filter('removeProtocol')(data.data.item)
}
*/
// 预先获取验证码
MobileService.getCaptcha({type: 'captcha-login-reg'}).then(function (data) {
if (data.code == 0 && data.data.item) {
params.codeImg = $filter('removeProtocol')(data.data.item)
}
params.isRegister = true;
$state.go('reset-password', params)
})
}
});
};
})
|
const fs = require('fs');
const path = require('path');
let result = [];
//the function for reading data from json file and return the array of customer records
function exportFileData (filePath) {
try {
var data = fs.readFileSync( path.join(__dirname,filePath), 'utf8');
result=data.trim().split('\n').map(str => JSON.parse(str.trim()));
} catch(e) {
console.log('Error:', e.stack);
}
return result;
}
module.exports = { exportFileData };
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.